Esempio n. 1
0
 def n_TrapV1Params_exit(self, cbCtx, node):
     snmpEngine, ctx = cbCtx
     # Initialize v1 PDU with passed params, then proxy it into v2c PDU
     v1Pdu = v1.TrapPDU()
     v1.apiTrapPDU.setDefaults(v1Pdu)
     if 'EnterpriseOid' in ctx:
         v1.apiTrapPDU.setEnterprise(v1Pdu, ctx['EnterpriseOid'])
     if 'AgentName' in ctx:
         v1.apiTrapPDU.setAgentAddr(v1Pdu, ctx['AgentName'])
     if 'GenericTrap' in ctx:
         v1.apiTrapPDU.setGenericTrap(v1Pdu, ctx['GenericTrap'])
     if 'SpecificTrap' in ctx:
         v1.apiTrapPDU.setSpecificTrap(v1Pdu, ctx['SpecificTrap'])
     if 'Uptime' in ctx:
         v1.apiTrapPDU.setTimeStamp(v1Pdu, ctx['Uptime'])
     ctx['pdu'] = rfc2576.v1ToV2(v1Pdu)
Esempio n. 2
0
 def n_TrapV1Params_exit(self, cbCtx, node):
     snmpEngine, ctx = cbCtx
     # Initialize v1 PDU with passed params, then proxy it into v2c PDU
     v1Pdu = v1.TrapPDU()
     v1.apiTrapPDU.setDefaults(v1Pdu)
     if 'EnterpriseOid' in ctx:
         v1.apiTrapPDU.setEnterprise(v1Pdu, ctx['EnterpriseOid'])
     if 'AgentName' in ctx:
         v1.apiTrapPDU.setAgentAddr(v1Pdu, ctx['AgentName'])
     if 'GenericTrap' in ctx:
         v1.apiTrapPDU.setGenericTrap(v1Pdu, ctx['GenericTrap'])
     if 'SpecificTrap' in ctx:
         v1.apiTrapPDU.setSpecificTrap(v1Pdu, ctx['SpecificTrap'])
     if 'Uptime' in ctx:
         v1.apiTrapPDU.setTimeStamp(v1Pdu, ctx['Uptime'])
     ctx['pdu'] = rfc2576.v1ToV2(v1Pdu)
Esempio n. 3
0
    def processPdu(self, snmpEngine, messageProcessingModel, securityModel,
                   securityName, securityLevel, contextEngineId, contextName,
                   pduVersion, PDU, maxSizeResponseScopedPDU, stateReference):

        # Agent-side API complies with SMIv2
        if messageProcessingModel == 0:
            origPdu = PDU
            PDU = rfc2576.v1ToV2(PDU)
        else:
            origPdu = None

        # 3.2.1
        if (PDU.tagSet not in rfc3411.readClassPDUs
                and PDU.tagSet not in rfc3411.writeClassPDUs):
            raise error.ProtocolError('Unexpected PDU class %s' % PDU.tagSet)

        # 3.2.2 --> no-op

        # 3.2.4
        rspPDU = v2c.apiPDU.getResponse(PDU)

        statusInformation = {}

        self.__pendingReqs[stateReference] = (messageProcessingModel,
                                              securityModel, securityName,
                                              securityLevel, contextEngineId,
                                              contextName, pduVersion, rspPDU,
                                              origPdu,
                                              maxSizeResponseScopedPDU,
                                              statusInformation)

        # 3.2.5
        varBinds = v2c.apiPDU.getVarBinds(PDU)

        debug.logger & debug.flagApp and debug.logger(
            'processPdu: stateReference %s, varBinds %s' %
            (stateReference, varBinds))

        self.initiateMgmtOperation(snmpEngine, stateReference, contextName,
                                   PDU)
Esempio n. 4
0
    def processPdu(self, snmpEngine, messageProcessingModel, securityModel,
                   securityName, securityLevel, contextEngineId, contextName,
                   pduVersion, PDU, maxSizeResponseScopedPDU, stateReference):

        # Agent-side API complies with SMIv2
        if messageProcessingModel == 0:
            origPdu = PDU
            PDU = rfc2576.v1ToV2(PDU)
        else:
            origPdu = None

        # 3.2.1
        if (PDU.tagSet not in rfc3411.READ_CLASS_PDUS and
                PDU.tagSet not in rfc3411.WRITE_CLASS_PDUS):
            raise error.ProtocolError('Unexpected PDU class %s' % PDU.tagSet)

        # 3.2.2 --> no-op

        # 3.2.4
        rspPDU = v2c.apiPDU.getResponse(PDU)

        statusInformation = {}

        self.__pendingReqs[stateReference] = (
            messageProcessingModel, securityModel, securityName,
            securityLevel, contextEngineId, contextName, pduVersion,
            rspPDU, origPdu, maxSizeResponseScopedPDU, statusInformation
        )

        # 3.2.5
        varBinds = v2c.apiPDU.getVarBinds(PDU)

        debug.logger & debug.FLAG_APP and debug.logger(
            'processPdu: stateReference %s, varBinds %s' % (stateReference, varBinds))

        self.initiateMgmtOperation(snmpEngine, stateReference, contextName, PDU)
Esempio n. 5
0
    def processPdu(
        self,
        snmpEngine,
        messageProcessingModel,
        securityModel,
        securityName,
        securityLevel,
        contextEngineId,
        contextName,
        pduVersion,
        PDU,
        maxSizeResponseScopedPDU,
        stateReference,
    ):

        # Agent-side API complies with SMIv2
        if messageProcessingModel == 0:
            origPdu = PDU
            PDU = rfc2576.v1ToV2(PDU)
        else:
            origPdu = None

        # 3.2.1
        if PDU.tagSet not in rfc3411.readClassPDUs and PDU.tagSet not in rfc3411.writeClassPDUs:
            raise error.ProtocolError("Unexpected PDU class %s" % PDU.tagSet)

        # 3.2.2 --> no-op

        # 3.2.4
        rspPDU = v2c.apiPDU.getResponse(PDU)

        statusInformation = {}

        self.__pendingReqs[stateReference] = (
            messageProcessingModel,
            securityModel,
            securityName,
            securityLevel,
            contextEngineId,
            contextName,
            pduVersion,
            rspPDU,
            origPdu,
            maxSizeResponseScopedPDU,
            statusInformation,
        )

        # 3.2.5
        varBinds = v2c.apiPDU.getVarBinds(PDU)
        errorStatus, errorIndex = "noError", 0

        debug.logger & debug.flagApp and debug.logger(
            "processPdu: stateReference %s, varBinds %s" % (stateReference, varBinds)
        )

        try:
            self.handleMgmtOperation(snmpEngine, stateReference, contextName, PDU, (self.__verifyAccess, snmpEngine))
        # SNMPv2 SMI exceptions
        except pysnmp.smi.error.GenError:
            errorIndication = sys.exc_info()[1]
            debug.logger & debug.flagApp and debug.logger(
                "processPdu: stateReference %s, errorIndication %s" % (stateReference, errorIndication)
            )
            if "oid" in errorIndication:
                # Request REPORT generation
                statusInformation["oid"] = errorIndication["oid"]
                statusInformation["val"] = errorIndication["val"]

        # PDU-level SMI errors
        except pysnmp.smi.error.NoAccessError:
            errorStatus, errorIndex = "noAccess", sys.exc_info()[1]["idx"] + 1
        except pysnmp.smi.error.WrongTypeError:
            errorStatus, errorIndex = "wrongType", sys.exc_info()[1]["idx"] + 1
        except pysnmp.smi.error.WrongLengthError:
            errorStatus, errorIndex = "wrongLength", sys.exc_info()[1]["idx"] + 1
        except pysnmp.smi.error.WrongEncodingError:
            errorStatus, errorIndex = "wrongEncoding", sys.exc_info()[1]["idx"] + 1
        except pysnmp.smi.error.WrongValueError:
            errorStatus, errorIndex = "wrongValue", sys.exc_info()[1]["idx"] + 1
        except pysnmp.smi.error.NoCreationError:
            errorStatus, errorIndex = "noCreation", sys.exc_info()[1]["idx"] + 1
        except pysnmp.smi.error.InconsistentValueError:
            errorStatus, errorIndex = "inconsistentValue", sys.exc_info()[1]["idx"] + 1
        except pysnmp.smi.error.ResourceUnavailableError:
            errorStatus, errorIndex = "resourceUnavailable", sys.exc_info()[1]["idx"] + 1
        except pysnmp.smi.error.CommitFailedError:
            errorStatus, errorIndex = "commitFailed", sys.exc_info()[1]["idx"] + 1
        except pysnmp.smi.error.UndoFailedError:
            errorStatus, errorIndex = "undoFailed", sys.exc_info()[1]["idx"] + 1
        except pysnmp.smi.error.AuthorizationError:
            errorStatus, errorIndex = "authorizationError", sys.exc_info()[1]["idx"] + 1
        except pysnmp.smi.error.NotWritableError:
            errorStatus, errorIndex = "notWritable", sys.exc_info()[1]["idx"] + 1
        except pysnmp.smi.error.InconsistentNameError:
            errorStatus, errorIndex = "inconsistentName", sys.exc_info()[1]["idx"] + 1
        except pysnmp.smi.error.SmiError:
            errorStatus, errorIndex = "genErr", len(varBinds) and 1 or 0
        except pysnmp.error.PySnmpError:
            self.releaseStateInformation(stateReference)
            return
        else:  # successful request processor must release state info
            return

        self.sendVarBinds(snmpEngine, stateReference, errorStatus, errorIndex, varBinds)

        self.releaseStateInformation(stateReference)
