/
SslConnection.java
1659 lines (1468 loc) · 63.5 KB
/
SslConnection.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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// ========================================================================
// Copyright (c) 1995-2022 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// https://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 org.eclipse.jetty.io.ssl;
import java.io.IOException;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.ToIntFunction;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLEngineResult.Status;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLSession;
import org.eclipse.jetty.io.AbstractConnection;
import org.eclipse.jetty.io.AbstractEndPoint;
import org.eclipse.jetty.io.ByteBufferPool;
import org.eclipse.jetty.io.Connection;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.io.RetainableByteBuffer;
import org.eclipse.jetty.io.RetainableByteBufferPool;
import org.eclipse.jetty.io.WriteFlusher;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.thread.AutoLock;
import org.eclipse.jetty.util.thread.Invocable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A Connection that acts as an interceptor between an EndPoint providing SSL encrypted data
* and another consumer of an EndPoint (typically an {@link Connection} like HttpConnection) that
* wants unencrypted data.
* <p>
* The connector uses an {@link EndPoint} (typically SocketChannelEndPoint) as
* it's source/sink of encrypted data. It then provides an endpoint via {@link #getDecryptedEndPoint()} to
* expose a source/sink of unencrypted data to another connection (eg HttpConnection).
* <p>
* The design of this class is based on a clear separation between the passive methods, which do not block nor schedule any
* asynchronous callbacks, and active methods that do schedule asynchronous callbacks.
* <p>
* The passive methods are {@link DecryptedEndPoint#fill(ByteBuffer)} and {@link DecryptedEndPoint#flush(ByteBuffer...)}. They make best
* effort attempts to progress the connection using only calls to the encrypted {@link EndPoint#fill(ByteBuffer)} and {@link EndPoint#flush(ByteBuffer...)}
* methods. They will never block nor schedule any readInterest or write callbacks. If a fill/flush cannot progress either because
* of network congestion or waiting for an SSL handshake message, then the fill/flush will simply return with zero bytes filled/flushed.
* Specifically, if a flush cannot proceed because it needs to receive a handshake message, then the flush will attempt to fill bytes from the
* encrypted endpoint, but if insufficient bytes are read it will NOT call {@link EndPoint#fillInterested(Callback)}.
* <p>
* It is only the active methods : {@link DecryptedEndPoint#fillInterested(Callback)} and
* {@link DecryptedEndPoint#write(Callback, ByteBuffer...)} that may schedule callbacks by calling the encrypted
* {@link EndPoint#fillInterested(Callback)} and {@link EndPoint#write(Callback, ByteBuffer...)}
* methods. For normal data handling, the decrypted fillInterest method will result in an encrypted fillInterest and a decrypted
* write will result in an encrypted write. However, due to SSL handshaking requirements, it is also possible for a decrypted fill
* to call the encrypted write and for the decrypted flush to call the encrypted fillInterested methods.
* <p>
* MOST IMPORTANTLY, the encrypted callbacks from the active methods (#onFillable() and WriteFlusher#completeWrite()) do no filling or flushing
* themselves. Instead they simple make the callbacks to the decrypted callbacks, so that the passive encrypted fill/flush will
* be called again and make another best effort attempt to progress the connection.
*/
public class SslConnection extends AbstractConnection implements Connection.UpgradeTo
{
private static final Logger LOG = LoggerFactory.getLogger(SslConnection.class);
private static final String TLS_1_3 = "TLSv1.3";
private enum HandshakeState
{
INITIAL,
HANDSHAKE,
SUCCEEDED,
FAILED
}
private enum FillState
{
IDLE, // Not Filling any data
INTERESTED, // We have a pending read interest
WAIT_FOR_FLUSH // Waiting for a flush to happen
}
private enum FlushState
{
IDLE, // Not flushing any data
WRITING, // We have a pending write of encrypted data
WAIT_FOR_FILL // Waiting for a fill to happen
}
private final AutoLock _lock = new AutoLock();
private final AtomicReference<HandshakeState> _handshake = new AtomicReference<>(HandshakeState.INITIAL);
private final List<SslHandshakeListener> handshakeListeners = new ArrayList<>();
private final AtomicLong _bytesIn = new AtomicLong();
private final AtomicLong _bytesOut = new AtomicLong();
private final ByteBufferPool _bufferPool;
private final RetainableByteBufferPool _retainableByteBufferPool;
private final SSLEngine _sslEngine;
private final DecryptedEndPoint _decryptedEndPoint;
private ByteBuffer _decryptedInput;
private RetainableByteBuffer _encryptedInput;
private ByteBuffer _encryptedOutput;
private final boolean _encryptedDirectBuffers;
private final boolean _decryptedDirectBuffers;
private boolean _renegotiationAllowed;
private int _renegotiationLimit = -1;
private boolean _closedOutbound;
private boolean _requireCloseMessage;
private FlushState _flushState = FlushState.IDLE;
private FillState _fillState = FillState.IDLE;
private boolean _underflown;
private final Runnable _runFillable = new RunnableTask("runFillable")
{
@Override
public void run()
{
_decryptedEndPoint.getFillInterest().fillable();
}
@Override
public InvocationType getInvocationType()
{
return _decryptedEndPoint.getFillInterest().getCallbackInvocationType();
}
};
private final Callback _sslReadCallback = new Callback()
{
@Override
public void succeeded()
{
onFillable();
}
@Override
public void failed(final Throwable x)
{
onFillInterestedFailed(x);
}
@Override
public InvocationType getInvocationType()
{
return getDecryptedEndPoint().getFillInterest().getCallbackInvocationType();
}
@Override
public String toString()
{
return String.format("SSLC.NBReadCB@%x{%s}", SslConnection.this.hashCode(), SslConnection.this);
}
};
public SslConnection(ByteBufferPool byteBufferPool, Executor executor, EndPoint endPoint, SSLEngine sslEngine)
{
this(byteBufferPool, executor, endPoint, sslEngine, false, false);
}
public SslConnection(ByteBufferPool byteBufferPool, Executor executor, EndPoint endPoint, SSLEngine sslEngine,
boolean useDirectBuffersForEncryption, boolean useDirectBuffersForDecryption)
{
this(RetainableByteBufferPool.findOrAdapt(null, byteBufferPool), byteBufferPool, executor, endPoint, sslEngine, useDirectBuffersForEncryption, useDirectBuffersForDecryption);
}
public SslConnection(RetainableByteBufferPool retainableByteBufferPool, ByteBufferPool byteBufferPool, Executor executor, EndPoint endPoint, SSLEngine sslEngine,
boolean useDirectBuffersForEncryption, boolean useDirectBuffersForDecryption)
{
// This connection does not execute calls to onFillable(), so they will be called by the selector thread.
// onFillable() does not block and will only wakeup another thread to do the actual reading and handling.
super(endPoint, executor);
this._bufferPool = byteBufferPool;
this._retainableByteBufferPool = retainableByteBufferPool;
this._sslEngine = sslEngine;
this._decryptedEndPoint = newDecryptedEndPoint();
this._encryptedDirectBuffers = useDirectBuffersForEncryption;
this._decryptedDirectBuffers = useDirectBuffersForDecryption;
}
@Override
public long getBytesIn()
{
return _bytesIn.get();
}
@Override
public long getBytesOut()
{
return _bytesOut.get();
}
public void addHandshakeListener(SslHandshakeListener listener)
{
handshakeListeners.add(listener);
}
public boolean removeHandshakeListener(SslHandshakeListener listener)
{
return handshakeListeners.remove(listener);
}
protected DecryptedEndPoint newDecryptedEndPoint()
{
return new DecryptedEndPoint();
}
public SSLEngine getSSLEngine()
{
return _sslEngine;
}
public DecryptedEndPoint getDecryptedEndPoint()
{
return _decryptedEndPoint;
}
public boolean isRenegotiationAllowed()
{
return _renegotiationAllowed;
}
public void setRenegotiationAllowed(boolean renegotiationAllowed)
{
_renegotiationAllowed = renegotiationAllowed;
}
/**
* @return The number of renegotiations allowed for this connection. When the limit
* is 0 renegotiation will be denied. If the limit is less than 0 then no limit is applied.
*/
public int getRenegotiationLimit()
{
return _renegotiationLimit;
}
/**
* @param renegotiationLimit The number of renegotiations allowed for this connection.
* When the limit is 0 renegotiation will be denied. If the limit is less than 0 then no limit is applied.
* Default -1.
*/
public void setRenegotiationLimit(int renegotiationLimit)
{
_renegotiationLimit = renegotiationLimit;
}
/**
* @return whether peers must send the TLS {@code close_notify} message
*/
public boolean isRequireCloseMessage()
{
return _requireCloseMessage;
}
/**
* <p>Sets whether it is required that a peer send the TLS {@code close_notify} message
* to indicate the will to close the connection, otherwise it may be interpreted as a
* truncation attack.</p>
* <p>This option is only useful on clients, since typically servers cannot accept
* connection-delimited content that may be truncated.</p>
*
* @param requireCloseMessage whether peers must send the TLS {@code close_notify} message
*/
public void setRequireCloseMessage(boolean requireCloseMessage)
{
_requireCloseMessage = requireCloseMessage;
}
private boolean isHandshakeInitial()
{
return _handshake.get() == HandshakeState.INITIAL;
}
private boolean isHandshakeSucceeded()
{
return _handshake.get() == HandshakeState.SUCCEEDED;
}
private boolean isHandshakeComplete()
{
HandshakeState state = _handshake.get();
return state == HandshakeState.SUCCEEDED || state == HandshakeState.FAILED;
}
private int getApplicationBufferSize()
{
return getBufferSize(SSLSession::getApplicationBufferSize);
}
private int getPacketBufferSize()
{
return getBufferSize(SSLSession::getPacketBufferSize);
}
private int getBufferSize(ToIntFunction<SSLSession> bufferSizeFn)
{
SSLSession hsSession = _sslEngine.getHandshakeSession();
SSLSession session = _sslEngine.getSession();
int size = bufferSizeFn.applyAsInt(session);
if (hsSession == null || hsSession == session)
return size;
int hsSize = bufferSizeFn.applyAsInt(hsSession);
return Math.max(hsSize, size);
}
private void acquireEncryptedInput()
{
if (_encryptedInput == null)
_encryptedInput = _retainableByteBufferPool.acquire(getPacketBufferSize(), _encryptedDirectBuffers);
}
private void acquireEncryptedOutput()
{
if (_encryptedOutput == null)
_encryptedOutput = _bufferPool.acquire(getPacketBufferSize(), _encryptedDirectBuffers);
}
@Override
public void onUpgradeTo(ByteBuffer buffer)
{
acquireEncryptedInput();
BufferUtil.append(_encryptedInput.getBuffer(), buffer);
}
@Override
public void onOpen()
{
super.onOpen();
getDecryptedEndPoint().getConnection().onOpen();
}
@Override
public void onClose(Throwable cause)
{
_decryptedEndPoint.getConnection().onClose(cause);
super.onClose(cause);
}
@Override
public void close()
{
getDecryptedEndPoint().getConnection().close();
}
@Override
public boolean onIdleExpired()
{
return getDecryptedEndPoint().getConnection().onIdleExpired();
}
@Override
public void onFillable()
{
// onFillable means that there are encrypted bytes ready to be filled.
// however we do not fill them here on this callback, but instead wakeup
// the decrypted readInterest and/or writeFlusher so that they will attempt
// to do the fill and/or flush again and these calls will do the actually
// filling.
if (LOG.isDebugEnabled())
LOG.debug(">c.onFillable {}", SslConnection.this);
// We have received a close handshake, close the end point to send FIN.
if (_decryptedEndPoint.isInputShutdown())
_decryptedEndPoint.close();
_decryptedEndPoint.onFillable();
if (LOG.isDebugEnabled())
LOG.debug("<c.onFillable {}", SslConnection.this);
}
@Override
public void onFillInterestedFailed(Throwable cause)
{
_decryptedEndPoint.onFillableFail(cause == null ? new IOException() : cause);
}
protected SSLEngineResult wrap(SSLEngine sslEngine, ByteBuffer[] input, ByteBuffer output) throws SSLException
{
return sslEngine.wrap(input, output);
}
protected SSLEngineResult unwrap(SSLEngine sslEngine, ByteBuffer input, ByteBuffer output) throws SSLException
{
return sslEngine.unwrap(input, output);
}
@Override
public String toConnectionString()
{
ByteBuffer b = _encryptedInput == null ? null : _encryptedInput.getBuffer();
int ei = b == null ? -1 : b.remaining();
b = _encryptedOutput;
int eo = b == null ? -1 : b.remaining();
b = _decryptedInput;
int di = b == null ? -1 : b.remaining();
Connection connection = _decryptedEndPoint.getConnection();
return String.format("%s@%x{%s,eio=%d/%d,di=%d,fill=%s,flush=%s}~>%s=>%s",
getClass().getSimpleName(),
hashCode(),
_sslEngine.getHandshakeStatus(),
ei, eo, di,
_fillState, _flushState,
_decryptedEndPoint.toEndPointString(),
connection instanceof AbstractConnection ? ((AbstractConnection)connection).toConnectionString() : connection);
}
private void releaseEmptyEncryptedInputBuffer()
{
if (!_lock.isHeldByCurrentThread())
throw new IllegalStateException();
if (_encryptedInput != null && !_encryptedInput.hasRemaining())
{
_encryptedInput.release();
_encryptedInput = null;
}
}
private void releaseEmptyDecryptedInputBuffer()
{
if (!_lock.isHeldByCurrentThread())
throw new IllegalStateException();
if (_decryptedInput != null && !_decryptedInput.hasRemaining())
{
_bufferPool.release(_decryptedInput);
_decryptedInput = null;
}
}
private void discardInputBuffers()
{
if (!_lock.isHeldByCurrentThread())
throw new IllegalStateException();
if (_encryptedInput != null)
_encryptedInput.clear();
BufferUtil.clear(_decryptedInput);
releaseEmptyInputBuffers();
}
private void releaseEmptyInputBuffers()
{
releaseEmptyEncryptedInputBuffer();
releaseEmptyDecryptedInputBuffer();
}
private void discardEncryptedOutputBuffer()
{
if (!_lock.isHeldByCurrentThread())
throw new IllegalStateException();
BufferUtil.clear(_encryptedOutput);
releaseEmptyEncryptedOutputBuffer();
}
private void releaseEmptyEncryptedOutputBuffer()
{
if (!_lock.isHeldByCurrentThread())
throw new IllegalStateException();
if (_encryptedOutput != null && !_encryptedOutput.hasRemaining())
{
_bufferPool.release(_encryptedOutput);
_encryptedOutput = null;
}
}
protected int networkFill(ByteBuffer input) throws IOException
{
return getEndPoint().fill(input);
}
protected boolean networkFlush(ByteBuffer output) throws IOException
{
return getEndPoint().flush(output);
}
public class DecryptedEndPoint extends AbstractEndPoint implements EndPoint.Wrapper
{
private final Callback _incompleteWriteCallback = new IncompleteWriteCallback();
private Throwable _failure;
public DecryptedEndPoint()
{
// Disable idle timeout checking: no scheduler and -1 timeout for this instance.
super(null);
super.setIdleTimeout(-1);
}
@Override
public EndPoint unwrap()
{
return getEndPoint();
}
@Override
public long getIdleTimeout()
{
return getEndPoint().getIdleTimeout();
}
@Override
public void setIdleTimeout(long idleTimeout)
{
getEndPoint().setIdleTimeout(idleTimeout);
}
@Override
public boolean isOpen()
{
return getEndPoint().isOpen();
}
@Override
public SocketAddress getLocalSocketAddress()
{
return getEndPoint().getLocalSocketAddress();
}
@Override
public SocketAddress getRemoteSocketAddress()
{
return getEndPoint().getRemoteSocketAddress();
}
@Override
public WriteFlusher getWriteFlusher()
{
return super.getWriteFlusher();
}
protected void onFillable()
{
try
{
// If we are handshaking, then wake up any waiting write as well as it may have been blocked on the read
boolean waitingForFill;
try (AutoLock l = _lock.lock())
{
if (LOG.isDebugEnabled())
LOG.debug("onFillable {}", SslConnection.this);
_fillState = FillState.IDLE;
waitingForFill = _flushState == FlushState.WAIT_FOR_FILL;
}
getFillInterest().fillable();
if (waitingForFill)
{
try (AutoLock l = _lock.lock())
{
waitingForFill = _flushState == FlushState.WAIT_FOR_FILL;
}
if (waitingForFill)
fill(BufferUtil.EMPTY_BUFFER);
}
}
catch (Throwable e)
{
close(e);
}
}
protected void onFillableFail(Throwable failure)
{
// If we are handshaking, then wake up any waiting write as well as it may have been blocked on the read
boolean fail = false;
try (AutoLock l = _lock.lock())
{
if (LOG.isDebugEnabled())
LOG.debug("onFillableFail {}", SslConnection.this, failure);
_fillState = FillState.IDLE;
if (_flushState == FlushState.WAIT_FOR_FILL)
{
_flushState = FlushState.IDLE;
fail = true;
}
}
// wake up whoever is doing the fill
getFillInterest().onFail(failure);
// Try to complete the write
if (fail)
{
if (!getWriteFlusher().onFail(failure))
close(failure);
}
}
@Override
public void setConnection(Connection connection)
{
if (connection instanceof AbstractConnection)
{
// This is an optimization to avoid that upper layer connections use small
// buffers and we need to copy decrypted data rather than decrypting in place.
AbstractConnection c = (AbstractConnection)connection;
int appBufferSize = getApplicationBufferSize();
if (c.getInputBufferSize() < appBufferSize)
c.setInputBufferSize(appBufferSize);
}
super.setConnection(connection);
}
public SslConnection getSslConnection()
{
return SslConnection.this;
}
@Override
public int fill(ByteBuffer buffer) throws IOException
{
try
{
try (AutoLock l = _lock.lock())
{
if (LOG.isDebugEnabled())
LOG.debug(">fill {}", SslConnection.this);
int filled = -2;
try
{
if (_fillState != FillState.IDLE)
return filled = 0;
// Do we already have some decrypted data?
if (BufferUtil.hasContent(_decryptedInput))
return filled = BufferUtil.append(buffer, _decryptedInput);
// loop filling and unwrapping until we have something
while (true)
{
HandshakeStatus status = _sslEngine.getHandshakeStatus();
if (LOG.isDebugEnabled())
LOG.debug("fill {}", status);
switch (status)
{
case NEED_UNWRAP:
case NOT_HANDSHAKING:
break;
case NEED_TASK:
_sslEngine.getDelegatedTask().run();
continue;
case NEED_WRAP:
if (_flushState == FlushState.IDLE && flush(BufferUtil.EMPTY_BUFFER))
{
Throwable failure = _failure;
if (failure != null)
rethrow(failure);
if (_sslEngine.isInboundDone())
return filled = -1;
continue;
}
// Handle in needsFillInterest().
return filled = 0;
default:
throw new IllegalStateException("Unexpected HandshakeStatus " + status);
}
acquireEncryptedInput();
// can we use the passed buffer if it is big enough
ByteBuffer appIn;
int appBufferSize = getApplicationBufferSize();
if (_decryptedInput == null)
{
if (BufferUtil.space(buffer) > appBufferSize)
appIn = buffer;
else
appIn = _decryptedInput = _bufferPool.acquire(appBufferSize, _decryptedDirectBuffers);
}
else
{
appIn = _decryptedInput;
}
// Let's try reading some encrypted data... even if we have some already.
int netFilled = networkFill(_encryptedInput.getBuffer());
if (netFilled > 0)
_bytesIn.addAndGet(netFilled);
if (LOG.isDebugEnabled())
LOG.debug("net filled={}", netFilled);
// Workaround for Java 11 behavior.
if (netFilled < 0 && isHandshakeInitial() && (_encryptedInput == null || _encryptedInput.isEmpty()))
closeInbound();
if (netFilled > 0 && !isHandshakeComplete() && isOutboundDone())
throw new SSLHandshakeException("Closed during handshake");
if (_handshake.compareAndSet(HandshakeState.INITIAL, HandshakeState.HANDSHAKE))
{
if (LOG.isDebugEnabled())
LOG.debug("fill starting handshake {}", SslConnection.this);
}
// Let's unwrap even if we have no net data because in that
// case we want to fall through to the handshake handling
int pos = BufferUtil.flipToFill(appIn);
SSLEngineResult unwrapResult;
try
{
_underflown = false;
unwrapResult = SslConnection.this.unwrap(_sslEngine, _encryptedInput.getBuffer(), appIn);
}
finally
{
BufferUtil.flipToFlush(appIn, pos);
}
if (LOG.isDebugEnabled())
LOG.debug("unwrap net_filled={} {} encryptedBuffer={} unwrapBuffer={} appBuffer={}",
netFilled,
StringUtil.replace(unwrapResult.toString(), '\n', ' '),
_encryptedInput,
BufferUtil.toDetailString(appIn),
BufferUtil.toDetailString(buffer));
SSLEngineResult.Status unwrap = unwrapResult.getStatus();
// Extra check on unwrapResultStatus == OK with zero bytes consumed
// or produced is due to an SSL client on Android (see bug #454773).
if (unwrap == Status.OK && unwrapResult.bytesConsumed() == 0 && unwrapResult.bytesProduced() == 0)
unwrap = Status.BUFFER_UNDERFLOW;
switch (unwrap)
{
case CLOSED:
Throwable failure = _failure;
if (failure != null)
rethrow(failure);
return filled = -1;
case BUFFER_UNDERFLOW:
// Continue if we can compact?
if (BufferUtil.compact(_encryptedInput.getBuffer()))
continue;
// Are we out of space?
if (BufferUtil.space(_encryptedInput.getBuffer()) == 0)
{
BufferUtil.clear(_encryptedInput.getBuffer());
throw new SSLHandshakeException("Encrypted buffer max length exceeded");
}
// if we just filled some
if (netFilled > 0)
continue; // try filling some more
_underflown = true;
if (netFilled < 0 && _sslEngine.getUseClientMode())
{
Throwable closeFailure = closeInbound();
if (_flushState == FlushState.WAIT_FOR_FILL)
{
Throwable handshakeFailure = new SSLHandshakeException("Abruptly closed by peer");
if (closeFailure != null)
handshakeFailure.addSuppressed(closeFailure);
throw handshakeFailure;
}
return filled = -1;
}
return filled = netFilled;
case BUFFER_OVERFLOW:
// It's possible that SSLSession.applicationBufferSize has been expanded
// by the SSLEngine implementation. Unwrapping a large encrypted buffer
// causes BUFFER_OVERFLOW because the (old) applicationBufferSize is
// too small. Release the decrypted input buffer so it will be re-acquired
// with the larger capacity.
// See also system property "jsse.SSLEngine.acceptLargeFragments".
if (BufferUtil.isEmpty(_decryptedInput) && appBufferSize < getApplicationBufferSize())
{
releaseEmptyDecryptedInputBuffer();
continue;
}
throw new IllegalStateException("Unexpected unwrap result " + unwrap);
case OK:
if (unwrapResult.getHandshakeStatus() == HandshakeStatus.FINISHED)
handshakeSucceeded();
if (isRenegotiating() && !allowRenegotiate())
return filled = -1;
// If bytes were produced, don't bother with the handshake status;
// pass the decrypted data to the application, which will perform
// another call to fill() or flush().
if (unwrapResult.bytesProduced() > 0)
{
if (appIn == buffer)
return filled = unwrapResult.bytesProduced();
return filled = BufferUtil.append(buffer, _decryptedInput);
}
break;
default:
throw new IllegalStateException("Unexpected unwrap result " + unwrap);
}
}
}
catch (Throwable x)
{
discardInputBuffers();
Throwable f = handleException(x, "fill");
Throwable failure = handshakeFailed(f);
if (_flushState == FlushState.WAIT_FOR_FILL)
{
_flushState = FlushState.IDLE;
getExecutor().execute(() -> _decryptedEndPoint.getWriteFlusher().onFail(failure));
}
throw failure;
}
finally
{
releaseEmptyInputBuffers();
if (_flushState == FlushState.WAIT_FOR_FILL)
{
_flushState = FlushState.IDLE;
getExecutor().execute(() -> _decryptedEndPoint.getWriteFlusher().completeWrite());
}
if (LOG.isDebugEnabled())
LOG.debug("<fill f={} uf={} {}", filled, _underflown, SslConnection.this);
}
}
}
catch (Throwable x)
{
close(x);
rethrow(x);
// Never reached.
throw new AssertionError();
}
}
@Override
protected void needsFillInterest()
{
try
{
boolean fillable;
ByteBuffer write = null;
boolean interest = false;
try (AutoLock l = _lock.lock())
{
if (LOG.isDebugEnabled())
LOG.debug(">needFillInterest s={}/{} uf={} ei={} di={} {}",
_flushState,
_fillState,
_underflown,
_encryptedInput,
BufferUtil.toDetailString(_decryptedInput),
SslConnection.this);
if (_fillState != FillState.IDLE)
return;
// Fillable if we have decrypted input OR enough encrypted input.
fillable = BufferUtil.hasContent(_decryptedInput) || (_encryptedInput != null && _encryptedInput.hasRemaining() && !_underflown);
HandshakeStatus status = _sslEngine.getHandshakeStatus();
switch (status)
{
case NEED_TASK:
// Pretend we are fillable
fillable = true;
break;
case NEED_UNWRAP:
case NOT_HANDSHAKING:
if (!fillable)
{
interest = true;
_fillState = FillState.INTERESTED;
if (_flushState == FlushState.IDLE && BufferUtil.hasContent(_encryptedOutput))
{
_flushState = FlushState.WRITING;
write = _encryptedOutput;
}
}
break;
case NEED_WRAP:
if (!fillable)
{
_fillState = FillState.WAIT_FOR_FLUSH;
if (_flushState == FlushState.IDLE)
{
_flushState = FlushState.WRITING;
write = BufferUtil.hasContent(_encryptedOutput) ? _encryptedOutput : BufferUtil.EMPTY_BUFFER;
}
}
break;
default:
throw new IllegalStateException("Unexpected HandshakeStatus " + status);
}
if (LOG.isDebugEnabled())
LOG.debug("<needFillInterest s={}/{} f={} i={} w={}", _flushState, _fillState, fillable, interest, BufferUtil.toDetailString(write));
}
if (write != null)
getEndPoint().write(_incompleteWriteCallback, write);
else if (fillable)
getExecutor().execute(_runFillable);
else if (interest)
ensureFillInterested();
}
catch (Throwable x)
{
if (LOG.isDebugEnabled())
LOG.debug(SslConnection.this.toString(), x);
close(x);
throw x;
}
}
private void handshakeSucceeded() throws SSLException
{
if (_handshake.compareAndSet(HandshakeState.HANDSHAKE, HandshakeState.SUCCEEDED))
{
if (LOG.isDebugEnabled())
LOG.debug("handshake succeeded {} {} {}/{}", SslConnection.this,
_sslEngine.getUseClientMode() ? "client" : "resumed server",
_sslEngine.getSession().getProtocol(), _sslEngine.getSession().getCipherSuite());
notifyHandshakeSucceeded(_sslEngine);
}
else if (isHandshakeSucceeded())
{
if (_renegotiationLimit > 0)
_renegotiationLimit--;
}
}
private Throwable handshakeFailed(Throwable failure)
{
if (_handshake.compareAndSet(HandshakeState.HANDSHAKE, HandshakeState.FAILED))
{
if (LOG.isDebugEnabled())
LOG.debug("handshake failed {} {}", SslConnection.this, failure);
if (!(failure instanceof SSLHandshakeException))
failure = new SSLHandshakeException(failure.getMessage()).initCause(failure);
notifyHandshakeFailed(_sslEngine, failure);
}
return failure;
}
private void terminateInput()
{
try
{
_sslEngine.closeInbound();
}
catch (Throwable x)
{
LOG.trace("IGNORED", x);
}
}
private Throwable closeInbound() throws SSLException
{
HandshakeStatus handshakeStatus = _sslEngine.getHandshakeStatus();
try
{
_sslEngine.closeInbound();
return null;
}
catch (SSLException x)
{
if (handshakeStatus == HandshakeStatus.NOT_HANDSHAKING && isRequireCloseMessage())
throw x;
LOG.trace("IGNORED", x);
return x;
}
catch (Throwable x)
{
LOG.trace("IGNORED", x);
return x;
}
}