Package dkim :: Module util
[hide private]
[frames] | no frames]

Source Code for Module dkim.util

 1  # This software is provided 'as-is', without any express or implied 
 2  # warranty.  In no event will the author be held liable for any damages 
 3  # arising from the use of this software. 
 4  # 
 5  # Permission is granted to anyone to use this software for any purpose, 
 6  # including commercial applications, and to alter it and redistribute it 
 7  # freely, subject to the following restrictions: 
 8  # 
 9  # 1. The origin of this software must not be misrepresented; you must not 
10  #    claim that you wrote the original software. If you use this software 
11  #    in a product, an acknowledgment in the product documentation would be 
12  #    appreciated but is not required. 
13  # 2. Altered source versions must be plainly marked as such, and must not be 
14  #    misrepresented as being the original software. 
15  # 3. This notice may not be removed or altered from any source distribution. 
16  # 
17  # Copyright (c) 2011 William Grant <me@williamgrant.id.au> 
18   
19  import re 
20   
21  import logging 
22  try: 
23      from logging import NullHandler 
24  except ImportError: 
25 - class NullHandler(logging.Handler):
26 - def emit(self, record):
27 pass
28 29 30 __all__ = [ 31 'DuplicateTag', 32 'get_default_logger', 33 'InvalidTagSpec', 34 'InvalidTagValueList', 35 'parse_tag_value', 36 ] 37 38
39 -class InvalidTagValueList(Exception):
40 pass
41 42
43 -class DuplicateTag(InvalidTagValueList):
44 pass
45 46
47 -class InvalidTagSpec(InvalidTagValueList):
48 pass
49 50
51 -def parse_tag_value(tag_list):
52 """Parse a DKIM Tag=Value list. 53 54 Interprets the syntax specified by RFC6376 section 3.2. 55 Assumes that folding whitespace is already unfolded. 56 57 @param tag_list: A bytes string containing a DKIM Tag=Value list. 58 """ 59 tags = {} 60 tag_specs = tag_list.strip().split(b';') 61 # Trailing semicolons are valid. 62 if not tag_specs[-1]: 63 tag_specs.pop() 64 for tag_spec in tag_specs: 65 try: 66 key, value = [x.strip() for x in tag_spec.split(b'=', 1)] 67 except ValueError: 68 raise InvalidTagSpec(tag_spec) 69 if re.match(br'^[a-zA-Z](\w)*', key) is None: 70 raise InvalidTagSpec(tag_spec) 71 if key in tags: 72 raise DuplicateTag(key) 73 tags[key] = value 74 return tags
75 76
77 -def get_default_logger():
78 """Get the default dkimpy logger.""" 79 logger = logging.getLogger('dkimpy') 80 if not logger.handlers: 81 logger.addHandler(NullHandler()) 82 return logger
83