1# Copyright (C) 2001-2007, 2009-2011 Nominum, Inc. 2# 3# Permission to use, copy, modify, and distribute this software and its 4# documentation for any purpose with or without fee is hereby granted, 5# provided that the above copyright notice and this permission notice 6# appear in all copies. 7# 8# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES 9# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 10# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR 11# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 12# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 13# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT 14# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 15 16"""DNS Opcodes.""" 17 18import dns.exception 19 20QUERY = 0 21IQUERY = 1 22STATUS = 2 23NOTIFY = 4 24UPDATE = 5 25 26_by_text = { 27 'QUERY': QUERY, 28 'IQUERY': IQUERY, 29 'STATUS': STATUS, 30 'NOTIFY': NOTIFY, 31 'UPDATE': UPDATE 32} 33 34# We construct the inverse mapping programmatically to ensure that we 35# cannot make any mistakes (e.g. omissions, cut-and-paste errors) that 36# would cause the mapping not to be true inverse. 37 38_by_value = dict((y, x) for x, y in _by_text.items()) 39 40 41class UnknownOpcode(dns.exception.DNSException): 42 43 """An DNS opcode is unknown.""" 44 45 46def from_text(text): 47 """Convert text into an opcode. 48 49 @param text: the textual opcode 50 @type text: string 51 @raises UnknownOpcode: the opcode is unknown 52 @rtype: int 53 """ 54 55 if text.isdigit(): 56 value = int(text) 57 if value >= 0 and value <= 15: 58 return value 59 value = _by_text.get(text.upper()) 60 if value is None: 61 raise UnknownOpcode 62 return value 63 64 65def from_flags(flags): 66 """Extract an opcode from DNS message flags. 67 68 @param flags: int 69 @rtype: int 70 """ 71 72 return (flags & 0x7800) >> 11 73 74 75def to_flags(value): 76 """Convert an opcode to a value suitable for ORing into DNS message 77 flags. 78 @rtype: int 79 """ 80 81 return (value << 11) & 0x7800 82 83 84def to_text(value): 85 """Convert an opcode to text. 86 87 @param value: the opcdoe 88 @type value: int 89 @raises UnknownOpcode: the opcode is unknown 90 @rtype: string 91 """ 92 93 text = _by_value.get(value) 94 if text is None: 95 text = str(value) 96 return text 97 98 99def is_update(flags): 100 """True if the opcode in flags is UPDATE. 101 102 @param flags: DNS flags 103 @type flags: int 104 @rtype: bool 105 """ 106 107 return from_flags(flags) == UPDATE 108