package org.snmp4j.mp;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.WeakHashMap;
import org.snmp4j.MessageDispatcher;
import org.snmp4j.MessageException;
import org.snmp4j.PDU;
import org.snmp4j.SNMP4JSettings;
import org.snmp4j.ScopedPDU;
import org.snmp4j.Target;
import org.snmp4j.agent.mo.snmp.DisplayString;
import org.snmp4j.asn1.BER;
import org.snmp4j.asn1.BERInputStream;
import org.snmp4j.asn1.BEROutputStream;
import org.snmp4j.asn1.BERSerializable;
import org.snmp4j.event.CounterEvent;
import org.snmp4j.event.SnmpEngineEvent;
import org.snmp4j.event.SnmpEngineListener;
import org.snmp4j.log.LogAdapter;
import org.snmp4j.log.LogFactory;
import org.snmp4j.security.AuthenticationProtocol;
import org.snmp4j.security.PrivacyProtocol;
import org.snmp4j.security.SecurityModel;
import org.snmp4j.security.SecurityModels;
import org.snmp4j.security.SecurityProtocols;
import org.snmp4j.security.SecurityStateReference;
import org.snmp4j.security.USM;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.Integer32;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.util.PDUFactory;

/* JADX INFO: loaded from: classes.dex */
public class MPv3 implements MessageProcessingModel, EngineIdCacheSize {
    public static final int ID = 3;
    private static final int INT_LOW_16BIT_MASK = 65535;
    public static final OctetString LOCAL_ENGINE_ID = OctetString.fromHexString("80:00:00:00:06");
    public static final int MAXLEN_ENGINE_ID = 32;
    private static final int MAX_HEADER_LENGTH;
    private static final int MAX_HEADER_PAYLOAD_LENGTH;
    public static final int MAX_MESSAGE_ID = Integer.MAX_VALUE;
    public static final int MINLEN_ENGINE_ID = 5;
    public static final int MPv3_REPORTABLE_FLAG = 4;
    private static final LogAdapter logger;
    private Cache cache;
    private CounterSupport counterSupport;
    private int currentMsgID;
    private Map<Address, OctetString> engineIDs;
    protected EngineIdCacheFactory engineIdCacheFactory;
    protected PDUFactory incomingPDUFactory;
    private byte[] localEngineID;
    private int maxEngineIdCacheSize;
    private SecurityModels securityModels;
    private SecurityProtocols securityProtocols;
    transient List<SnmpEngineListener> snmpEngineListeners;

    protected static class Cache {
        private Map<PduHandle, StateReference> entries = new WeakHashMap(25);

        protected Cache() {
        }

        public synchronized int addEntry(StateReference stateReference) {
            if (MPv3.logger.isDebugEnabled()) {
                MPv3.logger.debug("Adding cache entry: " + stateReference);
            }
            StateReference stateReference2 = this.entries.get(stateReference.getPduHandle());
            if (stateReference2 != null) {
                stateReference2.setPduHandle(stateReference.getPduHandle());
                if (stateReference2.equals(stateReference)) {
                    if (MPv3.logger.isDebugEnabled()) {
                        MPv3.logger.debug("Doubled message: " + stateReference);
                    }
                    stateReference2.setPduHandle(null);
                    return SnmpConstants.SNMP_MP_DOUBLED_MESSAGE;
                }
                if (stateReference2.equalsExceptMsgID(stateReference)) {
                    if (MPv3.logger.isDebugEnabled()) {
                        MPv3.logger.debug("Adding previous message IDs " + stateReference2.getMessageIDs() + " to new entry " + stateReference);
                    }
                    stateReference.addMessageIDs(stateReference2.getMessageIDs());
                } else if (MPv3.logger.isDebugEnabled()) {
                    MPv3.logger.debug("New entry does not match existing, although request ID is the same " + stateReference + " != " + stateReference2);
                }
                stateReference2.setPduHandle(null);
            }
            PduHandle pduHandle = stateReference.getPduHandle();
            stateReference.setPduHandle(null);
            this.entries.put(pduHandle, stateReference);
            return 0;
        }