Esempio n. 6
0
    def processPdu(self, snmpEngine, messageProcessingModel, securityModel,
                   securityName, securityLevel, contextEngineId, contextName,
                   pduVersion, PDU, maxSizeResponseScopedPDU, stateReference):

        # Agent-side API complies with SMIv2
        if messageProcessingModel == 0:
            origPdu = PDU
            PDU = rfc2576.v1ToV2(PDU)
        else:
            origPdu = None

        # 3.2.1
        if PDU.tagSet not in rfc3411.readClassPDUs and \
           PDU.tagSet not in rfc3411.writeClassPDUs:
            raise error.ProtocolError('Unexpected PDU class %s' % PDU.tagSet)

        # 3.2.2 --> no-op

        # 3.2.4
        rspPDU = v2c.apiPDU.getResponse(PDU)

        statusInformation = {}

        self.__pendingReqs[stateReference] = (messageProcessingModel,
                                              securityModel, securityName,
                                              securityLevel, contextEngineId,
                                              contextName, pduVersion, rspPDU,
                                              origPdu,
                                              maxSizeResponseScopedPDU,
                                              statusInformation)

        acCtx = (snmpEngine, securityModel, securityName, securityLevel,
                 contextName, PDU.getTagSet())

        # 3.2.5
        varBinds = v2c.apiPDU.getVarBinds(PDU)
        errorStatus, errorIndex = 'noError', 0

        debug.logger & debug.flagApp and debug.logger(
            'processPdu: stateReference %s, varBinds %s' %
            (stateReference, varBinds))

        try:
            self.handleMgmtOperation(snmpEngine, stateReference, contextName,
                                     PDU, (self.__verifyAccess, acCtx))
        # SNMPv2 SMI exceptions
        except pysnmp.smi.error.GenError:
            errorIndication = sys.exc_info()[1]
            debug.logger & debug.flagApp and debug.logger(
                'processPdu: stateReference %s, errorIndication %s' %
                (stateReference, errorIndication))
            if 'oid' in errorIndication:
                # Request REPORT generation
                statusInformation['oid'] = errorIndication['oid']
                statusInformation['val'] = errorIndication['val']

        # PDU-level SMI errors
        except pysnmp.smi.error.NoAccessError:
            errorStatus, errorIndex = 'noAccess', sys.exc_info()[1]['idx'] + 1
        except pysnmp.smi.error.WrongTypeError:
            errorStatus, errorIndex = 'wrongType', sys.exc_info()[1]['idx'] + 1
        except pysnmp.smi.error.WrongValueError:
            errorStatus, errorIndex = 'wrongValue', sys.exc_info(
            )[1]['idx'] + 1
        except pysnmp.smi.error.NoCreationError:
            errorStatus, errorIndex = 'noCreation', sys.exc_info(
            )[1]['idx'] + 1
        except pysnmp.smi.error.InconsistentValueError:
            errorStatus, errorIndex = 'inconsistentValue', sys.exc_info(
            )[1]['idx'] + 1
        except pysnmp.smi.error.ResourceUnavailableError:
            errorStatus, errorIndex = 'resourceUnavailable', sys.exc_info(
            )[1]['idx'] + 1
        except pysnmp.smi.error.CommitFailedError:
            errorStatus, errorIndex = 'commitFailed', sys.exc_info(
            )[1]['idx'] + 1
        except pysnmp.smi.error.UndoFailedError:
            errorStatus, errorIndex = 'undoFailed', sys.exc_info(
            )[1]['idx'] + 1
        except pysnmp.smi.error.AuthorizationError:
            errorStatus, errorIndex = 'authorizationError', sys.exc_info(
            )[1]['idx'] + 1
        except pysnmp.smi.error.NotWritableError:
            errorStatus, errorIndex = 'notWritable', sys.exc_info(
            )[1]['idx'] + 1
        except pysnmp.smi.error.InconsistentNameError:
            errorStatus, errorIndex = 'inconsistentName', sys.exc_info(
            )[1]['idx'] + 1
        except pysnmp.smi.error.SmiError:
            errorStatus, errorIndex = 'genErr', len(varBinds) and 1 or 0
        except pysnmp.error.PySnmpError:
            self.releaseStateInformation(stateReference)
            return
        else:  # successful request processor must release state info
            return

        self.sendRsp(snmpEngine, stateReference, errorStatus, errorIndex,
                     varBinds)

        self.releaseStateInformation(stateReference)
Esempio n. 7
0
    def processPdu(self, snmpEngine, messageProcessingModel,
                   securityModel, securityName, securityLevel,
                   contextEngineId, contextName, pduVersion, PDU,
                   maxSizeResponseScopedPDU, stateReference):

        # Agent-side API complies with SMIv2
        if messageProcessingModel == 0:
            origPdu = PDU
            PDU = rfc2576.v1ToV2(PDU, snmpTrapCommunity=self.__snmpTrapCommunity)
        else:
            origPdu = None

        errorStatus = 'noError'
        errorIndex = 0
        varBinds = v2c.apiPDU.getVarBinds(PDU)

        debug.logger & debug.flagApp and debug.logger(
            'processPdu: stateReference %s, varBinds %s' % (stateReference, varBinds))

        # 3.4
        if PDU.tagSet in rfc3411.confirmedClassPDUs:
            # 3.4.1 --> no-op

            rspPDU = v2c.apiPDU.getResponse(PDU)

            # 3.4.2
            v2c.apiPDU.setErrorStatus(rspPDU, errorStatus)
            v2c.apiPDU.setErrorIndex(rspPDU, errorIndex)
            v2c.apiPDU.setVarBinds(rspPDU, varBinds)

            debug.logger & debug.flagApp and debug.logger(
                'processPdu: stateReference %s, confirm PDU %s' % (stateReference, rspPDU.prettyPrint()))

            # Agent-side API complies with SMIv2
            if messageProcessingModel == 0:
                rspPDU = rfc2576.v2ToV1(rspPDU, origPdu)

            statusInformation = {}

            # 3.4.3
            try:
                snmpEngine.msgAndPduDsp.returnResponsePdu(
                    snmpEngine, messageProcessingModel, securityModel,
                    securityName, securityLevel, contextEngineId,
                    contextName, pduVersion, rspPDU, maxSizeResponseScopedPDU,
                    stateReference, statusInformation)

            except error.StatusInformation:
                debug.logger & debug.flagApp and debug.logger(
                    'processPdu: stateReference %s, statusInformation %s' % (stateReference, sys.exc_info()[1]))
                snmpSilentDrops, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB',
                                                                                                         'snmpSilentDrops')
                snmpSilentDrops.syntax += 1

        elif PDU.tagSet in rfc3411.unconfirmedClassPDUs:
            pass
        else:
            raise error.ProtocolError('Unexpected PDU class %s' % PDU.tagSet)

        debug.logger & debug.flagApp and debug.logger(
            'processPdu: stateReference %s, user cbFun %s, cbCtx %s, varBinds %s' % (
                stateReference, self.__cbFun, self.__cbCtx, varBinds))

        self.__cbFun(snmpEngine, stateReference, contextEngineId,
                     contextName, varBinds, self.__cbCtx)
Esempio n. 8
0
    def processPdu(self, snmpEngine, messageProcessingModel,
                   securityModel, securityName, securityLevel,
                   contextEngineId, contextName, pduVersion, PDU,
                   maxSizeResponseScopedPDU, stateReference):

        # Agent-side API complies with SMIv2
        if messageProcessingModel == 0:
            origPdu = PDU
            PDU = rfc2576.v1ToV2(PDU)
        else:
            origPdu = None

        errorStatus = 'noError'
        errorIndex = 0
        varBinds = v2c.apiPDU.getVarBinds(PDU)

        debug.logger & debug.flagApp and debug.logger(
            'processPdu: stateReference %s, varBinds %s' % (stateReference, varBinds))

        # 3.4
        if PDU.tagSet in rfc3411.confirmedClassPDUs:
            # 3.4.1 --> no-op

            rspPDU = v2c.apiPDU.getResponse(PDU)

            # 3.4.2
            v2c.apiPDU.setErrorStatus(rspPDU, errorStatus)
            v2c.apiPDU.setErrorIndex(rspPDU, errorIndex)
            v2c.apiPDU.setVarBinds(rspPDU, varBinds)

            debug.logger & debug.flagApp and debug.logger(
                'processPdu: stateReference %s, confirm PDU %s' % (stateReference, rspPDU.prettyPrint()))

            # Agent-side API complies with SMIv2
            if messageProcessingModel == 0:
                rspPDU = rfc2576.v2ToV1(rspPDU, origPdu)

            statusInformation = {}

            # 3.4.3
            try:
                snmpEngine.msgAndPduDsp.returnResponsePdu(
                    snmpEngine, messageProcessingModel, securityModel,
                    securityName, securityLevel, contextEngineId,
                    contextName, pduVersion, rspPDU, maxSizeResponseScopedPDU,
                    stateReference, statusInformation)

            except error.StatusInformation:
                debug.logger & debug.flagApp and debug.logger(
                    'processPdu: stateReference %s, statusInformation %s' % (stateReference, sys.exc_info()[1]))
                snmpSilentDrops, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB',
                                                                                                         'snmpSilentDrops')
                snmpSilentDrops.syntax += 1

        elif PDU.tagSet in rfc3411.unconfirmedClassPDUs:
            pass
        else:
            raise error.ProtocolError('Unexpected PDU class %s' % PDU.tagSet)

        debug.logger & debug.flagApp and debug.logger(
            'processPdu: stateReference %s, user cbFun %s, cbCtx %s, varBinds %s' % (
                stateReference, self.__cbFun, self.__cbCtx, varBinds))

        if self.__cbFunVer:
            self.__cbFun(snmpEngine, stateReference, contextEngineId,
                         contextName, varBinds, self.__cbCtx)
        else:
            # Compatibility stub (handle legacy cbFun interface)
            try:
                self.__cbFun(snmpEngine, contextEngineId, contextName,
                             varBinds, self.__cbCtx)
            except TypeError:
                self.__cbFunVer = 1
                self.__cbFun(snmpEngine, stateReference, contextEngineId,
                             contextName, varBinds, self.__cbCtx)
