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.Objects;
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 i) {
        ByteBufAllocator byteBufAllocatorAlloc = channelHandlerContext.alloc();
        return this.wantsDirectBuffer ? byteBufAllocatorAlloc.directBuffer(i) : byteBufAllocatorAlloc.buffer(i);
    }

    private ByteBuf allocateOutNetBuf(ChannelHandlerContext channelHandlerContext, int i) {
        return this.wantsLargeOutboundNetworkBuffer ? allocate(channelHandlerContext, this.maxPacketBufferSize) : allocate(channelHandlerContext, Math.min(i + 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 j = this.handshakeTimeoutMillis;
        if (j <= 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);
            }
        }, j, 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());
        InternalLogger internalLogger = logger;
        if (internalLogger.isDebugEnabled()) {
            internalLogger.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 i, int i2) {
        return byteBuf.nioBufferCount() == 1 ? byteBuf.internalNioBuffer(i, i2) : byteBuf.nioBuffer(i, i2);
    }

    /* JADX WARN: Finally extract failed */
    private boolean unwrap(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, int i, int i2) throws SSLException {
        SSLEngineResult.HandshakeStatus handshakeStatus;
        int i3 = i2;
        ByteBuf byteBufAllocate = allocate(channelHandlerContext, i2);
        boolean z = false;
        boolean z2 = false;
        boolean z3 = false;
        int i4 = i;
        while (true) {
            try {
                try {
                    SSLEngineResult sSLEngineResultUnwrap = unwrap(this.engine, byteBuf, i4, i3, byteBufAllocate);
                    SSLEngineResult.Status status = sSLEngineResultUnwrap.getStatus();
                    handshakeStatus = sSLEngineResultUnwrap.getHandshakeStatus();
                    int iBytesProduced = sSLEngineResultUnwrap.bytesProduced();
                    int iBytesConsumed = sSLEngineResultUnwrap.bytesConsumed();
                    i4 += iBytesConsumed;
                    i3 -= iBytesConsumed;
                    int i5 = AnonymousClass9.$SwitchMap$javax$net$ssl$SSLEngineResult$Status[status.ordinal()];
                    if (i5 != 1) {
                        if (i5 == 2) {
                            z2 = true;
                        }
                        int i6 = AnonymousClass9.$SwitchMap$javax$net$ssl$SSLEngineResult$HandshakeStatus[handshakeStatus.ordinal()];
                        if (i6 != 1) {
                            if (i6 == 2) {
                                setHandshakeSuccess();
                            } else if (i6 != 3) {
                                if (i6 == 4) {
                                    wrapNonAppData(channelHandlerContext, true);
                                } else if (i6 != 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 i7 = byteBufAllocate.readableBytes();
                        if (i7 > 0) {
                            channelHandlerContext.fireChannelRead((Object) byteBufAllocate);
                            z3 = true;
                        } else {
                            byteBufAllocate.release();
                        }
                        byteBufAllocate = allocate(channelHandlerContext, this.engine.getSession().getApplicationBufferSize() - i7);
                    }
                } 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:22:0x0049, code lost:
    
        finishWrap(r13, r3, r2, r14, r11);
     */
    /* JADX WARN: Code restructure failed: missing block: B:23:0x0051, code lost:
    
        return;
     */
    /* JADX WARN: Code restructure failed: missing block: B:27:0x0062, code lost:
    
        if (r5 == 2) goto L37;
     */
    /* JADX WARN: Code restructure failed: missing block: B:29:0x0065, code lost:
    
        if (r5 == 3) goto L38;
     */
    /* JADX WARN: Code restructure failed: missing block: B:31:0x0068, code lost:
    
        if (r5 == 4) goto L68;
     */
    /* JADX WARN: Code restructure failed: missing block: B:33:0x006b, code lost:
    
        if (r5 != 5) goto L35;
     */
    /* JADX WARN: Code restructure failed: missing block: B:34:0x006d, code lost:
    
        r11 = true;
     */
    /* JADX WARN: Code restructure failed: missing block: B:36:0x0089, code lost:
    
        throw new java.lang.IllegalStateException("Unknown handshake status: " + r4.getHandshakeStatus());
     */
    /* JADX WARN: Code restructure failed: missing block: B:37:0x008a, code lost:
    
        setHandshakeSuccess();
     */
    /* JADX WARN: Code restructure failed: missing block: B:38:0x008d, 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 -> Lad javax.net.ssl.SSLException -> Lb1
            java.lang.Object r2 = r2.current()     // Catch: java.lang.Throwable -> Lad javax.net.ssl.SSLException -> Lb1
            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 -> Lad javax.net.ssl.SSLException -> Lb1
            if (r4 != 0) goto L24
            int r3 = r2.readableBytes()     // Catch: java.lang.Throwable -> Lad javax.net.ssl.SSLException -> Lb1
            io.netty.buffer.ByteBuf r3 = r12.allocateOutNetBuf(r13, r3)     // Catch: java.lang.Throwable -> Lad javax.net.ssl.SSLException -> Lb1
            goto L25
        L24:
            r3 = r4
        L25:
            javax.net.ssl.SSLEngine r4 = r12.engine     // Catch: java.lang.Throwable -> La8 javax.net.ssl.SSLException -> Laa
            javax.net.ssl.SSLEngineResult r4 = r12.wrap(r0, r4, r2, r3)     // Catch: java.lang.Throwable -> La8 javax.net.ssl.SSLException -> Laa
            boolean r2 = r2.isReadable()     // Catch: java.lang.Throwable -> La8 javax.net.ssl.SSLException -> Laa
            if (r2 != 0) goto L38
            io.netty.channel.PendingWriteQueue r2 = r12.pendingUnencryptedWrites     // Catch: java.lang.Throwable -> La8 javax.net.ssl.SSLException -> Laa
            io.netty.channel.ChannelPromise r2 = r2.remove()     // Catch: java.lang.Throwable -> La8 javax.net.ssl.SSLException -> Laa
            goto L39
        L38:
            r2 = r1
        L39:
            javax.net.ssl.SSLEngineResult$Status r5 = r4.getStatus()     // Catch: java.lang.Throwable -> La2 javax.net.ssl.SSLException -> La5
            javax.net.ssl.SSLEngineResult$Status r6 = javax.net.ssl.SSLEngineResult.Status.CLOSED     // Catch: java.lang.Throwable -> La2 javax.net.ssl.SSLException -> La5
            if (r5 != r6) goto L52
            io.netty.channel.PendingWriteQueue r0 = r12.pendingUnencryptedWrites     // Catch: java.lang.Throwable -> La2 javax.net.ssl.SSLException -> La5
            javax.net.ssl.SSLException r1 = io.netty.handler.ssl.SslHandler.SSLENGINE_CLOSED     // Catch: java.lang.Throwable -> La2 javax.net.ssl.SSLException -> La5
            r0.removeAndFailAll(r1)     // Catch: java.lang.Throwable -> La2 javax.net.ssl.SSLException -> La5
            r11 = 0
        L49:
            r6 = r12
            r7 = r13
            r8 = r3
            r9 = r2
            r10 = r14
            r6.finishWrap(r7, r8, r9, r10, r11)
            return
        L52:
            int[] r5 = io.netty.handler.ssl.SslHandler.AnonymousClass9.$SwitchMap$javax$net$ssl$SSLEngineResult$HandshakeStatus     // Catch: java.lang.Throwable -> La2 javax.net.ssl.SSLException -> La5
            javax.net.ssl.SSLEngineResult$HandshakeStatus r6 = r4.getHandshakeStatus()     // Catch: java.lang.Throwable -> La2 javax.net.ssl.SSLException -> La5
            int r6 = r6.ordinal()     // Catch: java.lang.Throwable -> La2 javax.net.ssl.SSLException -> La5
            r5 = r5[r6]     // Catch: java.lang.Throwable -> La2 javax.net.ssl.SSLException -> La5
            r6 = 1
            if (r5 == r6) goto L9b
            r6 = 2
            if (r5 == r6) goto L8a
            r6 = 3
            if (r5 == r6) goto L8d
            r6 = 4
            if (r5 == r6) goto L90
            r0 = 5
            if (r5 != r0) goto L6f
            r11 = 1
            goto L49
        L6f:
            java.lang.IllegalStateException r0 = new java.lang.IllegalStateException     // Catch: java.lang.Throwable -> La2 javax.net.ssl.SSLException -> La5
            java.lang.StringBuilder r1 = new java.lang.StringBuilder     // Catch: java.lang.Throwable -> La2 javax.net.ssl.SSLException -> La5
            r1.<init>()     // Catch: java.lang.Throwable -> La2 javax.net.ssl.SSLException -> La5
            java.lang.String r5 = "Unknown handshake status: "
            r1.append(r5)     // Catch: java.lang.Throwable -> La2 javax.net.ssl.SSLException -> La5
            javax.net.ssl.SSLEngineResult$HandshakeStatus r4 = r4.getHandshakeStatus()     // Catch: java.lang.Throwable -> La2 javax.net.ssl.SSLException -> La5
            r1.append(r4)     // Catch: java.lang.Throwable -> La2 javax.net.ssl.SSLException -> La5
            java.lang.String r1 = r1.toString()     // Catch: java.lang.Throwable -> La2 javax.net.ssl.SSLException -> La5
            r0.<init>(r1)     // Catch: java.lang.Throwable -> La2 javax.net.ssl.SSLException -> La5
            throw r0     // Catch: java.lang.Throwable -> La2 javax.net.ssl.SSLException -> La5
        L8a:
            r12.setHandshakeSuccess()     // Catch: java.lang.Throwable -> La2 javax.net.ssl.SSLException -> La5
        L8d:
            r12.setHandshakeSuccessIfStillHandshaking()     // Catch: java.lang.Throwable -> La2 javax.net.ssl.SSLException -> La5
        L90:
            r11 = 0
            r6 = r12
            r7 = r13
            r8 = r3
            r9 = r2
            r10 = r14
            r6.finishWrap(r7, r8, r9, r10, r11)     // Catch: java.lang.Throwable -> La2 javax.net.ssl.SSLException -> La5
            goto L5
        L9b:
            r12.runDelegatedTasks()     // Catch: java.lang.Throwable -> La2 javax.net.ssl.SSLException -> La5
            r5 = r2
            r4 = r3
            goto L7
        La2:
            r0 = move-exception
            r4 = r2
            goto Lb6
        La5:
            r0 = move-exception
            r5 = r2
            goto Lab
        La8:
            r0 = move-exception
            goto Laf
        Laa:
            r0 = move-exception
        Lab:
            r4 = r3
            goto Lb2
        Lad:
            r0 = move-exception
            r3 = r4
        Laf:
            r4 = r5
            goto Lb6
        Lb1:
            r0 = move-exception
        Lb2:
            r12.setHandshakeFailure(r13, r0)     // Catch: java.lang.Throwable -> Lad
            throw r0     // Catch: java.lang.Throwable -> Lad
        Lb6:
            r6 = 0
            r1 = r12
            r2 = r13
            r5 = r14
            r1.finishWrap(r2, r3, r4, r5, r6)
            throw r0
        */
        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:
            throw r8
        */
        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 i;
        int i2;
        int i3 = byteBuf.readerIndex();
        int iWriterIndex = byteBuf.writerIndex();
        int i4 = this.packetLength;
        boolean z = false;
        if (i4 <= 0) {
            i = i3;
            i4 = 0;
        } else {
            if (iWriterIndex - i3 < i4) {
                return;
            }
            i = i3 + i4;
            this.packetLength = 0;
        }
        while (true) {
            if (i4 >= 18713 || (i2 = iWriterIndex - i) < 5) {
                break;
            }
            int encryptedPacketLength = SslUtils.getEncryptedPacketLength(byteBuf, i);
            if (encryptedPacketLength == -1) {
                z = true;
                break;
            }
            if (encryptedPacketLength > i2) {
                this.packetLength = encryptedPacketLength;
                break;
            }
            int i5 = i4 + encryptedPacketLength;
            if (i5 > 18713) {
                break;
            }
            i += encryptedPacketLength;
            i4 = i5;
        }
        if (i4 > 0) {
            byteBuf.skipBytes(i4);
            boolean zUnwrap = unwrap(channelHandlerContext, byteBuf, i3, i4);
            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;
        }
        InternalLogger internalLogger = logger;
        if (internalLogger.isDebugEnabled()) {
            internalLogger.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 j, TimeUnit timeUnit) {
        Objects.requireNonNull(timeUnit, "unit");
        setCloseNotifyTimeoutMillis(timeUnit.toMillis(j));
    }

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

    public void setHandshakeTimeout(long j, TimeUnit timeUnit) {
        Objects.requireNonNull(timeUnit, "unit");
        setHandshakeTimeoutMillis(timeUnit.toMillis(j));
    }

    public void setHandshakeTimeoutMillis(long j) {
        if (j >= 0) {
            this.handshakeTimeoutMillis = j;
            return;
        }
        throw new IllegalArgumentException("handshakeTimeoutMillis: " + j + " (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;
        Objects.requireNonNull(sSLEngine, "engine");
        Objects.requireNonNull(executor, "delegatedTaskExecutor");
        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);
    }

    @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) {
        Objects.requireNonNull(promise, "promise");
        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();
    }

    private SSLEngineResult wrap(ByteBufAllocator byteBufAllocator, SSLEngine sSLEngine, ByteBuf byteBuf, ByteBuf byteBuf2) throws Throwable {
        ByteBuf byteBufDirectBuffer;
        ByteBuffer[] byteBufferArrNioBuffers;
        SSLEngineResult sSLEngineResultWrap;
        try {
            int i = byteBuf.readerIndex();
            int i2 = byteBuf.readableBytes();
            if (!byteBuf.isDirect() && this.wantsDirectBuffer) {
                byteBufDirectBuffer = byteBufAllocator.directBuffer(i2);
                try {
                    byteBufDirectBuffer.writeBytes(byteBuf, i, i2);
                    byteBufferArrNioBuffers = this.singleBuffer;
                    byteBufferArrNioBuffers[0] = byteBufDirectBuffer.internalNioBuffer(0, i2);
                } 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(i, i2);
                    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 i, int i2, 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(i, i2), this.singleBuffer);
                byteBuf2.writerIndex(sSLEngineResultUnwrap.bytesProduced() + iWriterIndex);
            } finally {
                this.singleBuffer[0] = null;
            }
        } else {
            sSLEngineResultUnwrap = sSLEngine.unwrap(toByteBuffer(byteBuf, i, i2), toByteBuffer(byteBuf2, iWriterIndex, byteBuf2.writableBytes()));
        }
        byteBuf2.writerIndex(iWriterIndex + sSLEngineResultUnwrap.bytesProduced());
        return sSLEngineResultUnwrap;
    }
}