        public synchronized boolean deleteEntry(PduHandle pduHandle) {
            return this.entries.remove(pduHandle) != null;
        }

        public synchronized StateReference popEntry(int i2) {
            Iterator<PduHandle> it = this.entries.keySet().iterator();
            while (it.hasNext()) {
                PduHandle next = it.next();
                StateReference stateReference = this.entries.get(next);
                if (stateReference != null && stateReference.isMatchingMessageID(i2)) {
                    it.remove();
                    stateReference.setPduHandle(next);
                    if (MPv3.logger.isDebugEnabled()) {
                        MPv3.logger.debug("Removed cache entry: " + stateReference);
                    }
                    return stateReference;
                }
            }
            return null;
        }
    }

    protected static class CacheEntry extends StateReference {
        byte[] contextEngineID;
        byte[] contextName;
        int errorCode;
        int msgID;
        byte[] secEngineID;
        int secLevel;
        SecurityModel secModel;
        byte[] secName;
        SecurityStateReference secStateReference;
        long transactionID;

        public CacheEntry(int i2, long j2, byte[] bArr, SecurityModel securityModel, byte[] bArr2, int i3, byte[] bArr3, byte[] bArr4, SecurityStateReference securityStateReference, int i4) {
            this.msgID = i2;
            this.transactionID = j2;
            this.secEngineID = bArr;
            this.secModel = securityModel;
            this.secName = bArr2;
            this.secLevel = i3;
            this.contextEngineID = bArr3;
            this.contextName = bArr4;
            this.secStateReference = securityStateReference;
            this.errorCode = i4;
        }
    }

    public interface EngineIdCacheFactory {
        Map<Address, OctetString> createEngineIdMap(EngineIdCacheSize engineIdCacheSize);
    }

    public static class HeaderData implements BERSerializable {
        public static final byte FLAG_AUTH = 1;
        public static final byte FLAG_PRIV = 2;
        Integer32 msgID = new Integer32(0);
        Integer32 msgMaxSize = new Integer32(MPv3.MAX_MESSAGE_ID);
        OctetString msgFlags = new OctetString(new byte[1]);
        Integer32 securityModel = new Integer32(0);

        @Override // org.snmp4j.asn1.BERSerializable
        public void decodeBER(BERInputStream bERInputStream) throws IOException {
            BER.MutableByte mutableByte = new BER.MutableByte();
            int iDecodeHeader = BER.decodeHeader(bERInputStream, mutableByte);
            if (mutableByte.getValue() != 48) {
                throw new IOException("Unexpected sequence header type: " + ((int) mutableByte.getValue()));
            }
            this.msgID.decodeBER(bERInputStream);
            this.msgMaxSize.decodeBER(bERInputStream);
            if (this.msgMaxSize.getValue() < 484) {
                throw new IOException("Invalid msgMaxSize: " + this.msgMaxSize);
            }
            this.msgFlags.decodeBER(bERInputStream);
            if (this.msgFlags.length() != 1) {
                throw new IOException("Message flags length != 1: " + this.msgFlags.length());
            }
            this.securityModel.decodeBER(bERInputStream);
            if (MPv3.logger.isDebugEnabled()) {
                MPv3.logger.debug("SNMPv3 header decoded: msgId=" + this.msgID + ", msgMaxSize=" + this.msgMaxSize + ", msgFlags=" + this.msgFlags.toHexString() + ", secModel=" + this.securityModel);
            }
            BER.checkSequenceLength(iDecodeHeader, this);
        }

        @Override // org.snmp4j.asn1.BERSerializable
        public void encodeBER(OutputStream outputStream) throws IOException {
            BER.encodeHeader(outputStream, 48, getBERPayloadLength());
            this.msgID.encodeBER(outputStream);
            this.msgMaxSize.encodeBER(outputStream);
            this.msgFlags.encodeBER(outputStream);
            this.securityModel.encodeBER(outputStream);
        }

