Package dns :: Module opcode
[hide private]
[frames] | no frames]

Source Code for Module dns.opcode

  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   
 18  import dns.exception 
 19   
 20  QUERY = 0 
 21  IQUERY = 1 
 22  STATUS = 2 
 23  NOTIFY = 4 
 24  UPDATE = 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.iteritems()]) 
 39   
 40   
41 -class UnknownOpcode(dns.exception.DNSException):
42 """An DNS opcode is unknown."""
43
44 -def from_text(text):
45 """Convert text into an opcode. 46 47 @param text: the textual opcode 48 @type text: string 49 @raises UnknownOpcode: the opcode is unknown 50 @rtype: int 51 """ 52 53 if text.isdigit(): 54 value = int(text) 55 if value >= 0 and value <= 15: 56 return value 57 value = _by_text.get(text.upper()) 58 if value is None: 59 raise UnknownOpcode 60 return value
61
62 -def from_flags(flags):
63 """Extract an opcode from DNS message flags. 64 65 @param flags: int 66 @rtype: int 67 """ 68 69 return (flags & 0x7800) >> 11
70
71 -def to_flags(value):
72 """Convert an opcode to a value suitable for ORing into DNS message 73 flags. 74 @rtype: int 75 """ 76 77 return (value << 11) & 0x7800
78
79 -def to_text(value):
80 """Convert an opcode to text. 81 82 @param value: the opcdoe 83 @type value: int 84 @raises UnknownOpcode: the opcode is unknown 85 @rtype: string 86 """ 87 88 text = _by_value.get(value) 89 if text is None: 90 text = str(value) 91 return text
92
93 -def is_update(flags):
94 """True if the opcode in flags is UPDATE. 95 96 @param flags: DNS flags 97 @type flags: int 98 @rtype: bool 99 """ 100 101 if (from_flags(flags) == UPDATE): 102 return True 103 return False
104