Esempio n. 9
0
    def processResponsePdu(self, snmpEngine, messageProcessingModel,
                           securityModel, securityName, securityLevel,
                           contextEngineId, contextName, pduVersion,
                           PDU, statusInformation, sendPduHandle, cbCtx):
        origSendRequestHandle, cbFun, cbCtx = cbCtx

        # 3.1.1
        if sendPduHandle not in self.__pendingReqs:
            raise error.PySnmpError('Missing sendPduHandle %s' % sendPduHandle)

        (origTransportDomain, origTransportAddress,
         origMessageProcessingModel, origSecurityModel,
         origSecurityName, origSecurityLevel, origContextEngineId,
         origContextName, origPduVersion, origPdu,
         origTimeout, origRetryCount,
         origRetries) = self.__pendingReqs.pop(sendPduHandle)

        snmpEngine.transportDispatcher.jobFinished(id(self))

        # 3.1.3
        if statusInformation:
            debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendPduHandle %s, statusInformation %s' % (sendPduHandle, statusInformation))
            errorIndication = statusInformation['errorIndication']
            # SNMP engine discovery will take extra retries, allow that
            if errorIndication in (errind.notInTimeWindow,
                                   errind.unknownEngineID) and \
                                   origRetries == origRetryCount + 2 or \
               errorIndication not in (errind.notInTimeWindow,
                                       errind.unknownEngineID) and \
                                   origRetries == origRetryCount:
                debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendPduHandle %s, retry count %d exceeded' % (sendPduHandle, origRetries))
                cbFun(snmpEngine, origSendRequestHandle,
                      statusInformation['errorIndication'], None, cbCtx)
                return
            try:
                sendPduHandle = snmpEngine.msgAndPduDsp.sendPdu(
                    snmpEngine, origTransportDomain, origTransportAddress,
                    origMessageProcessingModel, origSecurityModel,
                    origSecurityName, origSecurityLevel, origContextEngineId,
                    origContextName, origPduVersion, origPdu,
                    True, origTimeout, self.processResponsePdu,
                    (origSendRequestHandle, cbFun, cbCtx))

                snmpEngine.transportDispatcher.jobStarted(id(self))

                self.__pendingReqs[sendPduHandle] = (
                    origTransportDomain, origTransportAddress,
                    origMessageProcessingModel, origSecurityModel,
                    origSecurityName, origSecurityLevel, origContextEngineId,
                    origContextName, origPduVersion, origPdu, origTimeout,
                    origRetryCount, origRetries + 1
                )
                return

            except StatusInformation:
                statusInformation = sys.exc_info()[1]
                debug.logger & debug.flagApp and debug.logger('processResponsePdu: origSendRequestHandle %s, _sendPdu() failed with %r' % (sendPduHandle, statusInformation))
                cbFun(snmpEngine, origSendRequestHandle,
                      statusInformation['errorIndication'],
                      None, cbCtx)
                return

        if origMessageProcessingModel != messageProcessingModel or \
           origSecurityModel != securityModel or \
           origSecurityName != origSecurityName or \
           origContextEngineId and origContextEngineId != contextEngineId or \
           origContextName and origContextName != contextName or \
           origPduVersion != pduVersion:
            debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendPduHandle %s, request/response data mismatch' % sendPduHandle)

            cbFun(snmpEngine, origSendRequestHandle,
                  'badResponse', None, cbCtx)
            return

        # User-side API assumes SMIv2
        if messageProcessingModel == 0:
            PDU = rfc2576.v1ToV2(PDU, origPdu)

        # 3.1.2
        if v2c.apiPDU.getRequestID(PDU) != v2c.apiPDU.getRequestID(origPdu):
            debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendPduHandle %s, request-id/response-id mismatch' % sendPduHandle)
            cbFun(snmpEngine, origSendRequestHandle,
                  'badResponse', None, cbCtx)
            return

        cbFun(snmpEngine, origSendRequestHandle, None, PDU, cbCtx)
Esempio n. 10
0
    def processResponsePdu(
        self,
        snmpEngine,
        messageProcessingModel,
        securityModel,
        securityName,
        securityLevel,
        contextEngineId,
        contextName,
        pduVersion,
        PDU,
        statusInformation,
        sendPduHandle,
        cbInfo,
    ):
        (cbFun, cbCtx) = cbInfo
        # 3.1.1
        (
            origTransportDomain,
            origTransportAddress,
            origMessageProcessingModel,
            origSecurityModel,
            origSecurityName,
            origSecurityLevel,
            origContextEngineId,
            origContextName,
            origPduVersion,
            origPdu,
            origTimeout,
            origRetryCount,
            origRetries,
            origSendRequestHandle,
        ) = self.__pendingReqs[sendPduHandle]
        del self.__pendingReqs[sendPduHandle]

        snmpEngine.transportDispatcher.jobFinished(id(self))

        # 3.1.3
        if statusInformation:
            debug.logger & debug.flagApp and debug.logger(
                "processResponsePdu: sendPduHandle %s, statusInformation %s" % (sendPduHandle, statusInformation)
            )
            if origRetries == origRetryCount:
                debug.logger & debug.flagApp and debug.logger(
                    "processResponsePdu: sendPduHandle %s, retry count %d exceeded" % (sendPduHandle, origRetries)
                )
                cbFun(origSendRequestHandle, statusInformation["errorIndication"], 0, 0, (), cbCtx)
                return
            self._sendPdu(
                snmpEngine,
                origTransportDomain,
                origTransportAddress,
                origMessageProcessingModel,
                origSecurityModel,
                origSecurityName,
                origSecurityLevel,
                origContextEngineId,
                origContextName,
                origPduVersion,
                origPdu,
                origTimeout,
                origRetryCount,
                origRetries + 1,
                origSendRequestHandle,
                (self.processResponsePdu, (cbFun, cbCtx)),
            )
            return

        if (
            origMessageProcessingModel != messageProcessingModel
            or origSecurityModel != securityModel
            or origSecurityName != origSecurityName
            or origContextEngineId
            and origContextEngineId != contextEngineId
            or origContextName
            and origContextName != contextName
            or origPduVersion != pduVersion
        ):
            debug.logger & debug.flagApp and debug.logger(
                "processResponsePdu: sendPduHandle %s, request/response data mismatch" % sendPduHandle
            )
            cbFun(origSendRequestHandle, "badResponse", 0, 0, (), cbCtx)
            return

        pMod = api.protoModules[pduVersion]

        # 3.1.2
        if pMod.apiPDU.getRequestID(PDU) != pMod.apiPDU.getRequestID(origPdu):
            debug.logger & debug.flagApp and debug.logger(
                "processResponsePdu: sendPduHandle %s, request-id/response-id mismatch" % sendPduHandle
            )
            cbFun(origSendRequestHandle, "badResponse", 0, 0, (), cbCtx)
            return

        # User-side API assumes SMIv2
        if messageProcessingModel == 0:
            PDU = rfc2576.v1ToV2(PDU, origPdu)
            pMod = api.protoModules[api.protoVersion2c]

        self._handleResponse(
            snmpEngine,
            origTransportDomain,
            origTransportAddress,
            origMessageProcessingModel,
            origSecurityModel,
            origSecurityName,
            origSecurityLevel,
            origContextEngineId,
            origContextName,
            origPduVersion,
            origPdu,
            origTimeout,
            origRetryCount,
            pMod,
            PDU,
            origSendRequestHandle,
            (cbFun, cbCtx),
        )