        @Override // org.snmp4j.asn1.BERSerializable
        public int getBERLength() {
            int bERPayloadLength = getBERPayloadLength();
            return bERPayloadLength + BER.getBERLengthOfLength(bERPayloadLength) + 1;
        }

        @Override // org.snmp4j.asn1.BERSerializable
        public int getBERPayloadLength() {
            return this.msgID.getBERLength() + this.msgMaxSize.getBERLength() + this.msgFlags.getBERLength() + this.securityModel.getBERLength();
        }

        public int getMsgFlags() {
            return this.msgFlags.getValue()[0] & 255;
        }

        public int getMsgID() {
            return this.msgID.getValue();
        }

        public int getMsgMaxSize() {
            return this.msgMaxSize.getValue();
        }

        public int getSecurityModel() {
            return this.securityModel.getValue();
        }

        public void setMsgFlags(int i2) {
            this.msgFlags.getValue()[0] = (byte) i2;
        }

        public void setMsgID(int i2) {
            this.msgID.setValue(i2);
        }

        public void setMsgMaxSize(int i2) {
            this.msgMaxSize.setValue(i2);
        }

        public void setSecurityModel(int i2) {
            this.securityModel.setValue(i2);
        }
    }

    private static class LimitedCapacityEngineIdCacheFactory implements EngineIdCacheFactory {
        private LimitedCapacityEngineIdCacheFactory() {
        }

        @Override // org.snmp4j.mp.MPv3.EngineIdCacheFactory
        public Map<Address, OctetString> createEngineIdMap(EngineIdCacheSize engineIdCacheSize) {
            return Collections.synchronizedMap(new HashMap());
        }
    }

    static {
        int bERLength = new OctetString("\u0000").getBERLength() + (new Integer32(MAX_MESSAGE_ID).getBERLength() * 3);
        MAX_HEADER_PAYLOAD_LENGTH = bERLength;
        MAX_HEADER_LENGTH = bERLength + BER.getBERLengthOfLength(bERLength) + 1;
        logger = LogFactory.getLogger(MPv3.class);
    }

    public MPv3() {
        this(createLocalEngineID(), null);
    }

    public static byte[] createLocalEngineID() {
        int enterpriseID = SNMP4JSettings.getEnterpriseID();
        byte[] bArr = {(byte) (((enterpriseID >> 24) & DisplayString.MAX_SIZE) | 128), (byte) ((enterpriseID >> 16) & DisplayString.MAX_SIZE), (byte) ((enterpriseID >> 8) & DisplayString.MAX_SIZE), (byte) (enterpriseID & DisplayString.MAX_SIZE), 2};
        OctetString octetString = new OctetString();
        try {
            byte[] address = InetAddress.getLocalHost().getAddress();
            if (address.length == 4) {
                bArr[4] = 1;
            }
            octetString.setValue(address);
        } catch (UnknownHostException unused) {
            logger.debug("Local host cannot be determined for creation of local engine ID");
            bArr[4] = 4;
            octetString.setValue("SNMP4J".getBytes());
        }
        OctetString octetString2 = new OctetString(bArr);
        byte[] bArr2 = new byte[4];
        new Random(System.nanoTime()).nextBytes(bArr2);
        octetString2.append(octetString);
        octetString2.append(bArr2);
        return octetString2.getValue();
    }

    public static int getEnterpriseID() {
        return SNMP4JSettings.getEnterpriseID();
    }

    public static int randomMsgID(int i2) {
        return ((i2 & 65535) << 16) | (new Random().nextInt(MAX_MESSAGE_ID) & 65535);
    }

    public static void setEnterpriseID(int i2) {
        SNMP4JSettings.setEnterpriseID(i2);
    }

