summaryrefslogtreecommitdiff
path: root/pysnmp/entity/rfc3413/ntforg.py
blob: 0c686635dc3bfac7be1b820a8178a17f7daae8a4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
#
# This file is part of pysnmp software.
#
# Copyright (c) 2005-2019, Ilya Etingof <etingof@gmail.com>
# License: http://snmplabs.com/pysnmp/license.html
#
import sys
from pyasn1.compat.octets import null
from pysnmp.entity.rfc3413 import config
from pysnmp.proto.proxy import rfc2576
from pysnmp.proto import rfc3411
from pysnmp.proto.api import v2c
from pysnmp.proto import errind, error
from pysnmp.smi import view, rfc1902
from pysnmp import nextid
from pysnmp import debug

getNextHandle = nextid.Integer(0x7fffffff)


class NotificationOriginator(object):
    ACM_ID = 3  # default MIB access control method to use

    def __init__(self, **options):
        self.__pendingReqs = {}
        self.__pendingNotifications = {}
        self.snmpContext = options.pop('snmpContext', None)  # this is deprecated
        self.__options = options

    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)

    def sendPdu(self, snmpEngine, targetName, contextEngineId,
                contextName, pdu, cbFun=None, cbCtx=None):
        (transportDomain, transportAddress, timeout,
         retryCount, params) = config.getTargetAddr(snmpEngine, targetName)

        (messageProcessingModel, securityModel, securityName,
         securityLevel) = config.getTargetParams(snmpEngine, params)

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

        # 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()

            sendRequestHandle = getNextHandle()

            # 3.3.6a
            sendPduHandle = snmpEngine.msgAndPduDsp.sendPdu(
                snmpEngine, transportDomain, transportAddress,
                messageProcessingModel, securityModel, securityName,
                securityLevel, contextEngineId, contextName,
                pduVersion, reqPDU, True, timeoutInTicks,
                self.processResponsePdu, (sendRequestHandle, cbFun, cbCtx)
            )

            debug.logger & debug.FLAG_APP and debug.logger(
                'sendPdu: sendPduHandle %s, timeout %d' % (sendPduHandle, timeout))

            # 3.3.6b
            self.__pendingReqs[sendPduHandle] = (
                transportDomain, transportAddress, messageProcessingModel,
                securityModel, securityName, securityLevel, contextEngineId,
                contextName, pdu, timeout, retryCount, 0, 0
            )
            snmpEngine.transportDispatcher.jobStarted(id(self))
        else:
            snmpEngine.msgAndPduDsp.sendPdu(
                snmpEngine, transportDomain, transportAddress,
                messageProcessingModel, securityModel,
                securityName, securityLevel, contextEngineId,
                contextName, pduVersion, reqPDU, False
            )

            sendRequestHandle = None

            debug.logger & debug.FLAG_APP and debug.logger('sendPdu: message sent')

        return sendRequestHandle

    def processResponseVarBinds(self, snmpEngine, sendRequestHandle,
                                errorIndication, pdu, cbCtx):
        notificationHandle, cbFun, cbCtx = cbCtx

        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]))

        if not self.__pendingNotifications[notificationHandle]:
            debug.logger & debug.FLAG_APP and debug.logger(
                '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,
                  pdu and v2c.apiPDU.getVarBinds(pdu) or (),
                  cbCtx)

    #
    # 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))

        if contextName:
            __SnmpAdminString, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols(
                'SNMP-FRAMEWORK-MIB', 'SnmpAdminString')
            contextName = __SnmpAdminString(contextName)

        # 3.3
        (notifyTag, notifyType) = config.getNotificationInfo(snmpEngine, notificationTarget)

        notificationHandle = getNextHandle()

        debug.logger & debug.FLAG_APP and debug.logger(
            'sendVarBinds: notificationHandle %s, notifyTag %s, notifyType %s' % (
                notificationHandle, notifyTag, notifyType))

        varBinds = [(v2c.ObjectIdentifier(x), y) for x, y in varBinds]

        # 3.3.2 & 3.3.3
        snmpTrapOID, sysUpTime = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB',
                                                                                                       'snmpTrapOID',
                                                                                                       'sysUpTime')

        for idx in range(len(varBinds)):
            if idx and varBinds[idx][0] == sysUpTime.getName():
                if varBinds[0][0] == sysUpTime.getName():
                    varBinds[0] = varBinds[idx]
                else:
                    varBinds.insert(0, varBinds[idx])
                    del varBinds[idx]

            if varBinds[0][0] != sysUpTime.getName():
                varBinds.insert(0, (v2c.ObjectIdentifier(sysUpTime.getName()),
                                    sysUpTime.getSyntax().clone()))

        if len(varBinds) < 2 or varBinds[1][0] != snmpTrapOID.getName():
            varBinds.insert(1, (v2c.ObjectIdentifier(snmpTrapOID.getName()),
                                snmpTrapOID.getSyntax()))

        sendRequestHandle = -1

        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)

            # 3.3.1 XXX
            # XXX filtering's yet to be implemented
            #             filterProfileName = config.getNotifyFilterProfile(params)

            #             (filterSubtree, filterMask,
            #              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))

            for varName, varVal in varBinds:
                if varName in (sysUpTime.name, snmpTrapOID.name):
                    continue
                try:
                    snmpEngine.accessControlModel[self.ACM_ID].isAccessAllowed(
                        snmpEngine, securityModel, securityName,
                        securityLevel, 'notify', contextName, varName
                    )

                    debug.logger & debug.FLAG_APP and debug.logger(
                        '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))
                    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)

            v2c.apiPDU.setDefaults(pdu)
            v2c.apiPDU.setVarBinds(pdu, varBinds)

            # 3.3.5
            try:
                sendRequestHandle = self.sendPdu(
                    snmpEngine, targetAddrName, contextEngineId,
                    contextName, pdu, self.processResponseVarBinds,
                    (notificationHandle, cbFun, cbCtx)
                )

            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]:
                    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))

            if notifyType == 2:
                if notificationHandle not in self.__pendingNotifications:
                    self.__pendingNotifications[notificationHandle] = set()
                self.__pendingNotifications[notificationHandle].add(sendRequestHandle)

        debug.logger & debug.FLAG_APP and debug.logger(
            'sendVarBinds: notificationHandle %s, sendRequestHandle %s, notification(s) sent' % (
                notificationHandle, sendRequestHandle))

        return notificationHandle

# XXX
# move/group/implement config setting/retrieval at a stand-alone module