Esempio n. 11
0
    def processResponsePdu(self, snmpEngine, messageProcessingModel,
                           securityModel, securityName, securityLevel,
                           contextEngineId, contextName, pduVersion, PDU,
                           statusInformation, sendPduHandle, cbInfo):
        (cbFun, cbCtx) = cbInfo
        # 3.1.1
        if sendPduHandle not in self.__pendingReqs:
            raise error.PySnmpError('Missing sendPduHandle %s' % sendPduHandle)

        (origTransportDomain, origTransportAddress, origMessageProcessingModel,
         origSecurityModel, origSecurityName, origSecurityLevel,
         origContextEngineId, origContextName, origPduVersion, origPdu,
         origTimeout, origRetryCount, origRetries,
         origSendRequestHandle) = self.__pendingReqs[sendPduHandle]

        del self.__pendingReqs[sendPduHandle]

        snmpEngine.transportDispatcher.jobFinished(id(self))

        # 3.1.3
        if statusInformation:
            debug.logger & debug.flagApp and debug.logger(
                'processResponsePdu: sendPduHandle %s, statusInformation %s' %
                (sendPduHandle, statusInformation))
            errorIndication = statusInformation['errorIndication']
            # SNMP engine discovery will take extra retries, allow that
            if errorIndication in (errind.notInTimeWindow,
                                   errind.unknownEngineID) and \
                                   origRetries == origRetryCount + 2 or \
               errorIndication not in (errind.notInTimeWindow,
                                       errind.unknownEngineID) and \
                                   origRetries == origRetryCount:
                debug.logger & debug.flagApp and debug.logger(
                    'processResponsePdu: sendPduHandle %s, retry count %d exceeded'
                    % (sendPduHandle, origRetries))
                cbFun(origSendRequestHandle,
                      statusInformation['errorIndication'], 0, 0, (), cbCtx)
                return
            try:
                self._sendPdu(snmpEngine, origTransportDomain,
                              origTransportAddress, origMessageProcessingModel,
                              origSecurityModel, origSecurityName,
                              origSecurityLevel, origContextEngineId,
                              origContextName, origPdu, origTimeout,
                              origRetryCount, origRetries + 1,
                              origSendRequestHandle, (self.processResponsePdu,
                                                      (cbFun, cbCtx)))
            except StatusInformation:
                statusInformation = sys.exc_info()[1]
                debug.logger & debug.flagApp and debug.logger(
                    'processResponsePdu: origSendRequestHandle %s, _sendPdu() failed with %r'
                    % (sendPduHandle, statusInformation))
                cbFun(origSendRequestHandle,
                      statusInformation['errorIndication'], 0, 0, (), cbCtx)
            return

        if origMessageProcessingModel != messageProcessingModel or \
           origSecurityModel != securityModel or \
           origSecurityName != origSecurityName or \
           origContextEngineId and origContextEngineId != contextEngineId or \
           origContextName and origContextName != contextName or \
           origPduVersion != pduVersion:
            debug.logger & debug.flagApp and debug.logger(
                'processResponsePdu: sendPduHandle %s, request/response data mismatch'
                % sendPduHandle)
            cbFun(origSendRequestHandle, 'badResponse', 0, 0, (), cbCtx)
            return

        # User-side API assumes SMIv2
        if messageProcessingModel == 0:
            PDU = rfc2576.v1ToV2(PDU, origPdu)

        # 3.1.2
        if v2c.apiPDU.getRequestID(PDU) != v2c.apiPDU.getRequestID(origPdu):
            debug.logger & debug.flagApp and debug.logger(
                'processResponsePdu: sendPduHandle %s, request-id/response-id mismatch'
                % sendPduHandle)
            cbFun(origSendRequestHandle, 'badResponse', 0, 0, (), cbCtx)
            return

        self._handleResponse(
            snmpEngine,
            origTransportDomain,
            origTransportAddress,
            origMessageProcessingModel,
            origSecurityModel,
            origSecurityName,
            origSecurityLevel,
            origContextEngineId,
            origContextName,
            origPdu,
            origTimeout,
            origRetryCount,
            PDU,
            origSendRequestHandle,
            (cbFun, cbCtx),
        )
Esempio n. 12
0
    def processResponsePdu(self, snmpEngine, messageProcessingModel,
                           securityModel, securityName, securityLevel,
                           contextEngineId, contextName, pduVersion, PDU,
                           statusInformation, sendPduHandle, cbInfo):

        sendRequestHandle, cbFun, cbCtx = cbInfo

        # 3.3.6d
        if sendPduHandle not in self.__pendingReqs:
            raise error.ProtocolError('Missing sendPduHandle %s' %
                                      sendPduHandle)

        (origTransportDomain, origTransportAddress, origMessageProcessingModel,
         origSecurityModel, origSecurityName, origSecurityLevel,
         origContextEngineId, origContextName, origPdu, origTimeout,
         origRetryCount, origRetries,
         origDiscoveryRetries) = self.__pendingReqs.pop(sendPduHandle)

        snmpEngine.transportDispatcher.jobFinished(id(self))

        if statusInformation:
            debug.logger & debug.FLAG_APP and debug.logger(
                'processResponsePdu: sendRequestHandle %s, sendPduHandle %s '
                'statusInformation %s' %
                (sendRequestHandle, sendPduHandle, statusInformation))

            errorIndication = statusInformation['errorIndication']

            if errorIndication in (errind.notInTimeWindow,
                                   errind.unknownEngineID):
                origDiscoveryRetries += 1
                origRetries = 0

            else:
                origDiscoveryRetries = 0
                origRetries += 1

            if (origRetries > origRetryCount
                    or origDiscoveryRetries > self.__options.get(
                        'discoveryRetries', 4)):

                debug.logger & debug.FLAG_APP and debug.logger(
                    'processResponsePdu: sendRequestHandle %s, sendPduHandle %s '
                    'retry count %d exceeded' %
                    (sendRequestHandle, sendPduHandle, origRetries))

                cbFun(snmpEngine, sendRequestHandle, errorIndication, None,
                      cbCtx)

                return

            # Convert timeout in seconds into timeout in timer ticks
            timeoutInTicks = (
                float(origTimeout) / 100 /
                snmpEngine.transportDispatcher.getTimerResolution())

            # User-side API assumes SMIv2
            if messageProcessingModel == 0:
                reqPDU = rfc2576.v2ToV1(origPdu)
                pduVersion = 0

            else:
                reqPDU = origPdu
                pduVersion = 1

            # 3.3.6a
            try:
                sendPduHandle = snmpEngine.msgAndPduDsp.sendPdu(
                    snmpEngine, origTransportDomain, origTransportAddress,
                    origMessageProcessingModel, origSecurityModel,
                    origSecurityName, origSecurityLevel, origContextEngineId,
                    origContextName, pduVersion, reqPDU, True, timeoutInTicks,
                    self.processResponsePdu, (sendRequestHandle, cbFun, cbCtx))

            except error.StatusInformation as exc:
                statusInformation = exc

                debug.logger & debug.FLAG_APP and debug.logger(
                    'processResponsePdu: sendRequestHandle %s: sendPdu() '
                    'failed with %r ' % (sendRequestHandle, statusInformation))

                cbFun(snmpEngine, sendRequestHandle,
                      statusInformation['errorIndication'], None, cbCtx)

                return

            snmpEngine.transportDispatcher.jobStarted(id(self))

            debug.logger & debug.FLAG_APP and debug.logger(
                'processResponsePdu: sendRequestHandle %s, sendPduHandle %s, '
                'timeout %d, retry %d of %d' %
                (sendRequestHandle, sendPduHandle, origTimeout, origRetries,
                 origRetryCount))

            # 3.3.6b
            self.__pendingReqs[sendPduHandle] = (
                origTransportDomain, origTransportAddress,
                origMessageProcessingModel, origSecurityModel,
                origSecurityName, origSecurityLevel, origContextEngineId,
                origContextName, origPdu, origTimeout, origRetryCount,
                origRetries, origDiscoveryRetries)

            return

        # 3.3.6c
        # User-side API assumes SMIv2
        if messageProcessingModel == 0:
            PDU = rfc2576.v1ToV2(PDU, origPdu)

        cbFun(snmpEngine, sendRequestHandle, None, PDU, cbCtx)