    public boolean addEngineID(Address address, OctetString octetString) {
        if (!Arrays.equals(this.localEngineID, octetString.getValue())) {
            try {
                OctetString octetStringAddEngineIdToCache = addEngineIdToCache(address, octetString);
                if (this.snmpEngineListeners != null && (octetStringAddEngineIdToCache == null || !octetStringAddEngineIdToCache.equals(octetString))) {
                    fireEngineChanged(new SnmpEngineEvent(this, 1, octetString, address));
                }
                return true;
            } catch (IllegalArgumentException unused) {
                fireEngineChanged(new SnmpEngineEvent(this, 3, octetString, address));
            }
        }
        return false;
    }

    protected OctetString addEngineIdToCache(Address address, OctetString octetString) {
        if (this.maxEngineIdCacheSize <= 0 || this.engineIDs.size() < this.maxEngineIdCacheSize) {
            return this.engineIDs.put(address, octetString);
        }
        if (this.engineIDs.containsKey(address)) {
            return this.engineIDs.put(address, octetString);
        }
        String str = "MPv3: Failed to add engineID '" + octetString.toHexString() + "' for address '" + address + "' to local cache because its size limit of " + this.maxEngineIdCacheSize + "has been reached";
        logger.warn(str);
        throw new IllegalArgumentException(str);
    }

    public synchronized void addSnmpEngineListener(SnmpEngineListener snmpEngineListener) {
        ArrayList arrayList = this.snmpEngineListeners == null ? new ArrayList() : new ArrayList(this.snmpEngineListeners);
        arrayList.add(snmpEngineListener);
        this.snmpEngineListeners = arrayList;
    }

    public PDU createPDU(Target target) {
        return this.incomingPDUFactory.createPDU(target);
    }

    protected void fireEngineChanged(SnmpEngineEvent snmpEngineEvent) {
        List<SnmpEngineListener> list = this.snmpEngineListeners;
        if (list != null) {
            Iterator<SnmpEngineListener> it = list.iterator();
            while (it.hasNext()) {
                it.next().engineChanged(snmpEngineEvent);
            }
        }
    }

    protected void fireIncrementCounter(CounterEvent counterEvent) {
        CounterSupport counterSupport = this.counterSupport;
        if (counterSupport != null) {
            counterSupport.fireIncrementCounter(counterEvent);
        }
    }

    public AuthenticationProtocol getAuthProtocol(OID oid) {
        return this.securityProtocols.getAuthenticationProtocol(oid);
    }

    public CounterSupport getCounterSupport() {
        return this.counterSupport;
    }

    public OctetString getEngineID(Address address) {
        return this.engineIDs.get(address);
    }

    public EngineIdCacheFactory getEngineIdCacheFactory() {
        return this.engineIdCacheFactory;
    }

    public int getEngineIdCacheSize() {
        return this.engineIDs.size();
    }

    @Override // org.snmp4j.mp.MessageProcessingModel
    public int getID() {
        return 3;
    }

    public byte[] getLocalEngineID() {
        byte[] bArr = this.localEngineID;
        byte[] bArr2 = new byte[bArr.length];
        System.arraycopy(bArr, 0, bArr2, 0, bArr.length);
        return bArr2;
    }

    @Override // org.snmp4j.mp.EngineIdCacheSize
    public int getMaxEngineIdCacheSize() {
        return this.maxEngineIdCacheSize;
    }

    public synchronized int getNextMessageID() {
        int i2;
        if (this.currentMsgID >= Integer.MAX_VALUE) {
            this.currentMsgID = 1;
        }
        i2 = this.currentMsgID;
        this.currentMsgID = i2 + 1;
        return i2;
    }

    public int getNextMsgID() {
        return this.currentMsgID;
    }

    public PrivacyProtocol getPrivProtocol(OID oid) {
        return this.securityProtocols.getPrivacyProtocol(oid);
    }

    public SecurityModel getSecurityModel(int i2) {
        return this.securityModels.getSecurityModel(new Integer32(i2));
    }

    public SecurityModels getSecurityModels() {
        return this.securityModels;
    }

