Debian Codegraph @

dkim/util.py

raw symbols SCIP
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 <[email protected]>
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 'get_linesep',
37 ]
38
39
40 class InvalidTagValueList(Exception):
41 pass
42
43
44 class DuplicateTag(InvalidTagValueList):
45 pass
46
47
48 class InvalidTagSpec(InvalidTagValueList):
49 pass
50
51
52 def parse_tag_value(tag_list):
53 """Parse a DKIM Tag=Value list.
54
55 Interprets the syntax specified by RFC6376 section 3.2.
56 Assumes that folding whitespace is already unfolded.
57
58 @param tag_list: A bytes string containing a DKIM Tag=Value list.
59 """
60 tags = {}
61 tag_specs = tag_list.strip().split(b';')
62 # Trailing semicolons are valid.
63 if not tag_specs[-1]:
64 tag_specs.pop()
65 for tag_spec in tag_specs:
66 try:
67 key, value = [x.strip() for x in tag_spec.split(b'=', 1)]
68 except ValueError:
69 raise InvalidTagSpec(tag_spec)
70 if re.match(br'^[a-zA-Z](\w)*', key) is None:
71 raise InvalidTagSpec(tag_spec)
72 if key in tags:
73 raise DuplicateTag(key)
74 tags[key] = value
75 return tags
76
77
78 def get_default_logger():
79 """Get the default dkimpy logger."""
80 logger = logging.getLogger('dkimpy')
81 if not logger.handlers:
82 logger.addHandler(NullHandler())
83 return logger
84
85 def get_linesep(msg):
86 if msg[-2:] != b'\r\n' and msg[-1:] == b'\n':
87 return b'\n'
88 return b'\r\n'