Esempio n. 13
0
    def processResponsePdu(self, snmpEngine, messageProcessingModel,
                           securityModel, securityName, securityLevel,
                           contextEngineId, contextName, pduVersion,
                           PDU, statusInformation, sendPduHandle, cbCtx):
        origSendRequestHandle, cbFun, cbCtx = cbCtx

        # 3.1.1
        if sendPduHandle not in self.__pendingReqs:
            raise error.PySnmpError('Missing sendPduHandle %s' % sendPduHandle)

        (origTransportDomain, origTransportAddress,
         origMessageProcessingModel, origSecurityModel,
         origSecurityName, origSecurityLevel, origContextEngineId,
         origContextName, origPduVersion, origPdu,
         origTimeout, origRetryCount,
         origRetries, origDiscoveryRetries) = self.__pendingReqs.pop(sendPduHandle)

        snmpEngine.transportDispatcher.jobFinished(id(self))

        # 3.1.3
        if statusInformation:
            debug.logger & debug.FLAG_APP and debug.logger(
                'processResponsePdu: sendPduHandle %s, statusInformation '
                '%s' % (sendPduHandle, statusInformation))

            errorIndication = statusInformation['errorIndication']

            if errorIndication in (errind.notInTimeWindow, errind.unknownEngineID):
                origDiscoveryRetries += 1
                origRetries = 0
            else:
                origDiscoveryRetries = 0
                origRetries += 1

            if (origRetries > origRetryCount or
                    origDiscoveryRetries > self.__options.get('discoveryRetries', 4)):

                debug.logger & debug.FLAG_APP and debug.logger(
                    'processResponsePdu: sendPduHandle %s, retry count %d '
                    'exceeded' % (sendPduHandle, origRetries))

                cbFun(snmpEngine, origSendRequestHandle,
                      errorIndication, None, cbCtx)
                return

            # User-side API assumes SMIv2
            if origMessageProcessingModel == 0:
                reqPDU = rfc2576.v2ToV1(origPdu)
                pduVersion = 0

            else:
                reqPDU = origPdu
                pduVersion = 1

            try:
                sendPduHandle = snmpEngine.msgAndPduDsp.sendPdu(
                    snmpEngine, origTransportDomain, origTransportAddress,
                    origMessageProcessingModel, origSecurityModel,
                    origSecurityName, origSecurityLevel, origContextEngineId,
                    origContextName, pduVersion, reqPDU,
                    True, origTimeout, self.processResponsePdu,
                    (origSendRequestHandle, cbFun, cbCtx))

                snmpEngine.transportDispatcher.jobStarted(id(self))

                self.__pendingReqs[sendPduHandle] = (
                    origTransportDomain, origTransportAddress,
                    origMessageProcessingModel, origSecurityModel,
                    origSecurityName, origSecurityLevel, origContextEngineId,
                    origContextName, origPduVersion, origPdu, origTimeout,
                    origRetryCount, origRetries, origDiscoveryRetries
                )

                return

            except StatusInformation as exc:
                statusInformation = exc

                debug.logger & debug.FLAG_APP and debug.logger(
                    'processResponsePdu: origSendRequestHandle %s, _sendPdu() '
                    'failed with %r' % (sendPduHandle, statusInformation))

                cbFun(snmpEngine, origSendRequestHandle,
                      statusInformation['errorIndication'],
                      None, cbCtx)

                return

        if (origMessageProcessingModel != messageProcessingModel or
                origSecurityModel != securityModel or
                origSecurityName != origSecurityName or
                origContextEngineId and origContextEngineId != contextEngineId or
                origContextName and origContextName != contextName or
                origPduVersion != pduVersion):

            debug.logger & debug.FLAG_APP and debug.logger(
                'processResponsePdu: sendPduHandle %s, request/response '
                'data mismatch' % sendPduHandle)

            cbFun(snmpEngine, origSendRequestHandle,
                  'badResponse', None, cbCtx)

            return

        # User-side API assumes SMIv2
        if messageProcessingModel == 0:
            PDU = rfc2576.v1ToV2(PDU, origPdu)

        # 3.1.2
        if v2c.apiPDU.getRequestID(PDU) != v2c.apiPDU.getRequestID(origPdu):
            debug.logger & debug.FLAG_APP and debug.logger(
                'processResponsePdu: sendPduHandle %s, request-id/response-id '
                'mismatch' % sendPduHandle)

            cbFun(snmpEngine, origSendRequestHandle,
                  'badResponse', None, cbCtx)

            return

        cbFun(snmpEngine, origSendRequestHandle, None, PDU, cbCtx)
Esempio n. 14
0
class CommandGeneratorBase:
    def __init__(self):
        self.__pendingReqs = {}

    def processResponsePdu(self, snmpEngine, messageProcessingModel,
                           securityModel, securityName, securityLevel,
                           contextEngineId, contextName, pduVersion, PDU,
                           statusInformation, sendPduHandle, (cbFun, cbCtx)):
        # 3.1.1
        (origTransportDomain, origTransportAddress, origMessageProcessingModel,
         origSecurityModel, origSecurityName, origSecurityLevel,
         origContextEngineId, origContextName, origPduVersion, origPdu,
         origTimeout, origRetryCount, origRetries,
         origSendRequestHandle) = self.__pendingReqs[sendPduHandle]
        del self.__pendingReqs[sendPduHandle]

        snmpEngine.transportDispatcher.jobFinished(id(self))

        # 3.1.3
        if statusInformation:
            if origRetries == origRetryCount:
                cbFun(origSendRequestHandle,
                      statusInformation['errorIndication'], 0, 0, (), cbCtx)
                return
            self._sendPdu(snmpEngine, origTransportDomain,
                          origTransportAddress, origMessageProcessingModel,
                          origSecurityModel, origSecurityName,
                          origSecurityLevel, origContextEngineId,
                          origContextName, origPduVersion, origPdu,
                          origTimeout, origRetryCount, origRetries,
                          origSendRequestHandle, (self.processResponsePdu,
                                                  (cbFun, cbCtx)))
            return

        if origMessageProcessingModel != messageProcessingModel or \
           origSecurityModel != securityModel or \
           origSecurityName != origSecurityName or \
           origContextEngineId and origContextEngineId != contextEngineId or \
           origContextName and origContextName != contextName or \
           origPduVersion != pduVersion:
            return

        pMod = api.protoModules[pduVersion]

        # 3.1.2
        if pMod.apiPDU.getRequestID(PDU) != pMod.apiPDU.getRequestID(origPdu):
            return

        # User-side API assumes SMIv2
        if messageProcessingModel == 0:
            PDU = rfc2576.v1ToV2(PDU, origPdu)
            pMod = api.protoModules[api.protoVersion2c]

        self._handleResponse(
            snmpEngine,
            origTransportDomain,
            origTransportAddress,
            origMessageProcessingModel,
            origSecurityModel,
            origSecurityName,
            origSecurityLevel,
            origContextEngineId,
            origContextName,
            origPduVersion,
            origPdu,
            origTimeout,
            origRetryCount,
            pMod,
            PDU,
            origSendRequestHandle,
            (cbFun, cbCtx),
        )
Esempio n. 15
0
    def processPdu(
        self,
        snmpEngine,
        messageProcessingModel,
        securityModel,
        securityName,
        securityLevel,
        contextEngineId,
        contextName,
        pduVersion,
        PDU,
        maxSizeResponseScopedPDU,
        stateReference
        ):

        # Agent-side API complies with SMIv2
        if messageProcessingModel == 0:
            origPdu = PDU
            PDU = rfc2576.v1ToV2(PDU)
        else:
            origPdu = None
        
        # 3.2.1
        if PDU.tagSet not in rfc3411.readClassPDUs and \
           PDU.tagSet not in rfc3411.writeClassPDUs:
            raise error.ProtocolError('Unexpected PDU class %s' % PDU.tagSet)
        
        # 3.2.2 --> no-op

        # 3.2.4
        rspPDU = v2c.apiPDU.getResponse(PDU)
        
        statusInformation = {}
       
        self.__pendingReqs[stateReference] = (
            messageProcessingModel,
            securityModel,
            securityName,
            securityLevel,
            contextEngineId,
            contextName,
            pduVersion,
            rspPDU,
            origPdu,
            maxSizeResponseScopedPDU,
            statusInformation
            )

        acCtx = (
            snmpEngine, securityModel, securityName, securityLevel,
            contextName, PDU.getTagSet()
            )

        # 3.2.5
        varBinds = v2c.apiPDU.getVarBinds(PDU)
        errorStatus, errorIndex = 'noError', 0

        debug.logger & debug.flagApp and debug.logger('processPdu: stateReference %s, varBinds %s' % (stateReference, varBinds))
        
        try:
            self.handleMgmtOperation(
                snmpEngine, stateReference,
                contextName, PDU, (self.__verifyAccess, acCtx)
                )
            return
        # SNMPv2 SMI exceptions
        except pysnmp.smi.error.GenError:
            errorIndication = sys.exc_info()[1]
            debug.logger & debug.flagApp and debug.logger('processPdu: stateReference %s, errorIndication %s' % (stateReference, errorIndication))
            if 'oid' in errorIndication:
                # Request REPORT generation
                statusInformation['oid'] = errorIndication['oid'] 
                statusInformation['val'] = errorIndication['val']

        # PDU-level SMI errors
        except pysnmp.smi.error.NoAccessError:
            errorStatus, errorIndex = 'noAccess', sys.exc_info()[1]['idx']+1
        except pysnmp.smi.error.WrongTypeError:
            errorStatus, errorIndex = 'wrongType', sys.exc_info()[1]['idx']+1
        except pysnmp.smi.error.WrongValueError:
            errorStatus, errorIndex = 'wrongValue', sys.exc_info()[1]['idx']+1
        except pysnmp.smi.error.NoCreationError:
            errorStatus, errorIndex = 'noCreation', sys.exc_info()[1]['idx']+1
        except pysnmp.smi.error.InconsistentValueError:
            errorStatus, errorIndex = 'inconsistentValue', sys.exc_info()[1]['idx']+1
        except pysnmp.smi.error.ResourceUnavailableError:
            errorStatus, errorIndex = 'resourceUnavailable', sys.exc_info()[1]['idx']+1
        except pysnmp.smi.error.CommitFailedError:
            errorStatus, errorIndex = 'commitFailedError', sys.exc_info()[1]['idx']+1
        except pysnmp.smi.error.UndoFailedError:
            errorStatus, errorIndex = 'undoFailedError', sys.exc_info()[1]['idx']+1
        except pysnmp.smi.error.AuthorizationError:
            errorStatus, errorIndex = 'authorizationError', sys.exc_info()[1]['idx']+1
        except pysnmp.smi.error.NotWritableError:
            errorStatus, errorIndex = 'notWritable', sys.exc_info()[1]['idx']+1
        except pysnmp.smi.error.InconsistentNameError:
            errorStatus, errorIndex = 'inconsistentName', sys.exc_info()[1]['idx']+1
        except pysnmp.smi.error.SmiError:
            errorStatus, errorIndex = 'genErr', len(varBinds) and 1 or 0
        except pysnmp.error.PySnmpError:
            self.releaseStateInformation(stateReference)
            return
        
        self.sendRsp(
            snmpEngine, stateReference, errorStatus, errorIndex, varBinds
            )

        self.releaseStateInformation(stateReference)