    public SecurityProtocols getSecurityProtocols() {
        return this.securityProtocols;
    }

    public void initDefaults() {
        this.securityProtocols.addDefaultProtocols();
    }

    @Override // org.snmp4j.mp.MessageProcessingModel
    public boolean isProtocolVersionSupported(int i2) {
        return i2 == 3;
    }

    /* JADX WARN: Multi-variable type inference failed */
    /* JADX WARN: Removed duplicated region for block: B:192:0x0599  */
    /* JADX WARN: Removed duplicated region for block: B:45:0x01a0  */
    /* JADX WARN: Removed duplicated region for block: B:50:0x01b4 A[Catch: IOException -> 0x0567, TryCatch #2 {IOException -> 0x0567, blocks: (B:46:0x01a4, B:48:0x01aa, B:64:0x021a, B:67:0x023f, B:76:0x0261, B:78:0x027f, B:82:0x0290, B:83:0x0293, B:79:0x0283, B:75:0x025b, B:50:0x01b4, B:52:0x01ba, B:54:0x01c2, B:57:0x01e4, B:59:0x0206, B:60:0x0209, B:69:0x0245, B:71:0x024b), top: B:198:0x0171, inners: #0 }] */
    /* JADX WARN: Removed duplicated region for block: B:66:0x023d  */
    /* JADX WARN: Removed duplicated region for block: B:94:0x02f6 A[Catch: IOException -> 0x0576, TryCatch #3 {IOException -> 0x0576, blocks: (B:3:0x0014, B:5:0x001f, B:6:0x002a, B:9:0x0047, B:12:0x005a, B:14:0x0068, B:16:0x00af, B:18:0x00d2, B:23:0x00e1, B:25:0x00f8, B:28:0x0109, B:87:0x02d3, B:89:0x02d9, B:94:0x02f6, B:96:0x031d, B:99:0x0326, B:157:0x04d0, B:158:0x04d4, B:161:0x04da, B:163:0x04df, B:165:0x04e5, B:173:0x0530, B:175:0x053a, B:166:0x04ed, B:168:0x04f5, B:170:0x04fd, B:171:0x052a, B:100:0x033e, B:103:0x034c, B:105:0x0354, B:106:0x037c, B:109:0x038f, B:111:0x03af, B:127:0x041b, B:129:0x0423, B:130:0x0451, B:113:0x03b9, B:115:0x03c7, B:117:0x03d1, B:120:0x03d8, B:122:0x03e2, B:124:0x03ea, B:125:0x0411, B:132:0x0455, B:134:0x045d, B:136:0x0467, B:155:0x04c5, B:138:0x046e, B:140:0x047c, B:142:0x0486, B:144:0x0490, B:146:0x049e, B:148:0x04a5, B:150:0x04b3, B:153:0x04bb, B:178:0x053f, B:180:0x0547, B:26:0x00fd, B:27:0x0104, B:187:0x056e, B:188:0x0575), top: B:199:0x0014 }] */
    /* JADX WARN: Type inference fix 'apply assigned field type' failed
    java.lang.UnsupportedOperationException: ArgType.getObject(), call class: class jadx.core.dex.instructions.args.ArgType$UnknownArg
    	at jadx.core.dex.instructions.args.ArgType.getObject(ArgType.java:593)
    	at jadx.core.dex.attributes.nodes.ClassTypeVarsAttr.getTypeVarsMapFor(ClassTypeVarsAttr.java:35)
    	at jadx.core.dex.nodes.utils.TypeUtils.replaceClassGenerics(TypeUtils.java:177)
    	at jadx.core.dex.visitors.typeinference.FixTypesVisitor.insertExplicitUseCast(FixTypesVisitor.java:397)
    	at jadx.core.dex.visitors.typeinference.FixTypesVisitor.tryFieldTypeWithNewCasts(FixTypesVisitor.java:359)
    	at jadx.core.dex.visitors.typeinference.FixTypesVisitor.applyFieldType(FixTypesVisitor.java:309)
    	at jadx.core.dex.visitors.typeinference.FixTypesVisitor.visit(FixTypesVisitor.java:94)
     */
    @Override // org.snmp4j.mp.MessageProcessingModel
    /*
        Code decompiled incorrectly, please refer to instructions dump.
        To view partially-correct add '--show-bad-code' argument
    */
    public int prepareDataElements(org.snmp4j.MessageDispatcher r29, org.snmp4j.smi.Address r30, org.snmp4j.asn1.BERInputStream r31, org.snmp4j.TransportStateReference r32, org.snmp4j.smi.Integer32 r33, org.snmp4j.smi.Integer32 r34, org.snmp4j.smi.OctetString r35, org.snmp4j.smi.Integer32 r36, org.snmp4j.MutablePDU r37, org.snmp4j.mp.PduHandle r38, org.snmp4j.smi.Integer32 r39, org.snmp4j.mp.StatusInformation r40, org.snmp4j.mp.MutableStateReference r41) {
        /*
            Method dump skipped, instruction units count: 1458
            To view this dump add '--comments-level debug' option
        */
        throw new UnsupportedOperationException("Method not decompiled: org.snmp4j.mp.MPv3.prepareDataElements(org.snmp4j.MessageDispatcher, org.snmp4j.smi.Address, org.snmp4j.asn1.BERInputStream, org.snmp4j.TransportStateReference, org.snmp4j.smi.Integer32, org.snmp4j.smi.Integer32, org.snmp4j.smi.OctetString, org.snmp4j.smi.Integer32, org.snmp4j.MutablePDU, org.snmp4j.mp.PduHandle, org.snmp4j.smi.Integer32, org.snmp4j.mp.StatusInformation, org.snmp4j.mp.MutableStateReference):int");
    }

