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