diff options
author | Ilya Etingof <etingof@gmail.com> | 2019-02-26 08:56:24 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2019-02-26 08:56:24 +0100 |
commit | 3f2f132a9fdf7a48ec6131d5498145dded3cfcad (patch) | |
tree | 63e6170b35f6b392bf2e3d3feb6996b886e4d36f /pysnmp/entity | |
parent | 2ad26f8bfef0e39b3789d9e6d4fcbf76820c9867 (diff) | |
download | pysnmp-git-3f2f132a9fdf7a48ec6131d5498145dded3cfcad.tar.gz |
PEP-8 long lines and dunders (#245)
This patch massively reformats the whole codebase mainly wrapping
long lines and eliminating dundered private attributes.
Diffstat (limited to 'pysnmp/entity')
-rw-r--r-- | pysnmp/entity/config.py | 203 | ||||
-rw-r--r-- | pysnmp/entity/engine.py | 76 | ||||
-rw-r--r-- | pysnmp/entity/observer.py | 6 | ||||
-rw-r--r-- | pysnmp/entity/rfc3413/cmdgen.py | 99 | ||||
-rw-r--r-- | pysnmp/entity/rfc3413/cmdrsp.py | 42 | ||||
-rw-r--r-- | pysnmp/entity/rfc3413/config.py | 48 | ||||
-rw-r--r-- | pysnmp/entity/rfc3413/context.py | 27 | ||||
-rw-r--r-- | pysnmp/entity/rfc3413/ntforg.py | 107 | ||||
-rw-r--r-- | pysnmp/entity/rfc3413/ntfrcv.py | 13 |
9 files changed, 429 insertions, 192 deletions
diff --git a/pysnmp/entity/config.py b/pysnmp/entity/config.py index 0ae87c0b..57e8704f 100644 --- a/pysnmp/entity/config.py +++ b/pysnmp/entity/config.py @@ -77,9 +77,13 @@ PRIV_SERVICES = { def __cookV1SystemInfo(snmpEngine, communityIndex): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder - snmpEngineID, = mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') - snmpCommunityEntry, = mibBuilder.importSymbols('SNMP-COMMUNITY-MIB', 'snmpCommunityEntry') + snmpEngineID, = mibBuilder.importSymbols( + '__SNMP-FRAMEWORK-MIB', 'snmpEngineID') + snmpCommunityEntry, = mibBuilder.importSymbols( + 'SNMP-COMMUNITY-MIB', 'snmpCommunityEntry') + tblIdx = snmpCommunityEntry.getInstIdFromIndices(communityIndex) + return snmpCommunityEntry, tblIdx, snmpEngineID @@ -91,6 +95,7 @@ def addV1System(snmpEngine, communityIndex, communityName, if contextEngineId is None: contextEngineId = snmpEngineID.syntax + else: contextEngineId = snmpEngineID.syntax.clone(contextEngineId) @@ -101,10 +106,13 @@ def addV1System(snmpEngine, communityIndex, communityName, (snmpCommunityEntry.name + (8,) + tblIdx, 'destroy'), snmpEngine=snmpEngine ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeMibObjects( (snmpCommunityEntry.name + (1,) + tblIdx, communityIndex), (snmpCommunityEntry.name + (2,) + tblIdx, communityName), - (snmpCommunityEntry.name + (3,) + tblIdx, securityName is not None and securityName or communityIndex), + (snmpCommunityEntry.name + (3,) + tblIdx, ( + securityName is not None and securityName or + communityIndex)), (snmpCommunityEntry.name + (4,) + tblIdx, contextEngineId), (snmpCommunityEntry.name + (5,) + tblIdx, contextName), (snmpCommunityEntry.name + (6,) + tblIdx, transportTag), @@ -117,6 +125,7 @@ def addV1System(snmpEngine, communityIndex, communityName, def delV1System(snmpEngine, communityIndex): (snmpCommunityEntry, tblIdx, snmpEngineID) = __cookV1SystemInfo(snmpEngine, communityIndex) + snmpEngine.msgAndPduDsp.mibInstrumController.writeMibObjects( (snmpCommunityEntry.name + (8,) + tblIdx, 'destroy'), snmpEngine=snmpEngine @@ -126,17 +135,23 @@ def delV1System(snmpEngine, communityIndex): def __cookV3UserInfo(snmpEngine, securityName, securityEngineId): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder - snmpEngineID, = mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') + snmpEngineID, = mibBuilder.importSymbols( + '__SNMP-FRAMEWORK-MIB', 'snmpEngineID') if securityEngineId is None: snmpEngineID = snmpEngineID.syntax + else: snmpEngineID = snmpEngineID.syntax.clone(securityEngineId) - usmUserEntry, = mibBuilder.importSymbols('SNMP-USER-BASED-SM-MIB', 'usmUserEntry') + usmUserEntry, = mibBuilder.importSymbols( + 'SNMP-USER-BASED-SM-MIB', 'usmUserEntry') + tblIdx1 = usmUserEntry.getInstIdFromIndices(snmpEngineID, securityName) - pysnmpUsmSecretEntry, = mibBuilder.importSymbols('PYSNMP-USM-MIB', 'pysnmpUsmSecretEntry') + pysnmpUsmSecretEntry, = mibBuilder.importSymbols( + 'PYSNMP-USM-MIB', 'pysnmpUsmSecretEntry') + tblIdx2 = pysnmpUsmSecretEntry.getInstIdFromIndices(securityName) return snmpEngineID, usmUserEntry, tblIdx1, pysnmpUsmSecretEntry, tblIdx2 @@ -147,24 +162,29 @@ def addV3User(snmpEngine, userName, privProtocol=USM_PRIV_NONE, privKey=None, securityEngineId=None, securityName=None): + mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder if securityName is None: securityName = userName (snmpEngineID, usmUserEntry, tblIdx1, - pysnmpUsmSecretEntry, tblIdx2) = __cookV3UserInfo(snmpEngine, userName, securityEngineId) + pysnmpUsmSecretEntry, tblIdx2) = __cookV3UserInfo( + snmpEngine, userName, securityEngineId) # Load augmenting table before creating new row in base one - pysnmpUsmKeyEntry, = mibBuilder.importSymbols('PYSNMP-USM-MIB', 'pysnmpUsmKeyEntry') + pysnmpUsmKeyEntry, = mibBuilder.importSymbols( + 'PYSNMP-USM-MIB', 'pysnmpUsmKeyEntry') # Load clone-from (may not be needed) - zeroDotZero, = mibBuilder.importSymbols('SNMPv2-SMI', 'zeroDotZero') + zeroDotZero, = mibBuilder.importSymbols( + 'SNMPv2-SMI', 'zeroDotZero') snmpEngine.msgAndPduDsp.mibInstrumController.writeMibObjects( (usmUserEntry.name + (13,) + tblIdx1, 'destroy'), snmpEngine=snmpEngine ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeMibObjects( (usmUserEntry.name + (2,) + tblIdx1, userName), (usmUserEntry.name + (3,) + tblIdx1, securityName), @@ -180,9 +200,11 @@ def addV3User(snmpEngine, userName, hashedAuthPassphrase = AUTH_SERVICES[authProtocol].hashPassphrase( authKey and authKey or null ) + localAuthKey = AUTH_SERVICES[authProtocol].localizeKey( hashedAuthPassphrase, snmpEngineID ) + else: raise error.PySnmpError('Unknown auth protocol %s' % (authProtocol,)) @@ -190,9 +212,11 @@ def addV3User(snmpEngine, userName, hashedPrivPassphrase = PRIV_SERVICES[privProtocol].hashPassphrase( authProtocol, privKey and privKey or null ) + localPrivKey = PRIV_SERVICES[privProtocol].localizeKey( authProtocol, hashedPrivPassphrase, snmpEngineID ) + else: raise error.PySnmpError('Unknown priv protocol %s' % (privProtocol,)) @@ -211,6 +235,7 @@ def addV3User(snmpEngine, userName, (pysnmpUsmSecretEntry.name + (4,) + tblIdx2, 'destroy'), snmpEngine=snmpEngine ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeMibObjects( (pysnmpUsmSecretEntry.name + (1,) + tblIdx2, userName), (pysnmpUsmSecretEntry.name + (2,) + tblIdx2, authKey), @@ -225,10 +250,12 @@ def delV3User(snmpEngine, securityEngineId=None): (snmpEngineID, usmUserEntry, tblIdx1, pysnmpUsmSecretEntry, tblIdx2) = __cookV3UserInfo(snmpEngine, userName, securityEngineId) + snmpEngine.msgAndPduDsp.mibInstrumController.writeMibObjects( (usmUserEntry.name + (13,) + tblIdx1, 'destroy'), snmpEngine=snmpEngine ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeMibObjects( (pysnmpUsmSecretEntry.name + (4,) + tblIdx2, 'destroy'), snmpEngine=snmpEngine @@ -272,6 +299,7 @@ def __cookTargetParamsInfo(snmpEngine, name): snmpTargetParamsEntry, = mibBuilder.importSymbols('SNMP-TARGET-MIB', 'snmpTargetParamsEntry') tblIdx = snmpTargetParamsEntry.getInstIdFromIndices(name) + return snmpTargetParamsEntry, tblIdx @@ -279,10 +307,13 @@ def __cookTargetParamsInfo(snmpEngine, name): def addTargetParams(snmpEngine, name, securityName, securityLevel, mpModel=3): if mpModel == 0: securityModel = 1 + elif mpModel in (1, 2): securityModel = 2 + elif mpModel == 3: securityModel = 3 + else: raise error.PySnmpError('Unknown MP model %s' % mpModel) @@ -292,6 +323,7 @@ def addTargetParams(snmpEngine, name, securityName, securityLevel, mpModel=3): (snmpTargetParamsEntry.name + (7,) + tblIdx, 'destroy'), snmpEngine=snmpEngine ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeMibObjects( (snmpTargetParamsEntry.name + (1,) + tblIdx, name), (snmpTargetParamsEntry.name + (2,) + tblIdx, mpModel), @@ -323,28 +355,36 @@ def __cookTargetAddrInfo(snmpEngine, addrName): def addTargetAddr(snmpEngine, addrName, transportDomain, transportAddress, params, timeout=None, retryCount=None, tagList=null, sourceAddress=None): + mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder - (snmpTargetAddrEntry, snmpSourceAddrEntry, + (snmpTargetAddrEntry, + snmpSourceAddrEntry, tblIdx) = __cookTargetAddrInfo(snmpEngine, addrName) if transportDomain[:len(SNMP_UDP_DOMAIN)] == SNMP_UDP_DOMAIN: SnmpUDPAddress, = mibBuilder.importSymbols('SNMPv2-TM', 'SnmpUDPAddress') transportAddress = SnmpUDPAddress(transportAddress) + if sourceAddress is None: sourceAddress = ('0.0.0.0', 0) + sourceAddress = SnmpUDPAddress(sourceAddress) + elif transportDomain[:len(SNMP_UDP6_DOMAIN)] == SNMP_UDP6_DOMAIN: TransportAddressIPv6, = mibBuilder.importSymbols('TRANSPORT-ADDRESS-MIB', 'TransportAddressIPv6') transportAddress = TransportAddressIPv6(transportAddress) + if sourceAddress is None: sourceAddress = ('::', 0) + sourceAddress = TransportAddressIPv6(sourceAddress) snmpEngine.msgAndPduDsp.mibInstrumController.writeMibObjects( (snmpTargetAddrEntry.name + (9,) + tblIdx, 'destroy'), snmpEngine=snmpEngine ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeMibObjects( (snmpTargetAddrEntry.name + (1,) + tblIdx, addrName), (snmpTargetAddrEntry.name + (2,) + tblIdx, transportDomain), @@ -362,6 +402,7 @@ def addTargetAddr(snmpEngine, addrName, transportDomain, transportAddress, def delTargetAddr(snmpEngine, addrName): (snmpTargetAddrEntry, snmpSourceAddrEntry, tblIdx) = __cookTargetAddrInfo(snmpEngine, addrName) + snmpEngine.msgAndPduDsp.mibInstrumController.writeMibObjects( (snmpTargetAddrEntry.name + (9,) + tblIdx, 'destroy'), snmpEngine=snmpEngine @@ -372,18 +413,23 @@ def addTransport(snmpEngine, transportDomain, transport): if snmpEngine.transportDispatcher: if not transport.isCompatibleWithDispatcher(snmpEngine.transportDispatcher): raise error.PySnmpError( - 'Transport %r is not compatible with dispatcher %r' % (transport, snmpEngine.transportDispatcher)) + 'Transport %r is not compatible with dispatcher %r' % ( + transport, snmpEngine.transportDispatcher)) + else: snmpEngine.registerTransportDispatcher( transport.PROTO_TRANSPORT_DISPATCHER() ) + # here we note that we have created transportDispatcher automatically snmpEngine.setUserContext(automaticTransportDispatcher=0) snmpEngine.transportDispatcher.registerTransport(transportDomain, transport) + automaticTransportDispatcher = snmpEngine.getUserContext( 'automaticTransportDispatcher' ) + if automaticTransportDispatcher is not None: snmpEngine.setUserContext( automaticTransportDispatcher=automaticTransportDispatcher + 1 @@ -393,8 +439,10 @@ def addTransport(snmpEngine, transportDomain, transport): def getTransport(snmpEngine, transportDomain): if not snmpEngine.transportDispatcher: return + try: return snmpEngine.transportDispatcher.getTransport(transportDomain) + except error.PySnmpError: return @@ -402,21 +450,26 @@ def getTransport(snmpEngine, transportDomain): def delTransport(snmpEngine, transportDomain): if not snmpEngine.transportDispatcher: return + transport = getTransport(snmpEngine, transportDomain) + snmpEngine.transportDispatcher.unregisterTransport(transportDomain) + # automatically shutdown automatically created transportDispatcher automaticTransportDispatcher = snmpEngine.getUserContext( 'automaticTransportDispatcher' ) + if automaticTransportDispatcher is not None: automaticTransportDispatcher -= 1 snmpEngine.setUserContext( - automaticTransportDispatcher=automaticTransportDispatcher - ) + automaticTransportDispatcher=automaticTransportDispatcher) + if not automaticTransportDispatcher: snmpEngine.transportDispatcher.closeDispatcher() snmpEngine.unregisterTransportDispatcher() snmpEngine.delUserContext(automaticTransportDispatcher) + return transport @@ -428,8 +481,12 @@ delSocketTransport = delTransport def __cookVacmContextInfo(snmpEngine, contextName): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder - vacmContextEntry, = mibBuilder.importSymbols('SNMP-VIEW-BASED-ACM-MIB', 'vacmContextEntry') + + vacmContextEntry, = mibBuilder.importSymbols( + 'SNMP-VIEW-BASED-ACM-MIB', 'vacmContextEntry') + tblIdx = vacmContextEntry.getInstIdFromIndices(contextName) + return vacmContextEntry, tblIdx @@ -440,6 +497,7 @@ def addContext(snmpEngine, contextName): (vacmContextEntry.name + (2,) + tblIdx, 'destroy'), snmpEngine=snmpEngine ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeMibObjects( (vacmContextEntry.name + (1,) + tblIdx, contextName), (vacmContextEntry.name + (2,) + tblIdx, 'createAndGo'), @@ -459,20 +517,24 @@ def delContext(snmpEngine, contextName): def __cookVacmGroupInfo(snmpEngine, securityModel, securityName): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder - vacmSecurityToGroupEntry, = mibBuilder.importSymbols('SNMP-VIEW-BASED-ACM-MIB', - 'vacmSecurityToGroupEntry') - tblIdx = vacmSecurityToGroupEntry.getInstIdFromIndices(securityModel, - securityName) + vacmSecurityToGroupEntry, = mibBuilder.importSymbols( + 'SNMP-VIEW-BASED-ACM-MIB', 'vacmSecurityToGroupEntry') + + tblIdx = vacmSecurityToGroupEntry.getInstIdFromIndices( + securityModel, securityName) + return vacmSecurityToGroupEntry, tblIdx def addVacmGroup(snmpEngine, groupName, securityModel, securityName): (vacmSecurityToGroupEntry, tblIdx) = __cookVacmGroupInfo(snmpEngine, securityModel, securityName) + snmpEngine.msgAndPduDsp.mibInstrumController.writeMibObjects( (vacmSecurityToGroupEntry.name + (5,) + tblIdx, 'destroy'), snmpEngine=snmpEngine ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeMibObjects( (vacmSecurityToGroupEntry.name + (1,) + tblIdx, securityModel), (vacmSecurityToGroupEntry.name + (2,) + tblIdx, securityName), @@ -486,6 +548,7 @@ def delVacmGroup(snmpEngine, securityModel, securityName): vacmSecurityToGroupEntry, tblIdx = __cookVacmGroupInfo( snmpEngine, securityModel, securityName ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeMibObjects( (vacmSecurityToGroupEntry.name + (5,) + tblIdx, 'destroy'), snmpEngine=snmpEngine @@ -496,17 +559,19 @@ def __cookVacmAccessInfo(snmpEngine, groupName, contextName, securityModel, securityLevel): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder - vacmAccessEntry, = mibBuilder.importSymbols('SNMP-VIEW-BASED-ACM-MIB', 'vacmAccessEntry') - tblIdx = vacmAccessEntry.getInstIdFromIndices(groupName, contextName, - securityModel, securityLevel) + vacmAccessEntry, = mibBuilder.importSymbols( + 'SNMP-VIEW-BASED-ACM-MIB', 'vacmAccessEntry') + + tblIdx = vacmAccessEntry.getInstIdFromIndices( + groupName, contextName, securityModel, securityLevel) + return vacmAccessEntry, tblIdx def addVacmAccess(snmpEngine, groupName, contextName, securityModel, securityLevel, prefix, readView, writeView, notifyView): - vacmAccessEntry, tblIdx = __cookVacmAccessInfo(snmpEngine, groupName, - contextName, securityModel, - securityLevel) + vacmAccessEntry, tblIdx = __cookVacmAccessInfo( + snmpEngine, groupName, contextName, securityModel, securityLevel) addContext(snmpEngine, contextName) @@ -514,6 +579,7 @@ def addVacmAccess(snmpEngine, groupName, contextName, securityModel, (vacmAccessEntry.name + (9,) + tblIdx, 'destroy'), snmpEngine=snmpEngine ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeMibObjects( (vacmAccessEntry.name + (1,) + tblIdx, contextName), (vacmAccessEntry.name + (2,) + tblIdx, securityModel), @@ -529,9 +595,9 @@ def addVacmAccess(snmpEngine, groupName, contextName, securityModel, def delVacmAccess(snmpEngine, groupName, contextName, securityModel, securityLevel): - vacmAccessEntry, tblIdx = __cookVacmAccessInfo(snmpEngine, groupName, - contextName, securityModel, - securityLevel) + + vacmAccessEntry, tblIdx = __cookVacmAccessInfo( + snmpEngine, groupName, contextName, securityModel, securityLevel) delContext(snmpEngine, contextName) @@ -545,19 +611,23 @@ def __cookVacmViewInfo(snmpEngine, viewName, subTree): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder vacmViewTreeFamilyEntry, = mibBuilder.importSymbols( - 'SNMP-VIEW-BASED-ACM-MIB', 'vacmViewTreeFamilyEntry' - ) + 'SNMP-VIEW-BASED-ACM-MIB', 'vacmViewTreeFamilyEntry') + tblIdx = vacmViewTreeFamilyEntry.getInstIdFromIndices(viewName, subTree) + return vacmViewTreeFamilyEntry, tblIdx def addVacmView(snmpEngine, viewName, viewType, subTree, mask): - vacmViewTreeFamilyEntry, tblIdx = __cookVacmViewInfo(snmpEngine, viewName, - subTree) + + vacmViewTreeFamilyEntry, tblIdx = __cookVacmViewInfo( + snmpEngine, viewName, subTree) + snmpEngine.msgAndPduDsp.mibInstrumController.writeMibObjects( (vacmViewTreeFamilyEntry.name + (6,) + tblIdx, 'destroy'), snmpEngine=snmpEngine ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeMibObjects( (vacmViewTreeFamilyEntry.name + (1,) + tblIdx, viewName), (vacmViewTreeFamilyEntry.name + (2,) + tblIdx, subTree), @@ -569,8 +639,9 @@ def addVacmView(snmpEngine, viewName, viewType, subTree, mask): def delVacmView(snmpEngine, viewName, subTree): - vacmViewTreeFamilyEntry, tblIdx = __cookVacmViewInfo(snmpEngine, viewName, - subTree) + vacmViewTreeFamilyEntry, tblIdx = __cookVacmViewInfo( + snmpEngine, viewName, subTree) + snmpEngine.msgAndPduDsp.mibInstrumController.writeMibObjects( (vacmViewTreeFamilyEntry.name + (6,) + tblIdx, 'destroy'), snmpEngine=snmpEngine @@ -583,8 +654,11 @@ def __cookVacmUserInfo(snmpEngine, securityModel, securityName, securityLevel): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder groupName = 'v-%s-%d' % (hash(securityName), securityModel) + SnmpSecurityLevel, = mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpSecurityLevel') + securityLevel = SnmpSecurityLevel(securityLevel) + return (groupName, securityLevel, 'r' + groupName, 'w' + groupName, 'n' + groupName) @@ -592,16 +666,22 @@ def __cookVacmUserInfo(snmpEngine, securityModel, securityName, securityLevel): def addVacmUser(snmpEngine, securityModel, securityName, securityLevel, readSubTree=(), writeSubTree=(), notifySubTree=(), contextName=null): + (groupName, securityLevel, readView, writeView, - notifyView) = __cookVacmUserInfo(snmpEngine, securityModel, securityName, - securityLevel) + notifyView) = __cookVacmUserInfo( + snmpEngine, securityModel, securityName, securityLevel) + addVacmGroup(snmpEngine, groupName, securityModel, securityName) + addVacmAccess(snmpEngine, groupName, contextName, securityModel, securityLevel, 1, readView, writeView, notifyView) + if readSubTree: addVacmView(snmpEngine, readView, "included", readSubTree, null) + if writeSubTree: addVacmView(snmpEngine, writeView, "included", writeSubTree, null) + if notifySubTree: addVacmView(snmpEngine, notifyView, "included", notifySubTree, null) @@ -610,43 +690,48 @@ def delVacmUser(snmpEngine, securityModel, securityName, securityLevel, readSubTree=(), writeSubTree=(), notifySubTree=(), contextName=null): (groupName, securityLevel, readView, writeView, - notifyView) = __cookVacmUserInfo(snmpEngine, securityModel, - securityName, securityLevel) + notifyView) = __cookVacmUserInfo( + snmpEngine, securityModel, securityName, securityLevel) + delVacmGroup(snmpEngine, securityModel, securityName) + delVacmAccess(snmpEngine, groupName, contextName, securityModel, securityLevel) + if readSubTree: - delVacmView( - snmpEngine, readView, readSubTree - ) + delVacmView(snmpEngine, readView, readSubTree) + if writeSubTree: - delVacmView( - snmpEngine, writeView, writeSubTree - ) + delVacmView(snmpEngine, writeView, writeSubTree) + if notifySubTree: - delVacmView( - snmpEngine, notifyView, notifySubTree - ) + delVacmView(snmpEngine, notifyView, notifySubTree) # Notification target setup def __cookNotificationTargetInfo(snmpEngine, notificationName, paramsName, filterSubtree=None): + mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder - snmpNotifyEntry, = mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', 'snmpNotifyEntry') + snmpNotifyEntry, = mibBuilder.importSymbols( + 'SNMP-NOTIFICATION-MIB', 'snmpNotifyEntry') + tblIdx1 = snmpNotifyEntry.getInstIdFromIndices(notificationName) - snmpNotifyFilterProfileEntry, = mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', - 'snmpNotifyFilterProfileEntry') + snmpNotifyFilterProfileEntry, = mibBuilder.importSymbols( + 'SNMP-NOTIFICATION-MIB', 'snmpNotifyFilterProfileEntry') + tblIdx2 = snmpNotifyFilterProfileEntry.getInstIdFromIndices(paramsName) profileName = '%s-filter' % hash(notificationName) if filterSubtree: - snmpNotifyFilterEntry, = mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', - 'snmpNotifyFilterEntry') - tblIdx3 = snmpNotifyFilterEntry.getInstIdFromIndices(profileName, - filterSubtree) + snmpNotifyFilterEntry, = mibBuilder.importSymbols( + 'SNMP-NOTIFICATION-MIB', 'snmpNotifyFilterEntry') + + tblIdx3 = snmpNotifyFilterEntry.getInstIdFromIndices( + profileName, filterSubtree) + else: snmpNotifyFilterEntry = tblIdx3 = None @@ -658,15 +743,17 @@ def __cookNotificationTargetInfo(snmpEngine, notificationName, paramsName, def addNotificationTarget(snmpEngine, notificationName, paramsName, transportTag, notifyType=None, filterSubtree=None, filterMask=None, filterType=None): + (snmpNotifyEntry, tblIdx1, snmpNotifyFilterProfileEntry, tblIdx2, profileName, snmpNotifyFilterEntry, - tblIdx3) = __cookNotificationTargetInfo(snmpEngine, notificationName, - paramsName, filterSubtree) + tblIdx3) = __cookNotificationTargetInfo( + snmpEngine, notificationName, paramsName, filterSubtree) snmpEngine.msgAndPduDsp.mibInstrumController.writeMibObjects( (snmpNotifyEntry.name + (5,) + tblIdx1, 'destroy'), snmpEngine=snmpEngine ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeMibObjects( (snmpNotifyEntry.name + (2,) + tblIdx1, transportTag), (snmpNotifyEntry.name + (3,) + tblIdx1, notifyType), @@ -678,6 +765,7 @@ def addNotificationTarget(snmpEngine, notificationName, paramsName, (snmpNotifyFilterProfileEntry.name + (3,) + tblIdx2, 'destroy'), snmpEngine=snmpEngine ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeMibObjects( (snmpNotifyFilterProfileEntry.name + (1,) + tblIdx2, profileName), (snmpNotifyFilterProfileEntry.name + (3,) + tblIdx2, 'createAndGo'), @@ -691,6 +779,7 @@ def addNotificationTarget(snmpEngine, notificationName, paramsName, (snmpNotifyFilterEntry.name + (5,) + tblIdx3, 'destroy'), snmpEngine=snmpEngine ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeMibObjects( (snmpNotifyFilterEntry.name + (1,) + tblIdx3, filterSubtree), (snmpNotifyFilterEntry.name + (2,) + tblIdx3, filterMask), @@ -704,8 +793,8 @@ def delNotificationTarget(snmpEngine, notificationName, paramsName, filterSubtree=None): (snmpNotifyEntry, tblIdx1, snmpNotifyFilterProfileEntry, tblIdx2, profileName, snmpNotifyFilterEntry, - tblIdx3) = __cookNotificationTargetInfo(snmpEngine, notificationName, - paramsName, filterSubtree) + tblIdx3) = __cookNotificationTargetInfo( + snmpEngine, notificationName, paramsName, filterSubtree) snmpEngine.msgAndPduDsp.mibInstrumController.writeMibObjects( (snmpNotifyEntry.name + (5,) + tblIdx1, 'destroy'), diff --git a/pysnmp/entity/engine.py b/pysnmp/entity/engine.py index 60b45b0c..d7f16ff8 100644 --- a/pysnmp/entity/engine.py +++ b/pysnmp/entity/engine.py @@ -65,8 +65,12 @@ class SnmpEngine(object): if msgAndPduDsp is None: self.msgAndPduDsp = MsgAndPduDispatcher() + else: self.msgAndPduDsp = msgAndPduDsp + + mibBuilder = self.msgAndPduDsp.mibInstrumController.mibBuilder + self.messageProcessingSubsystems = { SnmpV1MessageProcessingModel.MESSAGE_PROCESSING_MODEL_ID: SnmpV1MessageProcessingModel(), @@ -75,11 +79,13 @@ class SnmpEngine(object): SnmpV3MessageProcessingModel.MESSAGE_PROCESSING_MODEL_ID: SnmpV3MessageProcessingModel() } + self.securityModels = { SnmpV1SecurityModel.SECURITY_MODEL_ID: SnmpV1SecurityModel(), SnmpV2cSecurityModel.SECURITY_MODEL_ID: SnmpV2cSecurityModel(), SnmpUSMSecurityModel.SECURITY_MODEL_ID: SnmpUSMSecurityModel() } + self.accessControlModel = { void.Vacm.ACCESS_MODEL_ID: void.Vacm(), rfc3415.Vacm.ACCESS_MODEL_ID: rfc3415.Vacm() @@ -88,48 +94,59 @@ class SnmpEngine(object): self.transportDispatcher = None if self.msgAndPduDsp.mibInstrumController is None: - raise error.PySnmpError( - 'MIB instrumentation does not yet exist' - ) - snmpEngineMaxMessageSize, = self.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + raise error.PySnmpError('MIB instrumentation does not yet exist') + + snmpEngineMaxMessageSize, = mibBuilder.importSymbols( '__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') + snmpEngineMaxMessageSize.syntax = snmpEngineMaxMessageSize.syntax.clone(maxMessageSize) - snmpEngineBoots, = self.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', - 'snmpEngineBoots') + + snmpEngineBoots, = mibBuilder.importSymbols( + '__SNMP-FRAMEWORK-MIB', 'snmpEngineBoots') + snmpEngineBoots.syntax += 1 - origSnmpEngineID, = self.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', - 'snmpEngineID') + + origSnmpEngineID, = mibBuilder.importSymbols( + '__SNMP-FRAMEWORK-MIB', 'snmpEngineID') if snmpEngineID is None: self.snmpEngineID = origSnmpEngineID.syntax + else: origSnmpEngineID.syntax = origSnmpEngineID.syntax.clone(snmpEngineID) self.snmpEngineID = origSnmpEngineID.syntax debug.logger & debug.FLAG_APP and debug.logger( - 'SnmpEngine: using custom SNMP Engine ID: %s' % self.snmpEngineID.prettyPrint()) + 'SnmpEngine: using custom SNMP Engine ' + 'ID: %s' % self.snmpEngineID.prettyPrint()) # Attempt to make some of snmp Engine settings persistent. # This should probably be generalized as a non-volatile MIB store. - persistentPath = os.path.join(tempfile.gettempdir(), '__pysnmp', self.snmpEngineID.prettyPrint()) + persistentPath = os.path.join(tempfile.gettempdir(), '__pysnmp', + self.snmpEngineID.prettyPrint()) - debug.logger & debug.FLAG_APP and debug.logger('SnmpEngine: using persistent directory: %s' % persistentPath) + debug.logger & debug.FLAG_APP and debug.logger( + 'SnmpEngine: using persistent directory: %s' % persistentPath) if not os.path.exists(persistentPath): try: os.makedirs(persistentPath) + except OSError: return f = os.path.join(persistentPath, 'boots') + try: snmpEngineBoots.syntax = snmpEngineBoots.syntax.clone(open(f).read()) + except Exception: pass try: snmpEngineBoots.syntax += 1 + except Exception: snmpEngineBoots.syntax = snmpEngineBoots.syntax.clone(1) @@ -138,12 +155,15 @@ class SnmpEngine(object): os.write(fd, str2octs(snmpEngineBoots.syntax.prettyPrint())) os.close(fd) shutil.move(fn, f) + except Exception as exc: debug.logger & debug.FLAG_APP and debug.logger( 'SnmpEngine: could not stored SNMP Engine Boots: %s' % exc) + else: debug.logger & debug.FLAG_APP and debug.logger( - 'SnmpEngine: stored SNMP Engine Boots: %s' % snmpEngineBoots.syntax.prettyPrint()) + 'SnmpEngine: stored SNMP Engine Boots: ' + '%s' % snmpEngineBoots.syntax.prettyPrint()) def __repr__(self): return '%s(snmpEngineID=%r)' % (self.__class__.__name__, self.snmpEngineID) @@ -158,31 +178,28 @@ class SnmpEngine(object): def __receiveTimerTickCbFun(self, timeNow): self.msgAndPduDsp.receiveTimerTick(self, timeNow) + for mpHandler in self.messageProcessingSubsystems.values(): mpHandler.receiveTimerTick(self, timeNow) + for smHandler in self.securityModels.values(): smHandler.receiveTimerTick(self, timeNow) def registerTransportDispatcher(self, transportDispatcher, recvId=None): - if self.transportDispatcher is not None and \ - self.transportDispatcher is not transportDispatcher: - raise error.PySnmpError( - 'Transport dispatcher already registered' - ) - transportDispatcher.registerRecvCbFun( - self.__receiveMessageCbFun, recvId - ) - if self.transportDispatcher is None: - transportDispatcher.registerTimerCbFun( - self.__receiveTimerTickCbFun - ) + if (self.transportDispatcher and + self.transportDispatcher is not transportDispatcher): + raise error.PySnmpError('Transport dispatcher already registered') + + transportDispatcher.registerRecvCbFun(self.__receiveMessageCbFun, recvId) + + if not self.transportDispatcher: + transportDispatcher.registerTimerCbFun(self.__receiveTimerTickCbFun) self.transportDispatcher = transportDispatcher def unregisterTransportDispatcher(self, recvId=None): if self.transportDispatcher is None: - raise error.PySnmpError( - 'Transport dispatcher not registered' - ) + raise error.PySnmpError('Transport dispatcher not registered') + self.transportDispatcher.unregisterRecvCbFun(recvId) self.transportDispatcher.unregisterTimerCbFun() self.transportDispatcher = None @@ -192,9 +209,7 @@ class SnmpEngine(object): # User app may attach opaque objects to SNMP Engine def setUserContext(self, **kwargs): - self.cache.update( - dict([('__%s' % k, kwargs[k]) for k in kwargs]) - ) + self.cache.update(dict([('__%s' % k, kwargs[k]) for k in kwargs])) def getUserContext(self, arg): return self.cache.get('__%s' % arg) @@ -202,5 +217,6 @@ class SnmpEngine(object): def delUserContext(self, arg): try: del self.cache['__%s' % arg] + except KeyError: pass diff --git a/pysnmp/entity/observer.py b/pysnmp/entity/observer.py index 3f7bd845..ddc959c3 100644 --- a/pysnmp/entity/observer.py +++ b/pysnmp/entity/observer.py @@ -31,21 +31,26 @@ class MetaObserver(object): def registerObserver(self, cbFun, *execpoints, **kwargs): if cbFun in self.__contexts: raise error.PySnmpError('duplicate observer %s' % cbFun) + else: self.__contexts[cbFun] = kwargs.get('cbCtx') + for execpoint in execpoints: if execpoint not in self.__observers: self.__observers[execpoint] = [] + self.__observers[execpoint].append(cbFun) def unregisterObserver(self, cbFun=None): if cbFun is None: self.__observers.clear() self.__contexts.clear() + else: for execpoint in dict(self.__observers): if cbFun in self.__observers[execpoint]: self.__observers[execpoint].remove(cbFun) + if not self.__observers[execpoint]: del self.__observers[execpoint] @@ -59,6 +64,7 @@ class MetaObserver(object): if execpoints: for execpoint in execpoints: del self.__execpoints[execpoint] + else: self.__execpoints.clear() diff --git a/pysnmp/entity/rfc3413/cmdgen.py b/pysnmp/entity/rfc3413/cmdgen.py index 6f13c265..17db6f33 100644 --- a/pysnmp/entity/rfc3413/cmdgen.py +++ b/pysnmp/entity/rfc3413/cmdgen.py @@ -49,7 +49,8 @@ class CommandGenerator(object): # 3.1.3 if statusInformation: debug.logger & debug.FLAG_APP and debug.logger( - 'processResponsePdu: sendPduHandle %s, statusInformation %s' % (sendPduHandle, statusInformation)) + 'processResponsePdu: sendPduHandle %s, statusInformation ' + '%s' % (sendPduHandle, statusInformation)) errorIndication = statusInformation['errorIndication'] @@ -60,16 +61,22 @@ class CommandGenerator(object): origDiscoveryRetries = 0 origRetries += 1 - if origRetries > origRetryCount or origDiscoveryRetries > self.__options.get('discoveryRetries', 4): + 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) + '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 @@ -92,16 +99,20 @@ class CommandGenerator(object): 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)) + 'processResponsePdu: origSendRequestHandle %s, _sendPdu() ' + 'failed with %r' % (sendPduHandle, statusInformation)) + cbFun(snmpEngine, origSendRequestHandle, statusInformation['errorIndication'], None, cbCtx) + return if (origMessageProcessingModel != messageProcessingModel or @@ -110,11 +121,14 @@ class CommandGenerator(object): 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) + 'processResponsePdu: sendPduHandle %s, request/response ' + 'data mismatch' % sendPduHandle) cbFun(snmpEngine, origSendRequestHandle, 'badResponse', None, cbCtx) + return # User-side API assumes SMIv2 @@ -124,9 +138,12 @@ class CommandGenerator(object): # 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) + 'processResponsePdu: sendPduHandle %s, request-id/response-id ' + 'mismatch' % sendPduHandle) + cbFun(snmpEngine, origSendRequestHandle, 'badResponse', None, cbCtx) + return cbFun(snmpEngine, origSendRequestHandle, None, PDU, cbCtx) @@ -139,14 +156,18 @@ class CommandGenerator(object): securityLevel) = config.getTargetInfo(snmpEngine, targetName) # Convert timeout in seconds into timeout in timer ticks - timeoutInTicks = float(timeout) / 100 / snmpEngine.transportDispatcher.getTimerResolution() + timeoutInTicks = (float(timeout) / 100 / + snmpEngine.transportDispatcher.getTimerResolution()) + + mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder - SnmpEngineID, SnmpAdminString = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + SnmpEngineID, SnmpAdminString = mibBuilder.importSymbols( 'SNMP-FRAMEWORK-MIB', 'SnmpEngineID', 'SnmpAdminString') # Cast possible strings into bytes if contextEngineId: contextEngineId = SnmpEngineID(contextEngineId) + contextName = SnmpAdminString(contextName) origPDU = PDU @@ -155,6 +176,7 @@ class CommandGenerator(object): if messageProcessingModel == 0: PDU = rfc2576.v2ToV1(PDU) pduVersion = 0 + else: pduVersion = 1 @@ -179,13 +201,14 @@ class CommandGenerator(object): ) debug.logger & debug.FLAG_APP and debug.logger( - 'sendPdu: sendPduHandle %s, timeout %d*10 ms/%d ticks, retry 0 of %d' % ( - sendPduHandle, timeout, timeoutInTicks, retryCount)) + 'sendPdu: sendPduHandle %s, timeout %d*10 ms/%d ticks, retry ' + '0 of %d' % (sendPduHandle, timeout, timeoutInTicks, retryCount)) return sendRequestHandle class GetCommandGenerator(CommandGenerator): + def processResponseVarBinds(self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx): cbFun, cbCtx = cbCtx @@ -208,6 +231,7 @@ class GetCommandGenerator(CommandGenerator): class SetCommandGenerator(CommandGenerator): + def processResponseVarBinds(self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx): cbFun, cbCtx = cbCtx @@ -225,11 +249,12 @@ class SetCommandGenerator(CommandGenerator): v2c.apiPDU.setVarBinds(reqPDU, varBinds) return self.sendPdu(snmpEngine, targetName, contextEngineId, - contextName, reqPDU, - self.processResponseVarBinds, (cbFun, cbCtx)) + contextName, reqPDU, self.processResponseVarBinds, + (cbFun, cbCtx)) class NextCommandGeneratorSingleRun(CommandGenerator): + def processResponseVarBinds(self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx): targetName, contextEngineId, contextName, reqPDU, cbFun, cbCtx = cbCtx @@ -253,6 +278,7 @@ class NextCommandGeneratorSingleRun(CommandGenerator): class NextCommandGenerator(NextCommandGeneratorSingleRun): + def processResponseVarBinds(self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx): targetName, contextEngineId, contextName, reqPDU, cbFun, cbCtx = cbCtx @@ -266,8 +292,10 @@ class NextCommandGenerator(NextCommandGeneratorSingleRun): if v2c.apiPDU.getErrorStatus(PDU): errorIndication, varBinds = None, () + elif not varBindTable: errorIndication, varBinds = errind.emptyResponse, () + else: errorIndication, varBinds = v2c.apiPDU.getNextVarBinds(varBindTable[-1]) @@ -275,9 +303,11 @@ class NextCommandGenerator(NextCommandGeneratorSingleRun): v2c.apiPDU.getErrorStatus(PDU), v2c.apiPDU.getErrorIndex(PDU, muteErrors=True), varBindTable, cbCtx): + debug.logger & debug.FLAG_APP and debug.logger( 'processResponseVarBinds: sendRequestHandle %s, app says to stop walking' % sendRequestHandle) - return # app says enough + + return # app says it's enough if not varBinds: return # no more objects available @@ -294,14 +324,18 @@ class NextCommandGenerator(NextCommandGeneratorSingleRun): except StatusInformation as exc: statusInformation = exc + debug.logger & debug.FLAG_APP and debug.logger( - 'sendVarBinds: sendPduHandle %s: sendPdu() failed with %r' % (sendRequestHandle, statusInformation)) + 'sendVarBinds: sendPduHandle %s: sendPdu() failed with ' + '%r' % (sendRequestHandle, statusInformation)) + cbFun(snmpEngine, sendRequestHandle, statusInformation['errorIndication'], 0, 0, (), cbCtx) class BulkCommandGeneratorSingleRun(CommandGenerator): + def processResponseVarBinds(self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx): (targetName, nonRepeaters, maxRepetitions, @@ -332,6 +366,7 @@ class BulkCommandGeneratorSingleRun(CommandGenerator): class BulkCommandGenerator(BulkCommandGeneratorSingleRun): + def processResponseVarBinds(self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx): (targetName, nonRepeaters, maxRepetitions, @@ -346,21 +381,27 @@ class BulkCommandGenerator(BulkCommandGeneratorSingleRun): if v2c.apiBulkPDU.getErrorStatus(PDU): errorIndication, varBinds = None, () + elif not varBindTable: errorIndication, varBinds = errind.emptyResponse, () + else: errorIndication, varBinds = v2c.apiBulkPDU.getNextVarBinds(varBindTable[-1]) nonRepeaters = v2c.apiBulkPDU.getNonRepeaters(reqPDU) + if nonRepeaters: varBinds = v2c.apiBulkPDU.getVarBinds(reqPDU)[:int(nonRepeaters)] + varBinds[int(nonRepeaters):] - if not cbFun(snmpEngine, sendRequestHandle, errorIndication, - v2c.apiBulkPDU.getErrorStatus(PDU), - v2c.apiBulkPDU.getErrorIndex(PDU, muteErrors=True), - varBindTable, cbCtx): + if not cbFun( + snmpEngine, sendRequestHandle, errorIndication, + v2c.apiBulkPDU.getErrorStatus(PDU), + v2c.apiBulkPDU.getErrorIndex(PDU, muteErrors=True), + varBindTable, cbCtx): + debug.logger & debug.FLAG_APP and debug.logger( 'processResponseVarBinds: sendRequestHandle %s, app says to stop walking' % sendRequestHandle) - return # app says enough + + return # app says it's enough if not varBinds: return # no more objects available @@ -369,16 +410,18 @@ class BulkCommandGenerator(BulkCommandGeneratorSingleRun): v2c.apiBulkPDU.setVarBinds(reqPDU, varBinds) try: - self.sendPdu(snmpEngine, targetName, contextEngineId, - contextName, reqPDU, - self.processResponseVarBinds, - (targetName, nonRepeaters, maxRepetitions, - contextEngineId, contextName, reqPDU, cbFun, cbCtx)) + self.sendPdu( + snmpEngine, targetName, contextEngineId, contextName, reqPDU, + self.processResponseVarBinds, + (targetName, nonRepeaters, maxRepetitions, + contextEngineId, contextName, reqPDU, cbFun, cbCtx)) except StatusInformation as exc: statusInformation = exc + debug.logger & debug.FLAG_APP and debug.logger( - 'processResponseVarBinds: sendPduHandle %s: _sendPdu() failed with %r' % ( - sendRequestHandle, statusInformation)) + 'processResponseVarBinds: sendPduHandle %s: _sendPdu() failed ' + 'with %r' % (sendRequestHandle, statusInformation)) + cbFun(snmpEngine, sendRequestHandle, statusInformation['errorIndication'], 0, 0, (), cbCtx) diff --git a/pysnmp/entity/rfc3413/cmdrsp.py b/pysnmp/entity/rfc3413/cmdrsp.py index 7910b86b..56eaaaf3 100644 --- a/pysnmp/entity/rfc3413/cmdrsp.py +++ b/pysnmp/entity/rfc3413/cmdrsp.py @@ -79,9 +79,8 @@ class CommandResponderBase(object): v2c.apiPDU.setVarBinds(PDU, varBinds) debug.logger & debug.FLAG_APP and debug.logger( - 'sendVarBinds: stateReference %s, errorStatus %s, errorIndex %s, varBinds %s' % ( - stateReference, errorStatus, errorIndex, varBinds) - ) + 'sendVarBinds: stateReference %s, errorStatus %s, errorIndex %s, ' + 'varBinds %s' % (stateReference, errorStatus, errorIndex, varBinds)) self.sendPdu(snmpEngine, stateReference, PDU) @@ -121,9 +120,12 @@ class CommandResponderBase(object): except error.StatusInformation as exc: debug.logger & debug.FLAG_APP and debug.logger( - 'sendPdu: stateReference %s, statusInformation %s' % (stateReference, exc)) - snmpSilentDrops, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', - 'snmpSilentDrops') + 'sendPdu: stateReference %s, statusInformation ' + '%s' % (stateReference, exc)) + + snmpSilentDrops, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + '__SNMPv2-MIB', 'snmpSilentDrops') + snmpSilentDrops.syntax += 1 _getRequestType = rfc1905.GetRequestPDU.tagSet @@ -172,6 +174,7 @@ class CommandResponderBase(object): def _storeAccessContext(snmpEngine): """Copy received message metadata while it lasts""" execCtx = snmpEngine.observer.getExecutionContext('rfc3412.receiveMessage:request') + return { 'securityModel': execCtx['securityModel'], 'securityName': execCtx['securityName'], @@ -205,14 +208,19 @@ class CommandResponderBase(object): # Map ACM errors onto SMI ones except error.StatusInformation as exc: statusInformation = exc + debug.logger & debug.FLAG_APP and debug.logger( - '__verifyAccess: name %s, statusInformation %s' % (name, statusInformation)) + '__verifyAccess: name %s, statusInformation ' + '%s' % (name, statusInformation)) + errorIndication = statusInformation['errorIndication'] + # 3.2.5... if (errorIndication == errind.noSuchView or errorIndication == errind.noAccessEntry or errorIndication == errind.noGroupName): - raise pysnmp.smi.error.AuthorizationError(name=name, idx=context.get('idx')) + raise pysnmp.smi.error.AuthorizationError( + name=name, idx=context.get('idx')) elif errorIndication == errind.otherError: raise pysnmp.smi.error.GenError(name=name, idx=context.get('idx')) @@ -221,16 +229,18 @@ class CommandResponderBase(object): snmpUnknownContexts, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( '__SNMP-TARGET-MIB', 'snmpUnknownContexts') snmpUnknownContexts.syntax += 1 + # Request REPORT generation - raise pysnmp.smi.error.GenError(name=name, idx=context.get('idx'), - oid=snmpUnknownContexts.name, - val=snmpUnknownContexts.syntax) + raise pysnmp.smi.error.GenError( + name=name, idx=context.get('idx'), oid=snmpUnknownContexts.name, + val=snmpUnknownContexts.syntax) elif errorIndication == errind.notInView: return True else: raise error.ProtocolError('Unknown ACM error %s' % errorIndication) + else: # rfc2576: 4.1.2.1 if (securityModel == 1 and val is not None and @@ -273,7 +283,6 @@ class CommandResponderBase(object): return errorIndication, errorStatus, errorIndex, varBinds def completeMgmtOperation(self, varBinds, **context): - (errorIndication, errorStatus, errorIndex, varBinds) = self._mapSmiErrors(varBinds, **context) @@ -330,11 +339,6 @@ class NextCommandResponder(CommandResponderBase): def _getManagedObjectsInstances(self, varBinds, **context): """Iterate over Managed Objects fulfilling SNMP query. - Parameters - ---------- - varBinds - context - Returns ------- :py:class:`list` - List of Managed Objects Instances to respond with or @@ -396,7 +400,7 @@ class NextCommandResponder(CommandResponderBase): class BulkCommandResponder(NextCommandResponder): SUPPORTED_PDU_TYPES = (rfc1905.GetBulkRequestPDU.tagSet,) - maxVarBinds = 64 + MAX_VAR_BINDS = 64 def _completeNonRepeaters(self, varBinds, **context): mgmtFun = context['mgmtFun'] @@ -470,7 +474,7 @@ class BulkCommandResponder(NextCommandResponder): R = max(len(varBinds) - N, 0) if R: - M = min(M, self.maxVarBinds // R) + M = min(M, self.MAX_VAR_BINDS // R) debug.logger & debug.FLAG_APP and debug.logger( 'initiateMgmtOperation: N %d, M %d, R %d' % (N, M, R)) diff --git a/pysnmp/entity/rfc3413/config.py b/pysnmp/entity/rfc3413/config.py index c58c74ba..162b70a0 100644 --- a/pysnmp/entity/rfc3413/config.py +++ b/pysnmp/entity/rfc3413/config.py @@ -36,7 +36,8 @@ def getTargetAddr(snmpEngine, snmpTargetAddrName): 'snmpTargetAddrTAddress', 'snmpTargetAddrTimeout', 'snmpTargetAddrRetryCount', 'snmpTargetAddrParams' ) - snmpSourceAddrTAddress, = mibBuilder.importSymbols('PYSNMP-SOURCE-MIB', 'snmpSourceAddrTAddress') + snmpSourceAddrTAddress, = mibBuilder.importSymbols( + 'PYSNMP-SOURCE-MIB', 'snmpSourceAddrTAddress') tblIdx = snmpTargetAddrEntry.getInstIdFromIndices(snmpTargetAddrName) @@ -44,38 +45,46 @@ def getTargetAddr(snmpEngine, snmpTargetAddrName): snmpTargetAddrTDomain = snmpTargetAddrTDomain.getNode( snmpTargetAddrTDomain.name + tblIdx ).syntax + snmpTargetAddrTAddress = snmpTargetAddrTAddress.getNode( snmpTargetAddrTAddress.name + tblIdx ).syntax + snmpTargetAddrTimeout = snmpTargetAddrTimeout.getNode( snmpTargetAddrTimeout.name + tblIdx ).syntax + snmpTargetAddrRetryCount = snmpTargetAddrRetryCount.getNode( snmpTargetAddrRetryCount.name + tblIdx ).syntax + snmpTargetAddrParams = snmpTargetAddrParams.getNode( snmpTargetAddrParams.name + tblIdx ).syntax + snmpSourceAddrTAddress = snmpSourceAddrTAddress.getNode( snmpSourceAddrTAddress.name + tblIdx ).syntax + except NoSuchInstanceError: raise SmiError('Target %s not configured to LCD' % snmpTargetAddrName) transport = snmpEngine.transportDispatcher.getTransport(snmpTargetAddrTDomain) if snmpTargetAddrTDomain[:len(config.SNMP_UDP_DOMAIN)] == config.SNMP_UDP_DOMAIN: - SnmpUDPAddress, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMPv2-TM', - 'SnmpUDPAddress') + SnmpUDPAddress, = mibBuilder.importSymbols('SNMPv2-TM', 'SnmpUDPAddress') + snmpTargetAddrTAddress = transport.ADDRESS_TYPE( SnmpUDPAddress(snmpTargetAddrTAddress) ).setLocalAddress(SnmpUDPAddress(snmpSourceAddrTAddress)) + elif snmpTargetAddrTDomain[:len(config.SNMP_UDP6_DOMAIN)] == config.SNMP_UDP6_DOMAIN: - TransportAddressIPv6, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( - 'TRANSPORT-ADDRESS-MIB', 'TransportAddressIPv6') + TransportAddressIPv6, = mibBuilder.importSymbols('TRANSPORT-ADDRESS-MIB', 'TransportAddressIPv6') + snmpTargetAddrTAddress = transport.ADDRESS_TYPE( TransportAddressIPv6(snmpTargetAddrTAddress) ).setLocalAddress(TransportAddressIPv6(snmpSourceAddrTAddress)) + elif snmpTargetAddrTDomain[:len(config.snmpLocalDomain)] == config.snmpLocalDomain: snmpTargetAddrTAddress = transport.ADDRESS_TYPE( snmpTargetAddrTAddress @@ -126,15 +135,19 @@ def getTargetParams(snmpEngine, paramsName): snmpTargetParamsMPModel = snmpTargetParamsMPModel.getNode( snmpTargetParamsMPModel.name + tblIdx ).syntax + snmpTargetParamsSecurityModel = snmpTargetParamsSecurityModel.getNode( snmpTargetParamsSecurityModel.name + tblIdx ).syntax + snmpTargetParamsSecurityName = snmpTargetParamsSecurityName.getNode( snmpTargetParamsSecurityName.name + tblIdx ).syntax + snmpTargetParamsSecurityLevel = snmpTargetParamsSecurityLevel.getNode( snmpTargetParamsSecurityLevel.name + tblIdx ).syntax + except NoSuchInstanceError: raise SmiError('Parameters %s not configured at LCD' % paramsName) @@ -159,8 +172,8 @@ def getTargetInfo(snmpEngine, snmpTargetAddrName): (snmpTargetParamsMPModel, snmpTargetParamsSecurityModel, snmpTargetParamsSecurityName, - snmpTargetParamsSecurityLevel) = getTargetParams(snmpEngine, - snmpTargetAddrParams) + snmpTargetParamsSecurityLevel) = getTargetParams( + snmpEngine, snmpTargetAddrParams) return (snmpTargetAddrTDomain, snmpTargetAddrTAddress, snmpTargetAddrTimeout, snmpTargetAddrRetryCount, @@ -171,8 +184,8 @@ def getTargetInfo(snmpEngine, snmpTargetAddrName): def getNotificationInfo(snmpEngine, notificationTarget): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder - snmpNotifyEntry, = mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', - 'snmpNotifyEntry') + snmpNotifyEntry, = mibBuilder.importSymbols( + 'SNMP-NOTIFICATION-MIB', 'snmpNotifyEntry') cache = snmpEngine.getUserContext('getNotificationInfo') if cache is None: @@ -185,10 +198,8 @@ def getNotificationInfo(snmpEngine, notificationTarget): targetToNotifyMap = cache['targetToNotifyMap'] if notificationTarget not in targetToNotifyMap: - (snmpNotifyTag, - snmpNotifyType) = mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', - 'snmpNotifyTag', - 'snmpNotifyType') + snmpNotifyTag, snmpNotifyType = mibBuilder.importSymbols( + 'SNMP-NOTIFICATION-MIB', 'snmpNotifyTag', 'snmpNotifyType') tblIdx = snmpNotifyEntry.getInstIdFromIndices(notificationTarget) @@ -196,6 +207,7 @@ def getNotificationInfo(snmpEngine, notificationTarget): snmpNotifyTag = snmpNotifyTag.getNode( snmpNotifyTag.name + tblIdx ).syntax + snmpNotifyType = snmpNotifyType.getNode( snmpNotifyType.name + tblIdx ).syntax @@ -216,8 +228,8 @@ def getNotificationInfo(snmpEngine, notificationTarget): def getTargetNames(snmpEngine, tag): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder - snmpTargetAddrEntry, = mibBuilder.importSymbols('SNMP-TARGET-MIB', - 'snmpTargetAddrEntry') + snmpTargetAddrEntry, = mibBuilder.importSymbols( + 'SNMP-TARGET-MIB', 'snmpTargetAddrEntry') cache = snmpEngine.getUserContext('getTargetNames') if cache is None: @@ -226,6 +238,7 @@ def getTargetNames(snmpEngine, tag): if cache['id'] == snmpTargetAddrEntry.branchVersionId: tagToTargetsMap = cache['tagToTargetsMap'] + else: cache['tagToTargetsMap'] = {} @@ -236,10 +249,13 @@ def getTargetNames(snmpEngine, tag): 'SNMP-TARGET-MIB', 'SnmpTagValue', 'snmpTargetAddrName', 'snmpTargetAddrTagList' ) + mibNode = snmpTargetAddrTagList + while True: try: mibNode = snmpTargetAddrTagList.getNextNode(mibNode.name) + except NoSuchInstanceError: break @@ -249,8 +265,10 @@ def getTargetNames(snmpEngine, tag): for _tag in mibNode.syntax.asOctets().split(): _tag = SnmpTagValue(_tag) + if _tag not in tagToTargetsMap: tagToTargetsMap[_tag] = [] + tagToTargetsMap[_tag].append(_snmpTargetAddrName) cache['id'] = snmpTargetAddrEntry.branchVersionId diff --git a/pysnmp/entity/rfc3413/context.py b/pysnmp/entity/rfc3413/context.py index 9a99f284..8c759075 100644 --- a/pysnmp/entity/rfc3413/context.py +++ b/pysnmp/entity/rfc3413/context.py @@ -13,14 +13,20 @@ from pysnmp import error class SnmpContext(object): def __init__(self, snmpEngine, contextEngineId=None): - snmpEngineId, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', - 'snmpEngineID') + mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + + snmpEngineId, = mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') + if contextEngineId is None: # Default to local snmpEngineId self.contextEngineId = snmpEngineId.syntax + else: self.contextEngineId = snmpEngineId.syntax.clone(contextEngineId) - debug.logger & debug.FLAG_INS and debug.logger('SnmpContext: contextEngineId \"%r\"' % (self.contextEngineId,)) + + debug.logger & debug.FLAG_INS and debug.logger( + 'SnmpContext: contextEngineId %r' % (self.contextEngineId,)) + self.contextNames = { null: snmpEngine.msgAndPduDsp.mibInstrumController # Default name } @@ -29,30 +35,35 @@ class SnmpContext(object): contextName = univ.OctetString(contextName).asOctets() if contextName in self.contextNames: raise error.PySnmpError( - 'Duplicate contextName %s' % contextName - ) + 'Duplicate contextName %s' % contextName) + debug.logger & debug.FLAG_INS and debug.logger( 'registerContextName: registered contextName %r, mibInstrum %r' % (contextName, mibInstrum)) + if mibInstrum is None: self.contextNames[contextName] = self.contextNames[null] + else: self.contextNames[contextName] = mibInstrum def unregisterContextName(self, contextName): contextName = univ.OctetString(contextName).asOctets() + if contextName in self.contextNames: debug.logger & debug.FLAG_INS and debug.logger( 'unregisterContextName: unregistered contextName %r' % contextName) + del self.contextNames[contextName] def getMibInstrum(self, contextName=null): contextName = univ.OctetString(contextName).asOctets() if contextName not in self.contextNames: debug.logger & debug.FLAG_INS and debug.logger('getMibInstrum: contextName %r not registered' % contextName) - raise error.PySnmpError( - 'Missing contextName %s' % contextName - ) + + raise error.PySnmpError('Missing contextName %s' % contextName) + else: debug.logger & debug.FLAG_INS and debug.logger( 'getMibInstrum: contextName %r, mibInstum %r' % (contextName, self.contextNames[contextName])) + return self.contextNames[contextName] diff --git a/pysnmp/entity/rfc3413/ntforg.py b/pysnmp/entity/rfc3413/ntforg.py index e73dbf19..fc1e8c0a 100644 --- a/pysnmp/entity/rfc3413/ntforg.py +++ b/pysnmp/entity/rfc3413/ntforg.py @@ -29,6 +29,7 @@ class NotificationOriginator(object): securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, PDU, statusInformation, sendPduHandle, cbInfo): + sendRequestHandle, cbFun, cbCtx = cbInfo # 3.3.6d @@ -39,38 +40,48 @@ class NotificationOriginator(object): origMessageProcessingModel, origSecurityModel, origSecurityName, origSecurityLevel, origContextEngineId, origContextName, origPdu, origTimeout, - origRetryCount, origRetries, origDiscoveryRetries) = self.__pendingReqs.pop(sendPduHandle) + 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)) + '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): + 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' % ( + '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() + 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 @@ -85,20 +96,26 @@ class NotificationOriginator(object): 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)) + '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)) + 'processResponsePdu: sendRequestHandle %s, sendPduHandle %s, ' + 'timeout %d, retry %d of %d' % ( + sendRequestHandle, sendPduHandle, origTimeout, origRetries, + origRetryCount)) # 3.3.6b self.__pendingReqs[sendPduHandle] = ( @@ -108,6 +125,7 @@ class NotificationOriginator(object): origContextEngineId, origContextName, origPdu, origTimeout, origRetryCount, origRetries, origDiscoveryRetries ) + return # 3.3.6c @@ -129,6 +147,7 @@ class NotificationOriginator(object): if messageProcessingModel == 0: reqPDU = rfc2576.v2ToV1(pdu) pduVersion = 0 + else: reqPDU = pdu pduVersion = 1 @@ -136,7 +155,8 @@ class NotificationOriginator(object): # 3.3.5 if reqPDU.tagSet in rfc3411.CONFIRMED_CLASS_PDUS: # Convert timeout in seconds into timeout in timer ticks - timeoutInTicks = float(timeout) / 100 / snmpEngine.transportDispatcher.getTimerResolution() + timeoutInTicks = (float(timeout) / 100 / + snmpEngine.transportDispatcher.getTimerResolution()) sendRequestHandle = getNextHandle() @@ -158,7 +178,9 @@ class NotificationOriginator(object): securityModel, securityName, securityLevel, contextEngineId, contextName, pdu, timeout, retryCount, 0, 0 ) + snmpEngine.transportDispatcher.jobStarted(id(self)) + else: snmpEngine.msgAndPduDsp.sendPdu( snmpEngine, transportDomain, transportAddress, @@ -180,14 +202,18 @@ class NotificationOriginator(object): self.__pendingNotifications[notificationHandle].remove(sendRequestHandle) debug.logger & debug.FLAG_APP and debug.logger( - 'processResponseVarBinds: notificationHandle %s, sendRequestHandle %s, errorIndication %s, pending requests %s' % ( - notificationHandle, sendRequestHandle, errorIndication, self.__pendingNotifications[notificationHandle])) + 'processResponseVarBinds: notificationHandle %s, sendRequestHandle %s, ' + 'errorIndication %s, pending requests %s' % ( + notificationHandle, sendRequestHandle, errorIndication, + self.__pendingNotifications[notificationHandle])) if not self.__pendingNotifications[notificationHandle]: debug.logger & debug.FLAG_APP and debug.logger( - 'processResponseVarBinds: notificationHandle %s, sendRequestHandle %s -- completed' % ( - notificationHandle, sendRequestHandle)) + 'processResponseVarBinds: notificationHandle %s, sendRequestHandle %s ' + '-- completed' % (notificationHandle, sendRequestHandle)) + del self.__pendingNotifications[notificationHandle] + cbFun(snmpEngine, sendRequestHandle, errorIndication, pdu and v2c.apiPDU.getErrorStatus(pdu) or 0, pdu and v2c.apiPDU.getErrorIndex(pdu, muteErrors=True) or 0, @@ -198,11 +224,14 @@ class NotificationOriginator(object): # Higher-level API to Notification Originator. Supports multiple # targets, automatic var-binding formation and is fully LCD-driven. # + def sendVarBinds(self, snmpEngine, notificationTarget, contextEngineId, contextName, varBinds=(), cbFun=None, cbCtx=None): debug.logger & debug.FLAG_APP and debug.logger( - 'sendVarBinds: notificationTarget %s, contextEngineId %s, contextName "%s", varBinds %s' % ( - notificationTarget, contextEngineId or '<default>', contextName, varBinds)) + 'sendVarBinds: notificationTarget %s, contextEngineId %s, ' + 'contextName "%s", varBinds %s' % ( + notificationTarget, contextEngineId or '<default>', + contextName, varBinds)) mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder @@ -251,6 +280,7 @@ class NotificationOriginator(object): del varBinds[idx + 2] if varBinds[1][0] == snmpTrapOID: varBinds[1] = varBind + else: varBinds.insert(1, varBind) break @@ -261,12 +291,14 @@ class NotificationOriginator(object): sendRequestHandle = -1 - debug.logger & debug.FLAG_APP and debug.logger('sendVarBinds: final varBinds %s' % (varBinds,)) + debug.logger & debug.FLAG_APP and debug.logger( + 'sendVarBinds: final varBinds %s' % (varBinds,)) for targetAddrName in config.getTargetNames(snmpEngine, notifyTag): (transportDomain, transportAddress, timeout, retryCount, params) = config.getTargetAddr(snmpEngine, targetAddrName) + (messageProcessingModel, securityModel, securityName, securityLevel) = config.getTargetParams(snmpEngine, params) @@ -278,13 +310,16 @@ class NotificationOriginator(object): # filterType) = config.getNotifyFilter(filterProfileName) debug.logger & debug.FLAG_APP and debug.logger( - 'sendVarBinds: notificationHandle %s, notifyTag %s yields: transportDomain %s, transportAddress %r, securityModel %s, securityName %s, securityLevel %s' % ( - notificationHandle, notifyTag, transportDomain, transportAddress, securityModel, - securityName, securityLevel)) + 'sendVarBinds: notificationHandle %s, notifyTag %s yields: ' + 'transportDomain %s, transportAddress %r, securityModel %s, ' + 'securityName %s, securityLevel %s' % ( + notificationHandle, notifyTag, transportDomain, transportAddress, + securityModel, securityName, securityLevel)) for varName, varVal in varBinds: if varName in (sysUpTime, snmpTrapOID): continue + try: snmpEngine.accessControlModel[self.ACM_ID].isAccessAllowed( snmpEngine, securityModel, securityName, @@ -292,19 +327,22 @@ class NotificationOriginator(object): ) debug.logger & debug.FLAG_APP and debug.logger( - 'sendVarBinds: ACL succeeded for OID %s securityName %s' % (varName, securityName)) + 'sendVarBinds: ACL succeeded for OID %s securityName %s' % ( + varName, securityName)) except error.StatusInformation: debug.logger & debug.FLAG_APP and debug.logger( - 'sendVarBinds: ACL denied access for OID %s securityName %s, droppping notification' % ( - varName, securityName)) + 'sendVarBinds: ACL denied access for OID %s securityName %s,' + 'dropping notification' % (varName, securityName)) return # 3.3.4 if notifyType == 1: pdu = v2c.SNMPv2TrapPDU() + elif notifyType == 2: pdu = v2c.InformRequestPDU() + else: raise error.ProtocolError('Unknown notify-type %r', notifyType) @@ -321,22 +359,27 @@ class NotificationOriginator(object): except error.StatusInformation as exc: statusInformation = exc + debug.logger & debug.FLAG_APP and debug.logger( - 'sendVarBinds: sendRequestHandle %s: sendPdu() failed with %r' % ( - sendRequestHandle, statusInformation)) - if notificationHandle not in self.__pendingNotifications or \ - not self.__pendingNotifications[notificationHandle]: + 'sendVarBinds: sendRequestHandle %s: sendPdu() failed ' + 'with %r' % (sendRequestHandle, statusInformation)) + + if (notificationHandle not in self.__pendingNotifications or + not self.__pendingNotifications[notificationHandle]): + if notificationHandle in self.__pendingNotifications: del self.__pendingNotifications[notificationHandle] + if cbFun: cbFun(snmpEngine, notificationHandle, statusInformation['errorIndication'], 0, 0, (), cbCtx) + return notificationHandle debug.logger & debug.FLAG_APP and debug.logger( - 'sendVarBinds: notificationHandle %s, sendRequestHandle %s, timeout %d' % ( - notificationHandle, sendRequestHandle, timeout)) + 'sendVarBinds: notificationHandle %s, sendRequestHandle %s, ' + 'timeout %d' % (notificationHandle, sendRequestHandle, timeout)) if notifyType == 2: if notificationHandle not in self.__pendingNotifications: @@ -344,8 +387,8 @@ class NotificationOriginator(object): self.__pendingNotifications[notificationHandle].add(sendRequestHandle) debug.logger & debug.FLAG_APP and debug.logger( - 'sendVarBinds: notificationHandle %s, sendRequestHandle %s, notification(s) sent' % ( - notificationHandle, sendRequestHandle)) + 'sendVarBinds: notificationHandle %s, sendRequestHandle %s, ' + 'notification(s) sent' % (notificationHandle, sendRequestHandle)) return notificationHandle diff --git a/pysnmp/entity/rfc3413/ntfrcv.py b/pysnmp/entity/rfc3413/ntfrcv.py index a4754be2..53cc7ac3 100644 --- a/pysnmp/entity/rfc3413/ntfrcv.py +++ b/pysnmp/entity/rfc3413/ntfrcv.py @@ -31,7 +31,8 @@ class NotificationReceiver(object): def storeSnmpTrapCommunity(snmpEngine, execpoint, variables, cbCtx): self.__snmpTrapCommunity = variables.get('communityName', '') - snmpEngine.observer.registerObserver(storeSnmpTrapCommunity, 'rfc2576.processIncomingMsg') + snmpEngine.observer.registerObserver( + storeSnmpTrapCommunity, 'rfc2576.processIncomingMsg') def close(self, snmpEngine): snmpEngine.msgAndPduDsp.unregisterContextEngineId( @@ -48,6 +49,7 @@ class NotificationReceiver(object): if messageProcessingModel == 0: origPdu = PDU PDU = rfc2576.v1ToV2(PDU, snmpTrapCommunity=self.__snmpTrapCommunity) + else: origPdu = None @@ -89,12 +91,17 @@ class NotificationReceiver(object): except error.StatusInformation as exc: debug.logger & debug.FLAG_APP and debug.logger( 'processPdu: stateReference %s, statusInformation %s' % (stateReference, exc)) - snmpSilentDrops, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', - 'snmpSilentDrops') + + mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + + snmpSilentDrops, = mibBuilder.importSymbols( + '__SNMPv2-MIB', 'snmpSilentDrops') + snmpSilentDrops.syntax += 1 elif PDU.tagSet in rfc3411.UNCONFIRMED_CLASS_PDUS: pass + else: raise error.ProtocolError('Unexpected PDU class %s' % PDU.tagSet) |