    /* JADX WARN: Removed duplicated region for block: B:56:0x0135  */
    /* JADX WARN: Removed duplicated region for block: B:64:0x0144  */
    /* JADX WARN: Removed duplicated region for block: B:65:0x0149  */
    @Override // org.snmp4j.mp.MessageProcessingModel
    /*
        Code decompiled incorrectly, please refer to instructions dump.
        To view partially-correct add '--show-bad-code' argument
    */
    public int prepareOutgoingMessage(org.snmp4j.smi.Address r23, int r24, int r25, int r26, byte[] r27, int r28, org.snmp4j.PDU r29, boolean r30, org.snmp4j.mp.PduHandle r31, org.snmp4j.smi.Address r32, org.snmp4j.asn1.BEROutputStream r33, org.snmp4j.TransportStateReference r34) throws java.io.IOException {
        /*
            Method dump skipped, instruction units count: 475
            To view this dump add '--comments-level debug' option
        */
        throw new UnsupportedOperationException("Method not decompiled: org.snmp4j.mp.MPv3.prepareOutgoingMessage(org.snmp4j.smi.Address, int, int, int, byte[], int, org.snmp4j.PDU, boolean, org.snmp4j.mp.PduHandle, org.snmp4j.smi.Address, org.snmp4j.asn1.BEROutputStream, org.snmp4j.TransportStateReference):int");
    }

