package io.netty.handler.ssl;

import g.a.a.a.a;
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.AbstractCoalescingBufferQueue;
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.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.UnsupportedMessageTypeException;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.ReferenceCounted;
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;

/* JADX INFO: loaded from: classes.dex */
public class SslHandler extends ByteToMessageDecoder implements ChannelOutboundHandler {
    public static final /* synthetic */ boolean $assertionsDisabled = false;
    private static final int MAX_PLAINTEXT_LENGTH = 16384;
    private boolean closeNotify;
    private volatile long closeNotifyFlushTimeoutMillis;
    private volatile long closeNotifyReadTimeoutMillis;
    private volatile ChannelHandlerContext ctx;
    private final Executor delegatedTaskExecutor;
    private final SSLEngine engine;
    private final SslEngineType engineType;
    private boolean firedChannelRead;
    private boolean flushedBeforeHandshake;
    private Promise<Channel> handshakePromise;
    private boolean handshakeStarted;
    private volatile long handshakeTimeoutMillis;
    private final boolean jdkCompatibilityMode;
    private boolean needsFlush;
    private boolean outboundClosed;
    private int packetLength;
    private SslHandlerCoalescingBufferQueue pendingUnencryptedWrites;
    private boolean readDuringHandshake;
    private boolean sentFirstMessage;
    private final ByteBuffer[] singleBuffer;
    private final LazyChannelPromise sslClosePromise;
    private final boolean startTls;
    public volatile int wrapDataSize;
    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) a.N(SslHandler.class, "channelInactive(...)");

    /* JADX INFO: renamed from: io.netty.handler.ssl.SslHandler$10, reason: invalid class name */
    public static /* synthetic */ class AnonymousClass10 {
        public static final /* synthetic */ int[] $SwitchMap$javax$net$ssl$SSLEngineResult$HandshakeStatus;
        public 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) {
            }
        }
    }

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

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

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

    /* JADX WARN: Enum visitor error
    jadx.core.utils.exceptions.JadxRuntimeException: Init of enum field 'TCNATIVE' uses external variables
    	at jadx.core.dex.visitors.EnumVisitor.createEnumFieldByConstructor(EnumVisitor.java:451)
    	at jadx.core.dex.visitors.EnumVisitor.processEnumFieldByRegister(EnumVisitor.java:395)
    	at jadx.core.dex.visitors.EnumVisitor.extractEnumFieldsFromFilledArray(EnumVisitor.java:324)
    	at jadx.core.dex.visitors.EnumVisitor.extractEnumFieldsFromInsn(EnumVisitor.java:262)
    	at jadx.core.dex.visitors.EnumVisitor.convertToEnum(EnumVisitor.java:151)
    	at jadx.core.dex.visitors.EnumVisitor.visit(EnumVisitor.java:100)
     */
    /* JADX WARN: Failed to restore enum class, 'enum' modifier and super class removed */
    public static abstract class SslEngineType {
        private static final /* synthetic */ SslEngineType[] $VALUES;
        public static final SslEngineType CONSCRYPT;
        public static final SslEngineType JDK;
        public static final SslEngineType TCNATIVE;
        public final ByteToMessageDecoder.Cumulator cumulator;
        public final boolean wantsDirectBuffer;

        /* JADX WARN: Multi-variable type inference failed */
        static {
            ByteToMessageDecoder.Cumulator cumulator = ByteToMessageDecoder.COMPOSITE_CUMULATOR;
            SslEngineType sslEngineType = new SslEngineType("TCNATIVE", 0, true, cumulator) { // from class: io.netty.handler.ssl.SslHandler.SslEngineType.1
                @Override // io.netty.handler.ssl.SslHandler.SslEngineType
                public int calculatePendingData(SslHandler sslHandler, int i2) {
                    int iSslPending = ((ReferenceCountedOpenSslEngine) sslHandler.engine).sslPending();
                    return iSslPending > 0 ? iSslPending : i2;
                }

                @Override // io.netty.handler.ssl.SslHandler.SslEngineType
                public int calculateWrapBufferCapacity(SslHandler sslHandler, int i2, int i3) {
                    return ((ReferenceCountedOpenSslEngine) sslHandler.engine).calculateMaxLengthForWrap(i2, i3);
                }

                @Override // io.netty.handler.ssl.SslHandler.SslEngineType
                public int getPacketBufferSize(SslHandler sslHandler) {
                    return ((ReferenceCountedOpenSslEngine) sslHandler.engine).maxEncryptedPacketLength0();
                }

                @Override // io.netty.handler.ssl.SslHandler.SslEngineType
                public boolean jdkCompatibilityMode(SSLEngine sSLEngine) {
                    return ((ReferenceCountedOpenSslEngine) sSLEngine).jdkCompatibilityMode;
                }

                @Override // io.netty.handler.ssl.SslHandler.SslEngineType
                public SSLEngineResult unwrap(SslHandler sslHandler, ByteBuf byteBuf, int i2, int i3, ByteBuf byteBuf2) throws SSLException {
                    SSLEngineResult sSLEngineResultUnwrap;
                    int iNioBufferCount = byteBuf.nioBufferCount();
                    int iWriterIndex = byteBuf2.writerIndex();
                    if (iNioBufferCount > 1) {
                        ReferenceCountedOpenSslEngine referenceCountedOpenSslEngine = (ReferenceCountedOpenSslEngine) sslHandler.engine;
                        try {
                            sslHandler.singleBuffer[0] = SslHandler.toByteBuffer(byteBuf2, iWriterIndex, byteBuf2.writableBytes());
                            sSLEngineResultUnwrap = referenceCountedOpenSslEngine.unwrap(byteBuf.nioBuffers(i2, i3), sslHandler.singleBuffer);
                        } finally {
                            sslHandler.singleBuffer[0] = null;
                        }
                    } else {
                        sSLEngineResultUnwrap = sslHandler.engine.unwrap(SslHandler.toByteBuffer(byteBuf, i2, i3), SslHandler.toByteBuffer(byteBuf2, iWriterIndex, byteBuf2.writableBytes()));
                    }
                    byteBuf2.writerIndex(sSLEngineResultUnwrap.bytesProduced() + iWriterIndex);
                    return sSLEngineResultUnwrap;
                }
            };
            TCNATIVE = sslEngineType;
            SslEngineType sslEngineType2 = new SslEngineType("CONSCRYPT", 1 == true ? 1 : 0, 1 == true ? 1 : 0, cumulator) { // from class: io.netty.handler.ssl.SslHandler.SslEngineType.2
                @Override // io.netty.handler.ssl.SslHandler.SslEngineType
                public int calculatePendingData(SslHandler sslHandler, int i2) {
                    return i2;
                }

                @Override // io.netty.handler.ssl.SslHandler.SslEngineType
                public int calculateWrapBufferCapacity(SslHandler sslHandler, int i2, int i3) {
                    return ((ConscryptAlpnSslEngine) sslHandler.engine).calculateOutNetBufSize(i2, i3);
                }

                @Override // io.netty.handler.ssl.SslHandler.SslEngineType
                public boolean jdkCompatibilityMode(SSLEngine sSLEngine) {
                    return true;
                }

                @Override // io.netty.handler.ssl.SslHandler.SslEngineType
                public SSLEngineResult unwrap(SslHandler sslHandler, ByteBuf byteBuf, int i2, int i3, ByteBuf byteBuf2) throws SSLException {
                    SSLEngineResult sSLEngineResultUnwrap;
                    int iNioBufferCount = byteBuf.nioBufferCount();
                    int iWriterIndex = byteBuf2.writerIndex();
                    if (iNioBufferCount > 1) {
                        try {
                            sslHandler.singleBuffer[0] = SslHandler.toByteBuffer(byteBuf2, iWriterIndex, byteBuf2.writableBytes());
                            sSLEngineResultUnwrap = ((ConscryptAlpnSslEngine) sslHandler.engine).unwrap(byteBuf.nioBuffers(i2, i3), sslHandler.singleBuffer);
                        } finally {
                            sslHandler.singleBuffer[0] = null;
                        }
                    } else {
                        sSLEngineResultUnwrap = sslHandler.engine.unwrap(SslHandler.toByteBuffer(byteBuf, i2, i3), SslHandler.toByteBuffer(byteBuf2, iWriterIndex, byteBuf2.writableBytes()));
                    }
                    byteBuf2.writerIndex(sSLEngineResultUnwrap.bytesProduced() + iWriterIndex);
                    return sSLEngineResultUnwrap;
                }
            };
            CONSCRYPT = sslEngineType2;
            SslEngineType sslEngineType3 = new SslEngineType("JDK", 2, 0 == true ? 1 : 0, ByteToMessageDecoder.MERGE_CUMULATOR) { // from class: io.netty.handler.ssl.SslHandler.SslEngineType.3
                @Override // io.netty.handler.ssl.SslHandler.SslEngineType
                public int calculatePendingData(SslHandler sslHandler, int i2) {
                    return i2;
                }

                @Override // io.netty.handler.ssl.SslHandler.SslEngineType
                public int calculateWrapBufferCapacity(SslHandler sslHandler, int i2, int i3) {
                    return sslHandler.engine.getSession().getPacketBufferSize();
                }

                @Override // io.netty.handler.ssl.SslHandler.SslEngineType
                public boolean jdkCompatibilityMode(SSLEngine sSLEngine) {
                    return true;
                }

                @Override // io.netty.handler.ssl.SslHandler.SslEngineType
                public SSLEngineResult unwrap(SslHandler sslHandler, ByteBuf byteBuf, int i2, int i3, ByteBuf byteBuf2) throws SSLException {
                    int iPosition;
                    int iWriterIndex = byteBuf2.writerIndex();
                    ByteBuffer byteBuffer = SslHandler.toByteBuffer(byteBuf, i2, i3);
                    int iPosition2 = byteBuffer.position();
                    SSLEngineResult sSLEngineResultUnwrap = sslHandler.engine.unwrap(byteBuffer, SslHandler.toByteBuffer(byteBuf2, iWriterIndex, byteBuf2.writableBytes()));
                    byteBuf2.writerIndex(sSLEngineResultUnwrap.bytesProduced() + iWriterIndex);
                    return (sSLEngineResultUnwrap.bytesConsumed() != 0 || (iPosition = byteBuffer.position() - iPosition2) == sSLEngineResultUnwrap.bytesConsumed()) ? sSLEngineResultUnwrap : new SSLEngineResult(sSLEngineResultUnwrap.getStatus(), sSLEngineResultUnwrap.getHandshakeStatus(), iPosition, sSLEngineResultUnwrap.bytesProduced());
                }
            };
            JDK = sslEngineType3;
            $VALUES = new SslEngineType[]{sslEngineType, sslEngineType2, sslEngineType3};
        }

        private SslEngineType(String str, int i2, boolean z2, ByteToMessageDecoder.Cumulator cumulator) {
            this.wantsDirectBuffer = z2;
            this.cumulator = cumulator;
        }

        public static SslEngineType forEngine(SSLEngine sSLEngine) {
            return sSLEngine instanceof ReferenceCountedOpenSslEngine ? TCNATIVE : sSLEngine instanceof ConscryptAlpnSslEngine ? CONSCRYPT : JDK;
        }

        public static SslEngineType valueOf(String str) {
            return (SslEngineType) Enum.valueOf(SslEngineType.class, str);
        }

        public static SslEngineType[] values() {
            return (SslEngineType[]) $VALUES.clone();
        }

        public abstract int calculatePendingData(SslHandler sslHandler, int i2);

        public abstract int calculateWrapBufferCapacity(SslHandler sslHandler, int i2, int i3);

        public int getPacketBufferSize(SslHandler sslHandler) {
            return sslHandler.engine.getSession().getPacketBufferSize();
        }

        public abstract boolean jdkCompatibilityMode(SSLEngine sSLEngine);

        public abstract SSLEngineResult unwrap(SslHandler sslHandler, ByteBuf byteBuf, int i2, int i3, ByteBuf byteBuf2);
    }

    public final class SslHandlerCoalescingBufferQueue extends AbstractCoalescingBufferQueue {
        public SslHandlerCoalescingBufferQueue(Channel channel, int i2) {
            super(channel, i2);
        }

        @Override // io.netty.channel.AbstractCoalescingBufferQueue
        public ByteBuf compose(ByteBufAllocator byteBufAllocator, ByteBuf byteBuf, ByteBuf byteBuf2) {
            int i2 = SslHandler.this.wrapDataSize;
            if (!(byteBuf instanceof CompositeByteBuf)) {
                return SslHandler.attemptCopyToCumulation(byteBuf, byteBuf2, i2) ? byteBuf : copyAndCompose(byteBufAllocator, byteBuf, byteBuf2);
            }
            CompositeByteBuf compositeByteBuf = (CompositeByteBuf) byteBuf;
            int iNumComponents = compositeByteBuf.numComponents();
            if (iNumComponents == 0 || !SslHandler.attemptCopyToCumulation(compositeByteBuf.internalComponent(iNumComponents - 1), byteBuf2, i2)) {
                compositeByteBuf.addComponent(true, byteBuf2);
            }
            return compositeByteBuf;
        }

        @Override // io.netty.channel.AbstractCoalescingBufferQueue
        public ByteBuf composeFirst(ByteBufAllocator byteBufAllocator, ByteBuf byteBuf) {
            if (!(byteBuf instanceof CompositeByteBuf)) {
                return byteBuf;
            }
            CompositeByteBuf compositeByteBuf = (CompositeByteBuf) byteBuf;
            ByteBuf byteBufDirectBuffer = byteBufAllocator.directBuffer(compositeByteBuf.readableBytes());
            try {
                byteBufDirectBuffer.writeBytes(compositeByteBuf);
            } catch (Throwable th) {
                byteBufDirectBuffer.release();
                PlatformDependent.throwException(th);
            }
            compositeByteBuf.release();
            return byteBufDirectBuffer;
        }

        @Override // io.netty.channel.AbstractCoalescingBufferQueue
        public ByteBuf removeEmptyValue() {
            return null;
        }
    }

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

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

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

    @Deprecated
    public SslHandler(SSLEngine sSLEngine, boolean z2, Executor executor) {
        this.singleBuffer = new ByteBuffer[1];
        this.handshakePromise = new LazyChannelPromise();
        this.sslClosePromise = new LazyChannelPromise();
        this.handshakeTimeoutMillis = 10000L;
        this.closeNotifyFlushTimeoutMillis = 3000L;
        this.wrapDataSize = 16384;
        Objects.requireNonNull(sSLEngine, "engine");
        Objects.requireNonNull(executor, "delegatedTaskExecutor");
        this.engine = sSLEngine;
        SslEngineType sslEngineTypeForEngine = SslEngineType.forEngine(sSLEngine);
        this.engineType = sslEngineTypeForEngine;
        this.delegatedTaskExecutor = executor;
        this.startTls = z2;
        this.jdkCompatibilityMode = sslEngineTypeForEngine.jdkCompatibilityMode(sSLEngine);
        setCumulator(sslEngineTypeForEngine.cumulator);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public static void addCloseListener(ChannelFuture channelFuture, ChannelPromise channelPromise) {
        channelFuture.addListener((GenericFutureListener<? extends Future<? super Void>>) new ChannelPromiseNotifier(false, channelPromise));
    }

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

    private ByteBuf allocateOutNetBuf(ChannelHandlerContext channelHandlerContext, int i2, int i3) {
        return allocate(channelHandlerContext, this.engineType.calculateWrapBufferCapacity(this, i2, i3));
    }

    private void applyHandshakeTimeout(final Promise<Channel> promise) {
        if (promise == null) {
            promise = this.handshakePromise;
        }
        long j2 = this.handshakeTimeoutMillis;
        if (j2 <= 0 || promise.isDone()) {
            return;
        }
        final ScheduledFuture<?> scheduledFutureSchedule = this.ctx.executor().schedule(new Runnable() { // from class: io.netty.handler.ssl.SslHandler.6
            @Override // java.lang.Runnable
            public void run() {
                if (promise.isDone()) {
                    return;
                }
                try {
                    if (SslHandler.this.handshakePromise.tryFailure(SslHandler.HANDSHAKE_TIMED_OUT)) {
                        SslUtils.handleHandshakeFailure(SslHandler.this.ctx, SslHandler.HANDSHAKE_TIMED_OUT, true);
                    }
                } finally {
                    SslHandler.this.releaseAndFailAll(SslHandler.HANDSHAKE_TIMED_OUT);
                }
            }
        }, j2, TimeUnit.MILLISECONDS);
        promise.addListener((GenericFutureListener<? extends Future<? super Channel>>) new FutureListener<Channel>() { // from class: io.netty.handler.ssl.SslHandler.7
            @Override // io.netty.util.concurrent.GenericFutureListener
            public void operationComplete(Future<Channel> future) {
                scheduledFutureSchedule.cancel(false);
            }
        });
    }

    /* JADX INFO: Access modifiers changed from: private */
    public static boolean attemptCopyToCumulation(ByteBuf byteBuf, ByteBuf byteBuf2, int i2) {
        int i3 = byteBuf2.readableBytes();
        int iCapacity = byteBuf.capacity();
        if (i2 - byteBuf.readableBytes() < i3 || ((!byteBuf.isWritable(i3) || iCapacity < i2) && (iCapacity >= i2 || !ByteBufUtil.ensureWritableSuccess(byteBuf.ensureWritable(i3, false))))) {
            return false;
        }
        byteBuf.writeBytes(byteBuf2);
        byteBuf2.release();
        return true;
    }

    /* JADX WARN: Multi-variable type inference failed */
    /* JADX WARN: Type inference failed for: r7v1, types: [io.netty.channel.ChannelPromise] */
    /* JADX WARN: Type inference failed for: r7v2, types: [io.netty.channel.ChannelPromise] */
    private void closeOutboundAndChannel(ChannelHandlerContext channelHandlerContext, final ChannelPromise channelPromise, boolean z2) {
        this.outboundClosed = true;
        this.engine.closeOutbound();
        if (!channelHandlerContext.channel().isActive()) {
            if (z2) {
                channelHandlerContext.disconnect(channelPromise);
                return;
            } else {
                channelHandlerContext.close(channelPromise);
                return;
            }
        }
        ChannelPromise channelPromiseNewPromise = channelHandlerContext.newPromise();
        try {
            flush(channelHandlerContext, channelPromiseNewPromise);
            if (this.closeNotify) {
                this.sslClosePromise.addListener((GenericFutureListener) new FutureListener<Channel>() { // from class: io.netty.handler.ssl.SslHandler.3
                    @Override // io.netty.util.concurrent.GenericFutureListener
                    public void operationComplete(Future<Channel> future) {
                        channelPromise.setSuccess();
                    }
                });
            } else {
                this.closeNotify = true;
                safeClose(channelHandlerContext, channelPromiseNewPromise, channelHandlerContext.newPromise().addListener((GenericFutureListener<? extends Future<? super Void>>) new ChannelPromiseNotifier(false, channelPromise)));
            }
        } catch (Throwable th) {
            if (this.closeNotify) {
                this.sslClosePromise.addListener((GenericFutureListener) new FutureListener<Channel>() { // from class: io.netty.handler.ssl.SslHandler.3
                    @Override // io.netty.util.concurrent.GenericFutureListener
                    public void operationComplete(Future<Channel> future) {
                        channelPromise.setSuccess();
                    }
                });
            } else {
                this.closeNotify = true;
                safeClose(channelHandlerContext, channelPromiseNewPromise, channelHandlerContext.newPromise().addListener((GenericFutureListener<? extends Future<? super Void>>) new ChannelPromiseNotifier(false, channelPromise)));
            }
            throw th;
        }
    }

    private void decodeJdkCompatible(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws NotSslRecordException {
        int i2 = this.packetLength;
        if (i2 <= 0) {
            int i3 = byteBuf.readableBytes();
            if (i3 < 5) {
                return;
            }
            int encryptedPacketLength = SslUtils.getEncryptedPacketLength(byteBuf, byteBuf.readerIndex());
            if (encryptedPacketLength == -2) {
                StringBuilder sbF = a.F("not an SSL/TLS record: ");
                sbF.append(ByteBufUtil.hexDump(byteBuf));
                NotSslRecordException notSslRecordException = new NotSslRecordException(sbF.toString());
                byteBuf.skipBytes(byteBuf.readableBytes());
                setHandshakeFailure(channelHandlerContext, notSslRecordException);
                throw notSslRecordException;
            }
            if (encryptedPacketLength > i3) {
                this.packetLength = encryptedPacketLength;
                return;
            }
            i2 = encryptedPacketLength;
        } else if (byteBuf.readableBytes() < i2) {
            return;
        }
        this.packetLength = 0;
        try {
            byteBuf.skipBytes(unwrap(channelHandlerContext, byteBuf, byteBuf.readerIndex(), i2));
        } catch (Throwable th) {
            handleUnwrapThrowable(channelHandlerContext, th);
        }
    }

    private void decodeNonJdkCompatible(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) {
        try {
            byteBuf.skipBytes(unwrap(channelHandlerContext, byteBuf, byteBuf.readerIndex(), byteBuf.readableBytes()));
        } catch (Throwable th) {
            handleUnwrapThrowable(channelHandlerContext, th);
        }
    }

    private void finishWrap(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, ChannelPromise channelPromise, boolean z2, boolean z3) {
        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 (z2) {
            this.needsFlush = true;
        }
        if (z3) {
            readIfNeeded(channelHandlerContext);
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void flush(ChannelHandlerContext channelHandlerContext, ChannelPromise channelPromise) {
        SslHandlerCoalescingBufferQueue sslHandlerCoalescingBufferQueue = this.pendingUnencryptedWrites;
        if (sslHandlerCoalescingBufferQueue != null) {
            sslHandlerCoalescingBufferQueue.add(Unpooled.EMPTY_BUFFER, channelPromise);
        } else {
            channelPromise.setFailure((Throwable) newPendingWritesNullException());
        }
        flush(channelHandlerContext);
    }

    private void flushIfNeeded(ChannelHandlerContext channelHandlerContext) {
        if (this.needsFlush) {
            forceFlush(channelHandlerContext);
        }
    }

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

    private void handleUnwrapThrowable(ChannelHandlerContext channelHandlerContext, Throwable th) {
        try {
            if (this.handshakePromise.tryFailure(th)) {
                channelHandlerContext.fireUserEventTriggered((Object) new SslHandshakeCompletionEvent(th));
            }
            wrapAndFlush(channelHandlerContext);
        } catch (SSLException e2) {
            logger.debug("SSLException during trying to call SSLEngine.wrap(...) because of an previous SSLException, ignoring...", (Throwable) e2);
        } finally {
            setHandshakeFailure(channelHandlerContext, th, true, false, true);
        }
        PlatformDependent.throwException(th);
    }

    /* 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.5
                    @Override // io.netty.util.concurrent.GenericFutureListener
                    public void operationComplete(Future<Channel> future) {
                        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);
        } finally {
            try {
            } catch (Throwable th) {
            }
        }
        forceFlush(channelHandlerContext);
        applyHandshakeTimeout(promise);
    }

    private boolean ignoreException(Throwable th) {
        if (!(th instanceof SSLException) && (th instanceof IOException) && this.sslClosePromise.isDone()) {
            String message = th.getMessage();
            if (message != null && IGNORABLE_ERROR_MESSAGE.matcher(message).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 (Throwable th2) {
                        logger.debug("Unexpected exception while loading class {} classname {}", getClass(), className, th2);
                    }
                }
            }
        }
        return false;
    }

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

    private static IllegalStateException newPendingWritesNullException() {
        return new IllegalStateException("pendingUnencryptedWrites is null, handlerRemoved0 called?");
    }

    private void notifyClosePromise(Throwable th) {
        if (th == null) {
            if (this.sslClosePromise.trySuccess(this.ctx.channel())) {
                this.ctx.fireUserEventTriggered((Object) SslCloseCompletionEvent.SUCCESS);
            }
        } else if (this.sslClosePromise.tryFailure(th)) {
            this.ctx.fireUserEventTriggered((Object) new SslCloseCompletionEvent(th));
        }
    }

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

    /* JADX INFO: Access modifiers changed from: private */
    public void releaseAndFailAll(Throwable th) {
        SslHandlerCoalescingBufferQueue sslHandlerCoalescingBufferQueue = this.pendingUnencryptedWrites;
        if (sslHandlerCoalescingBufferQueue != null) {
            sslHandlerCoalescingBufferQueue.releaseAndFailAll(this.ctx, th);
        }
    }

    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 z2 = false;
            while (countDownLatch.getCount() != 0) {
                try {
                    countDownLatch.await();
                } catch (InterruptedException unused) {
                    z2 = true;
                }
            }
            if (z2) {
                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, final ChannelFuture channelFuture, final ChannelPromise channelPromise) {
        if (!channelHandlerContext.channel().isActive()) {
            channelHandlerContext.close(channelPromise);
            return;
        }
        final ScheduledFuture<?> scheduledFutureSchedule = null;
        if (!channelFuture.isDone()) {
            long j2 = this.closeNotifyFlushTimeoutMillis;
            if (j2 > 0) {
                scheduledFutureSchedule = channelHandlerContext.executor().schedule(new Runnable() { // from class: io.netty.handler.ssl.SslHandler.8
                    @Override // java.lang.Runnable
                    public void run() {
                        if (channelFuture.isDone()) {
                            return;
                        }
                        SslHandler.logger.warn("{} Last write attempt timed out; force-closing the connection.", channelHandlerContext.channel());
                        ChannelHandlerContext channelHandlerContext2 = channelHandlerContext;
                        SslHandler.addCloseListener(channelHandlerContext2.close(channelHandlerContext2.newPromise()), channelPromise);
                    }
                }, j2, TimeUnit.MILLISECONDS);
            }
        }
        channelFuture.addListener((GenericFutureListener<? extends Future<? super Void>>) new ChannelFutureListener() { // from class: io.netty.handler.ssl.SslHandler.9
            @Override // io.netty.util.concurrent.GenericFutureListener
            public void operationComplete(ChannelFuture channelFuture2) {
                java.util.concurrent.ScheduledFuture scheduledFuture = scheduledFutureSchedule;
                if (scheduledFuture != null) {
                    scheduledFuture.cancel(false);
                }
                final long j3 = SslHandler.this.closeNotifyReadTimeoutMillis;
                if (j3 <= 0) {
                    ChannelHandlerContext channelHandlerContext2 = channelHandlerContext;
                    SslHandler.addCloseListener(channelHandlerContext2.close(channelHandlerContext2.newPromise()), channelPromise);
                } else {
                    final ScheduledFuture<?> scheduledFutureSchedule2 = !SslHandler.this.sslClosePromise.isDone() ? channelHandlerContext.executor().schedule(new Runnable() { // from class: io.netty.handler.ssl.SslHandler.9.1
                        @Override // java.lang.Runnable
                        public void run() {
                            if (SslHandler.this.sslClosePromise.isDone()) {
                                return;
                            }
                            SslHandler.logger.debug("{} did not receive close_notify in {}ms; force-closing the connection.", channelHandlerContext.channel(), Long.valueOf(j3));
                            ChannelHandlerContext channelHandlerContext3 = channelHandlerContext;
                            SslHandler.addCloseListener(channelHandlerContext3.close(channelHandlerContext3.newPromise()), channelPromise);
                        }
                    }, j3, TimeUnit.MILLISECONDS) : null;
                    SslHandler.this.sslClosePromise.addListener((GenericFutureListener) new FutureListener<Channel>() { // from class: io.netty.handler.ssl.SslHandler.9.2
                        @Override // io.netty.util.concurrent.GenericFutureListener
                        public void operationComplete(Future<Channel> future) {
                            java.util.concurrent.ScheduledFuture scheduledFuture2 = scheduledFutureSchedule2;
                            if (scheduledFuture2 != null) {
                                scheduledFuture2.cancel(false);
                            }
                            ChannelHandlerContext channelHandlerContext3 = channelHandlerContext;
                            SslHandler.addCloseListener(channelHandlerContext3.close(channelHandlerContext3.newPromise()), channelPromise);
                        }
                    });
                }
            }
        });
    }

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

    private void setHandshakeFailure(ChannelHandlerContext channelHandlerContext, Throwable th, boolean z2, boolean z3, boolean z4) {
        String message;
        try {
            this.outboundClosed = true;
            this.engine.closeOutbound();
            if (z2) {
                try {
                    this.engine.closeInbound();
                } catch (SSLException e2) {
                    InternalLogger internalLogger = logger;
                    if (internalLogger.isDebugEnabled() && ((message = e2.getMessage()) == null || !message.contains("possible truncation attack"))) {
                        internalLogger.debug("{} SSLEngine.closeInbound() raised an exception.", channelHandlerContext.channel(), e2);
                    }
                }
            }
            if (this.handshakePromise.tryFailure(th) || z4) {
                SslUtils.handleHandshakeFailure(channelHandlerContext, th, z3);
            }
        } finally {
            releaseAndFailAll(th);
        }
    }

    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 void startHandshakeProcessing() {
        this.handshakeStarted = true;
        if (this.engine.getUseClientMode()) {
            handshake(null);
        } else {
            applyHandshakeTimeout(null);
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public static ByteBuffer toByteBuffer(ByteBuf byteBuf, int i2, int i3) {
        return byteBuf.nioBufferCount() == 1 ? byteBuf.internalNioBuffer(i2, i3) : byteBuf.nioBuffer(i2, i3);
    }

    /* JADX WARN: Code restructure failed: missing block: B:10:0x0047, code lost:
    
        if (r5 == 2) goto L12;
     */
    /* JADX WARN: Code restructure failed: missing block: B:12:0x004a, code lost:
    
        r17 = true;
     */
    /* JADX WARN: Code restructure failed: missing block: B:13:0x004c, code lost:
    
        r5 = io.netty.handler.ssl.SslHandler.AnonymousClass10.$SwitchMap$javax$net$ssl$SSLEngineResult$HandshakeStatus[r3.ordinal()];
     */
    /* JADX WARN: Code restructure failed: missing block: B:14:0x0054, code lost:
    
        if (r5 == 1) goto L93;
     */
    /* JADX WARN: Code restructure failed: missing block: B:15:0x0056, code lost:
    
        if (r5 == 2) goto L94;
     */
    /* JADX WARN: Code restructure failed: missing block: B:17:0x0059, code lost:
    
        if (r5 == 3) goto L29;
     */
    /* JADX WARN: Code restructure failed: missing block: B:19:0x005c, code lost:
    
        if (r5 == 4) goto L25;
     */
    /* JADX WARN: Code restructure failed: missing block: B:21:0x005f, code lost:
    
        if (r5 != 5) goto L85;
     */
    /* JADX WARN: Code restructure failed: missing block: B:24:0x0078, code lost:
    
        throw new java.lang.IllegalStateException("unknown handshake status: " + r3);
     */
    /* JADX WARN: Code restructure failed: missing block: B:26:0x007d, code lost:
    
        if (wrapNonAppData(r19, true) == false) goto L39;
     */
    /* JADX WARN: Code restructure failed: missing block: B:27:0x007f, code lost:
    
        if (r14 != 0) goto L39;
     */
    /* JADX WARN: Code restructure failed: missing block: B:30:0x0087, code lost:
    
        if (setHandshakeSuccessIfStillHandshaking() == false) goto L96;
     */
    /* JADX WARN: Code restructure failed: missing block: B:31:0x0089, code lost:
    
        r16 = true;
     */
    /* JADX WARN: Code restructure failed: missing block: B:33:0x008e, code lost:
    
        if (r18.flushedBeforeHandshake == false) goto L35;
     */
    /* JADX WARN: Code restructure failed: missing block: B:34:0x0090, code lost:
    
        r18.flushedBeforeHandshake = false;
        r16 = true;
     */
    /* JADX WARN: Code restructure failed: missing block: B:35:0x0094, code lost:
    
        if (r14 != 0) goto L39;
     */
    /* JADX WARN: Code restructure failed: missing block: B:37:0x0098, code lost:
    
        setHandshakeSuccess();
        r16 = true;
     */
    /* JADX WARN: Code restructure failed: missing block: B:38:0x009e, code lost:
    
        runDelegatedTasks();
     */
    /* JADX WARN: Code restructure failed: missing block: B:40:0x00a3, code lost:
    
        if (r2 == javax.net.ssl.SSLEngineResult.Status.BUFFER_UNDERFLOW) goto L89;
     */
    /* JADX WARN: Code restructure failed: missing block: B:41:0x00a5, code lost:
    
        if (r1 != 0) goto L99;
     */
    /* JADX WARN: Code restructure failed: missing block: B:42:0x00a7, code lost:
    
        if (r4 != 0) goto L100;
     */
    /* JADX WARN: Code restructure failed: missing block: B:44:0x00ab, code lost:
    
        if (r3 != javax.net.ssl.SSLEngineResult.HandshakeStatus.NEED_UNWRAP) goto L63;
     */
    /* JADX WARN: Code restructure failed: missing block: B:45:0x00ad, code lost:
    
        readIfNeeded(r19);
     */
    /* JADX WARN: Code restructure failed: missing block: B:63:0x0122, code lost:
    
        if (r16 == false) goto L65;
     */
    /* JADX WARN: Code restructure failed: missing block: B:64:0x0124, code lost:
    
        wrap(r19, true);
     */
    /* JADX WARN: Code restructure failed: missing block: B:65:0x0127, code lost:
    
        if (r17 == false) goto L67;
     */
    /* JADX WARN: Code restructure failed: missing block: B:66:0x0129, code lost:
    
        notifyClosePromise(r9);
     */
    /* JADX WARN: Code restructure failed: missing block: B:67:0x012c, code lost:
    
        if (r13 == null) goto L72;
     */
    /* JADX WARN: Code restructure failed: missing block: B:69:0x0132, code lost:
    
        if (r13.isReadable() == false) goto L71;
     */
    /* JADX WARN: Code restructure failed: missing block: B:70:0x0134, code lost:
    
        r18.firedChannelRead = true;
        r19.fireChannelRead((java.lang.Object) r13);
     */
    /* JADX WARN: Code restructure failed: missing block: B:71:0x013a, code lost:
    
        r13.release();
     */
    /* JADX WARN: Code restructure failed: missing block: B:73:0x013e, code lost:
    
        return r22 - r14;
     */
    /* JADX WARN: Code restructure failed: missing block: B:99:0x0014, code lost:
    
        continue;
     */
    /*
        Code decompiled incorrectly, please refer to instructions dump.
        To view partially-correct add '--show-bad-code' argument
    */
    private int unwrap(io.netty.channel.ChannelHandlerContext r19, io.netty.buffer.ByteBuf r20, int r21, int r22) throws java.lang.Throwable {
        /*
            Method dump skipped, instruction units count: 338
            To view this dump add '--comments-level debug' option
        */
        throw new UnsupportedOperationException("Method not decompiled: io.netty.handler.ssl.SslHandler.unwrap(io.netty.channel.ChannelHandlerContext, io.netty.buffer.ByteBuf, int, int):int");
    }

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

    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.engineType.wantsDirectBuffer) {
                if ((byteBuf instanceof CompositeByteBuf) || byteBuf.nioBufferCount() != 1) {
                    byteBufferArrNioBuffers = byteBuf.nioBuffers();
                } else {
                    ByteBuffer[] byteBufferArr = this.singleBuffer;
                    byteBufferArr[0] = byteBuf.internalNioBuffer(i2, i3);
                    byteBufferArrNioBuffers = byteBufferArr;
                }
                byteBufDirectBuffer = null;
            } else {
                byteBufDirectBuffer = byteBufAllocator.directBuffer(i3);
                try {
                    byteBufDirectBuffer.writeBytes(byteBuf, i2, i3);
                    byteBufferArrNioBuffers = this.singleBuffer;
                    byteBufferArrNioBuffers[0] = byteBufDirectBuffer.internalNioBuffer(byteBufDirectBuffer.readerIndex(), i3);
                } catch (Throwable th) {
                    th = th;
                    this.singleBuffer[0] = null;
                    if (byteBufDirectBuffer != null) {
                        byteBufDirectBuffer.release();
                    }
                    throw th;
                }
            }
            while (true) {
                sSLEngineResultWrap = sSLEngine.wrap(byteBufferArrNioBuffers, byteBuf2.nioBuffer(byteBuf2.writerIndex(), byteBuf2.writableBytes()));
                byteBuf.skipBytes(sSLEngineResultWrap.bytesConsumed());
                byteBuf2.writerIndex(byteBuf2.writerIndex() + sSLEngineResultWrap.bytesProduced());
                if (AnonymousClass10.$SwitchMap$javax$net$ssl$SSLEngineResult$Status[sSLEngineResultWrap.getStatus().ordinal()] != 1) {
                    break;
                }
                byteBuf2.ensureWritable(sSLEngine.getSession().getPacketBufferSize());
            }
            this.singleBuffer[0] = null;
            if (byteBufDirectBuffer != null) {
                byteBufDirectBuffer.release();
            }
            return sSLEngineResultWrap;
        } catch (Throwable th2) {
            th = th2;
            byteBufDirectBuffer = null;
        }
    }

    /* JADX WARN: Code restructure failed: missing block: B:17:0x0044, code lost:
    
        r4.release();
     */
    /* JADX WARN: Code restructure failed: missing block: B:18:0x0047, code lost:
    
        r0 = io.netty.handler.ssl.SslHandler.SSLENGINE_CLOSED;
        r3.tryFailure(r0);
     */
    /* JADX WARN: Code restructure failed: missing block: B:19:0x004c, code lost:
    
        r9 = null;
     */
    /* JADX WARN: Code restructure failed: missing block: B:20:0x004d, code lost:
    
        r12.pendingUnencryptedWrites.releaseAndFailAll(r13, r0);
     */
    /* JADX WARN: Code restructure failed: missing block: B:21:0x0052, code lost:
    
        r11 = false;
        r6 = r12;
        r7 = r13;
        r8 = r5;
     */
    /* JADX WARN: Code restructure failed: missing block: B:22:0x0056, code lost:
    
        r6.finishWrap(r7, r8, r9, r14, r11);
     */
    /* JADX WARN: Code restructure failed: missing block: B:23:0x005a, code lost:
    
        return;
     */
    /* JADX WARN: Code restructure failed: missing block: B:24:0x005b, code lost:
    
        r0 = th;
     */
    /* JADX WARN: Code restructure failed: missing block: B:25:0x005c, code lost:
    
        r4 = r5;
        r5 = null;
     */
    /* JADX WARN: Code restructure failed: missing block: B:33:0x0080, code lost:
    
        if (r4 == 2) goto L43;
     */
    /* JADX WARN: Code restructure failed: missing block: B:35:0x0083, code lost:
    
        if (r4 == 3) goto L44;
     */
    /* JADX WARN: Code restructure failed: missing block: B:37:0x0086, code lost:
    
        if (r4 == 4) goto L75;
     */
    /* JADX WARN: Code restructure failed: missing block: B:39:0x0089, code lost:
    
        if (r4 != 5) goto L41;
     */
    /* JADX WARN: Code restructure failed: missing block: B:40:0x008b, code lost:
    
        r11 = true;
        r6 = r12;
        r7 = r13;
        r8 = r5;
        r9 = r3;
     */
    /* JADX WARN: Code restructure failed: missing block: B:42:0x00ab, code lost:
    
        throw new java.lang.IllegalStateException("Unknown handshake status: " + r6.getHandshakeStatus());
     */
    /* JADX WARN: Code restructure failed: missing block: B:43:0x00ac, code lost:
    
        setHandshakeSuccess();
     */
    /* JADX WARN: Code restructure failed: missing block: B:44:0x00af, code lost:
    
        setHandshakeSuccessIfStillHandshaking();
     */
    /* JADX WARN: Code restructure failed: missing block: B:51:0x00c6, code lost:
    
        if (r1 == null) goto L53;
     */
    /* JADX WARN: Code restructure failed: missing block: B:52:0x00c8, code lost:
    
        r1.release();
     */
    /* JADX WARN: Code restructure failed: missing block: B:53:0x00cb, code lost:
    
        finishWrap(r13, r5, r6, r14, false);
     */
    /* JADX WARN: Code restructure failed: missing block: B:54:0x00d2, code lost:
    
        return;
     */
    /* JADX WARN: Removed duplicated region for block: B:60:0x00dc  */
    /*
        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 {
        /*
            Method dump skipped, instruction units count: 231
            To view this dump add '--comments-level debug' option
        */
        throw new UnsupportedOperationException("Method not decompiled: io.netty.handler.ssl.SslHandler.wrap(io.netty.channel.ChannelHandlerContext, boolean):void");
    }

    private void wrapAndFlush(ChannelHandlerContext channelHandlerContext) {
        if (this.pendingUnencryptedWrites.isEmpty()) {
            this.pendingUnencryptedWrites.add(Unpooled.EMPTY_BUFFER, channelHandlerContext.newPromise());
        }
        if (!this.handshakePromise.isDone()) {
            this.flushedBeforeHandshake = true;
        }
        try {
            wrap(channelHandlerContext, false);
        } finally {
            forceFlush(channelHandlerContext);
        }
    }

    private boolean wrapNonAppData(ChannelHandlerContext channelHandlerContext, boolean z2) {
        ByteBufAllocator byteBufAllocatorAlloc = channelHandlerContext.alloc();
        ByteBuf byteBufAllocateOutNetBuf = null;
        while (!channelHandlerContext.isRemoved()) {
            try {
                if (byteBufAllocateOutNetBuf == null) {
                    byteBufAllocateOutNetBuf = allocateOutNetBuf(channelHandlerContext, 2048, 1);
                }
                SSLEngineResult sSLEngineResultWrap = wrap(byteBufAllocatorAlloc, this.engine, Unpooled.EMPTY_BUFFER, byteBufAllocateOutNetBuf);
                if (sSLEngineResultWrap.bytesProduced() > 0) {
                    channelHandlerContext.write(byteBufAllocateOutNetBuf);
                    if (z2) {
                        this.needsFlush = true;
                    }
                    byteBufAllocateOutNetBuf = null;
                }
                int i2 = AnonymousClass10.$SwitchMap$javax$net$ssl$SSLEngineResult$HandshakeStatus[sSLEngineResultWrap.getHandshakeStatus().ordinal()];
                if (i2 == 1) {
                    runDelegatedTasks();
                } else {
                    if (i2 == 2) {
                        setHandshakeSuccess();
                        if (byteBufAllocateOutNetBuf != null) {
                            byteBufAllocateOutNetBuf.release();
                        }
                        return false;
                    }
                    if (i2 == 3) {
                        setHandshakeSuccessIfStillHandshaking();
                        if (!z2) {
                            unwrapNonAppData(channelHandlerContext);
                        }
                        if (byteBufAllocateOutNetBuf != null) {
                            byteBufAllocateOutNetBuf.release();
                        }
                        return true;
                    }
                    if (i2 != 4) {
                        if (i2 != 5) {
                            throw new IllegalStateException("Unknown handshake status: " + sSLEngineResultWrap.getHandshakeStatus());
                        }
                        if (z2) {
                            return false;
                        }
                        unwrapNonAppData(channelHandlerContext);
                    }
                }
                if (sSLEngineResultWrap.bytesProduced() == 0 || (sSLEngineResultWrap.bytesConsumed() == 0 && sSLEngineResultWrap.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING)) {
                    break;
                }
            } finally {
                if (byteBufAllocateOutNetBuf != null) {
                    byteBufAllocateOutNetBuf.release();
                }
            }
        }
        if (byteBufAllocateOutNetBuf != null) {
            byteBufAllocateOutNetBuf.release();
        }
        return false;
    }

    public String applicationProtocol() {
        Object objEngine = engine();
        if (objEngine instanceof ApplicationProtocolAccessor) {
            return ((ApplicationProtocolAccessor) objEngine).getNegotiatedApplicationProtocol();
        }
        return null;
    }

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

    @Override // io.netty.channel.ChannelInboundHandlerAdapter, io.netty.channel.ChannelInboundHandler
    public void channelActive(ChannelHandlerContext channelHandlerContext) {
        if (!this.startTls) {
            startHandshakeProcessing();
        }
        channelHandlerContext.fireChannelActive();
    }

    @Override // io.netty.handler.codec.ByteToMessageDecoder, io.netty.channel.ChannelInboundHandlerAdapter, io.netty.channel.ChannelInboundHandler
    public void channelInactive(ChannelHandlerContext channelHandlerContext) {
        ClosedChannelException closedChannelException = CHANNEL_CLOSED;
        setHandshakeFailure(channelHandlerContext, closedChannelException, !this.outboundClosed, this.handshakeStarted, false);
        notifyClosePromise(closedChannelException);
        super.channelInactive(channelHandlerContext);
    }

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

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

    @Deprecated
    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.flush(channelHandlerContext, channelPromise);
                } catch (Exception e2) {
                    if (channelPromise.tryFailure(e2)) {
                        return;
                    }
                    SslHandler.logger.warn("{} flush() raised a masked exception.", channelHandlerContext.channel(), e2);
                }
            }
        });
        return channelPromise;
    }

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

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

    @Override // io.netty.handler.codec.ByteToMessageDecoder
    public void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws NotSslRecordException {
        if (this.jdkCompatibilityMode) {
            decodeJdkCompatible(channelHandlerContext, byteBuf);
        } else {
            decodeNonJdkCompatible(channelHandlerContext, byteBuf);
        }
    }

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

    @Override // io.netty.channel.ChannelOutboundHandler
    public void disconnect(ChannelHandlerContext channelHandlerContext, ChannelPromise channelPromise) {
        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) {
        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) {
        if (this.startTls && !this.sentFirstMessage) {
            this.sentFirstMessage = true;
            this.pendingUnencryptedWrites.writeAndRemoveAll(channelHandlerContext);
            forceFlush(channelHandlerContext);
        } else {
            try {
                wrapAndFlush(channelHandlerContext);
            } catch (Throwable th) {
                setHandshakeFailure(channelHandlerContext, th);
                PlatformDependent.throwException(th);
            }
        }
    }

    public final long getCloseNotifyFlushTimeoutMillis() {
        return this.closeNotifyFlushTimeoutMillis;
    }

    public final long getCloseNotifyReadTimeoutMillis() {
        return this.closeNotifyReadTimeoutMillis;
    }

    @Deprecated
    public long getCloseNotifyTimeoutMillis() {
        return getCloseNotifyFlushTimeoutMillis();
    }

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

    @Override // io.netty.channel.ChannelHandlerAdapter, io.netty.channel.ChannelHandler
    public void handlerAdded(ChannelHandlerContext channelHandlerContext) {
        this.ctx = channelHandlerContext;
        this.pendingUnencryptedWrites = new SslHandlerCoalescingBufferQueue(channelHandlerContext.channel(), 16);
        if (channelHandlerContext.channel().isActive()) {
            startHandshakeProcessing();
        }
    }

    @Override // io.netty.handler.codec.ByteToMessageDecoder
    public void handlerRemoved0(ChannelHandlerContext channelHandlerContext) {
        if (!this.pendingUnencryptedWrites.isEmpty()) {
            this.pendingUnencryptedWrites.releaseAndFailAll(channelHandlerContext, new ChannelException("Pending write on removal of SslHandler"));
        }
        this.pendingUnencryptedWrites = null;
        Object obj = this.engine;
        if (obj instanceof ReferenceCounted) {
            ((ReferenceCounted) obj).release();
        }
    }

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

    @Override // io.netty.channel.ChannelOutboundHandler
    public void read(ChannelHandlerContext channelHandlerContext) {
        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 Future<Channel> renegotiate(final Promise<Channel> promise) {
        Objects.requireNonNull(promise, "promise");
        ChannelHandlerContext channelHandlerContext = this.ctx;
        if (channelHandlerContext == null) {
            throw new IllegalStateException();
        }
        EventExecutor eventExecutorExecutor = channelHandlerContext.executor();
        if (eventExecutorExecutor.inEventLoop()) {
            handshake(promise);
            return promise;
        }
        eventExecutorExecutor.execute(new Runnable() { // from class: io.netty.handler.ssl.SslHandler.4
            @Override // java.lang.Runnable
            public void run() {
                SslHandler.this.handshake(promise);
            }
        });
        return promise;
    }

    public final void setCloseNotifyFlushTimeout(long j2, TimeUnit timeUnit) {
        setCloseNotifyFlushTimeoutMillis(timeUnit.toMillis(j2));
    }

    public final void setCloseNotifyFlushTimeoutMillis(long j2) {
        if (j2 < 0) {
            throw new IllegalArgumentException(a.r("closeNotifyFlushTimeoutMillis: ", j2, " (expected: >= 0)"));
        }
        this.closeNotifyFlushTimeoutMillis = j2;
    }

    public final void setCloseNotifyReadTimeout(long j2, TimeUnit timeUnit) {
        setCloseNotifyReadTimeoutMillis(timeUnit.toMillis(j2));
    }

    public final void setCloseNotifyReadTimeoutMillis(long j2) {
        if (j2 < 0) {
            throw new IllegalArgumentException(a.r("closeNotifyReadTimeoutMillis: ", j2, " (expected: >= 0)"));
        }
        this.closeNotifyReadTimeoutMillis = j2;
    }

    @Deprecated
    public void setCloseNotifyTimeout(long j2, TimeUnit timeUnit) {
        setCloseNotifyFlushTimeout(j2, timeUnit);
    }

    @Deprecated
    public void setCloseNotifyTimeoutMillis(long j2) {
        setCloseNotifyFlushTimeoutMillis(j2);
    }

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

    public void setHandshakeTimeoutMillis(long j2) {
        if (j2 < 0) {
            throw new IllegalArgumentException(a.r("handshakeTimeoutMillis: ", j2, " (expected: >= 0)"));
        }
        this.handshakeTimeoutMillis = j2;
    }

    public final void setWrapDataSize(int i2) {
        this.wrapDataSize = i2;
    }

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

    @Override // io.netty.channel.ChannelOutboundHandler
    public void write(ChannelHandlerContext channelHandlerContext, Object obj, ChannelPromise channelPromise) {
        Throwable thNewPendingWritesNullException;
        if (obj instanceof ByteBuf) {
            SslHandlerCoalescingBufferQueue sslHandlerCoalescingBufferQueue = this.pendingUnencryptedWrites;
            if (sslHandlerCoalescingBufferQueue != null) {
                sslHandlerCoalescingBufferQueue.add((ByteBuf) obj, channelPromise);
                return;
            } else {
                ReferenceCountUtil.safeRelease(obj);
                thNewPendingWritesNullException = newPendingWritesNullException();
            }
        } else {
            thNewPendingWritesNullException = new UnsupportedMessageTypeException(obj, (Class<?>[]) new Class[]{ByteBuf.class});
            ReferenceCountUtil.safeRelease(obj);
        }
        channelPromise.setFailure(thNewPendingWritesNullException);
    }
}