Esempio n. 16
0
    def processResponsePdu(self, snmpEngine, messageProcessingModel,
                           securityModel, securityName, securityLevel,
                           contextEngineId, contextName, pduVersion,
                           PDU, statusInformation, sendPduHandle, cbInfo):

        sendRequestHandle, cbFun, cbCtx = cbInfo

        # 3.3.6d
        if sendPduHandle not in self.__pendingReqs:
            raise error.ProtocolError('Missing sendPduHandle %s' % sendPduHandle)

        (origTransportDomain, origTransportAddress,
         origMessageProcessingModel, origSecurityModel,
         origSecurityName, origSecurityLevel, origContextEngineId,
         origContextName, origPdu, origTimeout,
         origRetryCount, origRetries,
         origDiscoveryRetries) = self.__pendingReqs.pop(sendPduHandle)

        snmpEngine.transportDispatcher.jobFinished(id(self))

        if statusInformation:
            debug.logger & debug.FLAG_APP and debug.logger(
                'processResponsePdu: sendRequestHandle %s, sendPduHandle %s '
                'statusInformation %s' % (sendRequestHandle, sendPduHandle,
                                          statusInformation))

            errorIndication = statusInformation['errorIndication']

            if errorIndication in (errind.notInTimeWindow, errind.unknownEngineID):
                origDiscoveryRetries += 1
                origRetries = 0

            else:
                origDiscoveryRetries = 0
                origRetries += 1

            if (origRetries > origRetryCount or
                    origDiscoveryRetries > self.__options.get('discoveryRetries', 4)):

                debug.logger & debug.FLAG_APP and debug.logger(
                    'processResponsePdu: sendRequestHandle %s, sendPduHandle %s '
                    'retry count %d exceeded' % (
                        sendRequestHandle, sendPduHandle, origRetries))

                cbFun(snmpEngine, sendRequestHandle, errorIndication, None, cbCtx)

                return

            # Convert timeout in seconds into timeout in timer ticks
            timeoutInTicks = (float(origTimeout) / 100 /
                              snmpEngine.transportDispatcher.getTimerResolution())

            # User-side API assumes SMIv2
            if messageProcessingModel == 0:
                reqPDU = rfc2576.v2ToV1(origPdu)
                pduVersion = 0

            else:
                reqPDU = origPdu
                pduVersion = 1

            # 3.3.6a
            try:
                sendPduHandle = snmpEngine.msgAndPduDsp.sendPdu(
                    snmpEngine, origTransportDomain, origTransportAddress,
                    origMessageProcessingModel, origSecurityModel,
                    origSecurityName, origSecurityLevel,
                    origContextEngineId, origContextName, pduVersion,
                    reqPDU, True, timeoutInTicks, self.processResponsePdu,
                    (sendRequestHandle, cbFun, cbCtx)
                )

            except error.StatusInformation as exc:
                statusInformation = exc

                debug.logger & debug.FLAG_APP and debug.logger(
                    'processResponsePdu: sendRequestHandle %s: sendPdu() '
                    'failed with %r ' % (sendRequestHandle, statusInformation))

                cbFun(snmpEngine, sendRequestHandle,
                      statusInformation['errorIndication'], None, cbCtx)

                return

            snmpEngine.transportDispatcher.jobStarted(id(self))

            debug.logger & debug.FLAG_APP and debug.logger(
                'processResponsePdu: sendRequestHandle %s, sendPduHandle %s, '
                'timeout %d, retry %d of %d' % (
                    sendRequestHandle, sendPduHandle, origTimeout, origRetries,
                    origRetryCount))

            # 3.3.6b
            self.__pendingReqs[sendPduHandle] = (
                origTransportDomain, origTransportAddress,
                origMessageProcessingModel, origSecurityModel,
                origSecurityName, origSecurityLevel,
                origContextEngineId, origContextName, origPdu,
                origTimeout, origRetryCount, origRetries, origDiscoveryRetries
            )

            return

        # 3.3.6c
        # User-side API assumes SMIv2
        if messageProcessingModel == 0:
            PDU = rfc2576.v1ToV2(PDU, origPdu)

        cbFun(snmpEngine, sendRequestHandle, None, PDU, cbCtx)
Esempio n. 17
0
        ctx['Uptime'] = long(node[0].attr)

    def n_TrapV1Params_exit(self, (snmpEngine, ctx), node):
        v1Pdu = v1.TrapPDU()
        v1.apiTrapPDU.setDefaults(v1Pdu)
        if ctx.has_key('EnterpriseOid'):
            v1.apiTrapPDU.setEnterprise(v1Pdu, ctx['EnterpriseOid'])
        if ctx.has_key('AgentName'):
            v1.apiTrapPDU.setAgentAddr(v1Pdu, ctx['AgentName'])
        if ctx.has_key('GenericTrap'):
            v1.apiTrapPDU.setGenericTrap(v1Pdu, ctx['GenericTrap'])
        if ctx.has_key('SpecificTrap'):
            v1.apiTrapPDU.setSpecificTrap(v1Pdu, ctx['SpecificTrap'])
        if ctx.has_key('Uptime'):
            v1.apiTrapPDU.setTimeStamp(v1Pdu, ctx['Uptime'])
        v2cPdu = rfc2576.v1ToV2(v1Pdu)
        if not ctx.has_key('varBinds'):
            ctx['varBinds'] = []
        ctx['varBinds'] = v2c.apiPDU.getVarBinds(v2cPdu) + ctx['varBinds']


def generator((snmpEngine, ctx), ast):
    return __Generator().preorder((snmpEngine, ctx), ast)


snmpEngine = engine.SnmpEngine()

try:
    # Parse c/l into AST
    ast = Parser().parse(Scanner().tokenize(string.join(sys.argv[1:], ' ')))
    print(sys.argv[1:])
Esempio n. 18
0
    def processPdu(
        self,
        snmpEngine,
        messageProcessingModel,
        securityModel,
        securityName,
        securityLevel,
        contextEngineId,
        contextName,
        pduVersion,
        PDU,
        maxSizeResponseScopedPDU,
        stateReference
        ):

        # Agent-side API complies with SMIv2
        if messageProcessingModel == 0:
            PDU = rfc2576.v1ToV2(PDU)

        errorStatus = 'noError'; errorIndex = 0
        varBinds = v2c.apiPDU.getVarBinds(PDU)
        
        # 3.4
        if rfc3411.confirmedClassPDUs.has_key(PDU.tagSet):
            # 3.4.1 --> no-op
            
            rspPDU = v2c.apiPDU.getResponse(PDU)
            
            # 3.4.2
            v2c.apiPDU.setErrorStatus(rspPDU, errorStatus)
            v2c.apiPDU.setErrorIndex(rspPDU, errorIndex)
            v2c.apiPDU.setVarBinds(rspPDU, varBinds)

            # Agent-side API complies with SMIv2
            if messageProcessingModel == 0:
                rspPDU = rfc2576.v2ToV1(rspPDU)

            statusInformation = {}
            
            # 3.4.3
            try:
                snmpEngine.msgAndPduDsp.returnResponsePdu(
                    snmpEngine,
                    messageProcessingModel,
                    securityModel,
                    securityName,
                    securityLevel,
                    contextEngineId,
                    contextName,
                    pduVersion,
                    rspPDU,
                    maxSizeResponseScopedPDU,
                    stateReference,
                    statusInformation
                    )
            except error.StatusInformation:
                snmpSilentDrops, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpSilentDrops')
                snmpSilentDrops.syntax = snmpSilentDrops.syntax + 1

        elif rfc3411.unconfirmedClassPDUs.has_key(PDU.tagSet):
            pass
        else:
            raise error.ProtocolError('Unexpected PDU class %s' % PDU.tagSet)

        if self.__cbFunVer:
            self.__cbFun(
                snmpEngine, stateReference, contextEngineId, contextName,
                varBinds, self.__cbCtx
                )
        else:
            # Compatibility stub (handle legacy cbFun interface)
            try:
                self.__cbFun(
                    snmpEngine, contextEngineId, contextName,
                    varBinds, self.__cbCtx
                    )
            except TypeError:
                self.__cbFunVer = 1
                self.__cbFun(
                    snmpEngine, stateReference, contextEngineId, contextName,
                    varBinds, self.__cbCtx
                    )