    @Override // org.snmp4j.mp.MessageProcessingModel
    public int prepareResponseMessage(int i2, int i3, int i4, byte[] bArr, int i5, PDU pdu, int i6, StateReference stateReference, StatusInformation statusInformation, BEROutputStream bEROutputStream) throws IOException {
        BEROutputStream bEROutputStream2;
        StateReference stateReferencePopEntry = this.cache.popEntry(stateReference.getMsgID().getID());
        if (stateReferencePopEntry == null) {
            return SnmpConstants.SNMP_MP_UNKNOWN_MSGID;
        }
        int bERLength = pdu.getBERLength();
        int i7 = 0;
        if (bERLength > i6) {
            ScopedPDU scopedPDU = new ScopedPDU((ScopedPDU) pdu);
            scopedPDU.clear();
            scopedPDU.setRequestID(pdu.getRequestID());
            scopedPDU.setErrorStatus(1);
            scopedPDU.setErrorIndex(0);
            bEROutputStream2 = new BEROutputStream(ByteBuffer.allocate(scopedPDU.getBERLength()));
            scopedPDU.encodeBER(bEROutputStream2);
        } else {
            bEROutputStream2 = new BEROutputStream(ByteBuffer.allocate(bERLength));
            pdu.encodeBER(bEROutputStream2);
        }
        HeaderData headerData = new HeaderData();
        if (i5 != 1) {
            if (i5 == 2) {
                i7 = 1;
            } else if (i5 == 3) {
                i7 = 3;
            }
        }
        headerData.setMsgFlags(i7);
        headerData.setMsgID(stateReference.getMsgID().getID());
        headerData.setMsgMaxSize(i3);
        headerData.setSecurityModel(i4);
        ByteBuffer byteBufferAllocate = ByteBuffer.allocate(headerData.getBERLength());
        headerData.encodeBER(new BEROutputStream(byteBufferAllocate));
        int type = pdu.getType();
        OctetString octetString = (type == -94 || type == -92 || type == -89 || type == -88) ? new OctetString(this.localEngineID) : new OctetString(stateReferencePopEntry.getSecurityEngineID());
        BERInputStream bERInputStream = new BERInputStream(bEROutputStream2.rewind());
        SecurityModel securityModel = this.securityModels.getSecurityModel(new Integer32(i4));
        return securityModel.generateResponseMessage(getID(), byteBufferAllocate.array(), i3, i4, octetString.getValue(), bArr, i5, bERInputStream, stateReferencePopEntry.getSecurityStateReference(), securityModel.newSecurityParametersInstance(), bEROutputStream);
    }

    @Override // org.snmp4j.mp.MessageProcessingModel
    public void releaseStateReference(PduHandle pduHandle) {
        this.cache.deleteEntry(pduHandle);
    }

    public OctetString removeEngineID(Address address) {
        OctetString octetStringRemove = this.engineIDs.remove(address);
        if (octetStringRemove != null && this.snmpEngineListeners != null) {
            fireEngineChanged(new SnmpEngineEvent(this, 2, octetStringRemove, address));
        }
        return octetStringRemove;
    }

    public synchronized void removeSnmpEngineListener(SnmpEngineListener snmpEngineListener) {
        List<SnmpEngineListener> list = this.snmpEngineListeners;
        if (list != null) {
            ArrayList arrayList = new ArrayList(list);
            arrayList.remove(snmpEngineListener);
            this.snmpEngineListeners = arrayList;
        }
    }

    public int sendReport(MessageDispatcher messageDispatcher, ScopedPDU scopedPDU, int i2, int i3, OctetString octetString, int i4, StateReference stateReference, VariableBinding variableBinding) {
        ScopedPDU scopedPDU2 = new ScopedPDU();
        scopedPDU2.setType(-88);
        if (scopedPDU != null) {
            scopedPDU2.setContextEngineID(scopedPDU.getContextEngineID());
            scopedPDU2.setContextName(scopedPDU.getContextName());
            scopedPDU2.setRequestID(scopedPDU.getRequestID());
        } else {
            scopedPDU2.setContextEngineID(new OctetString(getLocalEngineID()));
        }
        scopedPDU2.add(variableBinding);
        try {
            int iReturnResponsePdu = messageDispatcher.returnResponsePdu(getID(), i3, octetString.getValue(), i2, scopedPDU2, i4, stateReference, new StatusInformation());
            if (iReturnResponsePdu == 0) {
                return 0;
            }
            logger.warn("Error while sending report: " + iReturnResponsePdu);
            return SnmpConstants.SNMP_MP_ERROR;
        } catch (MessageException e2) {
            logger.error("Error while sending report: " + e2.getMessage());
            return SnmpConstants.SNMP_MP_ERROR;
        }
    }

