def testCount(self): self.s1.clear() for x in ['abc', 'def', 'abc']: self.s1.append(x) assert self.s1.count(str2octs('abc')) == 2 assert self.s1.count(str2octs('def')) == 1 assert self.s1.count(str2octs('ghi')) == 0
def testSort(self): self.s1.clear() self.s1[0] = 'b' self.s1[1] = 'a' assert list(self.s1) == [str2octs('b'), str2octs('a')] self.s1.sort() assert list(self.s1) == [str2octs('a'), str2octs('b')]
def testIndex(self): self.s1.clear() for x in ['abc', 'def', 'abc']: self.s1.append(x) assert self.s1.index(str2octs('abc')) == 0 assert self.s1.index(str2octs('def')) == 1 assert self.s1.index(str2octs('abc'), 1) == 2
def testUpdate(self): self.s1.clear() assert list(self.s1.values()) == [str2octs(''), str2octs(''), 34] self.s1.update(**{'name': 'abc', 'nick': 'def', 'age': 123}) assert list(self.s1.items()) == [(x[0], str2octs(x[1])) for x in [('name', 'abc'), ('nick', 'def')]] + [('age', 123)] self.s1.update(('name', 'ABC')) assert list(self.s1.items()) == [(x[0], str2octs(x[1])) for x in [('name', 'ABC'), ('nick', 'def')]] + [('age', 123)] self.s1.update(name='CBA') assert list(self.s1.items()) == [(x[0], str2octs(x[1])) for x in [('name', 'CBA'), ('nick', 'def')]] + [('age', 123)]
def __searchOid(self, oid, eol=str2octs('\n')): lo = mid = 0; prev_mid = -1; self.__text.seek(0, 2) hi = sz = self.__text.tell() while lo < hi: mid = (lo+hi)//2 self.__text.seek(mid) while mid: c = self.__text.read(1) if c == eol: mid = mid + 1 break mid = mid - 1 # pivot stepping back in search for full line self.__text.seek(mid) if mid == prev_mid: # loop condition due to stepping back pivot break if mid >= sz: return sz line = self.__text.readline() midval, _ = self.__textParser.evaluate(line, oidOnly=True) if midval < oid: lo = mid + len(line) elif midval > oid: hi = mid else: return mid prev_mid = mid if lo == mid: return lo else: return hi
def testAppend(self): self.s1.clear() self.s1.setComponentByPosition(0, univ.OctetString('abc')) assert len(self.s1) == 1 self.s1.append('def') assert len(self.s1) == 2 assert list(self.s1) == [str2octs(x) for x in ['abc', 'def']]
def testExtend(self): self.s1.clear() self.s1.setComponentByPosition(0, univ.OctetString('abc')) assert len(self.s1) == 1 self.s1.extend(['def', 'ghi']) assert len(self.s1) == 3 assert list(self.s1) == [str2octs(x) for x in ['abc', 'def', 'ghi']]
def testIndefModeChunkedSubst(self): assert decoder.decode( ints2octs((36, 128, 4, 4, 81, 117, 105, 99, 4, 4, 107, 32, 98, 114, 4, 4, 111, 119, 110, 32, 4, 3, 102, 111, 120, 0, 0)), substrateFun=lambda a, b, c: (b, str2octs('')) ) == (ints2octs( (4, 4, 81, 117, 105, 99, 4, 4, 107, 32, 98, 114, 4, 4, 111, 119, 110, 32, 4, 3, 102, 111, 120, 0, 0)), str2octs(''))
def testIndefModeChunked(self): assert decoder.decode( ints2octs( ( 36, 128, 4, 4, 81, 117, 105, 99, 4, 4, 107, 32, 98, 114, 4, 4, 111, 119, 110, 32, 4, 3, 102, 111, 120, 0, 0, ) ) ) == (str2octs("Quick brown fox"), null)
def searchRecordByOid(oid, fileObj, textParser, eol=str2octs('\n')): lo = mid = 0; prev_mid = -1 fileObj.seek(0, 2) hi = sz = fileObj.tell() while lo < hi: mid = (lo+hi)//2 fileObj.seek(mid) while mid: c = fileObj.read(1) if c == eol: mid = mid + 1 break mid = mid - 1 # pivot stepping back in search for full line fileObj.seek(mid) if mid == prev_mid: # loop condition due to stepping back pivot break if mid >= sz: return sz line, _, skippedOffset = getRecord(fileObj) if not line: return hi midval, _ = textParser.evaluate(line, oidOnly=True) if midval < oid: lo = mid + skippedOffset + len(line) elif midval > oid: hi = mid else: return mid prev_mid = mid if lo == mid: return lo else: return hi
def testOuterByTypeWithInstanceValue(self): self.s1.setComponentByType( univ.OctetString.tagSet, univ.OctetString('abc') ) assert self.s1.getComponentByType( univ.OctetString.tagSet ) == str2octs('abc')
def testTypeCheckOnAssignment(self): self.s.clear() self.s['blob'] = univ.Any(str2octs('xxx')) # this should succeed because Any is untagged and unconstrained self.s['blob'] = univ.Integer(123)
def testWithoutSchema(self): s = univ.SequenceOf().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 3)) s2, r = decoder.decode( ints2octs((163, 15, 48, 13, 4, 11, 113, 117, 105, 99, 107, 32, 98, 114, 111, 119, 110)) ) assert not r assert s2 == [str2octs('quick brown')] assert s.tagSet == s2.tagSet
def testStaticDef(self): class SequenceOf(univ.SequenceOf): componentType = univ.OctetString('') s = SequenceOf() s[0] = 'abc' assert len(s) == 1 assert s == [str2octs('abc')]
def testStaticDef(self): class Set(univ.Set): componentType = namedtype.NamedTypes( namedtype.NamedType('name', univ.OctetString('')), namedtype.OptionalNamedType('nick', univ.OctetString('')), namedtype.DefaultedNamedType('age', univ.Integer(34)) ) s = Set() s['name'] = 'abc' assert s['name'] == str2octs('abc')
def getRecord(fileObj, lineNo=None, offset=0): line = fileObj.readline() if lineNo is not None and line: lineNo += 1 while line: tline = line.strip() # skip comment or blank line if not tline or tline.startswith(str2octs('#')): offset += len(line) line = fileObj.readline() if lineNo is not None and line: lineNo += 1 else: break return line, lineNo, offset
def testUpdate(self): s = univ.Sequence() assert not s s.setComponentByPosition(0, univ.OctetString('abc')) s.setComponentByPosition(1, univ.Integer(123)) assert s assert list(s.keys()) == ['field-0', 'field-1'] assert list(s.values()) == [str2octs('abc'), 123] assert list(s.items()) == [('field-0', str2octs('abc')), ('field-1', 123)] s['field-0'] = univ.OctetString('def') assert list(s.values()) == [str2octs('def'), 123] s['field-1'] = univ.OctetString('ghi') assert list(s.values()) == [str2octs('def'), str2octs('ghi')] try: s['field-2'] = univ.OctetString('xxx') except KeyError: pass else: assert False, 'unknown field at schema-less object tolerated' assert 'field-0' in s s.clear() assert 'field-0' not in s
def testSubtypeSpec(self): s = self.s1.clone(subtypeSpec=constraint.ConstraintsUnion( constraint.SingleValueConstraint(str2octs('abc')) )) try: s.setComponentByPosition(0, univ.OctetString('abc')) except: assert 0, 'constraint fails' try: s.setComponentByPosition(1, univ.OctetString('Abc')) except: pass else: assert 0, 'constraint fails'
def lookup(self, oid): """ Returns the record which oid is exactly the given one or None if the record doesn't exist """ # Issue #4: Synchronizes access to the database self.__lock.acquire(True); try: oid, is_subtree, tag, val = self.__db[oid].split(str2octs(','), 3) finally: self.__lock.release(); try: tag_class = self.str2class(tag); except Exception: logger.error ( 'Could not interpret tag %s', tag, exc_info=True ); raise return univ.ObjectIdentifier(oid), is_subtree, tag_class, tag_class(val)
def encodeValue(self, encodeFun, value, defMode, maxChunkSize): if value.isPlusInfinity(): return int2oct(0x40), 0 if value.isMinusInfinity(): return int2oct(0x41), 0 m, b, e = value if not m: return null, 0 if b == 10: return str2octs('\x03%dE%s%d' % (m, e == 0 and '+' or '', e)), 0 elif b == 2: fo = 0x80 # binary enoding if m < 0: fo = fo | 0x40 # sign bit m = -m while int(m) != m: # drop floating point m *= 2 e -= 1 while m & 0x1 == 0: # mantissa normalization m >>= 1 e += 1 eo = null while e not in (0, -1): eo = int2oct(e&0xff) + eo e >>= 8 if e == 0 and eo and oct2int(eo[0]) & 0x80: eo = int2oct(0) + eo n = len(eo) if n > 0xff: raise error.PyAsn1Error('Real exponent overflow') if n == 1: pass elif n == 2: fo |= 1 elif n == 3: fo |= 2 else: fo |= 3 eo = int2oct(n//0xff+1) + eo po = null while m: po = int2oct(m&0xff) + po m >>= 8 substrate = int2oct(fo) + eo + po return substrate, 0 else: raise error.PyAsn1Error('Prohibited Real base %s' % b)
def testComponentConstraintsMatching(self): s = self.s1.clone() o = univ.OctetString().subtype( subtypeSpec=constraint.ConstraintsUnion(constraint.SingleValueConstraint(str2octs('cba')))) s.strictConstraints = True try: s.setComponentByName('name', o.clone('cba')) except PyAsn1Error: pass else: assert 0, 'inner supertype constraint allowed' s.strictConstraints = False try: s.setComponentByName('name', o.clone('cba')) except PyAsn1Error: assert 0, 'inner supertype constraint disallowed' else: pass
def testSubtypeSpec(self): s = self.s1.clone(subtypeSpec=constraint.ConstraintsUnion( constraint.SingleValueConstraint(str2octs('abc')) )) try: s.setComponentByPosition(0, univ.OctetString('abc')) except PyAsn1Error: assert 0, 'constraint fails' try: s.setComponentByPosition(1, univ.OctetString('Abc')) except PyAsn1Error: try: s.setComponentByPosition(1, univ.OctetString('Abc'), verifyConstraints=False) except PyAsn1Error: assert 0, 'constraint failes with verifyConstraints=True' else: assert 0, 'constraint fails'
def testComponentConstraintsMatching(self): s = self.s1.clone() o = univ.OctetString().subtype( subtypeSpec=constraint.ConstraintsUnion(constraint.SingleValueConstraint(str2octs('cba')))) s.strictConstraints = True # This requires types equality try: s.setComponentByPosition(0, o.clone('cba')) except PyAsn1Error: pass else: assert 0, 'inner supertype constraint allowed' s.strictConstraints = False # This requires subtype relationships try: s.setComponentByPosition(0, o.clone('cba')) except PyAsn1Error: assert 0, 'inner supertype constraint disallowed' else: pass
def encodeValue(self, value, encodeFun, **options): value.verifySizeSpec() substrate = null idx = len(value) if value.typeId == univ.Set.typeId: namedTypes = value.componentType comps = [] compsMap = {} while idx > 0: idx -= 1 if namedTypes: if namedTypes[idx].isOptional and not value[idx].isValue: continue if namedTypes[idx].isDefaulted and value[idx] == namedTypes[idx].asn1Object: continue comps.append(value[idx]) compsMap[id(value[idx])] = namedTypes and namedTypes[idx].isOptional for comp in self._sortComponents(comps): options.update(ifNotEmpty=compsMap[id(comp)]) substrate += encodeFun(comp, **options) else: components = [encodeFun(x, **options) for x in value] # sort by serialized and padded components if len(components) > 1: zero = str2octs('\x00') maxLen = max(map(len, components)) paddedComponents = [ (x.ljust(maxLen, zero), x) for x in components ] paddedComponents.sort(key=lambda x: x[0]) components = [x[1] for x in paddedComponents] substrate = null.join(components) return substrate, True, True
def encodeValue(self, value, asn1Spec, encodeFun, **options): if asn1Spec is None: value.verifySizeSpec() else: asn1Spec = asn1Spec.componentType components = [encodeFun(x, asn1Spec, **options) for x in value] # sort by serialised and padded components if len(components) > 1: zero = str2octs('\x00') maxLen = max(map(len, components)) paddedComponents = [ (x.ljust(maxLen, zero), x) for x in components ] paddedComponents.sort(key=lambda x: x[0]) components = [x[1] for x in paddedComponents] substrate = null.join(components) return substrate, True, True
def testSetComponentByPosition(self): self.s1.setComponentByPosition(0, univ.OctetString('Jim')) assert self.s1 == str2octs('Jim')
def testGetComponent(self): self.s1.setComponentByType(univ.OctetString.tagSet, 'abc') assert self.s1.getComponent() == str2octs( 'abc'), 'getComponent() fails'
def testMul(self): assert univ.OctetString('a') * 2 == str2octs('aa'), '__mul__() fails'
def prettyIn(self, value): # override asn1 type method """Implements DISPLAY-HINT parsing into base SNMP value Proper parsing seems impossible due to ambiguities. Here we are trying to do our best, but be prepared for failures on complicated DISPLAY-HINTs. Keep in mind that this parser only works with "text" input meaning `unicode` (Py2) or `str` (Py3). """ for base in inspect.getmro(self.__class__): if not issubclass(base, TextualConvention) and issubclass( base, Asn1Item): break else: raise SmiError( 'TEXTUAL-CONVENTION has no underlying SNMP base type') if self.displayHint and ( self.__integer.isSuperTypeOf(self, matchConstraints=False) and self.getNamedValues() or self.__unsigned32.isSuperTypeOf( self, matchConstraints=False) or self.__timeticks.isSuperTypeOf(self, matchConstraints=False)): value = str(value) _ = lambda t, f=0: (t, f) displayHintType, decimalPrecision = _(*self.displayHint.split('-')) if displayHintType == 'x' and (value.startswith('0x') or value.startswith('-0x')): try: if value.startswith('-'): return base.prettyIn(self, -int(value[3:], 16)) else: return base.prettyIn(self, int(value[2:], 16)) except Exception: raise SmiError('integer evaluation error: %s' % sys.exc_info()[1]) elif displayHintType == 'd': try: return base.prettyIn( self, int(float(value) * 10**int(decimalPrecision))) except Exception: raise SmiError('float evaluation error: %s' % sys.exc_info()[1]) elif displayHintType == 'o' and (value.startswith('0') or value.startswith('-0')): try: return base.prettyIn(self, int(value, 8)) except Exception: raise SmiError('octal evaluation error: %s' % sys.exc_info()[1]) elif displayHintType == 'b' and (value.startswith('B') or value.startswith('-B')): negative = value.startswith('-') if negative: value = value[2:] else: value = value[1:] value = [x != '0' and 1 or 0 for x in value] binValue = 0 while value: binValue <<= value[0] del value[0] return base.prettyIn(self, binValue) else: raise SmiError('Unsupported numeric type spec "%s" at %s' % (displayHintType, self.__class__.__name__)) elif self.displayHint and self.__octetString.isSuperTypeOf( self, matchConstraints=False): numBase = {'x': 16, 'd': 10, 'o': 8} numDigits = { 'x': octets.str2octs(string.hexdigits), 'o': octets.str2octs(string.octdigits), 'd': octets.str2octs(string.digits) } # how do we know if object is initialized with display-hint # formatted text? based on "text" input maybe? # That boils down to `str` object on Py3 or `unicode` on Py2. if octets.isStringType(value) and not octets.isOctetsType(value): value = base.prettyIn(self, value) else: return base.prettyIn(self, value) outputValue = octets.str2octs('') runningValue = value displayHint = self.displayHint while runningValue and displayHint: # 1 this information is totally lost, just fail explicitly if displayHint[0] == '*': raise SmiError('Can\'t parse "*" in DISPLAY-HINT (%s)' % self.__class__.__name__) # 2 this becomes ambiguous when it comes to rendered value octetLength = '' while displayHint and displayHint[0] in string.digits: octetLength += displayHint[0] displayHint = displayHint[1:] # length is mandatory but people ignore that if not octetLength: octetLength = len(runningValue) try: octetLength = int(octetLength) except Exception: raise SmiError('Bad octet length: %s' % octetLength) if not displayHint: raise SmiError('Short octet length: %s' % self.displayHint) # 3 displayFormat = displayHint[0] displayHint = displayHint[1:] # 4 this is the lifesaver -- we could use it as an anchor if displayHint and displayHint[ 0] not in string.digits and displayHint[0] != '*': displaySep = displayHint[0] displayHint = displayHint[1:] else: displaySep = '' # 5 is probably impossible to support if displayFormat in ('a', 't'): outputValue += runningValue[:octetLength] elif displayFormat in numBase: if displaySep: guessedOctetLength = runningValue.find( octets.str2octs(displaySep)) if guessedOctetLength == -1: guessedOctetLength = len(runningValue) else: for idx in range(len(runningValue)): if runningValue[idx] not in numDigits[ displayFormat]: guessedOctetLength = idx break else: guessedOctetLength = len(runningValue) try: num = int( octets.octs2str(runningValue[:guessedOctetLength]), numBase[displayFormat]) except Exception: raise SmiError('Display format eval failure: %s: %s' % (runningValue[:guessedOctetLength], sys.exc_info()[1])) num_as_bytes = [] if num: while num: num_as_bytes.append(num & 0xFF) num >>= 8 else: num_as_bytes = [0] while len(num_as_bytes) < octetLength: num_as_bytes.append(0) num_as_bytes.reverse() outputValue += octets.ints2octs(num_as_bytes) if displaySep: guessedOctetLength += 1 octetLength = guessedOctetLength else: raise SmiError('Unsupported display format char: %s' % displayFormat) runningValue = runningValue[octetLength:] if not displayHint: displayHint = self.displayHint return base.prettyIn(self, outputValue) else: return base.prettyIn(self, value)
def testObjectTypeSyntax(self): self.assertEqual( self.ctx['testObjectType'].getSyntax().clone(('set', )), str2octs('@'), 'bad BITS SYNTAX')
def test_str2octs(self): assert '\x01\x02\x03' == octets.str2octs('\x01\x02\x03')
def testIndefModeChunked(self): assert decoder.decode( ints2octs((36, 128, 4, 4, 81, 117, 105, 99, 4, 4, 107, 32, 98, 114, 4, 4, 111, 119, 110, 32, 4, 3, 102, 111, 120, 0, 0)) ) == (str2octs('Quick brown fox'), null)
def testOuterByTypeWithPythonValue(self): self.s1.setComponentByType(univ.OctetString.tagSet, 'abc') assert self.s1.getComponentByType( univ.OctetString.tagSet) == str2octs('abc')
def testRadd(self): assert 'b' + univ.OctetString('q') == str2octs( 'bq'), '__radd__() fails'
def testTypeCheckOnAssignment(self): self.s.clear() self.s['blob'] = univ.Any(str2octs('xxx')) self.s['blob'] = univ.Integer(123)
def testDefModeChunked(self): assert decoder.decode( ints2octs((36, 23, 4, 4, 81, 117, 105, 99, 4, 4, 107, 32, 98, 114, 4, 4, 111, 119, 110, 32, 4, 3, 102, 111, 120)) ) == (str2octs('Quick brown fox'), null)
def encodeValue(self, encodeFun, value, defMode, maxChunkSize): if value.isPlusInfinity(): return int2oct(0x40), 0 if value.isMinusInfinity(): return int2oct(0x41), 0 m, b, e = value if not m: return null, 0 if b == 10: return str2octs('\x03%dE%s%d' % (m, e == 0 and '+' or '', e)), 0 elif b == 2: fo = 0x80 # binary encoding ms, m, encbase, e = self._chooseEncBase(value) if ms < 0: # mantissa sign fo = fo | 0x40 # sign bit # exponenta & mantissa normalization if encbase == 2: while m & 0x1 == 0: m >>= 1 e += 1 elif encbase == 8: while m & 0x7 == 0: m >>= 3 e += 1 fo |= 0x10 else: # encbase = 16 while m & 0xf == 0: m >>= 4 e += 1 fo |= 0x20 sf = 0 # scale factor while m & 0x1 == 0: m >>= 1 sf += 1 if sf > 3: raise error.PyAsn1Error('Scale factor overflow') # bug if raised fo |= sf << 2 eo = null if e == 0 or e == -1: eo = int2oct(e&0xff) else: while e not in (0, -1): eo = int2oct(e&0xff) + eo e >>= 8 if e == 0 and eo and oct2int(eo[0]) & 0x80: eo = int2oct(0) + eo if e == -1 and eo and not (oct2int(eo[0]) & 0x80): eo = int2oct(0xff) + eo n = len(eo) if n > 0xff: raise error.PyAsn1Error('Real exponent overflow') if n == 1: pass elif n == 2: fo |= 1 elif n == 3: fo |= 2 else: fo |= 3 eo = int2oct(n&0xff) + eo po = null while m: po = int2oct(m&0xff) + po m >>= 8 substrate = int2oct(fo) + eo + po return substrate, 0 else: raise error.PyAsn1Error('Prohibited Real base %s' % b)
def testObjectTypeSyntax(self): self.assertEqual(self.ctx['testObjectType'].getSyntax().clone(''), str2octs(''), 'bad size constrained SYNTAX')
def testCmp(self): self.s1.setComponentByName('name', univ.OctetString('abc')) assert self.s1 == str2octs('abc'), '__cmp__() fails'
def testByKey(self): self.s1['name'] = 'abc' assert self.s1['name'] == str2octs('abc'), 'set by key fails'
def testOuterByTypeWithInstanceValue(self): self.s1.setComponentByType(univ.OctetString.tagSet, univ.OctetString('abc')) assert self.s1.getComponentByType( univ.OctetString.tagSet) == str2octs('abc')
def encodeValue(self, value, encodeFun, **options): if value.isPlusInf: return (0x40,), False, False if value.isMinusInf: return (0x41,), False, False m, b, e = value if not m: return null, False, True if b == 10: return str2octs('\x03%dE%s%d' % (m, e == 0 and '+' or '', e)), False, True elif b == 2: fo = 0x80 # binary encoding ms, m, encbase, e = self._chooseEncBase(value) if ms < 0: # mantissa sign fo |= 0x40 # sign bit # exponenta & mantissa normalization if encbase == 2: while m & 0x1 == 0: m >>= 1 e += 1 elif encbase == 8: while m & 0x7 == 0: m >>= 3 e += 1 fo |= 0x10 else: # encbase = 16 while m & 0xf == 0: m >>= 4 e += 1 fo |= 0x20 sf = 0 # scale factor while m & 0x1 == 0: m >>= 1 sf += 1 if sf > 3: raise error.PyAsn1Error('Scale factor overflow') # bug if raised fo |= sf << 2 eo = null if e == 0 or e == -1: eo = int2oct(e & 0xff) else: while e not in (0, -1): eo = int2oct(e & 0xff) + eo e >>= 8 if e == 0 and eo and oct2int(eo[0]) & 0x80: eo = int2oct(0) + eo if e == -1 and eo and not (oct2int(eo[0]) & 0x80): eo = int2oct(0xff) + eo n = len(eo) if n > 0xff: raise error.PyAsn1Error('Real exponent overflow') if n == 1: pass elif n == 2: fo |= 1 elif n == 3: fo |= 2 else: fo |= 3 eo = int2oct(n & 0xff) + eo po = null while m: po = int2oct(m & 0xff) + po m >>= 8 substrate = int2oct(fo) + eo + po return substrate, False, True else: raise error.PyAsn1Error('Prohibited Real base %s' % b)
def testByTypeWithInstance(self): self.s1.setComponentByType(univ.OctetString.tagSet, univ.OctetString('abc')) assert self.s1.getComponentByType( univ.OctetString.tagSet) == str2octs('abc'), 'set by name fails'
def testSimple(self): assert encoder.encode(self.s) == str2octs('fox')
def testShortMode(self): assert decoder.decode( ints2octs( (4, 15, 81, 117, 105, 99, 107, 32, 98, 114, 111, 119, 110, 32, 102, 111, 120)), ) == (str2octs('Quick brown fox'), null)
def test_str2octs(self): assert bytes([1, 2, 3]) == octets.str2octs('\x01\x02\x03')
def testById(self): self.s1.setComponentByName('name', univ.OctetString('abc')) assert self.s1.getComponentByName('name') == str2octs( 'abc'), 'set by name fails'
def testLongMode(self): assert decoder.decode( ints2octs((36, 128, 4, 130, 3, 232) + (81, ) * 1000 + (4, 1, 81, 0, 0))) == (str2octs('Q' * 1001), null)
def testValue(self): assert encoder.encode(self.o) == str2octs('Quick brown fox')
def testObjectTypeSyntax(self): self.assertEqual(self.ctx['testObjectType'].getSyntax(), str2octs('test value'), 'bad DEFVAL')
def testRmul(self): assert 2 * univ.OctetString('b') == str2octs('bb'), '__rmul__() fails'
def testSeq(self): self.s1.setComponentByPosition(0, univ.OctetString('abc')) assert self.s1[0] == str2octs('abc'), 'set by idx fails' self.s1[0] = 'cba' assert self.s1[0] == str2octs('cba'), 'set by idx fails'
def test_str2octs_empty(self): assert not octets.str2octs('')
def __init__(self, snmpEngineID=None, maxMessageSize=65507, msgAndPduDsp=None): self.cache = {} self.observer = observer.MetaObserver() if msgAndPduDsp is None: self.msgAndPduDsp = MsgAndPduDispatcher() else: self.msgAndPduDsp = msgAndPduDsp self.messageProcessingSubsystems = { SnmpV1MessageProcessingModel.messageProcessingModelID: SnmpV1MessageProcessingModel(), SnmpV2cMessageProcessingModel.messageProcessingModelID: SnmpV2cMessageProcessingModel(), SnmpV3MessageProcessingModel.messageProcessingModelID: SnmpV3MessageProcessingModel() } self.securityModels = { SnmpV1SecurityModel.securityModelID: SnmpV1SecurityModel(), SnmpV2cSecurityModel.securityModelID: SnmpV2cSecurityModel(), SnmpUSMSecurityModel.securityModelID: SnmpUSMSecurityModel() } self.accessControlModel = { void.Vacm.accessModelID: void.Vacm(), rfc3415.Vacm.accessModelID: rfc3415.Vacm() } self.transportDispatcher = None if self.msgAndPduDsp.mibInstrumController is None: raise error.PySnmpError('MIB instrumentation does not yet exist') snmpEngineMaxMessageSize, = self.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( '__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') snmpEngineMaxMessageSize.syntax = snmpEngineMaxMessageSize.syntax.clone( maxMessageSize) snmpEngineBoots, = self.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( '__SNMP-FRAMEWORK-MIB', 'snmpEngineBoots') snmpEngineBoots.syntax += 1 origSnmpEngineID, = self.msgAndPduDsp.mibInstrumController.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.flagApp and debug.logger( '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()) debug.logger & debug.flagApp 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) try: fd, fn = tempfile.mkstemp(dir=persistentPath) os.write(fd, str2octs(snmpEngineBoots.syntax.prettyPrint())) os.close(fd) shutil.move(fn, f) except Exception: debug.logger & debug.flagApp and debug.logger( 'SnmpEngine: could not stored SNMP Engine Boots: %s' % sys.exc_info()[1]) else: debug.logger & debug.flagApp and debug.logger( 'SnmpEngine: stored SNMP Engine Boots: %s' % snmpEngineBoots.syntax.prettyPrint())
def variate(oid, tag, value, **context): if 'settings' not in recordContext: recordContext['settings'] = dict( [split(x, '=') for x in split(value, ',')]) if 'dir' not in recordContext['settings']: log.info('multiplex: snapshot directory not specified') return context['origOid'], tag, context['errorStatus'] recordContext['settings']['dir'] = recordContext['settings'][ 'dir'].replace('/', os.path.sep) if recordContext['settings']['dir'][0] != os.path.sep: for x in confdir.data: d = os.path.join(x, recordContext['settings']['dir']) if os.path.exists(d): break else: log.info('multiplex: directory %s not ' 'found' % recordContext['settings']['dir']) return context['origOid'], tag, context['errorStatus'] else: d = recordContext['settings']['dir'] recordContext['dirmap'] = {} recordContext['parsermap'] = {} for fl in os.listdir(d): for ext in RECORD_SET: if not fl.endswith(ext): continue ident = int(os.path.basename(fl)[:-len(ext) - 1]) datafile = os.path.join(d, fl) recordContext['dirmap'][ident] = datafile recordContext['parsermap'][datafile] = RECORD_SET[ext] recordContext['keys'] = list(recordContext['dirmap']) recordContext['bounds'] = (min(recordContext['keys']), max(recordContext['keys'])) if 'period' in recordContext['settings']: recordContext['settings']['period'] = float( recordContext['settings']['period']) else: recordContext['settings']['period'] = 60.0 if 'wrap' in recordContext['settings']: recordContext['settings']['wrap'] = bool( recordContext['settings']['wrap']) else: recordContext['settings']['wrap'] = False if 'control' in recordContext['settings']: recordContext['settings']['control'] = rfc1902.ObjectName( recordContext['settings']['control']) log.info('multiplex: using control OID %s for subtree %s, ' 'time-based multiplexing ' 'disabled' % (recordContext['settings']['control'], oid)) recordContext['ready'] = True if 'ready' not in recordContext: return context['origOid'], tag, context['errorStatus'] if oid not in moduleContext: moduleContext[oid] = {} if context['setFlag']: if 'control' in (recordContext['settings'] and recordContext['settings']['control'] == context['origOid']): fileno = int(context['origValue']) if fileno >= len(recordContext['keys']): log.info('multiplex: .snmprec file number %s over limit of' ' %s' % (fileno, len(recordContext['keys']))) return context['origOid'], tag, context['errorStatus'] moduleContext[oid]['fileno'] = fileno log.info('multiplex: switched to file #%s ' '(%s)' % (recordContext['keys'][fileno], recordContext['dirmap'][recordContext['keys'][fileno]])) return context['origOid'], tag, context['origValue'] else: return context['origOid'], tag, context['errorStatus'] if 'control' in recordContext['settings']: if 'fileno' not in moduleContext[oid]: moduleContext[oid]['fileno'] = 0 if (not context['nextFlag'] and recordContext['settings']['control'] == context['origOid']): val = rfc1902.Integer32(moduleContext[oid]['fileno']) return context['origOid'], tag, val else: period = recordContext['settings']['period'] uptime = time.time() - moduleContext['booted'] timeslot = uptime % (period * len(recordContext['dirmap'])) fileslot = int(timeslot / period) + recordContext['bounds'][0] fileno = bisect.bisect(recordContext['keys'], fileslot) - 1 if ('fileno' not in moduleContext[oid] or moduleContext[oid]['fileno'] < fileno or recordContext['settings']['wrap']): moduleContext[oid]['fileno'] = fileno datafile = recordContext['dirmap'][recordContext['keys'][moduleContext[oid] ['fileno']]] parser = recordContext['parsermap'][datafile] if ('datafile' not in moduleContext[oid] or moduleContext[oid]['datafile'] != datafile): if 'datafileobj' in moduleContext[oid]: moduleContext[oid]['datafileobj'].close() recordIndex = RecordIndex(datafile, parser).create() moduleContext[oid]['datafileobj'] = recordIndex moduleContext[oid]['datafile'] = datafile log.info('multiplex: switching to data file %s for ' '%s' % (datafile, context['origOid'])) text, db = moduleContext[oid]['datafileobj'].get_handles() textOid = str( rfc1902.OctetString('.'.join(['%s' % x for x in context['origOid']]))) try: line = moduleContext[oid]['datafileobj'].lookup(textOid) except KeyError: offset = search_record_by_oid(context['origOid'], text, parser) exactMatch = False else: offset, subtreeFlag, prevOffset = line.split(str2octs(',')) exactMatch = True text.seek(int(offset)) line, _, _ = get_record(text) # matched line if context['nextFlag']: if exactMatch: line, _, _ = get_record(text) else: if not exactMatch: return context['origOid'], tag, context['errorStatus'] if not line: return context['origOid'], tag, context['errorStatus'] try: oid, value = parser.evaluate(line) except error.SnmpsimError: oid, value = context['origOid'], context['errorStatus'] return oid, tag, value
def testIndefMode(self): assert decoder.decode( ints2octs((36, 128, 4, 15, 81, 117, 105, 99, 107, 32, 98, 114, 111, 119, 110, 32, 102, 111, 120, 0, 0)) ) == (str2octs('Quick brown fox'), null)
def build(self, oid, tag, val): if oid and tag: return str2octs('%s|%s|%s\n' % (oid, tag, val)) raise error.SnmpsimError('empty OID/tag <%s/%s>' % (oid, tag))
def __init__(self, snmpEngineID=None, maxMessageSize=65507, msgAndPduDsp=None): self.cache = {} self.observer = observer.MetaObserver() if msgAndPduDsp is None: self.msgAndPduDsp = MsgAndPduDispatcher() else: self.msgAndPduDsp = msgAndPduDsp mibBuilder = self.msgAndPduDsp.mibInstrumController.mibBuilder self.messageProcessingSubsystems = { SnmpV1MessageProcessingModel.MESSAGE_PROCESSING_MODEL_ID: SnmpV1MessageProcessingModel(), SnmpV2cMessageProcessingModel.MESSAGE_PROCESSING_MODEL_ID: SnmpV2cMessageProcessingModel(), 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() } self.transportDispatcher = None if self.msgAndPduDsp.mibInstrumController is None: raise error.PySnmpError('MIB instrumentation does not yet exist') snmpEngineMaxMessageSize, = mibBuilder.importSymbols( '__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') snmpEngineMaxMessageSize.syntax = snmpEngineMaxMessageSize.syntax.clone(maxMessageSize) snmpEngineBoots, = mibBuilder.importSymbols( '__SNMP-FRAMEWORK-MIB', 'snmpEngineBoots') snmpEngineBoots.syntax += 1 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()) # 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()) 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) try: fd, fn = tempfile.mkstemp(dir=persistentPath) 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())
def testAdd(self): assert univ.OctetString('') + 'q' == str2octs('q'), '__add__() fails'