Esempio n. 19
0
    def processPdu(
        self,
        snmpEngine,
        messageProcessingModel,
        securityModel,
        securityName,
        securityLevel,
        contextEngineId,
        contextName,
        pduVersion,
        PDU,
        maxSizeResponseScopedPDU,
        stateReference
        ):

        # Agent-side API complies with SMIv2
        if messageProcessingModel == 0:
            PDU = rfc2576.v1ToV2(PDU)

        # 3.2.1
        if rfc3411.readClassPDUs.has_key(PDU.tagSet):
            viewType = 'read'
        elif rfc3411.writeClassPDUs.has_key(PDU.tagSet):
            viewType = 'write'
        else:
            raise error.ProtocolError('Unexpected PDU class %s' % PDU.tagSet)
        
        # 3.2.2 --> no-op

        # 3.2.4
        rspPDU = v2c.apiPDU.getResponse(PDU)
        
        statusInformation = {}
        
        self.__pendingReqs[stateReference] = (
            messageProcessingModel,
            securityModel,
            securityName,
            securityLevel,
            contextEngineId,
            contextName,
            pduVersion,
            rspPDU,
            maxSizeResponseScopedPDU,
            statusInformation
            )

        contextMibInstrumCtl = self.snmpContext.getMibInstrum(contextName)

        acCtx = (
            snmpEngine, securityModel, securityName, securityLevel, contextName
            )

        # 3.2.5
        varBinds = v2c.apiPDU.getVarBinds(PDU)
        errorStatus, errorIndex = 'noError', 0
        try:
            errorStatus, errorIndex, varBinds = self._handleManagementOperation(
                snmpEngine, contextMibInstrumCtl, PDU,
                (self.__verifyAccess, acCtx)
                )
        # SNMPv2 SMI exceptions
        except pysnmp.smi.error.GenError, errorIndication:
            if errorIndication.has_key('oid'):
                # Request REPORT generation
                statusInformation['oid'] = errorIndication['oid'] 
                statusInformation['val'] = errorIndication['val']
Esempio n. 20
0
    def processResponsePdu(
        self,
        snmpEngine,
        messageProcessingModel,
        securityModel,
        securityName,
        securityLevel,
        contextEngineId,
        contextName,
        pduVersion,
        PDU,
        statusInformation,
        sendPduHandle,
        cbInfo
        ):
        (cbFun, cbCtx) = cbInfo
        # 3.1.1
        if sendPduHandle not in self.__pendingReqs:
            raise error.PySnmpError('Missing sendPduHandle %s' % sendPduHandle)

        ( origTransportDomain,
          origTransportAddress,
          origMessageProcessingModel,
          origSecurityModel,
          origSecurityName,
          origSecurityLevel,
          origContextEngineId,
          origContextName,
          origPduVersion,
          origPdu,
          origTimeout,
          origRetryCount,
          origRetries,
          origSendRequestHandle
          ) = self.__pendingReqs[sendPduHandle]
  
        del self.__pendingReqs[sendPduHandle]

        snmpEngine.transportDispatcher.jobFinished(id(self))

        # 3.1.3
        if statusInformation:
            debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendPduHandle %s, statusInformation %s' % (sendPduHandle, statusInformation))
            errorIndication = statusInformation['errorIndication']
            # SNMP engine discovery will take extra retries, allow that
            if errorIndication in (errind.notInTimeWindow,
                                   errind.unknownEngineID) and \
                                   origRetries == origRetryCount + 2 or \
               errorIndication not in (errind.notInTimeWindow,
                                       errind.unknownEngineID) and \
                                   origRetries == origRetryCount:
                debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendPduHandle %s, retry count %d exceeded' % (sendPduHandle, origRetries))
                cbFun(origSendRequestHandle,
                      statusInformation['errorIndication'], 0, 0, (),
                      cbCtx)
                return
            self._sendPdu(
                snmpEngine,
                origTransportDomain,
                origTransportAddress,
                origMessageProcessingModel,
                origSecurityModel,
                origSecurityName,
                origSecurityLevel,
                origContextEngineId,
                origContextName,
                origPduVersion,
                origPdu,
                origTimeout,
                origRetryCount,
                origRetries + 1,
                origSendRequestHandle,
                (self.processResponsePdu, (cbFun, cbCtx))
                )
            return

        if origMessageProcessingModel != messageProcessingModel or \
           origSecurityModel != securityModel or \
           origSecurityName != origSecurityName or \
           origContextEngineId and origContextEngineId != contextEngineId or \
           origContextName and origContextName != contextName or \
           origPduVersion != pduVersion:
            debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendPduHandle %s, request/response data mismatch' % sendPduHandle)
            cbFun(origSendRequestHandle, 'badResponse', 0, 0, (), cbCtx)
            return

        pMod = api.protoModules[pduVersion]
        
        # 3.1.2
        if pMod.apiPDU.getRequestID(PDU) != pMod.apiPDU.getRequestID(origPdu):
            debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendPduHandle %s, request-id/response-id mismatch' % sendPduHandle)
            cbFun(origSendRequestHandle, 'badResponse', 0, 0, (), cbCtx)
            return

        # User-side API assumes SMIv2
        if messageProcessingModel == 0:
            PDU = rfc2576.v1ToV2(PDU, origPdu)
            pMod = api.protoModules[api.protoVersion2c]
        
        self._handleResponse(
            snmpEngine,
            origTransportDomain,
            origTransportAddress,
            origMessageProcessingModel,
            origSecurityModel,
            origSecurityName,
            origSecurityLevel,
            origContextEngineId,
            origContextName,
            origPduVersion,
            origPdu,
            origTimeout,
            origRetryCount,
            pMod,
            PDU,
            origSendRequestHandle,
            (cbFun, cbCtx),
            )
Esempio n. 21
0
    def processResponsePdu(self, snmpEngine, messageProcessingModel,
                           securityModel, securityName, securityLevel,
                           contextEngineId, contextName, pduVersion, PDU,
                           statusInformation, sendPduHandle, cbCtx):
        origSendRequestHandle, cbFun, cbCtx = cbCtx

        # 3.1.1
        if sendPduHandle not in self.__pendingReqs:
            raise error.PySnmpError('Missing sendPduHandle %s' % sendPduHandle)

        (origTransportDomain, origTransportAddress, origMessageProcessingModel,
         origSecurityModel, origSecurityName, origSecurityLevel,
         origContextEngineId, origContextName, origPduVersion, origPdu,
         origTimeout, origRetryCount, origRetries,
         origDiscoveryRetries) = self.__pendingReqs.pop(sendPduHandle)

        snmpEngine.transportDispatcher.jobFinished(id(self))

        # 3.1.3
        if statusInformation:
            debug.logger & debug.flagApp and debug.logger(
                'processResponsePdu: sendPduHandle %s, statusInformation %s' %
                (sendPduHandle, statusInformation))

            errorIndication = statusInformation['errorIndication']

            if errorIndication in (errind.notInTimeWindow,
                                   errind.unknownEngineID):
                origDiscoveryRetries += 1
                origRetries = 0
            else:
                origDiscoveryRetries = 0
                origRetries += 1

            if origRetries > origRetryCount or origDiscoveryRetries > self.__options.get(
                    'discoveryRetries', 4):
                debug.logger & debug.flagApp and debug.logger(
                    'processResponsePdu: sendPduHandle %s, retry count %d exceeded'
                    % (sendPduHandle, origRetries))
                cbFun(snmpEngine, origSendRequestHandle, errorIndication, None,
                      cbCtx)
                return

            # User-side API assumes SMIv2
            if origMessageProcessingModel == 0:
                reqPDU = rfc2576.v2ToV1(origPdu)
                pduVersion = 0
            else:
                reqPDU = origPdu
                pduVersion = 1

            try:
                sendPduHandle = snmpEngine.msgAndPduDsp.sendPdu(
                    snmpEngine, origTransportDomain, origTransportAddress,
                    origMessageProcessingModel, origSecurityModel,
                    origSecurityName, origSecurityLevel, origContextEngineId,
                    origContextName, pduVersion, reqPDU, True, origTimeout,
                    self.processResponsePdu,
                    (origSendRequestHandle, cbFun, cbCtx))

                snmpEngine.transportDispatcher.jobStarted(id(self))

                self.__pendingReqs[sendPduHandle] = (
                    origTransportDomain, origTransportAddress,
                    origMessageProcessingModel, origSecurityModel,
                    origSecurityName, origSecurityLevel, origContextEngineId,
                    origContextName, origPduVersion, origPdu, origTimeout,
                    origRetryCount, origRetries, origDiscoveryRetries)
                return

            except StatusInformation:
                statusInformation = sys.exc_info()[1]
                debug.logger & debug.flagApp and debug.logger(
                    'processResponsePdu: origSendRequestHandle %s, _sendPdu() failed with %r'
                    % (sendPduHandle, statusInformation))
                cbFun(snmpEngine, origSendRequestHandle,
                      statusInformation['errorIndication'], None, cbCtx)
                return

        if (origMessageProcessingModel != messageProcessingModel
                or origSecurityModel != securityModel
                or origSecurityName != origSecurityName or origContextEngineId
                and origContextEngineId != contextEngineId
                or origContextName and origContextName != contextName
                or origPduVersion != pduVersion):
            debug.logger & debug.flagApp and debug.logger(
                'processResponsePdu: sendPduHandle %s, request/response data mismatch'
                % sendPduHandle)

            cbFun(snmpEngine, origSendRequestHandle, 'badResponse', None,
                  cbCtx)
            return

        # User-side API assumes SMIv2
        if messageProcessingModel == 0:
            PDU = rfc2576.v1ToV2(PDU, origPdu)

        # 3.1.2
        if v2c.apiPDU.getRequestID(PDU) != v2c.apiPDU.getRequestID(origPdu):
            debug.logger & debug.flagApp and debug.logger(
                'processResponsePdu: sendPduHandle %s, request-id/response-id mismatch'
                % sendPduHandle)
            cbFun(snmpEngine, origSendRequestHandle, 'badResponse', None,
                  cbCtx)
            return

        cbFun(snmpEngine, origSendRequestHandle, None, PDU, cbCtx)