    public void setCounterSupport(CounterSupport counterSupport) {
        if (counterSupport == null) {
            throw null;
        }
        this.counterSupport = counterSupport;
    }

    public void setCurrentMsgID(int i2) {
        this.currentMsgID = i2;
    }

    public void setEngineIdCacheFactory(EngineIdCacheFactory engineIdCacheFactory) {
        this.engineIDs = engineIdCacheFactory.createEngineIdMap(this);
        this.engineIdCacheFactory = engineIdCacheFactory;
    }

    public void setLocalEngineID(byte[] bArr) {
        if (bArr == null || bArr.length < 5 || bArr.length > 32) {
            throw new IllegalArgumentException("Illegal (local) engine ID");
        }
        this.localEngineID = bArr;
    }

    public void setMaxEngineIdCacheSize(int i2) {
        this.maxEngineIdCacheSize = i2;
    }

    public void setSecurityModels(SecurityModels securityModels) {
        this.securityModels = securityModels;
    }

    public void setSecurityProtocols(SecurityProtocols securityProtocols) {
        this.securityProtocols = securityProtocols;
    }

    public MPv3(byte[] bArr) {
        this(bArr, null);
        setLocalEngineID(bArr);
    }

    public MPv3(byte[] bArr, PDUFactory pDUFactory) {
        this(bArr, pDUFactory, SecurityProtocols.getInstance(), SecurityModels.getInstance(), CounterSupport.getInstance());
    }

    public MPv3(USM usm) {
        this(usm.getLocalEngineID().getValue(), null, SecurityProtocols.getInstance(), SecurityModels.getCollection(new SecurityModel[]{usm}), CounterSupport.getInstance());
    }

    public MPv3(byte[] bArr, PDUFactory pDUFactory, SecurityProtocols securityProtocols, SecurityModels securityModels, CounterSupport counterSupport) {
        this.maxEngineIdCacheSize = SNMP4JSettings.getMaxEngineIdCacheSize();
        this.currentMsgID = new Random().nextInt(MAX_MESSAGE_ID);
        this.engineIdCacheFactory = new LimitedCapacityEngineIdCacheFactory();
        this.incomingPDUFactory = new PDUFactory() { // from class: org.snmp4j.mp.MPv3.1
            @Override // org.snmp4j.util.PDUFactory
            public PDU createPDU(Target target) {
                return new ScopedPDU();
            }

            @Override // org.snmp4j.util.PDUFactory
            public PDU createPDU(MessageProcessingModel messageProcessingModel) {
                return new ScopedPDU();
            }
        };
        if (pDUFactory != null) {
            this.incomingPDUFactory = pDUFactory;
        }
        this.engineIDs = this.engineIdCacheFactory.createEngineIdMap(this);
        this.cache = new Cache();
        if (securityProtocols != null) {
            this.securityProtocols = securityProtocols;
            if (securityModels != null) {
                this.securityModels = securityModels;
                if (counterSupport != null) {
                    this.counterSupport = counterSupport;
                    setLocalEngineID(bArr);
                    SecurityModel securityModel = securityModels.getSecurityModel(new Integer32(3));
                    if (securityModel instanceof USM) {
                        setCurrentMsgID(randomMsgID(((USM) securityModel).getEngineBoots()));
                        return;
                    }
                    return;
                }
                throw null;
            }
            throw null;
        }
        throw null;
    }

    public static byte[] createLocalEngineID(OctetString octetString) {
        int enterpriseID = SNMP4JSettings.getEnterpriseID();
        OctetString octetString2 = new OctetString(new byte[]{(byte) (((enterpriseID >> 24) & DisplayString.MAX_SIZE) | 128), (byte) ((enterpriseID >> 16) & DisplayString.MAX_SIZE), (byte) ((enterpriseID >> 8) & DisplayString.MAX_SIZE), (byte) (enterpriseID & DisplayString.MAX_SIZE), 4});
        octetString2.append(octetString);
        return octetString2.getValue();
    }
}
