package io.netty.handler.ssl;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.CompositeByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelException;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandler;
import io.netty.channel.ChannelPromise;
import io.netty.channel.ChannelPromiseNotifier;
import io.netty.channel.PendingWriteQueue;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.UnsupportedMessageTypeException;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.FutureListener;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.ImmediateExecutor;
import io.netty.util.concurrent.Promise;
import io.netty.util.concurrent.ScheduledFuture;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.ThrowableUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.io.IOException;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;

/* JADX INFO: loaded from: classes.dex */
public class SslHandler extends ByteToMessageDecoder implements ChannelOutboundHandler {
    static final /* synthetic */ boolean $assertionsDisabled = false;
    private volatile long closeNotifyTimeoutMillis;
    private volatile ChannelHandlerContext ctx;
    private final Executor delegatedTaskExecutor;
    private final SSLEngine engine;
    private boolean firedChannelRead;
    private boolean flushedBeforeHandshake;
    private Promise<Channel> handshakePromise;
    private volatile long handshakeTimeoutMillis;
    private final int maxPacketBufferSize;
    private boolean needsFlush;
    private boolean outboundClosed;
    private int packetLength;
    private PendingWriteQueue pendingUnencryptedWrites;
    private boolean readDuringHandshake;
    private boolean sentFirstMessage;
    private final ByteBuffer[] singleBuffer;
    private final LazyChannelPromise sslCloseFuture;
    private final boolean startTls;
    private final boolean wantsDirectBuffer;
    private final boolean wantsLargeOutboundNetworkBuffer;
    private static final InternalLogger logger = InternalLoggerFactory.getInstance((Class<?>) SslHandler.class);
    private static final Pattern IGNORABLE_CLASS_IN_STACK = Pattern.compile("^.*(?:Socket|Datagram|Sctp|Udt)Channel.*$");
    private static final Pattern IGNORABLE_ERROR_MESSAGE = Pattern.compile("^.*(?:connection.*(?:reset|closed|abort|broken)|broken.*pipe).*$", 2);
    private static final SSLException SSLENGINE_CLOSED = (SSLException) ThrowableUtil.unknownStackTrace(new SSLException("SSLEngine closed already"), SslHandler.class, "wrap(...)");
    private static final SSLException HANDSHAKE_TIMED_OUT = (SSLException) ThrowableUtil.unknownStackTrace(new SSLException("handshake timed out"), SslHandler.class, "handshake(...)");
    private static final ClosedChannelException CHANNEL_CLOSED = (ClosedChannelException) ThrowableUtil.unknownStackTrace(new ClosedChannelException(), SslHandler.class, "channelInactive(...)");

    /* JADX INFO: renamed from: io.netty.handler.ssl.SslHandler$9, reason: invalid class name */
    static /* synthetic */ class AnonymousClass9 {
        static final /* synthetic */ int[] $SwitchMap$javax$net$ssl$SSLEngineResult$HandshakeStatus;
        static final /* synthetic */ int[] $SwitchMap$javax$net$ssl$SSLEngineResult$Status;

        static {
            int[] iArr = new int[SSLEngineResult.Status.values().length];
            $SwitchMap$javax$net$ssl$SSLEngineResult$Status = iArr;
            try {
                iArr[SSLEngineResult.Status.BUFFER_OVERFLOW.ordinal()] = 1;
            } catch (NoSuchFieldError unused) {
            }
            try {
                $SwitchMap$javax$net$ssl$SSLEngineResult$Status[SSLEngineResult.Status.CLOSED.ordinal()] = 2;
            } catch (NoSuchFieldError unused2) {
            }
            int[] iArr2 = new int[SSLEngineResult.HandshakeStatus.values().length];
            $SwitchMap$javax$net$ssl$SSLEngineResult$HandshakeStatus = iArr2;
            try {
                iArr2[SSLEngineResult.HandshakeStatus.NEED_TASK.ordinal()] = 1;
            } catch (NoSuchFieldError unused3) {
            }
            try {
                $SwitchMap$javax$net$ssl$SSLEngineResult$HandshakeStatus[SSLEngineResult.HandshakeStatus.FINISHED.ordinal()] = 2;
            } catch (NoSuchFieldError unused4) {
            }
            try {
                $SwitchMap$javax$net$ssl$SSLEngineResult$HandshakeStatus[SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING.ordinal()] = 3;
            } catch (NoSuchFieldError unused5) {
            }
            try {
                $SwitchMap$javax$net$ssl$SSLEngineResult$HandshakeStatus[SSLEngineResult.HandshakeStatus.NEED_WRAP.ordinal()] = 4;
            } catch (NoSuchFieldError unused6) {
            }
            try {
                $SwitchMap$javax$net$ssl$SSLEngineResult$HandshakeStatus[SSLEngineResult.HandshakeStatus.NEED_UNWRAP.ordinal()] = 5;
            } catch (NoSuchFieldError unused7) {
            }
        }
    }

    private final class LazyChannelPromise extends DefaultPromise<Channel> {
        private LazyChannelPromise() {
        }

        @Override // io.netty.util.concurrent.DefaultPromise
        protected void checkDeadLock() {
            if (SslHandler.this.ctx == null) {
                return;
            }
            super.checkDeadLock();
        }

        @Override // io.netty.util.concurrent.DefaultPromise
        protected EventExecutor executor() {
            if (SslHandler.this.ctx != null) {
                return SslHandler.this.ctx.executor();
            }
            throw new IllegalStateException();
        }
    }

    public SslHandler(SSLEngine sSLEngine) {
        this(sSLEngine, false);
    }

    private ByteBuf allocate(ChannelHandlerContext channelHandlerContext, int i2) {
        ByteBufAllocator byteBufAllocatorAlloc = channelHandlerContext.alloc();
        return this.wantsDirectBuffer ? byteBufAllocatorAlloc.directBuffer(i2) : byteBufAllocatorAlloc.buffer(i2);
    }

    private ByteBuf allocateOutNetBuf(ChannelHandlerContext channelHandlerContext, int i2) {
        return this.wantsLargeOutboundNetworkBuffer ? allocate(channelHandlerContext, this.maxPacketBufferSize) : allocate(channelHandlerContext, Math.min(i2 + 2329, this.maxPacketBufferSize));
    }

    private void closeOutboundAndChannel(ChannelHandlerContext channelHandlerContext, ChannelPromise channelPromise, boolean z) throws Exception {
        if (!channelHandlerContext.channel().isActive()) {
            if (z) {
                channelHandlerContext.disconnect(channelPromise);
                return;
            } else {
                channelHandlerContext.close(channelPromise);
                return;
            }
        }
        this.outboundClosed = true;
        this.engine.closeOutbound();
        ChannelPromise channelPromiseNewPromise = channelHandlerContext.newPromise();
        write(channelHandlerContext, Unpooled.EMPTY_BUFFER, channelPromiseNewPromise);
        flush(channelHandlerContext);
        safeClose(channelHandlerContext, channelPromiseNewPromise, channelPromise);
    }