Esempio n. 22
0
        def processPdu(self, snmpEngine, messageProcessingModel, securityModel,
                       securityName, securityLevel, contextEngineId,
                       contextName, pduVersion, pdu, maxSizeResponseScopedPDU,
                       stateReference):

            trunkReq = gCurrentRequestContext.copy()

            if messageProcessingModel == 0:
                pdu = rfc2576.v1ToV2(pdu)

                # TODO: why this is not automatic?
                v2c.apiTrapPDU.setDefaults(pdu)

            trunkReq['snmp-pdu'] = pdu

            pluginIdList = trunkReq['plugins-list']

            logCtx = LogString(trunkReq)

            reqCtx = {}

            for pluginNum, pluginId in enumerate(pluginIdList):

                st, pdu = pluginManager.processNotificationRequest(
                    pluginId, snmpEngine, pdu, trunkReq, reqCtx)

                if st == status.BREAK:
                    log.debug('plugin %s inhibits other plugins' % pluginId,
                              ctx=logCtx)
                    pluginIdList = pluginIdList[:pluginNum]
                    break

                elif st == status.DROP:
                    log.debug('plugin %s muted request' % pluginId, ctx=logCtx)
                    return

                elif st == status.RESPOND:
                    log.debug('plugin %s NOT forced immediate response' %
                              pluginId,
                              ctx=logCtx)
                    # TODO: implement immediate response for confirmed-class PDU
                    return

            # pass query to trunk

            trunkIdList = trunkReq['trunk-id-list']
            if trunkIdList is None:
                log.error('no route configured', ctx=logCtx)
                return

            for trunkId in trunkIdList:

                # TODO: pass messageProcessingModel to respond
                cbCtx = pluginIdList, trunkId, trunkReq, snmpEngine, stateReference, reqCtx

                try:
                    msgId = trunkingManager.sendReq(trunkId, trunkReq,
                                                    self.trunkCbFun, cbCtx)

                except SnmpfwdError:
                    log.error(
                        'received SNMP message, message not sent to trunk "%s" %s'
                        % (trunkId, sys.exc_info()[1]),
                        ctx=logCtx)
                    return

                log.debug(
                    'received SNMP message, forwarded as trunk message #%s' %
                    msgId,
                    ctx=logCtx)
Esempio n. 23
0
    def processResponsePdu(self,
                           snmpEngine,
                           messageProcessingModel,
                           securityModel,
                           securityName,
                           securityLevel,
                           contextEngineId,
                           contextName,
                           pduVersion,
                           PDU,
                           statusInformation,
                           sendPduHandle,
                           cbInfo):
        sendRequestHandle, cbFun, cbCtx = cbInfo

        # 3.3.6d
        if sendPduHandle not in self.__pendingReqs:
            raise error.ProtocolError('Missing sendPduHandle %s' % sendPduHandle)

        ( origTransportDomain,
          origTransportAddress,
          origMessageProcessingModel,
          origSecurityModel,
          origSecurityName,
          origSecurityLevel,
          origContextEngineId,
          origContextName,
          origPdu,
          origTimeout,
          origRetryCount,
          origRetries ) = self.__pendingReqs.pop(sendPduHandle)

        snmpEngine.transportDispatcher.jobFinished(id(self))

        if statusInformation:
            debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendRequestHandle %s, sendPduHandle %s statusInformation %s' % (sendRequestHandle, sendPduHandle, statusInformation))
            if origRetries == origRetryCount:
                debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendRequestHandle %s, sendPduHandle %s retry count %d exceeded' % (sendRequestHandle, sendPduHandle, origRetries))
                cbFun(snmpEngine,
                      sendRequestHandle,
                      statusInformation['errorIndication'],
                      None,
                      cbCtx)
                return

            # Convert timeout in seconds into timeout in timer ticks
            timeoutInTicks = float(origTimeout)/100/snmpEngine.transportDispatcher.getTimerResolution()

            # User-side API assumes SMIv2
            if messageProcessingModel == 0:
                reqPDU = rfc2576.v2ToV1(origPdu)
                pduVersion = 0
            else:
                reqPDU = origPdu
                pduVersion = 1
 
            # 3.3.6a
            try:
                sendPduHandle = snmpEngine.msgAndPduDsp.sendPdu(
                    snmpEngine,
                    origTransportDomain,
                    origTransportAddress,
                    origMessageProcessingModel,
                    origSecurityModel,
                    origSecurityName,
                    origSecurityLevel,
                    origContextEngineId,
                    origContextName,
                    pduVersion,
                    reqPDU,
                    1,                              # expectResponse
                    timeoutInTicks,
                    self.processResponsePdu,
                    (sendRequestHandle, cbFun, cbCtx)
                )
            except error.StatusInformation:
                statusInformation = sys.exc_info()[1]
                debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendRequestHandle %s: sendPdu() failed with %r ' % (sendRequestHandle, statusInformation))
                cbFun(snmpEngine,
                      sendRequestHandle,
                      statusInformation['errorIndication'],
                      None,
                      cbCtx)
                return

            snmpEngine.transportDispatcher.jobStarted(id(self))

            debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendRequestHandle %s, sendPduHandle %s, timeout %d, retry %d of %d' % (sendRequestHandle, sendPduHandle, origTimeout, origRetries, origRetryCount))
        
            # 3.3.6b
            self.__pendingReqs[sendPduHandle] = (
                origTransportDomain,
                origTransportAddress,
                origMessageProcessingModel,
                origSecurityModel,
                origSecurityName,
                origSecurityLevel,
                origContextEngineId,
                origContextName,
                origPdu,
                origTimeout,
                origRetryCount,
                origRetries + 1
            )
            return

        # 3.3.6c
        # User-side API assumes SMIv2
        if messageProcessingModel == 0:
            PDU = rfc2576.v1ToV2(PDU, origPdu)

        cbFun(snmpEngine, sendRequestHandle, None, PDU, cbCtx)
Esempio n. 24
0
    def requestObserver(snmpEngine, execpoint, variables, cbCtx):

        trunkReq = {
            'callflow-id': '%10.10x' % random.randint(0, 0xffffffffff),
            'snmp-engine-id': snmpEngine.snmpEngineID,
            'snmp-transport-domain': variables['transportDomain'],
            'snmp-peer-address': variables['transportAddress'][0],
            'snmp-peer-port': variables['transportAddress'][1],
            'snmp-bind-address':
            variables['transportAddress'].getLocalAddress()[0],
            'snmp-bind-port':
            variables['transportAddress'].getLocalAddress()[1],
            'snmp-security-model': variables['securityModel'],
            'snmp-security-level': variables['securityLevel'],
            'snmp-security-name': variables['securityName'],
            'snmp-context-engine-id': variables['contextEngineId'],
            'snmp-context-name': variables['contextName'],
        }

        trunkReq['snmp-credentials-id'] = macro.expandMacro(
            credIdMap.get(
                (str(snmpEngine.snmpEngineID), variables['transportDomain'],
                 variables['securityModel'], variables['securityLevel'],
                 str(variables['securityName']))), trunkReq)

        k = '#'.join([
            str(x)
            for x in (variables['contextEngineId'], variables['contextName'])
        ])
        for x, y in contextIdList:
            if y.match(k):
                trunkReq['snmp-context-id'] = macro.expandMacro(x, trunkReq)
                break
            else:
                trunkReq['snmp-context-id'] = None

        addr = '%s:%s#%s:%s' % (
            variables['transportAddress'][0], variables['transportAddress'][1],
            variables['transportAddress'].getLocalAddress()[0],
            variables['transportAddress'].getLocalAddress()[1])

        for pat, peerId in peerIdMap.get(str(variables['transportDomain']),
                                         ()):
            if pat.match(addr):
                trunkReq['snmp-peer-id'] = macro.expandMacro(peerId, trunkReq)
                break
        else:
            trunkReq['snmp-peer-id'] = None

        pdu = variables['pdu']
        if pdu.tagSet == v1.TrapPDU.tagSet:
            pdu = rfc2576.v1ToV2(pdu)
            v2c.apiTrapPDU.setDefaults(pdu)

        k = '#'.join([
            snmpPduTypesMap.get(variables['pdu'].tagSet, '?'),
            '|'.join([str(x[0]) for x in v2c.apiTrapPDU.getVarBinds(pdu)])
        ])

        for x, y in contentIdList:
            if y.match(k):
                trunkReq['snmp-content-id'] = macro.expandMacro(x, trunkReq)
                break
            else:
                trunkReq['snmp-content-id'] = None

        trunkReq['plugins-list'] = pluginIdMap.get(
            (trunkReq['snmp-credentials-id'], trunkReq['snmp-context-id'],
             trunkReq['snmp-peer-id'], trunkReq['snmp-content-id']), [])
        trunkReq['trunk-id-list'] = trunkIdMap.get(
            (trunkReq['snmp-credentials-id'], trunkReq['snmp-context-id'],
             trunkReq['snmp-peer-id'], trunkReq['snmp-content-id']))

        cbCtx.clear()
        cbCtx.update(trunkReq)