View Javadoc
1   /*
2    * Copyright 2016 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.handler.ssl;
17  
18  import io.netty.buffer.ByteBuf;
19  import io.netty.buffer.ByteBufAllocator;
20  import io.netty.handler.ssl.util.LazyJavaxX509Certificate;
21  import io.netty.handler.ssl.util.LazyX509Certificate;
22  import io.netty.internal.tcnative.AsyncTask;
23  import io.netty.internal.tcnative.Buffer;
24  import io.netty.internal.tcnative.SSL;
25  import io.netty.util.AbstractReferenceCounted;
26  import io.netty.util.CharsetUtil;
27  import io.netty.util.ReferenceCounted;
28  import io.netty.util.ResourceLeakDetector;
29  import io.netty.util.ResourceLeakDetectorFactory;
30  import io.netty.util.ResourceLeakTracker;
31  import io.netty.util.internal.EmptyArrays;
32  import io.netty.util.internal.PlatformDependent;
33  import io.netty.util.internal.StringUtil;
34  import io.netty.util.internal.ThrowableUtil;
35  import io.netty.util.internal.UnstableApi;
36  import io.netty.util.internal.logging.InternalLogger;
37  import io.netty.util.internal.logging.InternalLoggerFactory;
38  
39  import java.nio.ByteBuffer;
40  import java.nio.ReadOnlyBufferException;
41  import java.security.AlgorithmConstraints;
42  import java.security.Principal;
43  import java.security.cert.Certificate;
44  import java.util.ArrayList;
45  import java.util.Arrays;
46  import java.util.Collection;
47  import java.util.Collections;
48  import java.util.HashSet;
49  import java.util.LinkedHashSet;
50  import java.util.List;
51  import java.util.Map;
52  import java.util.Set;
53  import java.util.concurrent.ConcurrentHashMap;
54  import java.util.concurrent.locks.Lock;
55  import javax.crypto.spec.SecretKeySpec;
56  import javax.net.ssl.SNIHostName;
57  import javax.net.ssl.SNIMatcher;
58  import javax.net.ssl.SNIServerName;
59  import javax.net.ssl.SSLEngine;
60  import javax.net.ssl.SSLEngineResult;
61  import javax.net.ssl.SSLException;
62  import javax.net.ssl.SSLHandshakeException;
63  import javax.net.ssl.SSLParameters;
64  import javax.net.ssl.SSLPeerUnverifiedException;
65  import javax.net.ssl.SSLSession;
66  import javax.net.ssl.SSLSessionBindingEvent;
67  import javax.net.ssl.SSLSessionBindingListener;
68  import javax.security.cert.X509Certificate;
69  
70  import static io.netty.handler.ssl.OpenSsl.memoryAddress;
71  import static io.netty.handler.ssl.SslUtils.SSL_RECORD_HEADER_LENGTH;
72  import static io.netty.util.internal.EmptyArrays.EMPTY_STRINGS;
73  import static io.netty.util.internal.ObjectUtil.checkNotNull;
74  import static io.netty.util.internal.ObjectUtil.checkNotNullArrayParam;
75  import static io.netty.util.internal.ObjectUtil.checkNotNullWithIAE;
76  import static java.lang.Integer.MAX_VALUE;
77  import static java.lang.Math.min;
78  import static javax.net.ssl.SSLEngineResult.HandshakeStatus.FINISHED;
79  import static javax.net.ssl.SSLEngineResult.HandshakeStatus.NEED_TASK;
80  import static javax.net.ssl.SSLEngineResult.HandshakeStatus.NEED_UNWRAP;
81  import static javax.net.ssl.SSLEngineResult.HandshakeStatus.NEED_WRAP;
82  import static javax.net.ssl.SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING;
83  import static javax.net.ssl.SSLEngineResult.Status.BUFFER_OVERFLOW;
84  import static javax.net.ssl.SSLEngineResult.Status.BUFFER_UNDERFLOW;
85  import static javax.net.ssl.SSLEngineResult.Status.CLOSED;
86  import static javax.net.ssl.SSLEngineResult.Status.OK;
87  
88  /**
89   * Implements a {@link SSLEngine} using
90   * <a href="https://www.openssl.org/docs/crypto/BIO_s_bio.html#EXAMPLE">OpenSSL BIO abstractions</a>.
91   * <p>Instances of this class must be {@link #release() released} or else native memory will leak!
92   *
93   * <p>Instances of this class <strong>must</strong> be released before the {@link ReferenceCountedOpenSslContext}
94   * the instance depends upon are released. Otherwise if any method of this class is called which uses the
95   * the {@link ReferenceCountedOpenSslContext} JNI resources the JVM may crash.
96   */
97  public class ReferenceCountedOpenSslEngine extends SSLEngine implements ReferenceCounted, ApplicationProtocolAccessor {
98  
99      private static final InternalLogger logger = InternalLoggerFactory.getInstance(ReferenceCountedOpenSslEngine.class);
100 
101     private static final ResourceLeakDetector<ReferenceCountedOpenSslEngine> leakDetector =
102             ResourceLeakDetectorFactory.instance().newResourceLeakDetector(ReferenceCountedOpenSslEngine.class);
103     private static final int OPENSSL_OP_NO_PROTOCOL_INDEX_SSLV2 = 0;
104     private static final int OPENSSL_OP_NO_PROTOCOL_INDEX_SSLV3 = 1;
105     private static final int OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1 = 2;
106     private static final int OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1_1 = 3;
107     private static final int OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1_2 = 4;
108     private static final int OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1_3 = 5;
109     private static final int[] OPENSSL_OP_NO_PROTOCOLS = {
110             SSL.SSL_OP_NO_SSLv2,
111             SSL.SSL_OP_NO_SSLv3,
112             SSL.SSL_OP_NO_TLSv1,
113             SSL.SSL_OP_NO_TLSv1_1,
114             SSL.SSL_OP_NO_TLSv1_2,
115             SSL.SSL_OP_NO_TLSv1_3
116     };
117 
118     /**
119      * Depends upon tcnative ... only use if tcnative is available!
120      */
121     static final int MAX_PLAINTEXT_LENGTH = SSL.SSL_MAX_PLAINTEXT_LENGTH;
122     /**
123      * Depends upon tcnative ... only use if tcnative is available!
124      */
125     static final int MAX_RECORD_SIZE = SSL.SSL_MAX_RECORD_LENGTH;
126 
127     private static final SSLEngineResult NEED_UNWRAP_OK = new SSLEngineResult(OK, NEED_UNWRAP, 0, 0);
128     private static final SSLEngineResult NEED_UNWRAP_CLOSED = new SSLEngineResult(CLOSED, NEED_UNWRAP, 0, 0);
129     private static final SSLEngineResult NEED_WRAP_OK = new SSLEngineResult(OK, NEED_WRAP, 0, 0);
130     private static final SSLEngineResult NEED_WRAP_CLOSED = new SSLEngineResult(CLOSED, NEED_WRAP, 0, 0);
131     private static final SSLEngineResult CLOSED_NOT_HANDSHAKING = new SSLEngineResult(CLOSED, NOT_HANDSHAKING, 0, 0);
132 
133     // OpenSSL state
134     private long ssl;
135     private long networkBIO;
136 
137     private enum HandshakeState {
138         /**
139          * Not started yet.
140          */
141         NOT_STARTED,
142         /**
143          * Started via unwrap/wrap.
144          */
145         STARTED_IMPLICITLY,
146         /**
147          * Started via {@link #beginHandshake()}.
148          */
149         STARTED_EXPLICITLY,
150         /**
151          * Handshake is finished.
152          */
153         FINISHED
154     }
155 
156     private HandshakeState handshakeState = HandshakeState.NOT_STARTED;
157     private boolean receivedShutdown;
158     private volatile boolean destroyed;
159     private volatile String applicationProtocol;
160     private volatile boolean needTask;
161     private boolean hasTLSv13Cipher;
162     private boolean sessionSet;
163 
164     // Reference Counting
165     private final ResourceLeakTracker<ReferenceCountedOpenSslEngine> leak;
166     private final AbstractReferenceCounted refCnt = new AbstractReferenceCounted() {
167         @Override
168         public ReferenceCounted touch(Object hint) {
169             if (leak != null) {
170                 leak.record(hint);
171             }
172 
173             return ReferenceCountedOpenSslEngine.this;
174         }
175 
176         @Override
177         protected void deallocate() {
178             shutdown();
179             if (leak != null) {
180                 boolean closed = leak.close(ReferenceCountedOpenSslEngine.this);
181                 assert closed;
182             }
183             parentContext.release();
184         }
185     };
186 
187     private final Set<String> enabledProtocols = new LinkedHashSet<String>();
188 
189     private volatile ClientAuth clientAuth = ClientAuth.NONE;
190 
191     private String endpointIdentificationAlgorithm;
192     // Store as object as AlgorithmConstraints only exists since java 7.
193     private Object algorithmConstraints;
194     private List<String> sniHostNames;
195 
196     // Mark as volatile as accessed by checkSniHostnameMatch(...).
197     private volatile Collection<SNIMatcher> matchers;
198 
199     // SSL Engine status variables
200     private boolean isInboundDone;
201     private boolean outboundClosed;
202 
203     final boolean jdkCompatibilityMode;
204     private final boolean clientMode;
205     final ByteBufAllocator alloc;
206     private final OpenSslEngineMap engineMap;
207     private final OpenSslApplicationProtocolNegotiator apn;
208     private final ReferenceCountedOpenSslContext parentContext;
209     private final OpenSslSession session;
210     private final ByteBuffer[] singleSrcBuffer = new ByteBuffer[1];
211     private final ByteBuffer[] singleDstBuffer = new ByteBuffer[1];
212     private final boolean enableOcsp;
213     private int maxWrapOverhead;
214     private int maxWrapBufferSize;
215     private Throwable pendingException;
216 
217     /**
218      * Create a new instance.
219      * @param context Reference count release responsibility is not transferred! The callee still owns this object.
220      * @param alloc The allocator to use.
221      * @param peerHost The peer host name.
222      * @param peerPort The peer port.
223      * @param jdkCompatibilityMode {@code true} to behave like described in
224      *                             https://docs.oracle.com/javase/7/docs/api/javax/net/ssl/SSLEngine.html.
225      *                             {@code false} allows for partial and/or multiple packets to be process in a single
226      *                             wrap or unwrap call.
227      * @param leakDetection {@code true} to enable leak detection of this object.
228      */
229     ReferenceCountedOpenSslEngine(ReferenceCountedOpenSslContext context, final ByteBufAllocator alloc, String peerHost,
230                                   int peerPort, boolean jdkCompatibilityMode, boolean leakDetection,
231                                   String endpointIdentificationAlgorithm) {
232         super(peerHost, peerPort);
233         OpenSsl.ensureAvailability();
234         engineMap = context.engineMap;
235         enableOcsp = context.enableOcsp;
236         this.jdkCompatibilityMode = jdkCompatibilityMode;
237         this.alloc = checkNotNull(alloc, "alloc");
238         apn = (OpenSslApplicationProtocolNegotiator) context.applicationProtocolNegotiator();
239         clientMode = context.isClient();
240         this.endpointIdentificationAlgorithm = endpointIdentificationAlgorithm;
241 
242         session = new ExtendedOpenSslSession(new DefaultOpenSslSession(context.sessionContext())) {
243             private String[] peerSupportedSignatureAlgorithms;
244             private List<SNIServerName> requestedServerNames;
245 
246             @Override
247             public List<SNIServerName> getRequestedServerNames() {
248                 if (clientMode) {
249                     return getSniHostNames(sniHostNames);
250                 } else {
251                     synchronized (ReferenceCountedOpenSslEngine.this) {
252                         if (requestedServerNames == null) {
253                             if (isDestroyed()) {
254                                 requestedServerNames = Collections.emptyList();
255                             } else {
256                                 String name = SSL.getSniHostname(ssl);
257                                 if (name == null) {
258                                     requestedServerNames = Collections.emptyList();
259                                 } else {
260                                     // Convert to bytes as we do not want to do any strict validation of the
261                                     // SNIHostName while creating it.
262                                     byte[] hostname = SSL.getSniHostname(ssl).getBytes(CharsetUtil.UTF_8);
263                                     requestedServerNames = hostname == null || hostname.length == 0 ?
264                                             Collections.emptyList() :
265                                                     Collections.singletonList(new SNIHostName(hostname));
266                                 }
267                             }
268                         }
269                         return requestedServerNames;
270                     }
271                 }
272             }
273 
274             @Override
275             public String[] getPeerSupportedSignatureAlgorithms() {
276                 synchronized (ReferenceCountedOpenSslEngine.this) {
277                     if (peerSupportedSignatureAlgorithms == null) {
278                         if (isDestroyed()) {
279                             peerSupportedSignatureAlgorithms = EMPTY_STRINGS;
280                         } else {
281                             String[] algs = SSL.getSigAlgs(ssl);
282                             if (algs == null) {
283                                 peerSupportedSignatureAlgorithms = EMPTY_STRINGS;
284                             } else {
285                                 Set<String> algorithmList = new LinkedHashSet<String>(algs.length);
286                                 for (String alg: algs) {
287                                     String converted = SignatureAlgorithmConverter.toJavaName(alg);
288 
289                                     if (converted != null) {
290                                         algorithmList.add(converted);
291                                     }
292                                 }
293                                 peerSupportedSignatureAlgorithms = algorithmList.toArray(EMPTY_STRINGS);
294                             }
295                         }
296                     }
297                     return peerSupportedSignatureAlgorithms.clone();
298                 }
299             }
300 
301             @Override
302             public List<byte[]> getStatusResponses() {
303                 byte[] ocspResponse = null;
304                 if (enableOcsp && clientMode) {
305                     synchronized (ReferenceCountedOpenSslEngine.this) {
306                         if (!isDestroyed()) {
307                             ocspResponse = SSL.getOcspResponse(ssl);
308                         }
309                     }
310                 }
311                 return ocspResponse == null ?
312                         Collections.<byte[]>emptyList() : Collections.singletonList(ocspResponse);
313             }
314         };
315 
316         if (!context.sessionContext().useKeyManager()) {
317             session.setLocalCertificate(context.keyCertChain);
318         }
319 
320         Lock readerLock = context.ctxLock.readLock();
321         readerLock.lock();
322         final long finalSsl;
323         try {
324             finalSsl = SSL.newSSL(context.ctx, !context.isClient());
325         } finally {
326             readerLock.unlock();
327         }
328         synchronized (this) {
329             ssl = finalSsl;
330             try {
331                 networkBIO = SSL.bioNewByteBuffer(ssl, context.getBioNonApplicationBufferSize());
332 
333                 // Set the client auth mode, this needs to be done via setClientAuth(...) method so we actually call the
334                 // needed JNI methods.
335                 setClientAuth(clientMode ? ClientAuth.NONE : context.clientAuth);
336 
337                 assert context.protocols != null;
338                 this.hasTLSv13Cipher = context.hasTLSv13Cipher;
339 
340                 setEnabledProtocols(context.protocols);
341 
342                 // Use SNI if peerHost was specified and a valid hostname
343                 // See https://github.com/netty/netty/issues/4746
344                 if (clientMode && SslUtils.isValidHostNameForSNI(peerHost)) {
345                     // We do some extra validation to ensure we can construct the SNIHostName later again.
346                     if (isValidHostNameForSNI(peerHost)) {
347                         SSL.setTlsExtHostName(ssl, peerHost);
348                         sniHostNames = Collections.singletonList(peerHost);
349                     }
350                 }
351 
352                 if (enableOcsp) {
353                     SSL.enableOcsp(ssl);
354                 }
355 
356                 if (!jdkCompatibilityMode) {
357                     SSL.setMode(ssl, SSL.getMode(ssl) | SSL.SSL_MODE_ENABLE_PARTIAL_WRITE);
358                 }
359 
360                 if (isProtocolEnabled(SSL.getOptions(ssl), SSL.SSL_OP_NO_TLSv1_3, SslProtocols.TLS_v1_3)) {
361                     final boolean enableTickets = clientMode ?
362                             ReferenceCountedOpenSslContext.CLIENT_ENABLE_SESSION_TICKET_TLSV13 :
363                             ReferenceCountedOpenSslContext.SERVER_ENABLE_SESSION_TICKET_TLSV13;
364                     if (enableTickets) {
365                         // We should enable session tickets for stateless resumption when TLSv1.3 is enabled. This
366                         // is also done by OpenJDK and without this session resumption does not work at all with
367                         // BoringSSL when TLSv1.3 is used as BoringSSL only supports stateless resumption with TLSv1.3:
368                         //
369                         // See:
370                         //  - https://bugs.openjdk.java.net/browse/JDK-8223922
371                         //  - https://boringssl.googlesource.com/boringssl/+/refs/heads/master/ssl/tls13_server.cc#104
372                         SSL.clearOptions(ssl, SSL.SSL_OP_NO_TICKET);
373                     }
374                 }
375 
376                 if (OpenSsl.isBoringSSL() && clientMode) {
377                     // If in client-mode and BoringSSL let's allow to renegotiate once as the server may use this
378                     // for client auth.
379                     //
380                     // See https://github.com/netty/netty/issues/11529
381                     SSL.setRenegotiateMode(ssl, SSL.SSL_RENEGOTIATE_ONCE);
382                 }
383                 // setMode may impact the overhead.
384                 calculateMaxWrapOverhead();
385 
386                 // Configure any endpoint verification specified by the SslContext.
387                 configureEndpointVerification(endpointIdentificationAlgorithm);
388             } catch (Throwable cause) {
389                 // Call shutdown so we are sure we correctly release all native memory and also guard against the
390                 // case when shutdown() will be called by the finalizer again.
391                 shutdown();
392 
393                 PlatformDependent.throwException(cause);
394             }
395         }
396 
397         // Now that everything looks good and we're going to successfully return the
398         // object so we need to retain a reference to the parent context.
399         parentContext = context;
400         parentContext.retain();
401 
402         // Only create the leak after everything else was executed and so ensure we don't produce a false-positive for
403         // the ResourceLeakDetector.
404         leak = leakDetection ? leakDetector.track(this) : null;
405     }
406 
407     private static boolean isValidHostNameForSNI(String hostname) {
408         try {
409             new SNIHostName(hostname);
410             return true;
411         } catch (IllegalArgumentException illegal) {
412             return false;
413         }
414     }
415 
416     final synchronized String[] authMethods() {
417         if (isDestroyed()) {
418             return EMPTY_STRINGS;
419         }
420         return SSL.authenticationMethods(ssl);
421     }
422 
423     final boolean setKeyMaterial(OpenSslKeyMaterial keyMaterial) throws  Exception {
424         synchronized (this) {
425             if (isDestroyed()) {
426                 return false;
427             }
428             SSL.setKeyMaterial(ssl, keyMaterial.certificateChainAddress(), keyMaterial.privateKeyAddress());
429         }
430         session.setLocalCertificate(keyMaterial.certificateChain());
431         return true;
432     }
433 
434     final synchronized SecretKeySpec masterKey() {
435         if (isDestroyed()) {
436             return null;
437         }
438         return new SecretKeySpec(SSL.getMasterKey(ssl), "AES");
439     }
440 
441     synchronized boolean isSessionReused() {
442         if (isDestroyed()) {
443             return false;
444         }
445         return SSL.isSessionReused(ssl);
446     }
447 
448     /**
449      * Sets the OCSP response.
450      */
451     @UnstableApi
452     public void setOcspResponse(byte[] response) {
453         if (!enableOcsp) {
454             throw new IllegalStateException("OCSP stapling is not enabled");
455         }
456 
457         if (clientMode) {
458             throw new IllegalStateException("Not a server SSLEngine");
459         }
460 
461         synchronized (this) {
462             if (!isDestroyed()) {
463                 SSL.setOcspResponse(ssl, response);
464             }
465         }
466     }
467 
468     /**
469      * Returns the OCSP response or {@code null} if the server didn't provide a stapled OCSP response.
470      */
471     @UnstableApi
472     public byte[] getOcspResponse() {
473         if (!enableOcsp) {
474             throw new IllegalStateException("OCSP stapling is not enabled");
475         }
476 
477         if (!clientMode) {
478             throw new IllegalStateException("Not a client SSLEngine");
479         }
480 
481         synchronized (this) {
482             if (isDestroyed()) {
483                 return EmptyArrays.EMPTY_BYTES;
484             }
485             return SSL.getOcspResponse(ssl);
486         }
487     }
488 
489     @Override
490     public final int refCnt() {
491         return refCnt.refCnt();
492     }
493 
494     @Override
495     public final ReferenceCounted retain() {
496         refCnt.retain();
497         return this;
498     }
499 
500     @Override
501     public final ReferenceCounted retain(int increment) {
502         refCnt.retain(increment);
503         return this;
504     }
505 
506     @Override
507     public final ReferenceCounted touch() {
508         refCnt.touch();
509         return this;
510     }
511 
512     @Override
513     public final ReferenceCounted touch(Object hint) {
514         refCnt.touch(hint);
515         return this;
516     }
517 
518     @Override
519     public final boolean release() {
520         return refCnt.release();
521     }
522 
523     @Override
524     public final boolean release(int decrement) {
525         return refCnt.release(decrement);
526     }
527 
528     // These method will override the method defined by Java 8u251 and later. As we may compile with an earlier
529     // java8 version we don't use @Override annotations here.
530     public String getApplicationProtocol() {
531         return applicationProtocol;
532     }
533 
534     // These method will override the method defined by Java 8u251 and later. As we may compile with an earlier
535     // java8 version we don't use @Override annotations here.
536     public String getHandshakeApplicationProtocol() {
537         return applicationProtocol;
538     }
539 
540     @Override
541     public final synchronized SSLSession getHandshakeSession() {
542         // Javadocs state return value should be:
543         // null if this instance is not currently handshaking, or if the current handshake has not
544         // progressed far enough to create a basic SSLSession. Otherwise, this method returns the
545         // SSLSession currently being negotiated.
546         switch(handshakeState) {
547             case NOT_STARTED:
548             case FINISHED:
549                 return null;
550             default:
551                 return session;
552         }
553     }
554 
555     /**
556      * Returns the pointer to the {@code SSL} object for this {@link ReferenceCountedOpenSslEngine}.
557      * Be aware that it is freed as soon as the {@link #release()} or {@link #shutdown()} methods are called.
558      * At this point {@code 0} will be returned.
559      */
560     public final synchronized long sslPointer() {
561         return ssl;
562     }
563 
564     /**
565      * Destroys this engine.
566      */
567     public final synchronized void shutdown() {
568         if (!destroyed) {
569             destroyed = true;
570             // Let's check if engineMap is null as it could be in theory if we throw an OOME during the construction of
571             // ReferenceCountedOpenSslEngine (before we assign the field). This is needed as shutdown() is called from
572             // the finalizer as well.
573             if (engineMap != null) {
574                 engineMap.remove(ssl);
575             }
576             SSL.freeSSL(ssl);
577             ssl = networkBIO = 0;
578 
579             isInboundDone = outboundClosed = true;
580         }
581 
582         // On shutdown clear all errors
583         SSL.clearError();
584     }
585 
586     /**
587      * Write plaintext data to the OpenSSL internal BIO
588      *
589      * Calling this function with src.remaining == 0 is undefined.
590      */
591     private int writePlaintextData(final ByteBuffer src, int len) {
592         final int pos = src.position();
593         final int limit = src.limit();
594         final int sslWrote;
595 
596         if (src.isDirect()) {
597             sslWrote = SSL.writeToSSL(ssl, bufferAddress(src) + pos, len);
598             if (sslWrote > 0) {
599                 src.position(pos + sslWrote);
600             }
601         } else {
602             ByteBuf buf = alloc.directBuffer(len);
603             try {
604                 src.limit(pos + len);
605 
606                 buf.setBytes(0, src);
607                 src.limit(limit);
608 
609                 sslWrote = SSL.writeToSSL(ssl, memoryAddress(buf), len);
610                 if (sslWrote > 0) {
611                     src.position(pos + sslWrote);
612                 } else {
613                     src.position(pos);
614                 }
615             } finally {
616                 buf.release();
617             }
618         }
619         return sslWrote;
620     }
621 
622    synchronized void bioSetFd(int fd) {
623         if (!isDestroyed()) {
624             SSL.bioSetFd(this.ssl, fd);
625         }
626     }
627 
628     /**
629      * Write encrypted data to the OpenSSL network BIO.
630      */
631     private ByteBuf writeEncryptedData(final ByteBuffer src, int len) throws SSLException {
632         final int pos = src.position();
633         if (src.isDirect()) {
634             SSL.bioSetByteBuffer(networkBIO, bufferAddress(src) + pos, len, false);
635         } else {
636             final ByteBuf buf = alloc.directBuffer(len);
637             try {
638                 final int limit = src.limit();
639                 src.limit(pos + len);
640                 buf.writeBytes(src);
641                 // Restore the original position and limit because we don't want to consume from `src`.
642                 src.position(pos);
643                 src.limit(limit);
644 
645                 SSL.bioSetByteBuffer(networkBIO, memoryAddress(buf), len, false);
646                 return buf;
647             } catch (Throwable cause) {
648                 buf.release();
649                 PlatformDependent.throwException(cause);
650             }
651         }
652         return null;
653     }
654 
655     /**
656      * Read plaintext data from the OpenSSL internal BIO
657      */
658     private int readPlaintextData(final ByteBuffer dst) throws SSLException {
659         final int sslRead;
660         final int pos = dst.position();
661         if (dst.isDirect()) {
662             sslRead = SSL.readFromSSL(ssl, bufferAddress(dst) + pos, dst.limit() - pos);
663             if (sslRead > 0) {
664                 dst.position(pos + sslRead);
665             }
666         } else {
667             final int limit = dst.limit();
668             final int len = min(maxEncryptedPacketLength0(), limit - pos);
669             final ByteBuf buf = alloc.directBuffer(len);
670             try {
671                 sslRead = SSL.readFromSSL(ssl, memoryAddress(buf), len);
672                 if (sslRead > 0) {
673                     dst.limit(pos + sslRead);
674                     buf.getBytes(buf.readerIndex(), dst);
675                     dst.limit(limit);
676                 }
677             } finally {
678                 buf.release();
679             }
680         }
681 
682         return sslRead;
683     }
684 
685     /**
686      * Visible only for testing!
687      */
688     final synchronized int maxWrapOverhead() {
689         return maxWrapOverhead;
690     }
691 
692     /**
693      * Visible only for testing!
694      */
695     final synchronized int maxEncryptedPacketLength() {
696         return maxEncryptedPacketLength0();
697     }
698 
699     /**
700      * This method is intentionally not synchronized, only use if you know you are in the EventLoop
701      * thread and visibility on {@link #maxWrapOverhead} is achieved via other synchronized blocks.
702      */
703     final int maxEncryptedPacketLength0() {
704         return maxWrapOverhead + MAX_PLAINTEXT_LENGTH;
705     }
706 
707     /**
708      * This method is intentionally not synchronized, only use if you know you are in the EventLoop
709      * thread and visibility on {@link #maxWrapBufferSize} and {@link #maxWrapOverhead} is achieved
710      * via other synchronized blocks.
711      * <br>
712      * Calculates the max size of a single wrap operation for the given plaintextLength and
713      * numComponents.
714      */
715     final int calculateMaxLengthForWrap(int plaintextLength, int numComponents) {
716         return (int) min(maxWrapBufferSize, plaintextLength + (long) maxWrapOverhead * numComponents);
717     }
718 
719     /**
720      * This method is intentionally not synchronized, only use if you know you are in the EventLoop
721      * thread and visibility on {@link #maxWrapOverhead} is achieved via other synchronized blocks.
722      * <br>
723      * Calculates the size of the out net buf to create for the given plaintextLength and numComponents.
724      * This is not related to the max size per wrap, as we can wrap chunks at a time into one out net buf.
725      */
726     final int calculateOutNetBufSize(int plaintextLength, int numComponents) {
727         return (int) min(MAX_VALUE, plaintextLength + (long) maxWrapOverhead * numComponents);
728     }
729 
730     final synchronized int sslPending() {
731         return sslPending0();
732     }
733 
734     /**
735      * It is assumed this method is called in a synchronized block (or the constructor)!
736      */
737     private void calculateMaxWrapOverhead() {
738         maxWrapOverhead = SSL.getMaxWrapOverhead(ssl);
739 
740         // maxWrapBufferSize must be set after maxWrapOverhead because there is a dependency on this value.
741         // If jdkCompatibility mode is off we allow enough space to encrypt 16 buffers at a time. This could be
742         // configurable in the future if necessary.
743         maxWrapBufferSize = jdkCompatibilityMode ? maxEncryptedPacketLength0() : maxEncryptedPacketLength0() << 4;
744     }
745 
746     private int sslPending0() {
747         // OpenSSL has a limitation where if you call SSL_pending before the handshake is complete OpenSSL will throw a
748         // "called a function you should not call" error. Using the TLS_method instead of SSLv23_method may solve this
749         // issue but this API is only available in 1.1.0+ [1].
750         // [1] https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_new.html
751         return handshakeState != HandshakeState.FINISHED ? 0 : SSL.sslPending(ssl);
752     }
753 
754     private boolean isBytesAvailableEnoughForWrap(int bytesAvailable, int plaintextLength, int numComponents) {
755         return bytesAvailable - (long) maxWrapOverhead * numComponents >= plaintextLength;
756     }
757 
758     @Override
759     public final SSLEngineResult wrap(
760             final ByteBuffer[] srcs, int offset, final int length, final ByteBuffer dst) throws SSLException {
761         // Throw required runtime exceptions
762         checkNotNullWithIAE(srcs, "srcs");
763         checkNotNullWithIAE(dst, "dst");
764 
765         if (offset >= srcs.length || offset + length > srcs.length) {
766             throw new IndexOutOfBoundsException(
767                     "offset: " + offset + ", length: " + length +
768                             " (expected: offset <= offset + length <= srcs.length (" + srcs.length + "))");
769         }
770 
771         if (dst.isReadOnly()) {
772             throw new ReadOnlyBufferException();
773         }
774 
775         synchronized (this) {
776             if (isOutboundDone()) {
777                 // All drained in the outbound buffer
778                 return isInboundDone() || isDestroyed() ? CLOSED_NOT_HANDSHAKING : NEED_UNWRAP_CLOSED;
779             }
780 
781             int bytesProduced = 0;
782             ByteBuf bioReadCopyBuf = null;
783             try {
784                 // Setup the BIO buffer so that we directly write the encryption results into dst.
785                 if (dst.isDirect()) {
786                     SSL.bioSetByteBuffer(networkBIO, bufferAddress(dst) + dst.position(), dst.remaining(),
787                             true);
788                 } else {
789                     bioReadCopyBuf = alloc.directBuffer(dst.remaining());
790                     SSL.bioSetByteBuffer(networkBIO, memoryAddress(bioReadCopyBuf), bioReadCopyBuf.writableBytes(),
791                             true);
792                 }
793 
794                 int bioLengthBefore = SSL.bioLengthByteBuffer(networkBIO);
795 
796                 // Explicitly use outboundClosed as we want to drain any bytes that are still present.
797                 if (outboundClosed) {
798                     // If the outbound was closed we want to ensure we can produce the alert to the destination buffer.
799                     // This is true even if we not using jdkCompatibilityMode.
800                     //
801                     // We use a plaintextLength of 2 as we at least want to have an alert fit into it.
802                     // https://tools.ietf.org/html/rfc5246#section-7.2
803                     if (!isBytesAvailableEnoughForWrap(dst.remaining(), 2, 1)) {
804                         return new SSLEngineResult(BUFFER_OVERFLOW, getHandshakeStatus(), 0, 0);
805                     }
806 
807                     // There is something left to drain.
808                     // See https://github.com/netty/netty/issues/6260
809                     bytesProduced = SSL.bioFlushByteBuffer(networkBIO);
810                     if (bytesProduced <= 0) {
811                         return newResultMayFinishHandshake(NOT_HANDSHAKING, 0, 0);
812                     }
813                     // It is possible when the outbound was closed there was not enough room in the non-application
814                     // buffers to hold the close_notify. We should keep trying to close until we consume all the data
815                     // OpenSSL can give us.
816                     if (!doSSLShutdown()) {
817                         return newResultMayFinishHandshake(NOT_HANDSHAKING, 0, bytesProduced);
818                     }
819                     bytesProduced = bioLengthBefore - SSL.bioLengthByteBuffer(networkBIO);
820                     return newResultMayFinishHandshake(NEED_WRAP, 0, bytesProduced);
821                 }
822 
823                 // Flush any data that may be implicitly generated by OpenSSL (handshake, close, etc..).
824                 SSLEngineResult.HandshakeStatus status = NOT_HANDSHAKING;
825                 HandshakeState oldHandshakeState = handshakeState;
826 
827                 // Prepare OpenSSL to work in server mode and receive handshake
828                 if (handshakeState != HandshakeState.FINISHED) {
829                     if (handshakeState != HandshakeState.STARTED_EXPLICITLY) {
830                         // Update accepted so we know we triggered the handshake via wrap
831                         handshakeState = HandshakeState.STARTED_IMPLICITLY;
832                     }
833 
834                     // Flush any data that may have been written implicitly during the handshake by OpenSSL.
835                     bytesProduced = SSL.bioFlushByteBuffer(networkBIO);
836 
837                     if (pendingException != null) {
838                         // TODO(scott): It is possible that when the handshake failed there was not enough room in the
839                         // non-application buffers to hold the alert. We should get all the data before progressing on.
840                         // However I'm not aware of a way to do this with the OpenSSL APIs.
841                         // See https://github.com/netty/netty/issues/6385.
842 
843                         // We produced / consumed some data during the handshake, signal back to the caller.
844                         // If there is a handshake exception and we have produced data, we should send the data before
845                         // we allow handshake() to throw the handshake exception.
846                         //
847                         // When the user calls wrap() again we will propagate the handshake error back to the user as
848                         // soon as there is no more data to was produced (as part of an alert etc).
849                         if (bytesProduced > 0) {
850                             return newResult(NEED_WRAP, 0, bytesProduced);
851                         }
852                         // Nothing was produced see if there is a handshakeException that needs to be propagated
853                         // to the caller by calling handshakeException() which will return the right HandshakeStatus
854                         // if it can "recover" from the exception for now.
855                         return newResult(handshakeException(), 0, 0);
856                     }
857 
858                     status = handshake();
859 
860                     // Handshake may have generated more data, for example if the internal SSL buffer is small
861                     // we may have freed up space by flushing above.
862                     bytesProduced = bioLengthBefore - SSL.bioLengthByteBuffer(networkBIO);
863 
864                     if (status == NEED_TASK) {
865                         return newResult(status, 0, bytesProduced);
866                     }
867 
868                     if (bytesProduced > 0) {
869                         // If we have filled up the dst buffer and we have not finished the handshake we should try to
870                         // wrap again. Otherwise we should only try to wrap again if there is still data pending in
871                         // SSL buffers.
872                         return newResult(mayFinishHandshake(status != FINISHED ?
873                                          bytesProduced == bioLengthBefore ? NEED_WRAP :
874                                          getHandshakeStatus(SSL.bioLengthNonApplication(networkBIO)) : FINISHED),
875                                          0, bytesProduced);
876                     }
877 
878                     if (status == NEED_UNWRAP) {
879                         // Signal if the outbound is done or not.
880                         return isOutboundDone() ? NEED_UNWRAP_CLOSED : NEED_UNWRAP_OK;
881                     }
882 
883                     // Explicit use outboundClosed and not outboundClosed() as we want to drain any bytes that are
884                     // still present.
885                     if (outboundClosed) {
886                         bytesProduced = SSL.bioFlushByteBuffer(networkBIO);
887                         return newResultMayFinishHandshake(status, 0, bytesProduced);
888                     }
889                 }
890 
891                 final int endOffset = offset + length;
892                 if (jdkCompatibilityMode ||
893                         // If the handshake was not finished before we entered the method, we also ensure we only
894                         // wrap one record. We do this to ensure we not produce any extra data before the caller
895                         // of the method is able to observe handshake completion and react on it.
896                         oldHandshakeState != HandshakeState.FINISHED) {
897                     int srcsLen = 0;
898                     for (int i = offset; i < endOffset; ++i) {
899                         final ByteBuffer src = srcs[i];
900                         if (src == null) {
901                             throw new IllegalArgumentException("srcs[" + i + "] is null");
902                         }
903                         if (srcsLen == MAX_PLAINTEXT_LENGTH) {
904                             continue;
905                         }
906 
907                         srcsLen += src.remaining();
908                         if (srcsLen > MAX_PLAINTEXT_LENGTH || srcsLen < 0) {
909                             // If srcLen > MAX_PLAINTEXT_LENGTH or secLen < 0 just set it to MAX_PLAINTEXT_LENGTH.
910                             // This also help us to guard against overflow.
911                             // We not break out here as we still need to check for null entries in srcs[].
912                             srcsLen = MAX_PLAINTEXT_LENGTH;
913                         }
914                     }
915 
916                     // jdkCompatibilityMode will only produce a single TLS packet, and we don't aggregate src buffers,
917                     // so we always fix the number of buffers to 1 when checking if the dst buffer is large enough.
918                     if (!isBytesAvailableEnoughForWrap(dst.remaining(), srcsLen, 1)) {
919                         return new SSLEngineResult(BUFFER_OVERFLOW, getHandshakeStatus(), 0, 0);
920                     }
921                 }
922 
923                 // There was no pending data in the network BIO -- encrypt any application data
924                 int bytesConsumed = 0;
925                 assert bytesProduced == 0;
926 
927                 // Flush any data that may have been written implicitly by OpenSSL in case a shutdown/alert occurs.
928                 bytesProduced = SSL.bioFlushByteBuffer(networkBIO);
929 
930                 if (bytesProduced > 0) {
931                     return newResultMayFinishHandshake(status, bytesConsumed, bytesProduced);
932                 }
933                 // There was a pending exception that we just delayed because there was something to produce left.
934                 // Throw it now and shutdown the engine.
935                 if (pendingException != null) {
936                     Throwable error = pendingException;
937                     pendingException = null;
938                     shutdown();
939                     // Throw a new exception wrapping the pending exception, so the stacktrace is meaningful and
940                     // contains all the details.
941                     throw new SSLException(error);
942                 }
943 
944                 for (; offset < endOffset; ++offset) {
945                     final ByteBuffer src = srcs[offset];
946                     final int remaining = src.remaining();
947                     if (remaining == 0) {
948                         continue;
949                     }
950 
951                     final int bytesWritten;
952                     if (jdkCompatibilityMode) {
953                         // Write plaintext application data to the SSL engine. We don't have to worry about checking
954                         // if there is enough space if jdkCompatibilityMode because we only wrap at most
955                         // MAX_PLAINTEXT_LENGTH and we loop over the input before hand and check if there is space.
956                         bytesWritten = writePlaintextData(src, min(remaining, MAX_PLAINTEXT_LENGTH - bytesConsumed));
957                     } else {
958                         // OpenSSL's SSL_write keeps state between calls. We should make sure the amount we attempt to
959                         // write is guaranteed to succeed so we don't have to worry about keeping state consistent
960                         // between calls.
961                         final int availableCapacityForWrap = dst.remaining() - bytesProduced - maxWrapOverhead;
962                         if (availableCapacityForWrap <= 0) {
963                             return new SSLEngineResult(BUFFER_OVERFLOW, getHandshakeStatus(), bytesConsumed,
964                                     bytesProduced);
965                         }
966                         bytesWritten = writePlaintextData(src, min(remaining, availableCapacityForWrap));
967                     }
968 
969                     // Determine how much encrypted data was generated.
970                     //
971                     // Even if SSL_write doesn't consume any application data it is possible that OpenSSL will
972                     // produce non-application data into the BIO. For example session tickets....
973                     // See https://github.com/netty/netty/issues/10041
974                     final int pendingNow = SSL.bioLengthByteBuffer(networkBIO);
975                     bytesProduced += bioLengthBefore - pendingNow;
976                     bioLengthBefore = pendingNow;
977 
978                     if (bytesWritten > 0) {
979                         bytesConsumed += bytesWritten;
980 
981                         if (jdkCompatibilityMode || bytesProduced == dst.remaining()) {
982                             return newResultMayFinishHandshake(status, bytesConsumed, bytesProduced);
983                         }
984                     } else {
985                         int sslError = SSL.getError(ssl, bytesWritten);
986                         if (sslError == SSL.SSL_ERROR_ZERO_RETURN) {
987                             // This means the connection was shutdown correctly, close inbound and outbound
988                             if (!receivedShutdown) {
989                                 closeAll();
990 
991                                 bytesProduced += bioLengthBefore - SSL.bioLengthByteBuffer(networkBIO);
992 
993                                 // If we have filled up the dst buffer and we have not finished the handshake we should
994                                 // try to wrap again. Otherwise we should only try to wrap again if there is still data
995                                 // pending in SSL buffers.
996                                 SSLEngineResult.HandshakeStatus hs = mayFinishHandshake(
997                                         status != FINISHED ? bytesProduced == dst.remaining() ? NEED_WRAP
998                                                 : getHandshakeStatus(SSL.bioLengthNonApplication(networkBIO))
999                                                 : FINISHED);
1000                                 return newResult(hs, bytesConsumed, bytesProduced);
1001                             }
1002 
1003                             return newResult(NOT_HANDSHAKING, bytesConsumed, bytesProduced);
1004                         } else if (sslError == SSL.SSL_ERROR_WANT_READ) {
1005                             // If there is no pending data to read from BIO we should go back to event loop and try
1006                             // to read more data [1]. It is also possible that event loop will detect the socket has
1007                             // been closed. [1] https://www.openssl.org/docs/manmaster/ssl/SSL_write.html
1008                             return newResult(NEED_UNWRAP, bytesConsumed, bytesProduced);
1009                         } else if (sslError == SSL.SSL_ERROR_WANT_WRITE) {
1010                             // SSL_ERROR_WANT_WRITE typically means that the underlying transport is not writable
1011                             // and we should set the "want write" flag on the selector and try again when the
1012                             // underlying transport is writable [1]. However we are not directly writing to the
1013                             // underlying transport and instead writing to a BIO buffer. The OpenSsl documentation
1014                             // says we should do the following [1]:
1015                             //
1016                             // "When using a buffering BIO, like a BIO pair, data must be written into or retrieved
1017                             // out of the BIO before being able to continue."
1018                             //
1019                             // In practice this means the destination buffer doesn't have enough space for OpenSSL
1020                             // to write encrypted data to. This is an OVERFLOW condition.
1021                             // [1] https://www.openssl.org/docs/manmaster/ssl/SSL_write.html
1022                             if (bytesProduced > 0) {
1023                                 // If we produced something we should report this back and let the user call
1024                                 // wrap again.
1025                                 return newResult(NEED_WRAP, bytesConsumed, bytesProduced);
1026                             }
1027                             return newResult(BUFFER_OVERFLOW, status, bytesConsumed, bytesProduced);
1028                         } else if (sslError == SSL.SSL_ERROR_WANT_X509_LOOKUP ||
1029                                 sslError == SSL.SSL_ERROR_WANT_CERTIFICATE_VERIFY ||
1030                                 sslError == SSL.SSL_ERROR_WANT_PRIVATE_KEY_OPERATION) {
1031 
1032                             return newResult(NEED_TASK, bytesConsumed, bytesProduced);
1033                         } else {
1034                             // Everything else is considered as error
1035                             throw shutdownWithError("SSL_write", sslError, SSL.getLastErrorNumber());
1036                         }
1037                     }
1038                 }
1039                 return newResultMayFinishHandshake(status, bytesConsumed, bytesProduced);
1040             } finally {
1041                 SSL.bioClearByteBuffer(networkBIO);
1042                 if (bioReadCopyBuf == null) {
1043                     dst.position(dst.position() + bytesProduced);
1044                 } else {
1045                     assert bioReadCopyBuf.readableBytes() <= dst.remaining() : "The destination buffer " + dst +
1046                             " didn't have enough remaining space to hold the encrypted content in " + bioReadCopyBuf;
1047                     dst.put(bioReadCopyBuf.internalNioBuffer(bioReadCopyBuf.readerIndex(), bytesProduced));
1048                     bioReadCopyBuf.release();
1049                 }
1050             }
1051         }
1052     }
1053 
1054     private SSLEngineResult newResult(SSLEngineResult.HandshakeStatus hs, int bytesConsumed, int bytesProduced) {
1055         return newResult(OK, hs, bytesConsumed, bytesProduced);
1056     }
1057 
1058     private SSLEngineResult newResult(SSLEngineResult.Status status, SSLEngineResult.HandshakeStatus hs,
1059                                       int bytesConsumed, int bytesProduced) {
1060         // If isOutboundDone, then the data from the network BIO
1061         // was the close_notify message and all was consumed we are not required to wait
1062         // for the receipt the peer's close_notify message -- shutdown.
1063         if (isOutboundDone()) {
1064             if (isInboundDone()) {
1065                 // If the inbound was done as well, we need to ensure we return NOT_HANDSHAKING to signal we are done.
1066                 hs = NOT_HANDSHAKING;
1067 
1068                 // As the inbound and the outbound is done we can shutdown the engine now.
1069                 shutdown();
1070             }
1071             return new SSLEngineResult(CLOSED, hs, bytesConsumed, bytesProduced);
1072         }
1073         if (hs == NEED_TASK) {
1074             // Set needTask to true so getHandshakeStatus() will return the correct value.
1075             needTask = true;
1076         }
1077         return new SSLEngineResult(status, hs, bytesConsumed, bytesProduced);
1078     }
1079 
1080     private SSLEngineResult newResultMayFinishHandshake(SSLEngineResult.HandshakeStatus hs,
1081                                                         int bytesConsumed, int bytesProduced) throws SSLException {
1082         return newResult(mayFinishHandshake(hs, bytesConsumed, bytesProduced), bytesConsumed, bytesProduced);
1083     }
1084 
1085     private SSLEngineResult newResultMayFinishHandshake(SSLEngineResult.Status status,
1086                                                         SSLEngineResult.HandshakeStatus hs,
1087                                                         int bytesConsumed, int bytesProduced) throws SSLException {
1088         return newResult(status, mayFinishHandshake(hs, bytesConsumed, bytesProduced), bytesConsumed, bytesProduced);
1089     }
1090 
1091     /**
1092      * Log the error, shutdown the engine and throw an exception.
1093      */
1094     private SSLException shutdownWithError(String operation, int sslError, int error) {
1095         if (logger.isDebugEnabled()) {
1096             String errorString = SSL.getErrorString(error);
1097             logger.debug("{} failed with {}: OpenSSL error: {} {}",
1098                          operation, sslError, error, errorString);
1099         }
1100 
1101         // There was an internal error -- shutdown
1102         shutdown();
1103 
1104         SSLException exception = newSSLExceptionForError(error);
1105         // If we have a pendingException stored already we should include it as well to help the user debug things.
1106         if (pendingException != null) {
1107             exception.initCause(pendingException);
1108             pendingException = null;
1109         }
1110         return exception;
1111     }
1112 
1113     private SSLEngineResult handleUnwrapException(int bytesConsumed, int bytesProduced, SSLException e)
1114             throws SSLException {
1115         int lastError = SSL.getLastErrorNumber();
1116         if (lastError != 0) {
1117             return sslReadErrorResult(SSL.SSL_ERROR_SSL, lastError, bytesConsumed,
1118                     bytesProduced);
1119         }
1120         throw e;
1121     }
1122 
1123     public final SSLEngineResult unwrap(
1124             final ByteBuffer[] srcs, int srcsOffset, final int srcsLength,
1125             final ByteBuffer[] dsts, int dstsOffset, final int dstsLength) throws SSLException {
1126 
1127         // Throw required runtime exceptions
1128         checkNotNullWithIAE(srcs, "srcs");
1129         if (srcsOffset >= srcs.length
1130                 || srcsOffset + srcsLength > srcs.length) {
1131             throw new IndexOutOfBoundsException(
1132                     "offset: " + srcsOffset + ", length: " + srcsLength +
1133                             " (expected: offset <= offset + length <= srcs.length (" + srcs.length + "))");
1134         }
1135         checkNotNullWithIAE(dsts, "dsts");
1136         if (dstsOffset >= dsts.length || dstsOffset + dstsLength > dsts.length) {
1137             throw new IndexOutOfBoundsException(
1138                     "offset: " + dstsOffset + ", length: " + dstsLength +
1139                             " (expected: offset <= offset + length <= dsts.length (" + dsts.length + "))");
1140         }
1141         long capacity = 0;
1142         final int dstsEndOffset = dstsOffset + dstsLength;
1143         for (int i = dstsOffset; i < dstsEndOffset; i ++) {
1144             ByteBuffer dst = checkNotNullArrayParam(dsts[i], i, "dsts");
1145             if (dst.isReadOnly()) {
1146                 throw new ReadOnlyBufferException();
1147             }
1148             capacity += dst.remaining();
1149         }
1150 
1151         final int srcsEndOffset = srcsOffset + srcsLength;
1152         long len = 0;
1153         for (int i = srcsOffset; i < srcsEndOffset; i++) {
1154             ByteBuffer src = checkNotNullArrayParam(srcs[i], i, "srcs");
1155             len += src.remaining();
1156         }
1157 
1158         synchronized (this) {
1159             if (isInboundDone()) {
1160                 return isOutboundDone() || isDestroyed() ? CLOSED_NOT_HANDSHAKING : NEED_WRAP_CLOSED;
1161             }
1162 
1163             SSLEngineResult.HandshakeStatus status = NOT_HANDSHAKING;
1164             HandshakeState oldHandshakeState = handshakeState;
1165             // Prepare OpenSSL to work in server mode and receive handshake
1166             if (handshakeState != HandshakeState.FINISHED) {
1167                 if (handshakeState != HandshakeState.STARTED_EXPLICITLY) {
1168                     // Update accepted so we know we triggered the handshake via wrap
1169                     handshakeState = HandshakeState.STARTED_IMPLICITLY;
1170                 }
1171 
1172                 status = handshake();
1173 
1174                 if (status == NEED_TASK) {
1175                     return newResult(status, 0, 0);
1176                 }
1177 
1178                 if (status == NEED_WRAP) {
1179                     return NEED_WRAP_OK;
1180                 }
1181                 // Check if the inbound is considered to be closed if so let us try to wrap again.
1182                 if (isInboundDone) {
1183                     return NEED_WRAP_CLOSED;
1184                 }
1185             }
1186 
1187             int sslPending = sslPending0();
1188             int packetLength;
1189             // The JDK implies that only a single SSL packet should be processed per unwrap call [1]. If we are in
1190             // JDK compatibility mode then we should honor this, but if not we just wrap as much as possible. If there
1191             // are multiple records or partial records this may reduce thrashing events through the pipeline.
1192             // [1] https://docs.oracle.com/javase/7/docs/api/javax/net/ssl/SSLEngine.html
1193             if (jdkCompatibilityMode ||
1194                     // If the handshake was not finished before we entered the method, we also ensure we only
1195                     // unwrap one record. We do this to ensure we not produce any extra data before the caller
1196                     // of the method is able to observe handshake completion and react on it.
1197                     oldHandshakeState != HandshakeState.FINISHED) {
1198                 if (len < SSL_RECORD_HEADER_LENGTH) {
1199                     return newResultMayFinishHandshake(BUFFER_UNDERFLOW, status, 0, 0);
1200                 }
1201 
1202                 packetLength = SslUtils.getEncryptedPacketLength(srcs, srcsOffset);
1203                 if (packetLength == SslUtils.NOT_ENCRYPTED) {
1204                     throw new NotSslRecordException("not an SSL/TLS record");
1205                 }
1206 
1207                 final int packetLengthDataOnly = packetLength - SSL_RECORD_HEADER_LENGTH;
1208                 if (packetLengthDataOnly > capacity) {
1209                     // Not enough space in the destination buffer so signal the caller that the buffer needs to be
1210                     // increased.
1211                     if (packetLengthDataOnly > MAX_RECORD_SIZE) {
1212                         // The packet length MUST NOT exceed 2^14 [1]. However we do accommodate more data to support
1213                         // legacy use cases which may violate this condition (e.g. OpenJDK's SslEngineImpl). If the max
1214                         // length is exceeded we fail fast here to avoid an infinite loop due to the fact that we
1215                         // won't allocate a buffer large enough.
1216                         // [1] https://tools.ietf.org/html/rfc5246#section-6.2.1
1217                         throw new SSLException("Illegal packet length: " + packetLengthDataOnly + " > " +
1218                                                 session.getApplicationBufferSize());
1219                     } else {
1220                         session.tryExpandApplicationBufferSize(packetLengthDataOnly);
1221                     }
1222                     return newResultMayFinishHandshake(BUFFER_OVERFLOW, status, 0, 0);
1223                 }
1224 
1225                 if (len < packetLength) {
1226                     // We either don't have enough data to read the packet length or not enough for reading the whole
1227                     // packet.
1228                     return newResultMayFinishHandshake(BUFFER_UNDERFLOW, status, 0, 0);
1229                 }
1230             } else if (len == 0 && sslPending <= 0) {
1231                 return newResultMayFinishHandshake(BUFFER_UNDERFLOW, status, 0, 0);
1232             } else if (capacity == 0) {
1233                 return newResultMayFinishHandshake(BUFFER_OVERFLOW, status, 0, 0);
1234             } else {
1235                 packetLength = (int) min(MAX_VALUE, len);
1236             }
1237 
1238             // This must always be the case when we reached here as if not we returned BUFFER_UNDERFLOW.
1239             assert srcsOffset < srcsEndOffset;
1240 
1241             // This must always be the case if we reached here.
1242             assert capacity > 0;
1243 
1244             // Number of produced bytes
1245             int bytesProduced = 0;
1246             int bytesConsumed = 0;
1247             try {
1248                 srcLoop:
1249                 for (;;) {
1250                     ByteBuffer src = srcs[srcsOffset];
1251                     int remaining = src.remaining();
1252                     final ByteBuf bioWriteCopyBuf;
1253                     int pendingEncryptedBytes;
1254                     if (remaining == 0) {
1255                         if (sslPending <= 0) {
1256                             // We must skip empty buffers as BIO_write will return 0 if asked to write something
1257                             // with length 0.
1258                             if (++srcsOffset >= srcsEndOffset) {
1259                                 break;
1260                             }
1261                             continue;
1262                         } else {
1263                             bioWriteCopyBuf = null;
1264                             pendingEncryptedBytes = SSL.bioLengthByteBuffer(networkBIO);
1265                         }
1266                     } else {
1267                         // Write more encrypted data into the BIO. Ensure we only read one packet at a time as
1268                         // stated in the SSLEngine javadocs.
1269                         pendingEncryptedBytes = min(packetLength, remaining);
1270                         try {
1271                             bioWriteCopyBuf = writeEncryptedData(src, pendingEncryptedBytes);
1272                         } catch (SSLException e) {
1273                             // Ensure we correctly handle the error stack.
1274                             return handleUnwrapException(bytesConsumed, bytesProduced, e);
1275                         }
1276                     }
1277                     try {
1278                         for (;;) {
1279                             ByteBuffer dst = dsts[dstsOffset];
1280                             if (!dst.hasRemaining()) {
1281                                 // No space left in the destination buffer, skip it.
1282                                 if (++dstsOffset >= dstsEndOffset) {
1283                                     break srcLoop;
1284                                 }
1285                                 continue;
1286                             }
1287 
1288                             int bytesRead;
1289                             try {
1290                                 bytesRead = readPlaintextData(dst);
1291                             } catch (SSLException e) {
1292                                 // Ensure we correctly handle the error stack.
1293                                 return handleUnwrapException(bytesConsumed, bytesProduced, e);
1294                             }
1295                             // We are directly using the ByteBuffer memory for the write, and so we only know what has
1296                             // been consumed after we let SSL decrypt the data. At this point we should update the
1297                             // number of bytes consumed, update the ByteBuffer position, and release temp ByteBuf.
1298                             int localBytesConsumed = pendingEncryptedBytes - SSL.bioLengthByteBuffer(networkBIO);
1299                             bytesConsumed += localBytesConsumed;
1300                             packetLength -= localBytesConsumed;
1301                             pendingEncryptedBytes -= localBytesConsumed;
1302                             src.position(src.position() + localBytesConsumed);
1303 
1304                             if (bytesRead > 0) {
1305                                 bytesProduced += bytesRead;
1306 
1307                                 if (!dst.hasRemaining()) {
1308                                     sslPending = sslPending0();
1309                                     // Move to the next dst buffer as this one is full.
1310                                     if (++dstsOffset >= dstsEndOffset) {
1311                                         return sslPending > 0 ?
1312                                                 newResult(BUFFER_OVERFLOW, status, bytesConsumed, bytesProduced) :
1313                                                 newResultMayFinishHandshake(isInboundDone() ? CLOSED : OK, status,
1314                                                         bytesConsumed, bytesProduced);
1315                                     }
1316                                 } else if (packetLength == 0 || jdkCompatibilityMode) {
1317                                     // We either consumed all data or we are in jdkCompatibilityMode and have consumed
1318                                     // a single TLS packet and should stop consuming until this method is called again.
1319                                     break srcLoop;
1320                                 }
1321                             } else {
1322                                 int sslError = SSL.getError(ssl, bytesRead);
1323                                 if (sslError == SSL.SSL_ERROR_WANT_READ || sslError == SSL.SSL_ERROR_WANT_WRITE) {
1324                                     // break to the outer loop as we want to read more data which means we need to
1325                                     // write more to the BIO.
1326                                     break;
1327                                 } else if (sslError == SSL.SSL_ERROR_ZERO_RETURN) {
1328                                     // This means the connection was shutdown correctly, close inbound and outbound
1329                                     if (!receivedShutdown) {
1330                                         closeAll();
1331                                     }
1332                                     return newResultMayFinishHandshake(isInboundDone() ? CLOSED : OK, status,
1333                                             bytesConsumed, bytesProduced);
1334                                 } else if (sslError == SSL.SSL_ERROR_WANT_X509_LOOKUP ||
1335                                         sslError == SSL.SSL_ERROR_WANT_CERTIFICATE_VERIFY ||
1336                                         sslError == SSL.SSL_ERROR_WANT_PRIVATE_KEY_OPERATION) {
1337                                     return newResult(isInboundDone() ? CLOSED : OK,
1338                                             NEED_TASK, bytesConsumed, bytesProduced);
1339                                 } else {
1340                                     return sslReadErrorResult(sslError, SSL.getLastErrorNumber(), bytesConsumed,
1341                                             bytesProduced);
1342                                 }
1343                             }
1344                         }
1345 
1346                         if (++srcsOffset >= srcsEndOffset) {
1347                             break;
1348                         }
1349                     } finally {
1350                         if (bioWriteCopyBuf != null) {
1351                             bioWriteCopyBuf.release();
1352                         }
1353                     }
1354                 }
1355             } finally {
1356                 SSL.bioClearByteBuffer(networkBIO);
1357                 rejectRemoteInitiatedRenegotiation();
1358             }
1359 
1360             // Check to see if we received a close_notify message from the peer.
1361             if (!receivedShutdown && (SSL.getShutdown(ssl) & SSL.SSL_RECEIVED_SHUTDOWN) == SSL.SSL_RECEIVED_SHUTDOWN) {
1362                 closeAll();
1363             }
1364 
1365             return newResultMayFinishHandshake(isInboundDone() ? CLOSED : OK, status, bytesConsumed, bytesProduced);
1366         }
1367     }
1368 
1369     private boolean needWrapAgain(int stackError) {
1370         // Check if we have a pending handshakeException and if so see if we need to consume all pending data from the
1371         // BIO first or can just shutdown and throw it now.
1372         // This is needed so we ensure close_notify etc is correctly send to the remote peer.
1373         // See https://github.com/netty/netty/issues/3900
1374         if (SSL.bioLengthNonApplication(networkBIO) > 0) {
1375             // we seem to have data left that needs to be transferred and so the user needs
1376             // call wrap(...). Store the error so we can pick it up later.
1377             if (pendingException == null) {
1378                 pendingException = newSSLExceptionForError(stackError);
1379             } else if (shouldAddSuppressed(pendingException, stackError)) {
1380                 ThrowableUtil.addSuppressed(pendingException, newSSLExceptionForError(stackError));
1381             }
1382             // We need to clear all errors so we not pick up anything that was left on the stack on the next
1383             // operation. Note that shutdownWithError(...) will cleanup the stack as well so its only needed here.
1384             SSL.clearError();
1385             return true;
1386         }
1387         return false;
1388     }
1389 
1390     private SSLException newSSLExceptionForError(int stackError) {
1391         String message = SSL.getErrorString(stackError);
1392         return handshakeState == HandshakeState.FINISHED ?
1393                 new OpenSslException(message, stackError) : new OpenSslHandshakeException(message, stackError);
1394     }
1395 
1396     private static boolean shouldAddSuppressed(Throwable target, int errorCode) {
1397         for (Throwable suppressed: ThrowableUtil.getSuppressed(target)) {
1398             if (suppressed instanceof NativeSslException &&
1399                     ((NativeSslException) suppressed).errorCode() == errorCode) {
1400                 /// An exception with this errorCode was already added before.
1401                 return false;
1402             }
1403         }
1404         return true;
1405     }
1406 
1407     private SSLEngineResult sslReadErrorResult(int error, int stackError, int bytesConsumed, int bytesProduced)
1408             throws SSLException {
1409         if (needWrapAgain(stackError)) {
1410             // There is something that needs to be send to the remote peer before we can teardown.
1411             // This is most likely some alert.
1412             return new SSLEngineResult(OK, NEED_WRAP, bytesConsumed, bytesProduced);
1413         }
1414         throw shutdownWithError("SSL_read", error, stackError);
1415     }
1416 
1417     private void closeAll() throws SSLException {
1418         receivedShutdown = true;
1419         closeOutbound();
1420         closeInbound();
1421     }
1422 
1423     private void rejectRemoteInitiatedRenegotiation() throws SSLHandshakeException {
1424         // As rejectRemoteInitiatedRenegotiation() is called in a finally block we also need to check if we shutdown
1425         // the engine before as otherwise SSL.getHandshakeCount(ssl) will throw an NPE if the passed in ssl is 0.
1426         // See https://github.com/netty/netty/issues/7353
1427         if (!isDestroyed() && (!clientMode && SSL.getHandshakeCount(ssl) > 1 ||
1428                 // Let's allow to renegotiate once for client auth.
1429                 clientMode && SSL.getHandshakeCount(ssl) > 2) &&
1430             // As we may count multiple handshakes when TLSv1.3 is used we should just ignore this here as
1431             // renegotiation is not supported in TLSv1.3 as per spec.
1432             !SslProtocols.TLS_v1_3.equals(session.getProtocol()) && handshakeState == HandshakeState.FINISHED) {
1433             // TODO: In future versions me may also want to send a fatal_alert to the client and so notify it
1434             // that the renegotiation failed.
1435             shutdown();
1436             throw new SSLHandshakeException("remote-initiated renegotiation not allowed");
1437         }
1438     }
1439 
1440     public final SSLEngineResult unwrap(final ByteBuffer[] srcs, final ByteBuffer[] dsts) throws SSLException {
1441         return unwrap(srcs, 0, srcs.length, dsts, 0, dsts.length);
1442     }
1443 
1444     private ByteBuffer[] singleSrcBuffer(ByteBuffer src) {
1445         singleSrcBuffer[0] = src;
1446         return singleSrcBuffer;
1447     }
1448 
1449     private void resetSingleSrcBuffer() {
1450         singleSrcBuffer[0] = null;
1451     }
1452 
1453     private ByteBuffer[] singleDstBuffer(ByteBuffer src) {
1454         singleDstBuffer[0] = src;
1455         return singleDstBuffer;
1456     }
1457 
1458     private void resetSingleDstBuffer() {
1459         singleDstBuffer[0] = null;
1460     }
1461 
1462     @Override
1463     public final synchronized SSLEngineResult unwrap(
1464             final ByteBuffer src, final ByteBuffer[] dsts, final int offset, final int length) throws SSLException {
1465         try {
1466             return unwrap(singleSrcBuffer(src), 0, 1, dsts, offset, length);
1467         } finally {
1468             resetSingleSrcBuffer();
1469         }
1470     }
1471 
1472     @Override
1473     public final synchronized SSLEngineResult wrap(ByteBuffer src, ByteBuffer dst) throws SSLException {
1474         try {
1475             return wrap(singleSrcBuffer(src), dst);
1476         } finally {
1477             resetSingleSrcBuffer();
1478         }
1479     }
1480 
1481     @Override
1482     public final synchronized SSLEngineResult unwrap(ByteBuffer src, ByteBuffer dst) throws SSLException {
1483         try {
1484             return unwrap(singleSrcBuffer(src), singleDstBuffer(dst));
1485         } finally {
1486             resetSingleSrcBuffer();
1487             resetSingleDstBuffer();
1488         }
1489     }
1490 
1491     @Override
1492     public final synchronized SSLEngineResult unwrap(ByteBuffer src, ByteBuffer[] dsts) throws SSLException {
1493         try {
1494             return unwrap(singleSrcBuffer(src), dsts);
1495         } finally {
1496             resetSingleSrcBuffer();
1497         }
1498     }
1499 
1500     private class TaskDecorator<R extends Runnable> implements Runnable {
1501         protected final R task;
1502         TaskDecorator(R task) {
1503             this.task = task;
1504         }
1505 
1506         @Override
1507         public void run() {
1508             runAndResetNeedTask(task);
1509         }
1510     }
1511 
1512     private final class AsyncTaskDecorator extends TaskDecorator<AsyncTask> implements AsyncRunnable {
1513         AsyncTaskDecorator(AsyncTask task) {
1514             super(task);
1515         }
1516 
1517         @Override
1518         public void run(final Runnable runnable) {
1519             if (isDestroyed()) {
1520                 // The engine was destroyed in the meantime, just return.
1521                 return;
1522             }
1523             task.runAsync(new TaskDecorator<Runnable>(runnable));
1524         }
1525     }
1526 
1527     private void runAndResetNeedTask(Runnable task) {
1528         // We need to synchronize on the ReferenceCountedOpenSslEngine, we are sure the SSL object
1529         // will not be freed by the user calling for example shutdown() concurrently.
1530         synchronized (ReferenceCountedOpenSslEngine.this) {
1531             try {
1532                 if (isDestroyed()) {
1533                     // The engine was destroyed in the meantime, just return.
1534                     return;
1535                 }
1536                 task.run();
1537                 if (handshakeState != HandshakeState.FINISHED && !isDestroyed()) {
1538                     // Call SSL.doHandshake(...) If the handshake was not finished yet. This might be needed
1539                     // to fill the application buffer and so have getHandshakeStatus() return the right value
1540                     // in this case.
1541                     if (SSL.doHandshake(ssl) <= 0) {
1542                         SSL.clearError();
1543                     }
1544                 }
1545             } finally {
1546                 // The task was run, reset needTask to false so getHandshakeStatus() returns the correct value.
1547                 needTask = false;
1548             }
1549         }
1550     }
1551 
1552     @Override
1553     public final synchronized Runnable getDelegatedTask() {
1554         if (isDestroyed()) {
1555             return null;
1556         }
1557         final Runnable task = SSL.getTask(ssl);
1558         if (task == null) {
1559             return null;
1560         }
1561         if (task instanceof AsyncTask) {
1562             return new AsyncTaskDecorator((AsyncTask) task);
1563         }
1564         return new TaskDecorator<Runnable>(task);
1565     }
1566 
1567     @Override
1568     public final synchronized void closeInbound() throws SSLException {
1569         if (isInboundDone) {
1570             return;
1571         }
1572 
1573         isInboundDone = true;
1574 
1575         if (isOutboundDone()) {
1576             // Only call shutdown if there is no outbound data pending.
1577             // See https://github.com/netty/netty/issues/6167
1578             shutdown();
1579         }
1580 
1581         if (handshakeState != HandshakeState.NOT_STARTED && !receivedShutdown) {
1582             throw new SSLException(
1583                     "Inbound closed before receiving peer's close_notify: possible truncation attack?");
1584         }
1585     }
1586 
1587     @Override
1588     public final synchronized boolean isInboundDone() {
1589         return isInboundDone;
1590     }
1591 
1592     @Override
1593     public final synchronized void closeOutbound() {
1594         if (outboundClosed) {
1595             return;
1596         }
1597 
1598         outboundClosed = true;
1599 
1600         if (handshakeState != HandshakeState.NOT_STARTED && !isDestroyed()) {
1601             int mode = SSL.getShutdown(ssl);
1602             if ((mode & SSL.SSL_SENT_SHUTDOWN) != SSL.SSL_SENT_SHUTDOWN) {
1603                 doSSLShutdown();
1604             }
1605         } else {
1606             // engine closing before initial handshake
1607             shutdown();
1608         }
1609     }
1610 
1611     /**
1612      * Attempt to call {@link SSL#shutdownSSL(long)}.
1613      * @return {@code false} if the call to {@link SSL#shutdownSSL(long)} was not attempted or returned an error.
1614      */
1615     private boolean doSSLShutdown() {
1616         if (SSL.isInInit(ssl) != 0) {
1617             // Only try to call SSL_shutdown if we are not in the init state anymore.
1618             // Otherwise we will see 'error:140E0197:SSL routines:SSL_shutdown:shutdown while in init' in our logs.
1619             //
1620             // See also https://hg.nginx.org/nginx/rev/062c189fee20
1621             return false;
1622         }
1623         int err = SSL.shutdownSSL(ssl);
1624         if (err < 0) {
1625             int sslErr = SSL.getError(ssl, err);
1626             if (sslErr == SSL.SSL_ERROR_SYSCALL || sslErr == SSL.SSL_ERROR_SSL) {
1627                 if (logger.isDebugEnabled()) {
1628                     int error = SSL.getLastErrorNumber();
1629                     logger.debug("SSL_shutdown failed: OpenSSL error: {} {}", error, SSL.getErrorString(error));
1630                 }
1631                 // There was an internal error -- shutdown
1632                 shutdown();
1633                 return false;
1634             }
1635             SSL.clearError();
1636         }
1637         return true;
1638     }
1639 
1640     @Override
1641     public final synchronized boolean isOutboundDone() {
1642         // Check if there is anything left in the outbound buffer.
1643         // We need to ensure we only call SSL.pendingWrittenBytesInBIO(...) if the engine was not destroyed yet.
1644         return outboundClosed && (networkBIO == 0 || SSL.bioLengthNonApplication(networkBIO) == 0);
1645     }
1646 
1647     @Override
1648     public final String[] getSupportedCipherSuites() {
1649         return OpenSsl.AVAILABLE_CIPHER_SUITES.toArray(EMPTY_STRINGS);
1650     }
1651 
1652     @Override
1653     public final String[] getEnabledCipherSuites() {
1654         final String[] extraCiphers;
1655         final String[] enabled;
1656         final boolean tls13Enabled;
1657         synchronized (this) {
1658             if (!isDestroyed()) {
1659                 enabled = SSL.getCiphers(ssl);
1660                 int opts = SSL.getOptions(ssl);
1661                 if (isProtocolEnabled(opts, SSL.SSL_OP_NO_TLSv1_3, SslProtocols.TLS_v1_3)) {
1662                     extraCiphers = OpenSsl.EXTRA_SUPPORTED_TLS_1_3_CIPHERS;
1663                     tls13Enabled = true;
1664                 } else {
1665                     extraCiphers = EMPTY_STRINGS;
1666                     tls13Enabled = false;
1667                 }
1668             } else {
1669                 return EMPTY_STRINGS;
1670             }
1671         }
1672         if (enabled == null) {
1673             return EMPTY_STRINGS;
1674         } else {
1675             Set<String> enabledSet = new LinkedHashSet<String>(enabled.length + extraCiphers.length);
1676             synchronized (this) {
1677                 for (int i = 0; i < enabled.length; i++) {
1678                     String mapped = toJavaCipherSuite(enabled[i]);
1679                     final String cipher = mapped == null ? enabled[i] : mapped;
1680                     if ((!tls13Enabled || !OpenSsl.isTlsv13Supported()) && SslUtils.isTLSv13Cipher(cipher)) {
1681                         continue;
1682                     }
1683                     enabledSet.add(cipher);
1684                 }
1685                 Collections.addAll(enabledSet, extraCiphers);
1686             }
1687             return enabledSet.toArray(EMPTY_STRINGS);
1688         }
1689     }
1690 
1691     @Override
1692     public final void setEnabledCipherSuites(String[] cipherSuites) {
1693         checkNotNull(cipherSuites, "cipherSuites");
1694 
1695         final StringBuilder buf = new StringBuilder();
1696         final StringBuilder bufTLSv13 = new StringBuilder();
1697 
1698         CipherSuiteConverter.convertToCipherStrings(Arrays.asList(cipherSuites), buf, bufTLSv13, OpenSsl.isBoringSSL());
1699         final String cipherSuiteSpec = buf.toString();
1700         final String cipherSuiteSpecTLSv13 = bufTLSv13.toString();
1701 
1702         if (!OpenSsl.isTlsv13Supported() && !cipherSuiteSpecTLSv13.isEmpty()) {
1703             throw new IllegalArgumentException("TLSv1.3 is not supported by this java version.");
1704         }
1705         synchronized (this) {
1706             hasTLSv13Cipher = !cipherSuiteSpecTLSv13.isEmpty();
1707             if (!isDestroyed()) {
1708                 try {
1709                     // Set non TLSv1.3 ciphers.
1710                     SSL.setCipherSuites(ssl, cipherSuiteSpec, false);
1711                     if (OpenSsl.isTlsv13Supported()) {
1712                         // Set TLSv1.3 ciphers.
1713                         SSL.setCipherSuites(ssl, OpenSsl.checkTls13Ciphers(logger, cipherSuiteSpecTLSv13), true);
1714                     }
1715 
1716                     // We also need to update the enabled protocols to ensure we disable the protocol if there are
1717                     // no compatible ciphers left.
1718                     Set<String> protocols = new HashSet<String>(enabledProtocols);
1719 
1720                     // We have no ciphers that are compatible with none-TLSv1.3, let us explicit disable all other
1721                     // protocols.
1722                     if (cipherSuiteSpec.isEmpty()) {
1723                         protocols.remove(SslProtocols.TLS_v1);
1724                         protocols.remove(SslProtocols.TLS_v1_1);
1725                         protocols.remove(SslProtocols.TLS_v1_2);
1726                         protocols.remove(SslProtocols.SSL_v3);
1727                         protocols.remove(SslProtocols.SSL_v2);
1728                         protocols.remove(SslProtocols.SSL_v2_HELLO);
1729                     }
1730                     // We have no ciphers that are compatible with TLSv1.3, let us explicit disable it.
1731                     if (cipherSuiteSpecTLSv13.isEmpty()) {
1732                         protocols.remove(SslProtocols.TLS_v1_3);
1733                     }
1734                     // Update the protocols but not cache the value. We only cache when we call it from the user
1735                     // code or when we construct the engine.
1736                     setEnabledProtocols0(protocols.toArray(EMPTY_STRINGS), !hasTLSv13Cipher);
1737                 } catch (Exception e) {
1738                     throw new IllegalStateException("failed to enable cipher suites: " + cipherSuiteSpec, e);
1739                 }
1740             } else {
1741                 throw new IllegalStateException("failed to enable cipher suites: " + cipherSuiteSpec);
1742             }
1743         }
1744     }
1745 
1746     @Override
1747     public final String[] getSupportedProtocols() {
1748         return OpenSsl.SUPPORTED_PROTOCOLS_SET.toArray(EMPTY_STRINGS);
1749     }
1750 
1751     @Override
1752     public final String[] getEnabledProtocols() {
1753         return enabledProtocols.toArray(EMPTY_STRINGS);
1754     }
1755 
1756     private static boolean isProtocolEnabled(int opts, int disableMask, String protocolString) {
1757         // We also need to check if the actual protocolString is supported as depending on the openssl API
1758         // implementations it may use a disableMask of 0 (BoringSSL is doing this for example).
1759         return (opts & disableMask) == 0 && OpenSsl.SUPPORTED_PROTOCOLS_SET.contains(protocolString);
1760     }
1761 
1762     /**
1763      * {@inheritDoc}
1764      * TLS doesn't support a way to advertise non-contiguous versions from the client's perspective, and the client
1765      * just advertises the max supported version. The TLS protocol also doesn't support all different combinations of
1766      * discrete protocols, and instead assumes contiguous ranges. OpenSSL has some unexpected behavior
1767      * (e.g. handshake failures) if non-contiguous protocols are used even where there is a compatible set of protocols
1768      * and ciphers. For these reasons this method will determine the minimum protocol and the maximum protocol and
1769      * enabled a contiguous range from [min protocol, max protocol] in OpenSSL.
1770      */
1771     @Override
1772     public final void setEnabledProtocols(String[] protocols) {
1773         checkNotNullWithIAE(protocols, "protocols");
1774         synchronized (this) {
1775             enabledProtocols.clear();
1776             // Seems like there is no way to explicit disable SSLv2Hello in openssl, so it is always enabled
1777             enabledProtocols.add(SslProtocols.SSL_v2_HELLO);
1778 
1779             Collections.addAll(enabledProtocols, protocols);
1780 
1781             setEnabledProtocols0(protocols, !hasTLSv13Cipher);
1782         }
1783     }
1784 
1785     private void setEnabledProtocols0(String[] protocols, boolean explicitDisableTLSv13) {
1786         assert Thread.holdsLock(this);
1787         // This is correct from the API docs
1788         int minProtocolIndex = OPENSSL_OP_NO_PROTOCOLS.length;
1789         int maxProtocolIndex = 0;
1790         for (String p: protocols) {
1791             if (!OpenSsl.SUPPORTED_PROTOCOLS_SET.contains(p)) {
1792                 throw new IllegalArgumentException("Protocol " + p + " is not supported.");
1793             }
1794             if (p.equals(SslProtocols.SSL_v2)) {
1795                 if (minProtocolIndex > OPENSSL_OP_NO_PROTOCOL_INDEX_SSLV2) {
1796                     minProtocolIndex = OPENSSL_OP_NO_PROTOCOL_INDEX_SSLV2;
1797                 }
1798                 if (maxProtocolIndex < OPENSSL_OP_NO_PROTOCOL_INDEX_SSLV2) {
1799                     maxProtocolIndex = OPENSSL_OP_NO_PROTOCOL_INDEX_SSLV2;
1800                 }
1801             } else if (p.equals(SslProtocols.SSL_v3)) {
1802                 if (minProtocolIndex > OPENSSL_OP_NO_PROTOCOL_INDEX_SSLV3) {
1803                     minProtocolIndex = OPENSSL_OP_NO_PROTOCOL_INDEX_SSLV3;
1804                 }
1805                 if (maxProtocolIndex < OPENSSL_OP_NO_PROTOCOL_INDEX_SSLV3) {
1806                     maxProtocolIndex = OPENSSL_OP_NO_PROTOCOL_INDEX_SSLV3;
1807                 }
1808             } else if (p.equals(SslProtocols.TLS_v1)) {
1809                 if (minProtocolIndex > OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1) {
1810                     minProtocolIndex = OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1;
1811                 }
1812                 if (maxProtocolIndex < OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1) {
1813                     maxProtocolIndex = OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1;
1814                 }
1815             } else if (p.equals(SslProtocols.TLS_v1_1)) {
1816                 if (minProtocolIndex > OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1_1) {
1817                     minProtocolIndex = OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1_1;
1818                 }
1819                 if (maxProtocolIndex < OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1_1) {
1820                     maxProtocolIndex = OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1_1;
1821                 }
1822             } else if (p.equals(SslProtocols.TLS_v1_2)) {
1823                 if (minProtocolIndex > OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1_2) {
1824                     minProtocolIndex = OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1_2;
1825                 }
1826                 if (maxProtocolIndex < OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1_2) {
1827                     maxProtocolIndex = OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1_2;
1828                 }
1829             } else if (!explicitDisableTLSv13 && p.equals(SslProtocols.TLS_v1_3)) {
1830                 if (minProtocolIndex > OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1_3) {
1831                     minProtocolIndex = OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1_3;
1832                 }
1833                 if (maxProtocolIndex < OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1_3) {
1834                     maxProtocolIndex = OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1_3;
1835                 }
1836             }
1837         }
1838         if (!isDestroyed()) {
1839             // Clear out options which disable protocols
1840             SSL.clearOptions(ssl, SSL.SSL_OP_NO_SSLv2 | SSL.SSL_OP_NO_SSLv3 | SSL.SSL_OP_NO_TLSv1 |
1841                     SSL.SSL_OP_NO_TLSv1_1 | SSL.SSL_OP_NO_TLSv1_2 | SSL.SSL_OP_NO_TLSv1_3);
1842 
1843             int opts = 0;
1844             for (int i = 0; i < minProtocolIndex; ++i) {
1845                 opts |= OPENSSL_OP_NO_PROTOCOLS[i];
1846             }
1847             assert maxProtocolIndex != MAX_VALUE;
1848             for (int i = maxProtocolIndex + 1; i < OPENSSL_OP_NO_PROTOCOLS.length; ++i) {
1849                 opts |= OPENSSL_OP_NO_PROTOCOLS[i];
1850             }
1851 
1852             // Disable protocols we do not want
1853             SSL.setOptions(ssl, opts);
1854         } else {
1855             throw new IllegalStateException("failed to enable protocols: " + Arrays.asList(protocols));
1856         }
1857     }
1858 
1859     @Override
1860     public final SSLSession getSession() {
1861         return session;
1862     }
1863 
1864     @Override
1865     public final synchronized void beginHandshake() throws SSLException {
1866         switch (handshakeState) {
1867             case STARTED_IMPLICITLY:
1868                 checkEngineClosed();
1869 
1870                 // A user did not start handshake by calling this method by him/herself,
1871                 // but handshake has been started already by wrap() or unwrap() implicitly.
1872                 // Because it's the user's first time to call this method, it is unfair to
1873                 // raise an exception.  From the user's standpoint, he or she never asked
1874                 // for renegotiation.
1875 
1876                 handshakeState = HandshakeState.STARTED_EXPLICITLY; // Next time this method is invoked by the user,
1877                 calculateMaxWrapOverhead();
1878                 // we should raise an exception.
1879                 break;
1880             case STARTED_EXPLICITLY:
1881                 // Nothing to do as the handshake is not done yet.
1882                 break;
1883             case FINISHED:
1884                 throw new SSLException("renegotiation unsupported");
1885             case NOT_STARTED:
1886                 handshakeState = HandshakeState.STARTED_EXPLICITLY;
1887                 if (handshake() == NEED_TASK) {
1888                     // Set needTask to true so getHandshakeStatus() will return the correct value.
1889                     needTask = true;
1890                 }
1891                 calculateMaxWrapOverhead();
1892                 break;
1893             default:
1894                 throw new Error();
1895         }
1896     }
1897 
1898     private void checkEngineClosed() throws SSLException {
1899         if (isDestroyed()) {
1900             throw new SSLException("engine closed");
1901         }
1902     }
1903 
1904     private static SSLEngineResult.HandshakeStatus pendingStatus(int pendingStatus) {
1905         // Depending on if there is something left in the BIO we need to WRAP or UNWRAP
1906         return pendingStatus > 0 ? NEED_WRAP : NEED_UNWRAP;
1907     }
1908 
1909     private static boolean isEmpty(Object[] arr) {
1910         return arr == null || arr.length == 0;
1911     }
1912 
1913     private static boolean isEmpty(byte[] cert) {
1914         return cert == null || cert.length == 0;
1915     }
1916 
1917     private SSLEngineResult.HandshakeStatus handshakeException() throws SSLException {
1918         if (SSL.bioLengthNonApplication(networkBIO) > 0) {
1919             // There is something pending, we need to consume it first via a WRAP so we don't loose anything.
1920             return NEED_WRAP;
1921         }
1922 
1923         Throwable exception = pendingException;
1924         assert exception != null;
1925         pendingException = null;
1926         shutdown();
1927         if (exception instanceof SSLHandshakeException) {
1928             throw (SSLHandshakeException) exception;
1929         }
1930         SSLHandshakeException e = new SSLHandshakeException("General OpenSslEngine problem");
1931         e.initCause(exception);
1932         throw e;
1933     }
1934 
1935     /**
1936      * Should be called if the handshake will be failed due a callback that throws an exception.
1937      * This cause will then be used to give more details as part of the {@link SSLHandshakeException}.
1938      */
1939     final void initHandshakeException(Throwable cause) {
1940         if (pendingException == null) {
1941             pendingException = cause;
1942         } else {
1943             ThrowableUtil.addSuppressed(pendingException, cause);
1944         }
1945     }
1946 
1947     private SSLEngineResult.HandshakeStatus handshake() throws SSLException {
1948         if (needTask) {
1949             return NEED_TASK;
1950         }
1951         if (handshakeState == HandshakeState.FINISHED) {
1952             return FINISHED;
1953         }
1954 
1955         checkEngineClosed();
1956 
1957         if (pendingException != null) {
1958             // Let's call SSL.doHandshake(...) again in case there is some async operation pending that would fill the
1959             // outbound buffer.
1960             if (SSL.doHandshake(ssl) <= 0) {
1961                 // Clear any error that was put on the stack by the handshake
1962                 SSL.clearError();
1963             }
1964             return handshakeException();
1965         }
1966 
1967         // Adding the OpenSslEngine to the OpenSslEngineMap so it can be used in the AbstractCertificateVerifier.
1968         engineMap.add(this);
1969 
1970         if (!sessionSet) {
1971             if (!parentContext.sessionContext().setSessionFromCache(ssl, session, getPeerHost(), getPeerPort())) {
1972                 // The session was not reused via the cache. Call prepareHandshake() to ensure we remove all previous
1973                 // stored key-value pairs.
1974                 session.prepareHandshake();
1975             }
1976             sessionSet = true;
1977         }
1978 
1979         int code = SSL.doHandshake(ssl);
1980         if (code <= 0) {
1981             int sslError = SSL.getError(ssl, code);
1982             if (sslError == SSL.SSL_ERROR_WANT_READ || sslError == SSL.SSL_ERROR_WANT_WRITE) {
1983                 return pendingStatus(SSL.bioLengthNonApplication(networkBIO));
1984             }
1985 
1986             if (sslError == SSL.SSL_ERROR_WANT_X509_LOOKUP ||
1987                     sslError == SSL.SSL_ERROR_WANT_CERTIFICATE_VERIFY ||
1988                     sslError == SSL.SSL_ERROR_WANT_PRIVATE_KEY_OPERATION) {
1989                 return NEED_TASK;
1990             }
1991 
1992             int errorNumber = SSL.getLastErrorNumber();
1993             if (needWrapAgain(errorNumber)) {
1994                 // There is something that needs to be send to the remote peer before we can teardown.
1995                 // This is most likely some alert.
1996                 return NEED_WRAP;
1997             }
1998             // Check if we have a pending exception that was created during the handshake and if so throw it after
1999             // shutdown the connection.
2000             if (pendingException != null) {
2001                 return handshakeException();
2002             }
2003 
2004             // Everything else is considered as error
2005             throw shutdownWithError("SSL_do_handshake", sslError, errorNumber);
2006         }
2007         // We have produced more data as part of the handshake if this is the case the user should call wrap(...)
2008         if (SSL.bioLengthNonApplication(networkBIO) > 0) {
2009             return NEED_WRAP;
2010         }
2011         // if SSL_do_handshake returns > 0 or sslError == SSL.SSL_ERROR_NAME it means the handshake was finished.
2012         session.handshakeFinished(SSL.getSessionId(ssl), SSL.getCipherForSSL(ssl), SSL.getVersion(ssl),
2013                 SSL.getPeerCertificate(ssl), SSL.getPeerCertChain(ssl),
2014                 SSL.getTime(ssl) * 1000L, parentContext.sessionTimeout() * 1000L);
2015         selectApplicationProtocol();
2016         return FINISHED;
2017     }
2018 
2019     private SSLEngineResult.HandshakeStatus mayFinishHandshake(
2020             SSLEngineResult.HandshakeStatus hs, int bytesConsumed, int bytesProduced) throws SSLException {
2021         return hs == NEED_UNWRAP && bytesProduced > 0 || hs == NEED_WRAP && bytesConsumed > 0 ?
2022             handshake() : mayFinishHandshake(hs != FINISHED ? getHandshakeStatus() : FINISHED);
2023     }
2024 
2025     private SSLEngineResult.HandshakeStatus mayFinishHandshake(SSLEngineResult.HandshakeStatus status)
2026             throws SSLException {
2027         if (status == NOT_HANDSHAKING) {
2028             if (handshakeState != HandshakeState.FINISHED) {
2029                 // If the status was NOT_HANDSHAKING and we not finished the handshake we need to call
2030                 // SSL_do_handshake() again
2031                 return handshake();
2032             }
2033             if (!isDestroyed() && SSL.bioLengthNonApplication(networkBIO) > 0) {
2034                 // We have something left that needs to be wrapped.
2035                 return NEED_WRAP;
2036             }
2037         }
2038         return status;
2039     }
2040 
2041     @Override
2042     public final synchronized SSLEngineResult.HandshakeStatus getHandshakeStatus() {
2043         // Check if we are in the initial handshake phase or shutdown phase
2044         if (needPendingStatus()) {
2045             if (needTask) {
2046                 // There is a task outstanding
2047                 return NEED_TASK;
2048             }
2049             return pendingStatus(SSL.bioLengthNonApplication(networkBIO));
2050         }
2051         return NOT_HANDSHAKING;
2052     }
2053 
2054     private SSLEngineResult.HandshakeStatus getHandshakeStatus(int pending) {
2055         // Check if we are in the initial handshake phase or shutdown phase
2056         if (needPendingStatus()) {
2057             if (needTask) {
2058                 // There is a task outstanding
2059                 return NEED_TASK;
2060             }
2061             return pendingStatus(pending);
2062         }
2063         return NOT_HANDSHAKING;
2064     }
2065 
2066     private boolean needPendingStatus() {
2067         return handshakeState != HandshakeState.NOT_STARTED && !isDestroyed()
2068                 && (handshakeState != HandshakeState.FINISHED || isInboundDone() || isOutboundDone());
2069     }
2070 
2071     /**
2072      * Converts the specified OpenSSL cipher suite to the Java cipher suite.
2073      */
2074     private String toJavaCipherSuite(String openSslCipherSuite) {
2075         if (openSslCipherSuite == null) {
2076             return null;
2077         }
2078 
2079         String version = SSL.getVersion(ssl);
2080         String prefix = toJavaCipherSuitePrefix(version);
2081         return CipherSuiteConverter.toJava(openSslCipherSuite, prefix);
2082     }
2083 
2084     /**
2085      * Converts the protocol version string returned by {@link SSL#getVersion(long)} to protocol family string.
2086      */
2087     private static String toJavaCipherSuitePrefix(String protocolVersion) {
2088         final char c;
2089         if (protocolVersion == null || protocolVersion.isEmpty()) {
2090             c = 0;
2091         } else {
2092             c = protocolVersion.charAt(0);
2093         }
2094 
2095         switch (c) {
2096             case 'T':
2097                 return "TLS";
2098             case 'S':
2099                 return "SSL";
2100             default:
2101                 return "UNKNOWN";
2102         }
2103     }
2104 
2105     @Override
2106     public final void setUseClientMode(boolean clientMode) {
2107         if (clientMode != this.clientMode) {
2108             throw new UnsupportedOperationException();
2109         }
2110     }
2111 
2112     @Override
2113     public final boolean getUseClientMode() {
2114         return clientMode;
2115     }
2116 
2117     @Override
2118     public final void setNeedClientAuth(boolean b) {
2119         setClientAuth(b ? ClientAuth.REQUIRE : ClientAuth.NONE);
2120     }
2121 
2122     @Override
2123     public final boolean getNeedClientAuth() {
2124         return clientAuth == ClientAuth.REQUIRE;
2125     }
2126 
2127     @Override
2128     public final void setWantClientAuth(boolean b) {
2129         setClientAuth(b ? ClientAuth.OPTIONAL : ClientAuth.NONE);
2130     }
2131 
2132     @Override
2133     public final boolean getWantClientAuth() {
2134         return clientAuth == ClientAuth.OPTIONAL;
2135     }
2136 
2137     /**
2138      * See <a href="https://www.openssl.org/docs/man1.0.2/ssl/SSL_set_verify.html">SSL_set_verify</a> and
2139      * {@link SSL#setVerify(long, int, int)}.
2140      */
2141     @UnstableApi
2142     public final synchronized void setVerify(int verifyMode, int depth) {
2143         if (!isDestroyed()) {
2144             SSL.setVerify(ssl, verifyMode, depth);
2145         }
2146     }
2147 
2148     private void setClientAuth(ClientAuth mode) {
2149         if (clientMode) {
2150             return;
2151         }
2152         synchronized (this) {
2153             if (clientAuth == mode) {
2154                 // No need to issue any JNI calls if the mode is the same
2155                 return;
2156             }
2157             if (!isDestroyed()) {
2158                 switch (mode) {
2159                     case NONE:
2160                         SSL.setVerify(ssl, SSL.SSL_CVERIFY_NONE, ReferenceCountedOpenSslContext.VERIFY_DEPTH);
2161                         break;
2162                     case REQUIRE:
2163                         SSL.setVerify(ssl, SSL.SSL_CVERIFY_REQUIRED, ReferenceCountedOpenSslContext.VERIFY_DEPTH);
2164                         break;
2165                     case OPTIONAL:
2166                         SSL.setVerify(ssl, SSL.SSL_CVERIFY_OPTIONAL, ReferenceCountedOpenSslContext.VERIFY_DEPTH);
2167                         break;
2168                     default:
2169                         throw new Error(mode.toString());
2170                 }
2171             }
2172             clientAuth = mode;
2173         }
2174     }
2175 
2176     @Override
2177     public final void setEnableSessionCreation(boolean b) {
2178         if (b) {
2179             throw new UnsupportedOperationException();
2180         }
2181     }
2182 
2183     @Override
2184     public final boolean getEnableSessionCreation() {
2185         return false;
2186     }
2187 
2188     @Override
2189     public final synchronized SSLParameters getSSLParameters() {
2190         SSLParameters sslParameters = super.getSSLParameters();
2191 
2192         sslParameters.setEndpointIdentificationAlgorithm(endpointIdentificationAlgorithm);
2193         sslParameters.setAlgorithmConstraints((AlgorithmConstraints) algorithmConstraints);
2194         if (sniHostNames != null) {
2195             sslParameters.setServerNames(getSniHostNames(sniHostNames));
2196         }
2197         if (!isDestroyed()) {
2198             sslParameters.setUseCipherSuitesOrder((SSL.getOptions(ssl) & SSL.SSL_OP_CIPHER_SERVER_PREFERENCE) != 0);
2199         }
2200 
2201         sslParameters.setSNIMatchers(matchers);
2202         return sslParameters;
2203     }
2204 
2205     private static List<SNIServerName> getSniHostNames(List<String> names) {
2206         if (names == null || names.isEmpty()) {
2207             return Collections.emptyList();
2208         }
2209         List<SNIServerName> sniServerNames = new ArrayList<SNIServerName>(names.size());
2210         for (String name: names) {
2211             sniServerNames.add(new SNIHostName(name.getBytes(CharsetUtil.UTF_8)));
2212         }
2213         return sniServerNames;
2214     }
2215 
2216     @Override
2217     public final synchronized void setSSLParameters(SSLParameters sslParameters) {
2218         if (sslParameters.getAlgorithmConstraints() != null) {
2219             throw new IllegalArgumentException("AlgorithmConstraints are not supported.");
2220         }
2221 
2222         boolean isDestroyed = isDestroyed();
2223         if (!isDestroyed) {
2224             if (clientMode) {
2225                 final List<String> sniHostNames = getSniHostNames(sslParameters);
2226                 for (String name: sniHostNames) {
2227                     SSL.setTlsExtHostName(ssl, name);
2228                 }
2229                 this.sniHostNames = sniHostNames;
2230             }
2231             if (sslParameters.getUseCipherSuitesOrder()) {
2232                 SSL.setOptions(ssl, SSL.SSL_OP_CIPHER_SERVER_PREFERENCE);
2233             } else {
2234                 SSL.clearOptions(ssl, SSL.SSL_OP_CIPHER_SERVER_PREFERENCE);
2235             }
2236         }
2237         matchers = sslParameters.getSNIMatchers();
2238 
2239         final String endpointIdentificationAlgorithm = sslParameters.getEndpointIdentificationAlgorithm();
2240         if (!isDestroyed) {
2241             configureEndpointVerification(endpointIdentificationAlgorithm);
2242         }
2243         this.endpointIdentificationAlgorithm = endpointIdentificationAlgorithm;
2244         algorithmConstraints = sslParameters.getAlgorithmConstraints();
2245         super.setSSLParameters(sslParameters);
2246     }
2247 
2248     private void configureEndpointVerification(String endpointIdentificationAlgorithm) {
2249         // If the user asks for hostname verification we must ensure we verify the peer.
2250         // If the user disables hostname verification we leave it up to the user to change the mode manually.
2251         if (clientMode && isEndPointVerificationEnabled(endpointIdentificationAlgorithm)) {
2252             SSL.setVerify(ssl, SSL.SSL_CVERIFY_REQUIRED, -1);
2253         }
2254     }
2255 
2256     private static List<String> getSniHostNames(SSLParameters sslParameters) {
2257         List<SNIServerName> names = sslParameters.getServerNames();
2258         if (names == null || names.isEmpty()) {
2259             return Collections.emptyList();
2260         }
2261         List<String> strings = new ArrayList<String>(names.size());
2262 
2263         for (SNIServerName serverName : names) {
2264             if (serverName instanceof SNIHostName) {
2265                 strings.add(((SNIHostName) serverName).getAsciiName());
2266             } else {
2267                 throw new IllegalArgumentException("Only " + SNIHostName.class.getName()
2268                         + " instances are supported, but found: " + serverName);
2269             }
2270         }
2271         return strings;
2272     }
2273 
2274     private static boolean isEndPointVerificationEnabled(String endPointIdentificationAlgorithm) {
2275         return endPointIdentificationAlgorithm != null && !endPointIdentificationAlgorithm.isEmpty();
2276     }
2277 
2278     private boolean isDestroyed() {
2279         return destroyed;
2280     }
2281 
2282     final boolean checkSniHostnameMatch(byte[] hostname) {
2283         Collection<SNIMatcher> matchers = this.matchers;
2284         if (matchers != null && !matchers.isEmpty()) {
2285             SNIHostName name = new SNIHostName(hostname);
2286             for (SNIMatcher matcher : matchers) {
2287                 // type 0 is for hostname
2288                 if (matcher.getType() == 0 && matcher.matches(name)) {
2289                     return true;
2290                 }
2291             }
2292             return false;
2293         }
2294         return true;
2295     }
2296 
2297     @Override
2298     public String getNegotiatedApplicationProtocol() {
2299         return applicationProtocol;
2300     }
2301 
2302     private static long bufferAddress(ByteBuffer b) {
2303         assert b.isDirect();
2304         if (PlatformDependent.hasUnsafe()) {
2305             return PlatformDependent.directBufferAddress(b);
2306         }
2307         return Buffer.address(b);
2308     }
2309 
2310     /**
2311      * Select the application protocol used.
2312      */
2313     private void selectApplicationProtocol() throws SSLException {
2314         ApplicationProtocolConfig.SelectedListenerFailureBehavior behavior = apn.selectedListenerFailureBehavior();
2315         List<String> protocols = apn.protocols();
2316         String applicationProtocol;
2317         switch (apn.protocol()) {
2318             case NONE:
2319                 break;
2320             // We always need to check for applicationProtocol == null as the remote peer may not support
2321             // the TLS extension or may have returned an empty selection.
2322             case ALPN:
2323                 applicationProtocol = SSL.getAlpnSelected(ssl);
2324                 if (applicationProtocol != null) {
2325                     this.applicationProtocol = selectApplicationProtocol(
2326                             protocols, behavior, applicationProtocol);
2327                 }
2328                 break;
2329             case NPN:
2330                 applicationProtocol = SSL.getNextProtoNegotiated(ssl);
2331                 if (applicationProtocol != null) {
2332                     this.applicationProtocol = selectApplicationProtocol(
2333                             protocols, behavior, applicationProtocol);
2334                 }
2335                 break;
2336             case NPN_AND_ALPN:
2337                 applicationProtocol = SSL.getAlpnSelected(ssl);
2338                 if (applicationProtocol == null) {
2339                     applicationProtocol = SSL.getNextProtoNegotiated(ssl);
2340                 }
2341                 if (applicationProtocol != null) {
2342                     this.applicationProtocol = selectApplicationProtocol(
2343                             protocols, behavior, applicationProtocol);
2344                 }
2345                 break;
2346             default:
2347                 throw new Error();
2348         }
2349     }
2350 
2351     private static String selectApplicationProtocol(List<String> protocols,
2352                                                     ApplicationProtocolConfig.SelectedListenerFailureBehavior behavior,
2353                                                     String applicationProtocol) throws SSLException {
2354         if (behavior == ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT) {
2355             return applicationProtocol;
2356         } else {
2357             int size = protocols.size();
2358             assert size > 0;
2359             if (protocols.contains(applicationProtocol)) {
2360                 return applicationProtocol;
2361             } else {
2362                 if (behavior == ApplicationProtocolConfig.SelectedListenerFailureBehavior.CHOOSE_MY_LAST_PROTOCOL) {
2363                     return protocols.get(size - 1);
2364                 } else {
2365                     throw new SSLException("unknown protocol " + applicationProtocol);
2366                 }
2367             }
2368         }
2369     }
2370 
2371     private static final X509Certificate[] JAVAX_CERTS_NOT_SUPPORTED = new X509Certificate[0];
2372 
2373     private final class DefaultOpenSslSession implements OpenSslSession  {
2374         private final OpenSslSessionContext sessionContext;
2375 
2376         // These are guarded by synchronized(OpenSslEngine.this) as handshakeFinished() may be triggered by any
2377         // thread.
2378         private X509Certificate[] x509PeerCerts;
2379         private Certificate[] peerCerts;
2380 
2381         private boolean valid = true;
2382         private String protocol;
2383         private String cipher;
2384         private OpenSslSessionId id = OpenSslSessionId.NULL_ID;
2385         private long creationTime;
2386 
2387         // Updated once a new handshake is started and so the SSLSession reused.
2388         private long lastAccessed = -1;
2389 
2390         private volatile int applicationBufferSize = MAX_PLAINTEXT_LENGTH;
2391         private volatile Certificate[] localCertificateChain;
2392         private volatile Map<String, Object> keyValueStorage = new ConcurrentHashMap<String, Object>();
2393 
2394         DefaultOpenSslSession(OpenSslSessionContext sessionContext) {
2395             this.sessionContext = sessionContext;
2396         }
2397 
2398         private SSLSessionBindingEvent newSSLSessionBindingEvent(String name) {
2399             return new SSLSessionBindingEvent(session, name);
2400         }
2401 
2402         @Override
2403         public void prepareHandshake() {
2404             keyValueStorage.clear();
2405         }
2406 
2407         @Override
2408         public void setSessionDetails(
2409                 long creationTime, long lastAccessedTime, OpenSslSessionId sessionId,
2410                 Map<String, Object> keyValueStorage) {
2411             synchronized (ReferenceCountedOpenSslEngine.this) {
2412                 if (this.id == OpenSslSessionId.NULL_ID) {
2413                     this.id = sessionId;
2414                     this.creationTime = creationTime;
2415                     this.lastAccessed = lastAccessedTime;
2416 
2417                     // Update the key value storage. It's fine to just drop the previous stored values on the floor
2418                     // as the JDK does the same in the sense that it will use a new SSLSessionImpl instance once the
2419                     // handshake was done
2420                     this.keyValueStorage = keyValueStorage;
2421                 }
2422             }
2423         }
2424 
2425         @Override
2426         public Map<String, Object> keyValueStorage() {
2427             return keyValueStorage;
2428         }
2429 
2430         @Override
2431         public OpenSslSessionId sessionId() {
2432             synchronized (ReferenceCountedOpenSslEngine.this) {
2433                 if (this.id == OpenSslSessionId.NULL_ID && !isDestroyed()) {
2434                     byte[] sessionId = SSL.getSessionId(ssl);
2435                     if (sessionId != null) {
2436                         id = new OpenSslSessionId(sessionId);
2437                     }
2438                 }
2439 
2440                 return id;
2441             }
2442         }
2443 
2444         @Override
2445         public void setLocalCertificate(Certificate[] localCertificate) {
2446             this.localCertificateChain = localCertificate;
2447         }
2448 
2449         @Override
2450         public byte[] getId() {
2451             return sessionId().cloneBytes();
2452         }
2453 
2454         @Override
2455         public OpenSslSessionContext getSessionContext() {
2456             return sessionContext;
2457         }
2458 
2459         @Override
2460         public long getCreationTime() {
2461             synchronized (ReferenceCountedOpenSslEngine.this) {
2462                 return creationTime;
2463             }
2464         }
2465 
2466         @Override
2467         public void setLastAccessedTime(long time) {
2468             synchronized (ReferenceCountedOpenSslEngine.this) {
2469                 this.lastAccessed = time;
2470             }
2471         }
2472 
2473         @Override
2474         public long getLastAccessedTime() {
2475             // if lastAccessed is -1 we will just return the creation time as the handshake was not started yet.
2476             synchronized (ReferenceCountedOpenSslEngine.this) {
2477                 return lastAccessed == -1 ? creationTime : lastAccessed;
2478             }
2479         }
2480 
2481         @Override
2482         public void invalidate() {
2483             synchronized (ReferenceCountedOpenSslEngine.this) {
2484                 valid = false;
2485                 sessionContext.removeFromCache(id);
2486             }
2487         }
2488 
2489         @Override
2490         public boolean isValid() {
2491             synchronized (ReferenceCountedOpenSslEngine.this) {
2492                 return valid || sessionContext.isInCache(id);
2493             }
2494         }
2495 
2496         @Override
2497         public void putValue(String name, Object value) {
2498             checkNotNull(name, "name");
2499             checkNotNull(value, "value");
2500 
2501             final Object old = keyValueStorage.put(name, value);
2502             if (value instanceof SSLSessionBindingListener) {
2503                 // Use newSSLSessionBindingEvent so we always use the wrapper if needed.
2504                 ((SSLSessionBindingListener) value).valueBound(newSSLSessionBindingEvent(name));
2505             }
2506             notifyUnbound(old, name);
2507         }
2508 
2509         @Override
2510         public Object getValue(String name) {
2511             checkNotNull(name, "name");
2512             return keyValueStorage.get(name);
2513         }
2514 
2515         @Override
2516         public void removeValue(String name) {
2517             checkNotNull(name, "name");
2518             final Object old = keyValueStorage.remove(name);
2519             notifyUnbound(old, name);
2520         }
2521 
2522         @Override
2523         public String[] getValueNames() {
2524             return keyValueStorage.keySet().toArray(EMPTY_STRINGS);
2525         }
2526 
2527         private void notifyUnbound(Object value, String name) {
2528             if (value instanceof SSLSessionBindingListener) {
2529                 // Use newSSLSessionBindingEvent so we always use the wrapper if needed.
2530                 ((SSLSessionBindingListener) value).valueUnbound(newSSLSessionBindingEvent(name));
2531             }
2532         }
2533 
2534         /**
2535          * Finish the handshake and so init everything in the {@link OpenSslSession} that should be accessible by
2536          * the user.
2537          */
2538         @Override
2539         public void handshakeFinished(byte[] id, String cipher, String protocol, byte[] peerCertificate,
2540                                       byte[][] peerCertificateChain, long creationTime, long timeout)
2541                 throws SSLException {
2542             synchronized (ReferenceCountedOpenSslEngine.this) {
2543                 if (!isDestroyed()) {
2544                     if (this.id == OpenSslSessionId.NULL_ID) {
2545                         // if the handshake finished and it was not a resumption let ensure we try to set the id
2546 
2547                         this.id = id == null ? OpenSslSessionId.NULL_ID : new OpenSslSessionId(id);
2548                         // Once the handshake was done the lastAccessed and creationTime should be the same if we
2549                         // did not set it earlier via setSessionDetails(...)
2550                         this.creationTime = lastAccessed = creationTime;
2551                     }
2552                     this.cipher = toJavaCipherSuite(cipher);
2553                     this.protocol = protocol;
2554 
2555                     if (clientMode) {
2556                         if (isEmpty(peerCertificateChain)) {
2557                             peerCerts = EmptyArrays.EMPTY_CERTIFICATES;
2558                             if (OpenSsl.JAVAX_CERTIFICATE_CREATION_SUPPORTED) {
2559                                 x509PeerCerts = EmptyArrays.EMPTY_JAVAX_X509_CERTIFICATES;
2560                             } else {
2561                                 x509PeerCerts = JAVAX_CERTS_NOT_SUPPORTED;
2562                             }
2563                         } else {
2564                             peerCerts = new Certificate[peerCertificateChain.length];
2565                             if (OpenSsl.JAVAX_CERTIFICATE_CREATION_SUPPORTED) {
2566                                 x509PeerCerts = new X509Certificate[peerCertificateChain.length];
2567                             } else {
2568                                 x509PeerCerts = JAVAX_CERTS_NOT_SUPPORTED;
2569                             }
2570                             initCerts(peerCertificateChain, 0);
2571                         }
2572                     } else {
2573                         // if used on the server side SSL_get_peer_cert_chain(...) will not include the remote peer
2574                         // certificate. We use SSL_get_peer_certificate to get it in this case and add it to our
2575                         // array later.
2576                         //
2577                         // See https://www.openssl.org/docs/ssl/SSL_get_peer_cert_chain.html
2578                         if (isEmpty(peerCertificate)) {
2579                             peerCerts = EmptyArrays.EMPTY_CERTIFICATES;
2580                             x509PeerCerts = EmptyArrays.EMPTY_JAVAX_X509_CERTIFICATES;
2581                         } else {
2582                             if (isEmpty(peerCertificateChain)) {
2583                                 peerCerts = new Certificate[] {new LazyX509Certificate(peerCertificate)};
2584                                 if (OpenSsl.JAVAX_CERTIFICATE_CREATION_SUPPORTED) {
2585                                     x509PeerCerts = new X509Certificate[] {
2586                                             new LazyJavaxX509Certificate(peerCertificate)
2587                                     };
2588                                 } else {
2589                                     x509PeerCerts = JAVAX_CERTS_NOT_SUPPORTED;
2590                                 }
2591                             } else {
2592                                 peerCerts = new Certificate[peerCertificateChain.length + 1];
2593                                 peerCerts[0] = new LazyX509Certificate(peerCertificate);
2594 
2595                                 if (OpenSsl.JAVAX_CERTIFICATE_CREATION_SUPPORTED) {
2596                                     x509PeerCerts = new X509Certificate[peerCertificateChain.length + 1];
2597                                     x509PeerCerts[0] = new LazyJavaxX509Certificate(peerCertificate);
2598                                 } else {
2599                                     x509PeerCerts = JAVAX_CERTS_NOT_SUPPORTED;
2600                                 }
2601 
2602                                 initCerts(peerCertificateChain, 1);
2603                             }
2604                         }
2605                     }
2606 
2607                     calculateMaxWrapOverhead();
2608 
2609                     handshakeState = HandshakeState.FINISHED;
2610                 } else {
2611                     throw new SSLException("Already closed");
2612                 }
2613             }
2614         }
2615 
2616         private void initCerts(byte[][] chain, int startPos) {
2617             for (int i = 0; i < chain.length; i++) {
2618                 int certPos = startPos + i;
2619                 peerCerts[certPos] = new LazyX509Certificate(chain[i]);
2620                 if (x509PeerCerts != JAVAX_CERTS_NOT_SUPPORTED) {
2621                     x509PeerCerts[certPos] = new LazyJavaxX509Certificate(chain[i]);
2622                 }
2623             }
2624         }
2625 
2626         @Override
2627         public Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException {
2628             synchronized (ReferenceCountedOpenSslEngine.this) {
2629                 if (isEmpty(peerCerts)) {
2630                     throw new SSLPeerUnverifiedException("peer not verified");
2631                 }
2632                 return peerCerts.clone();
2633             }
2634         }
2635 
2636         @Override
2637         public Certificate[] getLocalCertificates() {
2638             Certificate[] localCerts = this.localCertificateChain;
2639             if (localCerts == null) {
2640                 return null;
2641             }
2642             return localCerts.clone();
2643         }
2644 
2645         @Override
2646         public X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException {
2647             synchronized (ReferenceCountedOpenSslEngine.this) {
2648                 if (x509PeerCerts == JAVAX_CERTS_NOT_SUPPORTED) {
2649                     // Not supported by the underlying JDK, so just throw. This is fine in terms of the API
2650                     // contract. See SSLSession.html#getPeerCertificateChain().
2651                     throw new UnsupportedOperationException();
2652                 }
2653                 if (isEmpty(x509PeerCerts)) {
2654                     throw new SSLPeerUnverifiedException("peer not verified");
2655                 }
2656                 return x509PeerCerts.clone();
2657             }
2658         }
2659 
2660         @Override
2661         public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
2662             Certificate[] peer = getPeerCertificates();
2663             // No need for null or length > 0 is needed as this is done in getPeerCertificates()
2664             // already.
2665             return ((java.security.cert.X509Certificate) peer[0]).getSubjectX500Principal();
2666         }
2667 
2668         @Override
2669         public Principal getLocalPrincipal() {
2670             Certificate[] local = this.localCertificateChain;
2671             if (local == null || local.length == 0) {
2672                 return null;
2673             }
2674             return ((java.security.cert.X509Certificate) local[0]).getSubjectX500Principal();
2675         }
2676 
2677         @Override
2678         public String getCipherSuite() {
2679             synchronized (ReferenceCountedOpenSslEngine.this) {
2680                 if (cipher == null) {
2681                     return SslUtils.INVALID_CIPHER;
2682                 }
2683                 return cipher;
2684             }
2685         }
2686 
2687         @Override
2688         public String getProtocol() {
2689             String protocol = this.protocol;
2690             if (protocol == null) {
2691                 synchronized (ReferenceCountedOpenSslEngine.this) {
2692                     if (!isDestroyed()) {
2693                         protocol = SSL.getVersion(ssl);
2694                     } else {
2695                         protocol = StringUtil.EMPTY_STRING;
2696                     }
2697                 }
2698             }
2699             return protocol;
2700         }
2701 
2702         @Override
2703         public String getPeerHost() {
2704             return ReferenceCountedOpenSslEngine.this.getPeerHost();
2705         }
2706 
2707         @Override
2708         public int getPeerPort() {
2709             return ReferenceCountedOpenSslEngine.this.getPeerPort();
2710         }
2711 
2712         @Override
2713         public int getPacketBufferSize() {
2714             return SSL.SSL_MAX_ENCRYPTED_LENGTH;
2715         }
2716 
2717         @Override
2718         public int getApplicationBufferSize() {
2719             return applicationBufferSize;
2720         }
2721 
2722         @Override
2723         public void tryExpandApplicationBufferSize(int packetLengthDataOnly) {
2724             if (packetLengthDataOnly > MAX_PLAINTEXT_LENGTH && applicationBufferSize != MAX_RECORD_SIZE) {
2725                 applicationBufferSize = MAX_RECORD_SIZE;
2726             }
2727         }
2728 
2729         @Override
2730         public String toString() {
2731             return "DefaultOpenSslSession{" +
2732                     "sessionContext=" + sessionContext +
2733                     ", id=" + id +
2734                     '}';
2735         }
2736 
2737         @Override
2738         public int hashCode() {
2739             return sessionId().hashCode();
2740         }
2741 
2742         @Override
2743         public boolean equals(Object o) {
2744             if (o == this) {
2745                 return true;
2746             }
2747             // We trust all sub-types as we use different types but the interface is package-private
2748             if (!(o instanceof OpenSslSession)) {
2749                 return false;
2750             }
2751             return sessionId().equals(((OpenSslSession) o).sessionId());
2752         }
2753     }
2754 
2755     private interface NativeSslException {
2756         int errorCode();
2757     }
2758 
2759     private static final class OpenSslException extends SSLException implements NativeSslException {
2760         private final int errorCode;
2761 
2762         OpenSslException(String reason, int errorCode) {
2763             super(reason);
2764             this.errorCode = errorCode;
2765         }
2766 
2767         @Override
2768         public int errorCode() {
2769             return errorCode;
2770         }
2771     }
2772 
2773     private static final class OpenSslHandshakeException extends SSLHandshakeException implements NativeSslException {
2774         private final int errorCode;
2775 
2776         OpenSslHandshakeException(String reason, int errorCode) {
2777             super(reason);
2778             this.errorCode = errorCode;
2779         }
2780 
2781         @Override
2782         public int errorCode() {
2783             return errorCode;
2784         }
2785     }
2786 }