    private void finishWrap(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, ChannelPromise channelPromise, boolean z, boolean z2) {
        if (byteBuf == null) {
            byteBuf = Unpooled.EMPTY_BUFFER;
        } else if (!byteBuf.isReadable()) {
            byteBuf.release();
            byteBuf = Unpooled.EMPTY_BUFFER;
        }
        if (channelPromise != null) {
            channelHandlerContext.write(byteBuf, channelPromise);
        } else {
            channelHandlerContext.write(byteBuf);
        }
        if (z) {
            this.needsFlush = true;
        }
        if (z2) {
            readIfNeeded(channelHandlerContext);
        }
    }

    private void flushIfNeeded(ChannelHandlerContext channelHandlerContext) {
        if (this.needsFlush) {
            this.needsFlush = false;
            channelHandlerContext.flush();
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void handshake(final Promise<Channel> promise) {
        if (promise != null) {
            Promise<Channel> promise2 = this.handshakePromise;
            if (!promise2.isDone()) {
                promise2.addListener((GenericFutureListener<? extends Future<? super Channel>>) new FutureListener<Channel>() { // from class: io.netty.handler.ssl.SslHandler.4
                    @Override // io.netty.util.concurrent.GenericFutureListener
                    public void operationComplete(Future<Channel> future) throws Exception {
                        if (future.isSuccess()) {
                            promise.setSuccess(future.getNow());
                        } else {
                            promise.setFailure(future.cause());
                        }
                    }
                });
                return;
            }
            this.handshakePromise = promise;
        } else if (this.engine.getHandshakeStatus() != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) {
            return;
        } else {
            promise = this.handshakePromise;
        }
        ChannelHandlerContext channelHandlerContext = this.ctx;
        try {
            this.engine.beginHandshake();
            wrapNonAppData(channelHandlerContext, false);
            channelHandlerContext.flush();
        } catch (Exception e2) {
            notifyHandshakeFailure(e2);
        }
        long j2 = this.handshakeTimeoutMillis;
        if (j2 <= 0 || promise.isDone()) {
            return;
        }
        final ScheduledFuture<?> scheduledFutureSchedule = channelHandlerContext.executor().schedule(new Runnable() { // from class: io.netty.handler.ssl.SslHandler.5
            @Override // java.lang.Runnable
            public void run() {
                if (promise.isDone()) {
                    return;
                }
                SslHandler.this.notifyHandshakeFailure(SslHandler.HANDSHAKE_TIMED_OUT);
            }
        }, j2, TimeUnit.MILLISECONDS);
        promise.addListener((GenericFutureListener<? extends Future<? super Channel>>) new FutureListener<Channel>() { // from class: io.netty.handler.ssl.SslHandler.6
            @Override // io.netty.util.concurrent.GenericFutureListener
            public void operationComplete(Future<Channel> future) throws Exception {
                scheduledFutureSchedule.cancel(false);
            }
        });
    }

    private boolean ignoreException(Throwable th) {
        if (!(th instanceof SSLException) && (th instanceof IOException) && this.sslCloseFuture.isDone()) {
            if (IGNORABLE_ERROR_MESSAGE.matcher(String.valueOf(th.getMessage()).toLowerCase()).matches()) {
                return true;
            }
            for (StackTraceElement stackTraceElement : th.getStackTrace()) {
                String className = stackTraceElement.getClassName();
                String methodName = stackTraceElement.getMethodName();
                if (!className.startsWith("io.netty.") && "read".equals(methodName)) {
                    if (IGNORABLE_CLASS_IN_STACK.matcher(className).matches()) {
                        return true;
                    }
                    try {
                        Class<?> clsLoadClass = PlatformDependent.getClassLoader(getClass()).loadClass(className);
                        if (!SocketChannel.class.isAssignableFrom(clsLoadClass) && !DatagramChannel.class.isAssignableFrom(clsLoadClass) && (PlatformDependent.javaVersion() < 7 || !"com.sun.nio.sctp.SctpChannel".equals(clsLoadClass.getSuperclass().getName()))) {
                        }
                        return true;
                    } catch (ClassNotFoundException unused) {
                        continue;
                    }
                }
            }
        }
        return false;
    }

    public static boolean isEncrypted(ByteBuf byteBuf) {
        if (byteBuf.readableBytes() >= 5) {
            return SslUtils.getEncryptedPacketLength(byteBuf, byteBuf.readerIndex()) != -1;
        }
        throw new IllegalArgumentException("buffer must have at least 5 readable bytes");
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void notifyHandshakeFailure(Throwable th) {
        if (this.handshakePromise.tryFailure(th)) {
            SslUtils.notifyHandshakeFailure(this.ctx, th);
        }
    }

    private void readIfNeeded(ChannelHandlerContext channelHandlerContext) {
        if (channelHandlerContext.channel().config().isAutoRead()) {
            return;
        }
        if (this.firedChannelRead && this.handshakePromise.isDone()) {
            return;
        }
        channelHandlerContext.read();
    }

    private void runDelegatedTasks() {
        if (this.delegatedTaskExecutor != ImmediateExecutor.INSTANCE) {
            final ArrayList arrayList = new ArrayList(2);
            while (true) {
                Runnable delegatedTask = this.engine.getDelegatedTask();
                if (delegatedTask == null) {
                    break;
                } else {
                    arrayList.add(delegatedTask);
                }
            }
            if (arrayList.isEmpty()) {
                return;
            }
            final CountDownLatch countDownLatch = new CountDownLatch(1);
            this.delegatedTaskExecutor.execute(new Runnable() { // from class: io.netty.handler.ssl.SslHandler.2
                @Override // java.lang.Runnable
                public void run() {
                    try {
                        try {
                            Iterator it = arrayList.iterator();
                            while (it.hasNext()) {
                                ((Runnable) it.next()).run();
                            }
                        } catch (Exception e2) {
                            SslHandler.this.ctx.fireExceptionCaught((Throwable) e2);
                        }
                    } finally {
                        countDownLatch.countDown();
                    }
                }
            });
            boolean z = false;
            while (countDownLatch.getCount() != 0) {
                try {
                    countDownLatch.await();
                } catch (InterruptedException unused) {
                    z = true;
                }
            }
            if (z) {
                Thread.currentThread().interrupt();
                return;
            }
            return;
        }
        while (true) {
            Runnable delegatedTask2 = this.engine.getDelegatedTask();
            if (delegatedTask2 == null) {
                return;
            } else {
                delegatedTask2.run();
            }
        }
    }

    private void safeClose(final ChannelHandlerContext channelHandlerContext, ChannelFuture channelFuture, final ChannelPromise channelPromise) {
        if (!channelHandlerContext.channel().isActive()) {
            channelHandlerContext.close(channelPromise);
        } else {
            final ScheduledFuture<?> scheduledFutureSchedule = this.closeNotifyTimeoutMillis > 0 ? channelHandlerContext.executor().schedule(new Runnable() { // from class: io.netty.handler.ssl.SslHandler.7
                @Override // java.lang.Runnable
                public void run() {
                    SslHandler.logger.warn("{} Last write attempt timed out; force-closing the connection.", channelHandlerContext.channel());
                    ChannelHandlerContext channelHandlerContext2 = channelHandlerContext;
                    channelHandlerContext2.close(channelHandlerContext2.newPromise()).addListener((GenericFutureListener<? extends Future<? super Void>>) new ChannelPromiseNotifier(channelPromise));
                }
            }, this.closeNotifyTimeoutMillis, TimeUnit.MILLISECONDS) : null;
            channelFuture.addListener((GenericFutureListener<? extends Future<? super Void>>) new ChannelFutureListener() { // from class: io.netty.handler.ssl.SslHandler.8
                @Override // io.netty.util.concurrent.GenericFutureListener
                public void operationComplete(ChannelFuture channelFuture2) throws Exception {
                    java.util.concurrent.ScheduledFuture scheduledFuture = scheduledFutureSchedule;
                    if (scheduledFuture != null) {
                        scheduledFuture.cancel(false);
                    }
                    ChannelHandlerContext channelHandlerContext2 = channelHandlerContext;
                    channelHandlerContext2.close(channelHandlerContext2.newPromise()).addListener((GenericFutureListener<? extends Future<? super Void>>) new ChannelPromiseNotifier(channelPromise));
                }
            });
        }
    }

    private void setHandshakeFailure(ChannelHandlerContext channelHandlerContext, Throwable th) {
        setHandshakeFailure(channelHandlerContext, th, true);
    }

    private void setHandshakeSuccess() {
        this.handshakePromise.trySuccess(this.ctx.channel());
        if (logger.isDebugEnabled()) {
            logger.debug("{} HANDSHAKEN: {}", this.ctx.channel(), this.engine.getSession().getCipherSuite());
        }
        this.ctx.fireUserEventTriggered((Object) SslHandshakeCompletionEvent.SUCCESS);
        if (!this.readDuringHandshake || this.ctx.channel().config().isAutoRead()) {
            return;
        }
        this.readDuringHandshake = false;
        this.ctx.read();
    }

    private boolean setHandshakeSuccessIfStillHandshaking() {
        if (this.handshakePromise.isDone()) {
            return false;
        }
        setHandshakeSuccess();
        return true;
    }

    private static ByteBuffer toByteBuffer(ByteBuf byteBuf, int i2, int i3) {
        return byteBuf.nioBufferCount() == 1 ? byteBuf.internalNioBuffer(i2, i3) : byteBuf.nioBuffer(i2, i3);
    }

    /* JADX WARN: Finally extract failed */
    private boolean unwrap(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, int i2, int i3) throws SSLException {
        SSLEngineResult.HandshakeStatus handshakeStatus;
        int i4 = i3;
        ByteBuf byteBufAllocate = allocate(channelHandlerContext, i3);
        boolean z = false;
        boolean z2 = false;
        boolean z3 = false;
        int i5 = i2;
        while (true) {
            try {
                try {
                    SSLEngineResult sSLEngineResultUnwrap = unwrap(this.engine, byteBuf, i5, i4, byteBufAllocate);
                    SSLEngineResult.Status status = sSLEngineResultUnwrap.getStatus();
                    handshakeStatus = sSLEngineResultUnwrap.getHandshakeStatus();
                    int iBytesProduced = sSLEngineResultUnwrap.bytesProduced();
                    int iBytesConsumed = sSLEngineResultUnwrap.bytesConsumed();
                    i5 += iBytesConsumed;
                    i4 -= iBytesConsumed;
                    int i6 = AnonymousClass9.$SwitchMap$javax$net$ssl$SSLEngineResult$Status[status.ordinal()];
                    if (i6 != 1) {
                        if (i6 == 2) {
                            z2 = true;
                        }
                        int i7 = AnonymousClass9.$SwitchMap$javax$net$ssl$SSLEngineResult$HandshakeStatus[handshakeStatus.ordinal()];
                        if (i7 != 1) {
                            if (i7 == 2) {
                                setHandshakeSuccess();
                            } else if (i7 != 3) {
                                if (i7 == 4) {
                                    wrapNonAppData(channelHandlerContext, true);
                                } else if (i7 != 5) {
                                    throw new IllegalStateException("unknown handshake status: " + handshakeStatus);
                                }
                            } else if (setHandshakeSuccessIfStillHandshaking()) {
                                z = true;
                            } else if (this.flushedBeforeHandshake) {
                                this.flushedBeforeHandshake = false;
                            }
                            z = true;
                        } else {
                            runDelegatedTasks();
                        }
                        if (status == SSLEngineResult.Status.BUFFER_UNDERFLOW || (iBytesConsumed == 0 && iBytesProduced == 0)) {
                            break;
                        }
                    } else {
                        int i8 = byteBufAllocate.readableBytes();
                        if (i8 > 0) {
                            channelHandlerContext.fireChannelRead((Object) byteBufAllocate);
                            z3 = true;
                        } else {
                            byteBufAllocate.release();
                        }
                        byteBufAllocate = allocate(channelHandlerContext, this.engine.getSession().getApplicationBufferSize() - i8);
                    }
                } catch (SSLException e2) {
                    setHandshakeFailure(channelHandlerContext, e2);
                    throw e2;
                }
            } catch (Throwable th) {
                if (byteBufAllocate.isReadable()) {
                    channelHandlerContext.fireChannelRead((Object) byteBufAllocate);
                } else {
                    byteBufAllocate.release();
                }
                throw th;
            }
        }
        if (handshakeStatus == SSLEngineResult.HandshakeStatus.NEED_UNWRAP) {
            readIfNeeded(channelHandlerContext);
        }
        if (z) {
            wrap(channelHandlerContext, true);
        }
        if (z2) {
            this.sslCloseFuture.trySuccess(channelHandlerContext.channel());
        }
        if (byteBufAllocate.isReadable()) {
            channelHandlerContext.fireChannelRead((Object) byteBufAllocate);
            return true;
        }
        byteBufAllocate.release();
        return z3;
    }

    private void unwrapNonAppData(ChannelHandlerContext channelHandlerContext) throws SSLException {
        unwrap(channelHandlerContext, Unpooled.EMPTY_BUFFER, 0, 0);
    }

    /* JADX WARN: Code restructure failed: missing block: B:20:0x0047, code lost:
    
        finishWrap(r13, r4, r2, r14, r11);
     */
    /* JADX WARN: Code restructure failed: missing block: B:21:0x004f, code lost:
    
        return;
     */
    /* JADX WARN: Code restructure failed: missing block: B:25:0x0060, code lost:
    
        if (r5 == 2) goto L35;
     */
    /* JADX WARN: Code restructure failed: missing block: B:27:0x0063, code lost:
    
        if (r5 == 3) goto L36;
     */
    /* JADX WARN: Code restructure failed: missing block: B:29:0x0066, code lost:
    
        if (r5 == 4) goto L60;
     */
    /* JADX WARN: Code restructure failed: missing block: B:31:0x0069, code lost:
    
        if (r5 != 5) goto L33;
     */
    /* JADX WARN: Code restructure failed: missing block: B:32:0x006b, code lost:
    
        r11 = true;
     */
    /* JADX WARN: Code restructure failed: missing block: B:34:0x0087, code lost:
    
        throw new java.lang.IllegalStateException("Unknown handshake status: " + r3.getHandshakeStatus());
     */
    /* JADX WARN: Code restructure failed: missing block: B:35:0x0088, code lost:
    
        setHandshakeSuccess();
     */
    /* JADX WARN: Code restructure failed: missing block: B:36:0x008b, code lost:
    
        setHandshakeSuccessIfStillHandshaking();
     */
    /*
        Code decompiled incorrectly, please refer to instructions dump.
        To view partially-correct add '--show-bad-code' argument
    */
    private void wrap(io.netty.channel.ChannelHandlerContext r13, boolean r14) throws java.lang.Throwable {
        /*
            r12 = this;
            io.netty.buffer.ByteBufAllocator r0 = r13.alloc()
            r1 = 0
        L5:
            r4 = r1
            r5 = r4
        L7:
            io.netty.channel.PendingWriteQueue r2 = r12.pendingUnencryptedWrites     // Catch: java.lang.Throwable -> La6 javax.net.ssl.SSLException -> Laa
            java.lang.Object r2 = r2.current()     // Catch: java.lang.Throwable -> La6 javax.net.ssl.SSLException -> Laa
            if (r2 != 0) goto L17
            r7 = 0
            r2 = r12
            r3 = r13
            r6 = r14
            r2.finishWrap(r3, r4, r5, r6, r7)
            return
        L17:
            io.netty.buffer.ByteBuf r2 = (io.netty.buffer.ByteBuf) r2     // Catch: java.lang.Throwable -> La6 javax.net.ssl.SSLException -> Laa
            if (r4 != 0) goto L23
            int r3 = r2.readableBytes()     // Catch: java.lang.Throwable -> La6 javax.net.ssl.SSLException -> Laa
            io.netty.buffer.ByteBuf r4 = r12.allocateOutNetBuf(r13, r3)     // Catch: java.lang.Throwable -> La6 javax.net.ssl.SSLException -> Laa
        L23:
            javax.net.ssl.SSLEngine r3 = r12.engine     // Catch: java.lang.Throwable -> La6 javax.net.ssl.SSLException -> Laa
            javax.net.ssl.SSLEngineResult r3 = r12.wrap(r0, r3, r2, r4)     // Catch: java.lang.Throwable -> La6 javax.net.ssl.SSLException -> Laa
            boolean r2 = r2.isReadable()     // Catch: java.lang.Throwable -> La6 javax.net.ssl.SSLException -> Laa
            if (r2 != 0) goto L36
            io.netty.channel.PendingWriteQueue r2 = r12.pendingUnencryptedWrites     // Catch: java.lang.Throwable -> La6 javax.net.ssl.SSLException -> Laa
            io.netty.channel.ChannelPromise r2 = r2.remove()     // Catch: java.lang.Throwable -> La6 javax.net.ssl.SSLException -> Laa
            goto L37
        L36:
            r2 = r1
        L37:
            javax.net.ssl.SSLEngineResult$Status r5 = r3.getStatus()     // Catch: java.lang.Throwable -> L9f javax.net.ssl.SSLException -> La3
            javax.net.ssl.SSLEngineResult$Status r6 = javax.net.ssl.SSLEngineResult.Status.CLOSED     // Catch: java.lang.Throwable -> L9f javax.net.ssl.SSLException -> La3
            if (r5 != r6) goto L50
            io.netty.channel.PendingWriteQueue r0 = r12.pendingUnencryptedWrites     // Catch: java.lang.Throwable -> L9f javax.net.ssl.SSLException -> La3
            javax.net.ssl.SSLException r1 = io.netty.handler.ssl.SslHandler.SSLENGINE_CLOSED     // Catch: java.lang.Throwable -> L9f javax.net.ssl.SSLException -> La3
            r0.removeAndFailAll(r1)     // Catch: java.lang.Throwable -> L9f javax.net.ssl.SSLException -> La3
            r11 = 0
        L47:
            r6 = r12
            r7 = r13
            r8 = r4
            r9 = r2
            r10 = r14
            r6.finishWrap(r7, r8, r9, r10, r11)
            return
        L50:
            int[] r5 = io.netty.handler.ssl.SslHandler.AnonymousClass9.$SwitchMap$javax$net$ssl$SSLEngineResult$HandshakeStatus     // Catch: java.lang.Throwable -> L9f javax.net.ssl.SSLException -> La3
            javax.net.ssl.SSLEngineResult$HandshakeStatus r6 = r3.getHandshakeStatus()     // Catch: java.lang.Throwable -> L9f javax.net.ssl.SSLException -> La3
            int r6 = r6.ordinal()     // Catch: java.lang.Throwable -> L9f javax.net.ssl.SSLException -> La3
            r5 = r5[r6]     // Catch: java.lang.Throwable -> L9f javax.net.ssl.SSLException -> La3
            r6 = 1
            if (r5 == r6) goto L99
            r6 = 2
            if (r5 == r6) goto L88
            r6 = 3
            if (r5 == r6) goto L8b
            r6 = 4
            if (r5 == r6) goto L8e
            r0 = 5
            if (r5 != r0) goto L6d
            r11 = 1
            goto L47
        L6d:
            java.lang.IllegalStateException r0 = new java.lang.IllegalStateException     // Catch: java.lang.Throwable -> L9f javax.net.ssl.SSLException -> La3
            java.lang.StringBuilder r1 = new java.lang.StringBuilder     // Catch: java.lang.Throwable -> L9f javax.net.ssl.SSLException -> La3
            r1.<init>()     // Catch: java.lang.Throwable -> L9f javax.net.ssl.SSLException -> La3
            java.lang.String r5 = "Unknown handshake status: "
            r1.append(r5)     // Catch: java.lang.Throwable -> L9f javax.net.ssl.SSLException -> La3
            javax.net.ssl.SSLEngineResult$HandshakeStatus r3 = r3.getHandshakeStatus()     // Catch: java.lang.Throwable -> L9f javax.net.ssl.SSLException -> La3
            r1.append(r3)     // Catch: java.lang.Throwable -> L9f javax.net.ssl.SSLException -> La3
            java.lang.String r1 = r1.toString()     // Catch: java.lang.Throwable -> L9f javax.net.ssl.SSLException -> La3
            r0.<init>(r1)     // Catch: java.lang.Throwable -> L9f javax.net.ssl.SSLException -> La3
            throw r0     // Catch: java.lang.Throwable -> L9f javax.net.ssl.SSLException -> La3
        L88:
            r12.setHandshakeSuccess()     // Catch: java.lang.Throwable -> L9f javax.net.ssl.SSLException -> La3
        L8b:
            r12.setHandshakeSuccessIfStillHandshaking()     // Catch: java.lang.Throwable -> L9f javax.net.ssl.SSLException -> La3
        L8e:
            r11 = 0
            r6 = r12
            r7 = r13
            r8 = r4
            r9 = r2
            r10 = r14
            r6.finishWrap(r7, r8, r9, r10, r11)     // Catch: java.lang.Throwable -> L9f javax.net.ssl.SSLException -> La3
            goto L5
        L99:
            r12.runDelegatedTasks()     // Catch: java.lang.Throwable -> L9f javax.net.ssl.SSLException -> La3
            r5 = r2
            goto L7
        L9f:
            r0 = move-exception
            r3 = r4
            r4 = r2
            goto Laf
        La3:
            r0 = move-exception
            r5 = r2
            goto Lab
        La6:
            r0 = move-exception
            r3 = r4
            r4 = r5
            goto Laf
        Laa:
            r0 = move-exception
        Lab:
            r12.setHandshakeFailure(r13, r0)     // Catch: java.lang.Throwable -> La6
            throw r0     // Catch: java.lang.Throwable -> La6
        Laf:
            r6 = 0
            r1 = r12
            r2 = r13
            r5 = r14
            r1.finishWrap(r2, r3, r4, r5, r6)
            goto Lb8
        Lb7:
            throw r0
        Lb8:
            goto Lb7
        */
        throw new UnsupportedOperationException("Method not decompiled: io.netty.handler.ssl.SslHandler.wrap(io.netty.channel.ChannelHandlerContext, boolean):void");
    }

    /* JADX WARN: Code restructure failed: missing block: B:25:0x005e, code lost:
    
        throw new java.lang.IllegalStateException("Unknown handshake status: " + r3.getHandshakeStatus());
     */
    /*
        Code decompiled incorrectly, please refer to instructions dump.
        To view partially-correct add '--show-bad-code' argument
    */
    private void wrapNonAppData(io.netty.channel.ChannelHandlerContext r8, boolean r9) throws javax.net.ssl.SSLException {
        /*
            r7 = this;
            io.netty.buffer.ByteBufAllocator r0 = r8.alloc()
            r1 = 0
            r2 = r1
        L6:
            if (r2 != 0) goto Ld
            r3 = 0
            io.netty.buffer.ByteBuf r2 = r7.allocateOutNetBuf(r8, r3)     // Catch: java.lang.Throwable -> L8a javax.net.ssl.SSLException -> L8c
        Ld:
            javax.net.ssl.SSLEngine r3 = r7.engine     // Catch: java.lang.Throwable -> L8a javax.net.ssl.SSLException -> L8c
            io.netty.buffer.ByteBuf r4 = io.netty.buffer.Unpooled.EMPTY_BUFFER     // Catch: java.lang.Throwable -> L8a javax.net.ssl.SSLException -> L8c
            javax.net.ssl.SSLEngineResult r3 = r7.wrap(r0, r3, r4, r2)     // Catch: java.lang.Throwable -> L8a javax.net.ssl.SSLException -> L8c
            int r4 = r3.bytesProduced()     // Catch: java.lang.Throwable -> L8a javax.net.ssl.SSLException -> L8c
            r5 = 1
            if (r4 <= 0) goto L24
            r8.write(r2)     // Catch: java.lang.Throwable -> L8a javax.net.ssl.SSLException -> L8c
            if (r9 == 0) goto L23
            r7.needsFlush = r5     // Catch: java.lang.Throwable -> L8a javax.net.ssl.SSLException -> L8c
        L23:
            r2 = r1
        L24:
            int[] r4 = io.netty.handler.ssl.SslHandler.AnonymousClass9.$SwitchMap$javax$net$ssl$SSLEngineResult$HandshakeStatus     // Catch: java.lang.Throwable -> L8a javax.net.ssl.SSLException -> L8c
            javax.net.ssl.SSLEngineResult$HandshakeStatus r6 = r3.getHandshakeStatus()     // Catch: java.lang.Throwable -> L8a javax.net.ssl.SSLException -> L8c
            int r6 = r6.ordinal()     // Catch: java.lang.Throwable -> L8a javax.net.ssl.SSLException -> L8c
            r4 = r4[r6]     // Catch: java.lang.Throwable -> L8a javax.net.ssl.SSLException -> L8c
            if (r4 == r5) goto L6c
            r5 = 2
            if (r4 == r5) goto L68
            r5 = 3
            if (r4 == r5) goto L5f
            r5 = 4
            if (r4 == r5) goto L6f
            r5 = 5
            if (r4 != r5) goto L44
            if (r9 != 0) goto L6f
            r7.unwrapNonAppData(r8)     // Catch: java.lang.Throwable -> L8a javax.net.ssl.SSLException -> L8c
            goto L6f
        L44:
            java.lang.IllegalStateException r9 = new java.lang.IllegalStateException     // Catch: java.lang.Throwable -> L8a javax.net.ssl.SSLException -> L8c
            java.lang.StringBuilder r0 = new java.lang.StringBuilder     // Catch: java.lang.Throwable -> L8a javax.net.ssl.SSLException -> L8c
            r0.<init>()     // Catch: java.lang.Throwable -> L8a javax.net.ssl.SSLException -> L8c
            java.lang.String r1 = "Unknown handshake status: "
            r0.append(r1)     // Catch: java.lang.Throwable -> L8a javax.net.ssl.SSLException -> L8c
            javax.net.ssl.SSLEngineResult$HandshakeStatus r1 = r3.getHandshakeStatus()     // Catch: java.lang.Throwable -> L8a javax.net.ssl.SSLException -> L8c
            r0.append(r1)     // Catch: java.lang.Throwable -> L8a javax.net.ssl.SSLException -> L8c
            java.lang.String r0 = r0.toString()     // Catch: java.lang.Throwable -> L8a javax.net.ssl.SSLException -> L8c
            r9.<init>(r0)     // Catch: java.lang.Throwable -> L8a javax.net.ssl.SSLException -> L8c
            throw r9     // Catch: java.lang.Throwable -> L8a javax.net.ssl.SSLException -> L8c
        L5f:
            r7.setHandshakeSuccessIfStillHandshaking()     // Catch: java.lang.Throwable -> L8a javax.net.ssl.SSLException -> L8c
            if (r9 != 0) goto L6f
            r7.unwrapNonAppData(r8)     // Catch: java.lang.Throwable -> L8a javax.net.ssl.SSLException -> L8c
            goto L6f
        L68:
            r7.setHandshakeSuccess()     // Catch: java.lang.Throwable -> L8a javax.net.ssl.SSLException -> L8c
            goto L6f
        L6c:
            r7.runDelegatedTasks()     // Catch: java.lang.Throwable -> L8a javax.net.ssl.SSLException -> L8c
        L6f:
            int r4 = r3.bytesProduced()     // Catch: java.lang.Throwable -> L8a javax.net.ssl.SSLException -> L8c
            if (r4 != 0) goto L76
            goto L84
        L76:
            int r4 = r3.bytesConsumed()     // Catch: java.lang.Throwable -> L8a javax.net.ssl.SSLException -> L8c
            if (r4 != 0) goto L6
            javax.net.ssl.SSLEngineResult$HandshakeStatus r3 = r3.getHandshakeStatus()     // Catch: java.lang.Throwable -> L8a javax.net.ssl.SSLException -> L8c
            javax.net.ssl.SSLEngineResult$HandshakeStatus r4 = javax.net.ssl.SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING     // Catch: java.lang.Throwable -> L8a javax.net.ssl.SSLException -> L8c
            if (r3 != r4) goto L6
        L84:
            if (r2 == 0) goto L89
            r2.release()
        L89:
            return
        L8a:
            r8 = move-exception
            goto L94
        L8c:
            r9 = move-exception
            r7.setHandshakeFailure(r8, r9)     // Catch: java.lang.Throwable -> L8a
            r7.flushIfNeeded(r8)     // Catch: java.lang.Throwable -> L8a
            throw r9     // Catch: java.lang.Throwable -> L8a
        L94:
            if (r2 == 0) goto L99
            r2.release()
        L99:
            goto L9b
        L9a:
            throw r8
        L9b:
            goto L9a
        */
        throw new UnsupportedOperationException("Method not decompiled: io.netty.handler.ssl.SslHandler.wrapNonAppData(io.netty.channel.ChannelHandlerContext, boolean):void");
    }

    public String applicationProtocol() {
        SSLSession session = engine().getSession();
        if (session instanceof ApplicationProtocolAccessor) {
            return ((ApplicationProtocolAccessor) session).getApplicationProtocol();
        }
        return null;
    }

    @Override // io.netty.channel.ChannelOutboundHandler
    public void bind(ChannelHandlerContext channelHandlerContext, SocketAddress socketAddress, ChannelPromise channelPromise) throws Exception {
        channelHandlerContext.bind(socketAddress, channelPromise);
    }

    @Override // io.netty.channel.ChannelInboundHandlerAdapter, io.netty.channel.ChannelInboundHandler
    public void channelActive(ChannelHandlerContext channelHandlerContext) throws Exception {
        if (!this.startTls && this.engine.getUseClientMode()) {
            handshake(null);
        }
        channelHandlerContext.fireChannelActive();
    }

    @Override // io.netty.handler.codec.ByteToMessageDecoder, io.netty.channel.ChannelInboundHandlerAdapter, io.netty.channel.ChannelInboundHandler
    public void channelInactive(ChannelHandlerContext channelHandlerContext) throws Exception {
        setHandshakeFailure(channelHandlerContext, CHANNEL_CLOSED, !this.outboundClosed);
        super.channelInactive(channelHandlerContext);
    }

    @Override // io.netty.handler.codec.ByteToMessageDecoder, io.netty.channel.ChannelInboundHandlerAdapter, io.netty.channel.ChannelInboundHandler
    public void channelReadComplete(ChannelHandlerContext channelHandlerContext) throws Exception {
        discardSomeReadBytes();
        flushIfNeeded(channelHandlerContext);
        readIfNeeded(channelHandlerContext);
        this.firedChannelRead = false;
        channelHandlerContext.fireChannelReadComplete();
    }

    public ChannelFuture close() {
        return close(this.ctx.newPromise());
    }

    @Override // io.netty.channel.ChannelOutboundHandler
    public void connect(ChannelHandlerContext channelHandlerContext, SocketAddress socketAddress, SocketAddress socketAddress2, ChannelPromise channelPromise) throws Exception {
        channelHandlerContext.connect(socketAddress, socketAddress2, channelPromise);
    }

    @Override // io.netty.handler.codec.ByteToMessageDecoder
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws SSLException {
        int i2;
        int i3;
        int i4 = byteBuf.readerIndex();
        int iWriterIndex = byteBuf.writerIndex();
        int i5 = this.packetLength;
        boolean z = false;
        if (i5 <= 0) {
            i2 = i4;
            i5 = 0;
        } else {
            if (iWriterIndex - i4 < i5) {
                return;
            }
            i2 = i4 + i5;
            this.packetLength = 0;
        }
        while (true) {
            if (i5 >= 18713 || (i3 = iWriterIndex - i2) < 5) {
                break;
            }
            int encryptedPacketLength = SslUtils.getEncryptedPacketLength(byteBuf, i2);
            if (encryptedPacketLength == -1) {
                z = true;
                break;
            }
            if (encryptedPacketLength > i3) {
                this.packetLength = encryptedPacketLength;
                break;
            }
            int i6 = i5 + encryptedPacketLength;
            if (i6 > 18713) {
                break;
            }
            i2 += encryptedPacketLength;
            i5 = i6;
        }
        if (i5 > 0) {
            byteBuf.skipBytes(i5);
            boolean zUnwrap = unwrap(channelHandlerContext, byteBuf, i4, i5);
            if (!this.firedChannelRead) {
                this.firedChannelRead = zUnwrap;
            }
        }
        if (z) {
            NotSslRecordException notSslRecordException = new NotSslRecordException("not an SSL/TLS record: " + ByteBufUtil.hexDump(byteBuf));
            byteBuf.skipBytes(byteBuf.readableBytes());
            channelHandlerContext.fireExceptionCaught((Throwable) notSslRecordException);
            setHandshakeFailure(channelHandlerContext, notSslRecordException);
        }
    }

    @Override // io.netty.channel.ChannelOutboundHandler
    public void deregister(ChannelHandlerContext channelHandlerContext, ChannelPromise channelPromise) throws Exception {
        channelHandlerContext.deregister(channelPromise);
    }

    @Override // io.netty.channel.ChannelOutboundHandler
    public void disconnect(ChannelHandlerContext channelHandlerContext, ChannelPromise channelPromise) throws Exception {
        closeOutboundAndChannel(channelHandlerContext, channelPromise, true);
    }

    public SSLEngine engine() {
        return this.engine;
    }

    @Override // io.netty.channel.ChannelInboundHandlerAdapter, io.netty.channel.ChannelHandlerAdapter, io.netty.channel.ChannelHandler, io.netty.channel.ChannelInboundHandler
    public void exceptionCaught(ChannelHandlerContext channelHandlerContext, Throwable th) throws Exception {
        if (!ignoreException(th)) {
            channelHandlerContext.fireExceptionCaught(th);
            return;
        }
        if (logger.isDebugEnabled()) {
            logger.debug("{} Swallowing a harmless 'connection reset by peer / broken pipe' error that occurred while writing close_notify in response to the peer's close_notify", channelHandlerContext.channel(), th);
        }
        if (channelHandlerContext.channel().isActive()) {
            channelHandlerContext.close();
        }
    }

    @Override // io.netty.channel.ChannelOutboundHandler
    public void flush(ChannelHandlerContext channelHandlerContext) throws Exception {
        if (this.startTls && !this.sentFirstMessage) {
            this.sentFirstMessage = true;
            this.pendingUnencryptedWrites.removeAndWriteAll();
            return;
        }
        if (this.pendingUnencryptedWrites.isEmpty()) {
            this.pendingUnencryptedWrites.add(Unpooled.EMPTY_BUFFER, channelHandlerContext.newPromise());
        }
        if (!this.handshakePromise.isDone()) {
            this.flushedBeforeHandshake = true;
        }
        try {
            wrap(channelHandlerContext, false);
        } finally {
            channelHandlerContext.flush();
        }
    }

    public long getCloseNotifyTimeoutMillis() {
        return this.closeNotifyTimeoutMillis;
    }

    public long getHandshakeTimeoutMillis() {
        return this.handshakeTimeoutMillis;
    }

    @Override // io.netty.channel.ChannelHandlerAdapter, io.netty.channel.ChannelHandler
    public void handlerAdded(ChannelHandlerContext channelHandlerContext) throws Exception {
        this.ctx = channelHandlerContext;
        this.pendingUnencryptedWrites = new PendingWriteQueue(channelHandlerContext);
        if (channelHandlerContext.channel().isActive() && this.engine.getUseClientMode()) {
            handshake(null);
        }
    }

    @Override // io.netty.handler.codec.ByteToMessageDecoder
    public void handlerRemoved0(ChannelHandlerContext channelHandlerContext) throws Exception {
        if (!this.pendingUnencryptedWrites.isEmpty()) {
            this.pendingUnencryptedWrites.removeAndFailAll(new ChannelException("Pending write on removal of SslHandler"));
        }
        SSLEngine sSLEngine = this.engine;
        if (sSLEngine instanceof OpenSslEngine) {
            ((OpenSslEngine) sSLEngine).shutdown();
        }
    }

    public Future<Channel> handshakeFuture() {
        return this.handshakePromise;
    }

    @Override // io.netty.channel.ChannelOutboundHandler
    public void read(ChannelHandlerContext channelHandlerContext) throws Exception {
        if (!this.handshakePromise.isDone()) {
            this.readDuringHandshake = true;
        }
        channelHandlerContext.read();
    }

    public Future<Channel> renegotiate() {
        ChannelHandlerContext channelHandlerContext = this.ctx;
        if (channelHandlerContext != null) {
            return renegotiate(channelHandlerContext.executor().newPromise());
        }
        throw new IllegalStateException();
    }

    public void setCloseNotifyTimeout(long j2, TimeUnit timeUnit) {
        if (timeUnit == null) {
            throw new NullPointerException("unit");
        }
        setCloseNotifyTimeoutMillis(timeUnit.toMillis(j2));
    }

    public void setCloseNotifyTimeoutMillis(long j2) {
        if (j2 >= 0) {
            this.closeNotifyTimeoutMillis = j2;
            return;
        }
        throw new IllegalArgumentException("closeNotifyTimeoutMillis: " + j2 + " (expected: >= 0)");
    }

    public void setHandshakeTimeout(long j2, TimeUnit timeUnit) {
        if (timeUnit == null) {
            throw new NullPointerException("unit");
        }
        setHandshakeTimeoutMillis(timeUnit.toMillis(j2));
    }

    public void setHandshakeTimeoutMillis(long j2) {
        if (j2 >= 0) {
            this.handshakeTimeoutMillis = j2;
            return;
        }
        throw new IllegalArgumentException("handshakeTimeoutMillis: " + j2 + " (expected: >= 0)");
    }

    public Future<Channel> sslCloseFuture() {
        return this.sslCloseFuture;
    }

    @Override // io.netty.channel.ChannelOutboundHandler
    public void write(ChannelHandlerContext channelHandlerContext, Object obj, ChannelPromise channelPromise) throws Exception {
        if (obj instanceof ByteBuf) {
            this.pendingUnencryptedWrites.add(obj, channelPromise);
        } else {
            channelPromise.setFailure((Throwable) new UnsupportedMessageTypeException(obj, (Class<?>[]) new Class[]{ByteBuf.class}));
        }
    }

    public SslHandler(SSLEngine sSLEngine, boolean z) {
        this(sSLEngine, z, ImmediateExecutor.INSTANCE);
    }

    private void setHandshakeFailure(ChannelHandlerContext channelHandlerContext, Throwable th, boolean z) {
        this.engine.closeOutbound();
        if (z) {
            try {
                this.engine.closeInbound();
            } catch (SSLException e2) {
                String message = e2.getMessage();
                if (message == null || !message.contains("possible truncation attack")) {
                    logger.debug("{} SSLEngine.closeInbound() raised an exception.", channelHandlerContext.channel(), e2);
                }
            }
        }
        notifyHandshakeFailure(th);
        this.pendingUnencryptedWrites.removeAndFailAll(th);
    }

    public ChannelFuture close(final ChannelPromise channelPromise) {
        final ChannelHandlerContext channelHandlerContext = this.ctx;
        channelHandlerContext.executor().execute(new Runnable() { // from class: io.netty.handler.ssl.SslHandler.1
            @Override // java.lang.Runnable
            public void run() {
                SslHandler.this.outboundClosed = true;
                SslHandler.this.engine.closeOutbound();
                try {
                    SslHandler.this.write(channelHandlerContext, Unpooled.EMPTY_BUFFER, channelPromise);
                    SslHandler.this.flush(channelHandlerContext);
                } catch (Exception e2) {
                    if (channelPromise.tryFailure(e2)) {
                        return;
                    }
                    SslHandler.logger.warn("{} flush() raised a masked exception.", channelHandlerContext.channel(), e2);
                }
            }
        });
        return channelPromise;
    }

    @Deprecated
    public SslHandler(SSLEngine sSLEngine, Executor executor) {
        this(sSLEngine, false, executor);
    }

    @Deprecated
    public SslHandler(SSLEngine sSLEngine, boolean z, Executor executor) {
        this.singleBuffer = new ByteBuffer[1];
        this.handshakePromise = new LazyChannelPromise();
        this.sslCloseFuture = new LazyChannelPromise();
        this.handshakeTimeoutMillis = 10000L;
        this.closeNotifyTimeoutMillis = 3000L;
        if (sSLEngine == null) {
            throw new NullPointerException("engine");
        }
        if (executor != null) {
            this.engine = sSLEngine;
            this.delegatedTaskExecutor = executor;
            this.startTls = z;
            this.maxPacketBufferSize = sSLEngine.getSession().getPacketBufferSize();
            boolean z2 = sSLEngine instanceof OpenSslEngine;
            this.wantsDirectBuffer = z2;
            this.wantsLargeOutboundNetworkBuffer = !z2;
            setCumulator(z2 ? ByteToMessageDecoder.COMPOSITE_CUMULATOR : ByteToMessageDecoder.MERGE_CUMULATOR);
            return;
        }
        throw new NullPointerException("delegatedTaskExecutor");
    }

    @Override // io.netty.channel.ChannelOutboundHandler
    public void close(ChannelHandlerContext channelHandlerContext, ChannelPromise channelPromise) throws Exception {
        closeOutboundAndChannel(channelHandlerContext, channelPromise, false);
    }

    public Future<Channel> renegotiate(final Promise<Channel> promise) {
        if (promise != null) {
            ChannelHandlerContext channelHandlerContext = this.ctx;
            if (channelHandlerContext != null) {
                EventExecutor eventExecutorExecutor = channelHandlerContext.executor();
                if (!eventExecutorExecutor.inEventLoop()) {
                    eventExecutorExecutor.execute(new Runnable() { // from class: io.netty.handler.ssl.SslHandler.3
                        @Override // java.lang.Runnable
                        public void run() {
                            SslHandler.this.handshake(promise);
                        }
                    });
                    return promise;
                }
                handshake(promise);
                return promise;
            }
            throw new IllegalStateException();
        }
        throw new NullPointerException("promise");
    }

    private SSLEngineResult wrap(ByteBufAllocator byteBufAllocator, SSLEngine sSLEngine, ByteBuf byteBuf, ByteBuf byteBuf2) throws Throwable {
        ByteBuf byteBufDirectBuffer;
        ByteBuffer[] byteBufferArrNioBuffers;
        SSLEngineResult sSLEngineResultWrap;
        try {
            int i2 = byteBuf.readerIndex();
            int i3 = byteBuf.readableBytes();
            if (!byteBuf.isDirect() && this.wantsDirectBuffer) {
                byteBufDirectBuffer = byteBufAllocator.directBuffer(i3);
                try {
                    byteBufDirectBuffer.writeBytes(byteBuf, i2, i3);
                    byteBufferArrNioBuffers = this.singleBuffer;
                    byteBufferArrNioBuffers[0] = byteBufDirectBuffer.internalNioBuffer(0, i3);
                } catch (Throwable th) {
                    th = th;
                    this.singleBuffer[0] = null;
                    if (byteBufDirectBuffer != null) {
                        byteBufDirectBuffer.release();
                    }
                    throw th;
                }
            } else {
                if (!(byteBuf instanceof CompositeByteBuf) && byteBuf.nioBufferCount() == 1) {
                    ByteBuffer[] byteBufferArr = this.singleBuffer;
                    byteBufferArr[0] = byteBuf.internalNioBuffer(i2, i3);
                    byteBufferArrNioBuffers = byteBufferArr;
                } else {
                    byteBufferArrNioBuffers = byteBuf.nioBuffers();
                }
                byteBufDirectBuffer = null;
            }
            while (true) {
                sSLEngineResultWrap = sSLEngine.wrap(byteBufferArrNioBuffers, byteBuf2.nioBuffer(byteBuf2.writerIndex(), byteBuf2.writableBytes()));
                byteBuf.skipBytes(sSLEngineResultWrap.bytesConsumed());
                byteBuf2.writerIndex(byteBuf2.writerIndex() + sSLEngineResultWrap.bytesProduced());
                if (AnonymousClass9.$SwitchMap$javax$net$ssl$SSLEngineResult$Status[sSLEngineResultWrap.getStatus().ordinal()] != 1) {
                    break;
                }
                byteBuf2.ensureWritable(this.maxPacketBufferSize);
            }
            this.singleBuffer[0] = null;
            if (byteBufDirectBuffer != null) {
                byteBufDirectBuffer.release();
            }
            return sSLEngineResultWrap;
        } catch (Throwable th2) {
            th = th2;
            byteBufDirectBuffer = null;
        }
    }

    private SSLEngineResult unwrap(SSLEngine sSLEngine, ByteBuf byteBuf, int i2, int i3, ByteBuf byteBuf2) throws SSLException {
        SSLEngineResult sSLEngineResultUnwrap;
        int iNioBufferCount = byteBuf.nioBufferCount();
        int iWriterIndex = byteBuf2.writerIndex();
        if ((sSLEngine instanceof OpenSslEngine) && iNioBufferCount > 1) {
            OpenSslEngine openSslEngine = (OpenSslEngine) sSLEngine;
            try {
                this.singleBuffer[0] = toByteBuffer(byteBuf2, iWriterIndex, byteBuf2.writableBytes());
                sSLEngineResultUnwrap = openSslEngine.unwrap(byteBuf.nioBuffers(i2, i3), this.singleBuffer);
                byteBuf2.writerIndex(sSLEngineResultUnwrap.bytesProduced() + iWriterIndex);
            } finally {
                this.singleBuffer[0] = null;
            }
        } else {
            sSLEngineResultUnwrap = sSLEngine.unwrap(toByteBuffer(byteBuf, i2, i3), toByteBuffer(byteBuf2, iWriterIndex, byteBuf2.writableBytes()));
        }
        byteBuf2.writerIndex(iWriterIndex + sSLEngineResultUnwrap.bytesProduced());
        return sSLEngineResultUnwrap;
    }
}
