�ɲɾ�����ӯ�����һ��ˣ��������С���˴��ͣ�������P���ҹ��ñ˽��ά�Բ��������˸߸ԣ�������ơ��ҹ��ñ�����ά�Բ���ˡ���˳^�ӣ������ӡ� ���ͯj�ӣ��ƺ���ӣ� ? PNG ?%k25u25%fgd5n!? PNG ?%k25u25%fgd5n!? PNG ?%k25u25%fgd5n!? PNG ?%k25u25%fgd5n!feedparser.py000064400000050014152526700310007237 0ustar00# Copyright (C) 2004-2006 Python Software Foundation # Authors: Baxter, Wouters and Warsaw # Contact: email-sig@python.org """FeedParser - An email feed parser. The feed parser implements an interface for incrementally parsing an email message, line by line. This has advantages for certain applications, such as those reading email messages off a socket. FeedParser.feed() is the primary interface for pushing new data into the parser. It returns when there's nothing more it can do with the available data. When you have no more data to push into the parser, call .close(). This completes the parsing and returns the root message object. The other advantage of this parser is that it will never raise a parsing exception. Instead, when it finds something unexpected, it adds a 'defect' to the current message. Defects are just instances that live on the message object's .defects attribute. """ __all__ = ['FeedParser'] import re from email import errors from email import message NLCRE = re.compile('\r\n|\r|\n') NLCRE_bol = re.compile('(\r\n|\r|\n)') NLCRE_eol = re.compile('(\r\n|\r|\n)\Z') NLCRE_crack = re.compile('(\r\n|\r|\n)') # RFC 2822 $3.6.8 Optional fields. ftext is %d33-57 / %d59-126, Any character # except controls, SP, and ":". headerRE = re.compile(r'^(From |[\041-\071\073-\176]{1,}:|[\t ])') EMPTYSTRING = '' NL = '\n' NeedMoreData = object() class BufferedSubFile(object): """A file-ish object that can have new data loaded into it. You can also push and pop line-matching predicates onto a stack. When the current predicate matches the current line, a false EOF response (i.e. empty string) is returned instead. This lets the parser adhere to a simple abstraction -- it parses until EOF closes the current message. """ def __init__(self): # Chunks of the last partial line pushed into this object. self._partial = [] # The list of full, pushed lines, in reverse order self._lines = [] # The stack of false-EOF checking predicates. self._eofstack = [] # A flag indicating whether the file has been closed or not. self._closed = False def push_eof_matcher(self, pred): self._eofstack.append(pred) def pop_eof_matcher(self): return self._eofstack.pop() def close(self): # Don't forget any trailing partial line. self.pushlines(''.join(self._partial).splitlines(True)) self._partial = [] self._closed = True def readline(self): if not self._lines: if self._closed: return '' return NeedMoreData # Pop the line off the stack and see if it matches the current # false-EOF predicate. line = self._lines.pop() # RFC 2046, section 5.1.2 requires us to recognize outer level # boundaries at any level of inner nesting. Do this, but be sure it's # in the order of most to least nested. for ateof in self._eofstack[::-1]: if ateof(line): # We're at the false EOF. But push the last line back first. self._lines.append(line) return '' return line def unreadline(self, line): # Let the consumer push a line back into the buffer. assert line is not NeedMoreData self._lines.append(line) def push(self, data): """Push some new data into this object.""" # Crack into lines, but preserve the linesep characters on the end of each parts = data.splitlines(True) if not parts or not parts[0].endswith(('\n', '\r')): # No new complete lines, so just accumulate partials self._partial += parts return if self._partial: # If there are previous leftovers, complete them now self._partial.append(parts[0]) parts[0:1] = ''.join(self._partial).splitlines(True) del self._partial[:] # If the last element of the list does not end in a newline, then treat # it as a partial line. We only check for '\n' here because a line # ending with '\r' might be a line that was split in the middle of a # '\r\n' sequence (see bugs 1555570 and 1721862). if not parts[-1].endswith('\n'): self._partial = [parts.pop()] self.pushlines(parts) def pushlines(self, lines): # Reverse and insert at the front of the lines. self._lines[:0] = lines[::-1] def is_closed(self): return self._closed def __iter__(self): return self def next(self): line = self.readline() if line == '': raise StopIteration return line class FeedParser: """A feed-style parser of email.""" def __init__(self, _factory=message.Message): """_factory is called with no arguments to create a new message obj""" self._factory = _factory self._input = BufferedSubFile() self._msgstack = [] self._parse = self._parsegen().next self._cur = None self._last = None self._headersonly = False # Non-public interface for supporting Parser's headersonly flag def _set_headersonly(self): self._headersonly = True def feed(self, data): """Push more data into the parser.""" self._input.push(data) self._call_parse() def _call_parse(self): try: self._parse() except StopIteration: pass def close(self): """Parse all remaining data and return the root message object.""" self._input.close() self._call_parse() root = self._pop_message() assert not self._msgstack # Look for final set of defects if root.get_content_maintype() == 'multipart' \ and not root.is_multipart(): root.defects.append(errors.MultipartInvariantViolationDefect()) return root def _new_message(self): msg = self._factory() if self._cur and self._cur.get_content_type() == 'multipart/digest': msg.set_default_type('message/rfc822') if self._msgstack: self._msgstack[-1].attach(msg) self._msgstack.append(msg) self._cur = msg self._last = msg def _pop_message(self): retval = self._msgstack.pop() if self._msgstack: self._cur = self._msgstack[-1] else: self._cur = None return retval def _parsegen(self): # Create a new message and start by parsing headers. self._new_message() headers = [] # Collect the headers, searching for a line that doesn't match the RFC # 2822 header or continuation pattern (including an empty line). for line in self._input: if line is NeedMoreData: yield NeedMoreData continue if not headerRE.match(line): # If we saw the RFC defined header/body separator # (i.e. newline), just throw it away. Otherwise the line is # part of the body so push it back. if not NLCRE.match(line): self._input.unreadline(line) break headers.append(line) # Done with the headers, so parse them and figure out what we're # supposed to see in the body of the message. self._parse_headers(headers) # Headers-only parsing is a backwards compatibility hack, which was # necessary in the older parser, which could raise errors. All # remaining lines in the input are thrown into the message body. if self._headersonly: lines = [] while True: line = self._input.readline() if line is NeedMoreData: yield NeedMoreData continue if line == '': break lines.append(line) self._cur.set_payload(EMPTYSTRING.join(lines)) return if self._cur.get_content_type() == 'message/delivery-status': # message/delivery-status contains blocks of headers separated by # a blank line. We'll represent each header block as a separate # nested message object, but the processing is a bit different # than standard message/* types because there is no body for the # nested messages. A blank line separates the subparts. while True: self._input.push_eof_matcher(NLCRE.match) for retval in self._parsegen(): if retval is NeedMoreData: yield NeedMoreData continue break msg = self._pop_message() # We need to pop the EOF matcher in order to tell if we're at # the end of the current file, not the end of the last block # of message headers. self._input.pop_eof_matcher() # The input stream must be sitting at the newline or at the # EOF. We want to see if we're at the end of this subpart, so # first consume the blank line, then test the next line to see # if we're at this subpart's EOF. while True: line = self._input.readline() if line is NeedMoreData: yield NeedMoreData continue break while True: line = self._input.readline() if line is NeedMoreData: yield NeedMoreData continue break if line == '': break # Not at EOF so this is a line we're going to need. self._input.unreadline(line) return if self._cur.get_content_maintype() == 'message': # The message claims to be a message/* type, then what follows is # another RFC 2822 message. for retval in self._parsegen(): if retval is NeedMoreData: yield NeedMoreData continue break self._pop_message() return if self._cur.get_content_maintype() == 'multipart': boundary = self._cur.get_boundary() if boundary is None: # The message /claims/ to be a multipart but it has not # defined a boundary. That's a problem which we'll handle by # reading everything until the EOF and marking the message as # defective. self._cur.defects.append(errors.NoBoundaryInMultipartDefect()) lines = [] for line in self._input: if line is NeedMoreData: yield NeedMoreData continue lines.append(line) self._cur.set_payload(EMPTYSTRING.join(lines)) return # Create a line match predicate which matches the inter-part # boundary as well as the end-of-multipart boundary. Don't push # this onto the input stream until we've scanned past the # preamble. separator = '--' + boundary boundaryre = re.compile( '(?P' + re.escape(separator) + r')(?P--)?(?P[ \t]*)(?P\r\n|\r|\n)?$') capturing_preamble = True preamble = [] linesep = False while True: line = self._input.readline() if line is NeedMoreData: yield NeedMoreData continue if line == '': break mo = boundaryre.match(line) if mo: # If we're looking at the end boundary, we're done with # this multipart. If there was a newline at the end of # the closing boundary, then we need to initialize the # epilogue with the empty string (see below). if mo.group('end'): linesep = mo.group('linesep') break # We saw an inter-part boundary. Were we in the preamble? if capturing_preamble: if preamble: # According to RFC 2046, the last newline belongs # to the boundary. lastline = preamble[-1] eolmo = NLCRE_eol.search(lastline) if eolmo: preamble[-1] = lastline[:-len(eolmo.group(0))] self._cur.preamble = EMPTYSTRING.join(preamble) capturing_preamble = False self._input.unreadline(line) continue # We saw a boundary separating two parts. Consume any # multiple boundary lines that may be following. Our # interpretation of RFC 2046 BNF grammar does not produce # body parts within such double boundaries. while True: line = self._input.readline() if line is NeedMoreData: yield NeedMoreData continue mo = boundaryre.match(line) if not mo: self._input.unreadline(line) break # Recurse to parse this subpart; the input stream points # at the subpart's first line. self._input.push_eof_matcher(boundaryre.match) for retval in self._parsegen(): if retval is NeedMoreData: yield NeedMoreData continue break # Because of RFC 2046, the newline preceding the boundary # separator actually belongs to the boundary, not the # previous subpart's payload (or epilogue if the previous # part is a multipart). if self._last.get_content_maintype() == 'multipart': epilogue = self._last.epilogue if epilogue == '': self._last.epilogue = None elif epilogue is not None: mo = NLCRE_eol.search(epilogue) if mo: end = len(mo.group(0)) self._last.epilogue = epilogue[:-end] else: payload = self._last.get_payload() if isinstance(payload, basestring): mo = NLCRE_eol.search(payload) if mo: payload = payload[:-len(mo.group(0))] self._last.set_payload(payload) self._input.pop_eof_matcher() self._pop_message() # Set the multipart up for newline cleansing, which will # happen if we're in a nested multipart. self._last = self._cur else: # I think we must be in the preamble assert capturing_preamble preamble.append(line) # We've seen either the EOF or the end boundary. If we're still # capturing the preamble, we never saw the start boundary. Note # that as a defect and store the captured text as the payload. # Everything from here to the EOF is epilogue. if capturing_preamble: self._cur.defects.append(errors.StartBoundaryNotFoundDefect()) self._cur.set_payload(EMPTYSTRING.join(preamble)) epilogue = [] for line in self._input: if line is NeedMoreData: yield NeedMoreData continue self._cur.epilogue = EMPTYSTRING.join(epilogue) return # If the end boundary ended in a newline, we'll need to make sure # the epilogue isn't None if linesep: epilogue = [''] else: epilogue = [] for line in self._input: if line is NeedMoreData: yield NeedMoreData continue epilogue.append(line) # Any CRLF at the front of the epilogue is not technically part of # the epilogue. Also, watch out for an empty string epilogue, # which means a single newline. if epilogue: firstline = epilogue[0] bolmo = NLCRE_bol.match(firstline) if bolmo: epilogue[0] = firstline[len(bolmo.group(0)):] self._cur.epilogue = EMPTYSTRING.join(epilogue) return # Otherwise, it's some non-multipart type, so the entire rest of the # file contents becomes the payload. lines = [] for line in self._input: if line is NeedMoreData: yield NeedMoreData continue lines.append(line) self._cur.set_payload(EMPTYSTRING.join(lines)) def _parse_headers(self, lines): # Passed a list of lines that make up the headers for the current msg lastheader = '' lastvalue = [] for lineno, line in enumerate(lines): # Check for continuation if line[0] in ' \t': if not lastheader: # The first line of the headers was a continuation. This # is illegal, so let's note the defect, store the illegal # line, and ignore it for purposes of headers. defect = errors.FirstHeaderLineIsContinuationDefect(line) self._cur.defects.append(defect) continue lastvalue.append(line) continue if lastheader: # XXX reconsider the joining of folded lines lhdr = EMPTYSTRING.join(lastvalue)[:-1].rstrip('\r\n') self._cur[lastheader] = lhdr lastheader, lastvalue = '', [] # Check for envelope header, i.e. unix-from if line.startswith('From '): if lineno == 0: # Strip off the trailing newline mo = NLCRE_eol.search(line) if mo: line = line[:-len(mo.group(0))] self._cur.set_unixfrom(line) continue elif lineno == len(lines) - 1: # Something looking like a unix-from at the end - it's # probably the first line of the body, so push back the # line and stop. self._input.unreadline(line) return else: # Weirdly placed unix-from line. Note this as a defect # and ignore it. defect = errors.MisplacedEnvelopeHeaderDefect(line) self._cur.defects.append(defect) continue # Split the line on the colon separating field name from value. i = line.find(':') if i < 0: defect = errors.MalformedHeaderDefect(line) self._cur.defects.append(defect) continue lastheader = line[:i] lastvalue = [line[i+1:].lstrip()] # Done with all the lines, so handle the last header. if lastheader: # XXX reconsider the joining of folded lines self._cur[lastheader] = EMPTYSTRING.join(lastvalue).rstrip('\r\n') charset.py000064400000037254152526700310006563 0ustar00# Copyright (C) 2001-2006 Python Software Foundation # Author: Ben Gertzfield, Barry Warsaw # Contact: email-sig@python.org __all__ = [ 'Charset', 'add_alias', 'add_charset', 'add_codec', ] import codecs import email.base64mime import email.quoprimime from email import errors from email.encoders import encode_7or8bit # Flags for types of header encodings QP = 1 # Quoted-Printable BASE64 = 2 # Base64 SHORTEST = 3 # the shorter of QP and base64, but only for headers # In "=?charset?q?hello_world?=", the =?, ?q?, and ?= add up to 7 MISC_LEN = 7 DEFAULT_CHARSET = 'us-ascii' # Defaults CHARSETS = { # input header enc body enc output conv 'iso-8859-1': (QP, QP, None), 'iso-8859-2': (QP, QP, None), 'iso-8859-3': (QP, QP, None), 'iso-8859-4': (QP, QP, None), # iso-8859-5 is Cyrillic, and not especially used # iso-8859-6 is Arabic, also not particularly used # iso-8859-7 is Greek, QP will not make it readable # iso-8859-8 is Hebrew, QP will not make it readable 'iso-8859-9': (QP, QP, None), 'iso-8859-10': (QP, QP, None), # iso-8859-11 is Thai, QP will not make it readable 'iso-8859-13': (QP, QP, None), 'iso-8859-14': (QP, QP, None), 'iso-8859-15': (QP, QP, None), 'iso-8859-16': (QP, QP, None), 'windows-1252':(QP, QP, None), 'viscii': (QP, QP, None), 'us-ascii': (None, None, None), 'big5': (BASE64, BASE64, None), 'gb2312': (BASE64, BASE64, None), 'euc-jp': (BASE64, None, 'iso-2022-jp'), 'shift_jis': (BASE64, None, 'iso-2022-jp'), 'iso-2022-jp': (BASE64, None, None), 'koi8-r': (BASE64, BASE64, None), 'utf-8': (SHORTEST, BASE64, 'utf-8'), # We're making this one up to represent raw unencoded 8-bit '8bit': (None, BASE64, 'utf-8'), } # Aliases for other commonly-used names for character sets. Map # them to the real ones used in email. ALIASES = { 'latin_1': 'iso-8859-1', 'latin-1': 'iso-8859-1', 'latin_2': 'iso-8859-2', 'latin-2': 'iso-8859-2', 'latin_3': 'iso-8859-3', 'latin-3': 'iso-8859-3', 'latin_4': 'iso-8859-4', 'latin-4': 'iso-8859-4', 'latin_5': 'iso-8859-9', 'latin-5': 'iso-8859-9', 'latin_6': 'iso-8859-10', 'latin-6': 'iso-8859-10', 'latin_7': 'iso-8859-13', 'latin-7': 'iso-8859-13', 'latin_8': 'iso-8859-14', 'latin-8': 'iso-8859-14', 'latin_9': 'iso-8859-15', 'latin-9': 'iso-8859-15', 'latin_10':'iso-8859-16', 'latin-10':'iso-8859-16', 'cp949': 'ks_c_5601-1987', 'euc_jp': 'euc-jp', 'euc_kr': 'euc-kr', 'ascii': 'us-ascii', } # Map charsets to their Unicode codec strings. CODEC_MAP = { 'gb2312': 'eucgb2312_cn', 'big5': 'big5_tw', # Hack: We don't want *any* conversion for stuff marked us-ascii, as all # sorts of garbage might be sent to us in the guise of 7-bit us-ascii. # Let that stuff pass through without conversion to/from Unicode. 'us-ascii': None, } # Convenience functions for extending the above mappings def add_charset(charset, header_enc=None, body_enc=None, output_charset=None): """Add character set properties to the global registry. charset is the input character set, and must be the canonical name of a character set. Optional header_enc and body_enc is either Charset.QP for quoted-printable, Charset.BASE64 for base64 encoding, Charset.SHORTEST for the shortest of qp or base64 encoding, or None for no encoding. SHORTEST is only valid for header_enc. It describes how message headers and message bodies in the input charset are to be encoded. Default is no encoding. Optional output_charset is the character set that the output should be in. Conversions will proceed from input charset, to Unicode, to the output charset when the method Charset.convert() is called. The default is to output in the same character set as the input. Both input_charset and output_charset must have Unicode codec entries in the module's charset-to-codec mapping; use add_codec(charset, codecname) to add codecs the module does not know about. See the codecs module's documentation for more information. """ if body_enc == SHORTEST: raise ValueError('SHORTEST not allowed for body_enc') CHARSETS[charset] = (header_enc, body_enc, output_charset) def add_alias(alias, canonical): """Add a character set alias. alias is the alias name, e.g. latin-1 canonical is the character set's canonical name, e.g. iso-8859-1 """ ALIASES[alias] = canonical def add_codec(charset, codecname): """Add a codec that map characters in the given charset to/from Unicode. charset is the canonical name of a character set. codecname is the name of a Python codec, as appropriate for the second argument to the unicode() built-in, or to the encode() method of a Unicode string. """ CODEC_MAP[charset] = codecname class Charset: """Map character sets to their email properties. This class provides information about the requirements imposed on email for a specific character set. It also provides convenience routines for converting between character sets, given the availability of the applicable codecs. Given a character set, it will do its best to provide information on how to use that character set in an email in an RFC-compliant way. Certain character sets must be encoded with quoted-printable or base64 when used in email headers or bodies. Certain character sets must be converted outright, and are not allowed in email. Instances of this module expose the following information about a character set: input_charset: The initial character set specified. Common aliases are converted to their `official' email names (e.g. latin_1 is converted to iso-8859-1). Defaults to 7-bit us-ascii. header_encoding: If the character set must be encoded before it can be used in an email header, this attribute will be set to Charset.QP (for quoted-printable), Charset.BASE64 (for base64 encoding), or Charset.SHORTEST for the shortest of QP or BASE64 encoding. Otherwise, it will be None. body_encoding: Same as header_encoding, but describes the encoding for the mail message's body, which indeed may be different than the header encoding. Charset.SHORTEST is not allowed for body_encoding. output_charset: Some character sets must be converted before they can be used in email headers or bodies. If the input_charset is one of them, this attribute will contain the name of the charset output will be converted to. Otherwise, it will be None. input_codec: The name of the Python codec used to convert the input_charset to Unicode. If no conversion codec is necessary, this attribute will be None. output_codec: The name of the Python codec used to convert Unicode to the output_charset. If no conversion codec is necessary, this attribute will have the same value as the input_codec. """ def __init__(self, input_charset=DEFAULT_CHARSET): # RFC 2046, $4.1.2 says charsets are not case sensitive. We coerce to # unicode because its .lower() is locale insensitive. If the argument # is already a unicode, we leave it at that, but ensure that the # charset is ASCII, as the standard (RFC XXX) requires. try: if isinstance(input_charset, unicode): input_charset.encode('ascii') else: input_charset = unicode(input_charset, 'ascii') except UnicodeError: raise errors.CharsetError(input_charset) input_charset = input_charset.lower().encode('ascii') # Set the input charset after filtering through the aliases and/or codecs if not (input_charset in ALIASES or input_charset in CHARSETS): try: input_charset = codecs.lookup(input_charset).name except LookupError: pass self.input_charset = ALIASES.get(input_charset, input_charset) # We can try to guess which encoding and conversion to use by the # charset_map dictionary. Try that first, but let the user override # it. henc, benc, conv = CHARSETS.get(self.input_charset, (SHORTEST, BASE64, None)) if not conv: conv = self.input_charset # Set the attributes, allowing the arguments to override the default. self.header_encoding = henc self.body_encoding = benc self.output_charset = ALIASES.get(conv, conv) # Now set the codecs. If one isn't defined for input_charset, # guess and try a Unicode codec with the same name as input_codec. self.input_codec = CODEC_MAP.get(self.input_charset, self.input_charset) self.output_codec = CODEC_MAP.get(self.output_charset, self.output_charset) def __str__(self): return self.input_charset.lower() __repr__ = __str__ def __eq__(self, other): return str(self) == str(other).lower() def __ne__(self, other): return not self.__eq__(other) def get_body_encoding(self): """Return the content-transfer-encoding used for body encoding. This is either the string `quoted-printable' or `base64' depending on the encoding used, or it is a function in which case you should call the function with a single argument, the Message object being encoded. The function should then set the Content-Transfer-Encoding header itself to whatever is appropriate. Returns "quoted-printable" if self.body_encoding is QP. Returns "base64" if self.body_encoding is BASE64. Returns "7bit" otherwise. """ assert self.body_encoding != SHORTEST if self.body_encoding == QP: return 'quoted-printable' elif self.body_encoding == BASE64: return 'base64' else: return encode_7or8bit def convert(self, s): """Convert a string from the input_codec to the output_codec.""" if self.input_codec != self.output_codec: return unicode(s, self.input_codec).encode(self.output_codec) else: return s def to_splittable(self, s): """Convert a possibly multibyte string to a safely splittable format. Uses the input_codec to try and convert the string to Unicode, so it can be safely split on character boundaries (even for multibyte characters). Returns the string as-is if it isn't known how to convert it to Unicode with the input_charset. Characters that could not be converted to Unicode will be replaced with the Unicode replacement character U+FFFD. """ if isinstance(s, unicode) or self.input_codec is None: return s try: return unicode(s, self.input_codec, 'replace') except LookupError: # Input codec not installed on system, so return the original # string unchanged. return s def from_splittable(self, ustr, to_output=True): """Convert a splittable string back into an encoded string. Uses the proper codec to try and convert the string from Unicode back into an encoded format. Return the string as-is if it is not Unicode, or if it could not be converted from Unicode. Characters that could not be converted from Unicode will be replaced with an appropriate character (usually '?'). If to_output is True (the default), uses output_codec to convert to an encoded format. If to_output is False, uses input_codec. """ if to_output: codec = self.output_codec else: codec = self.input_codec if not isinstance(ustr, unicode) or codec is None: return ustr try: return ustr.encode(codec, 'replace') except LookupError: # Output codec not installed return ustr def get_output_charset(self): """Return the output character set. This is self.output_charset if that is not None, otherwise it is self.input_charset. """ return self.output_charset or self.input_charset def encoded_header_len(self, s): """Return the length of the encoded header string.""" cset = self.get_output_charset() # The len(s) of a 7bit encoding is len(s) if self.header_encoding == BASE64: return email.base64mime.base64_len(s) + len(cset) + MISC_LEN elif self.header_encoding == QP: return email.quoprimime.header_quopri_len(s) + len(cset) + MISC_LEN elif self.header_encoding == SHORTEST: lenb64 = email.base64mime.base64_len(s) lenqp = email.quoprimime.header_quopri_len(s) return min(lenb64, lenqp) + len(cset) + MISC_LEN else: return len(s) def header_encode(self, s, convert=False): """Header-encode a string, optionally converting it to output_charset. If convert is True, the string will be converted from the input charset to the output charset automatically. This is not useful for multibyte character sets, which have line length issues (multibyte characters must be split on a character, not a byte boundary); use the high-level Header class to deal with these issues. convert defaults to False. The type of encoding (base64 or quoted-printable) will be based on self.header_encoding. """ cset = self.get_output_charset() if convert: s = self.convert(s) # 7bit/8bit encodings return the string unchanged (modulo conversions) if self.header_encoding == BASE64: return email.base64mime.header_encode(s, cset) elif self.header_encoding == QP: return email.quoprimime.header_encode(s, cset, maxlinelen=None) elif self.header_encoding == SHORTEST: lenb64 = email.base64mime.base64_len(s) lenqp = email.quoprimime.header_quopri_len(s) if lenb64 < lenqp: return email.base64mime.header_encode(s, cset) else: return email.quoprimime.header_encode(s, cset, maxlinelen=None) else: return s def body_encode(self, s, convert=True): """Body-encode a string and convert it to output_charset. If convert is True (the default), the string will be converted from the input charset to output charset automatically. Unlike header_encode(), there are no issues with byte boundaries and multibyte charsets in email bodies, so this is usually pretty safe. The type of encoding (base64 or quoted-printable) will be based on self.body_encoding. """ if convert: s = self.convert(s) # 7bit/8bit encodings return the string unchanged (module conversions) if self.body_encoding is BASE64: return email.base64mime.body_encode(s) elif self.body_encoding is QP: return email.quoprimime.body_encode(s) else: return s base64mime.py000064400000013242152526700310007055 0ustar00# Copyright (C) 2002-2006 Python Software Foundation # Author: Ben Gertzfield # Contact: email-sig@python.org """Base64 content transfer encoding per RFCs 2045-2047. This module handles the content transfer encoding method defined in RFC 2045 to encode arbitrary 8-bit data using the three 8-bit bytes in four 7-bit characters encoding known as Base64. It is used in the MIME standards for email to attach images, audio, and text using some 8-bit character sets to messages. This module provides an interface to encode and decode both headers and bodies with Base64 encoding. RFC 2045 defines a method for including character set information in an `encoded-word' in a header. This method is commonly used for 8-bit real names in To:, From:, Cc:, etc. fields, as well as Subject: lines. This module does not do the line wrapping or end-of-line character conversion necessary for proper internationalized headers; it only does dumb encoding and decoding. To deal with the various line wrapping issues, use the email.header module. """ __all__ = [ 'base64_len', 'body_decode', 'body_encode', 'decode', 'decodestring', 'encode', 'encodestring', 'header_encode', ] from binascii import b2a_base64, a2b_base64 from email.utils import fix_eols CRLF = '\r\n' NL = '\n' EMPTYSTRING = '' # See also Charset.py MISC_LEN = 7 # Helpers def base64_len(s): """Return the length of s when it is encoded with base64.""" groups_of_3, leftover = divmod(len(s), 3) # 4 bytes out for each 3 bytes (or nonzero fraction thereof) in. # Thanks, Tim! n = groups_of_3 * 4 if leftover: n += 4 return n def header_encode(header, charset='iso-8859-1', keep_eols=False, maxlinelen=76, eol=NL): """Encode a single header line with Base64 encoding in a given charset. Defined in RFC 2045, this Base64 encoding is identical to normal Base64 encoding, except that each line must be intelligently wrapped (respecting the Base64 encoding), and subsequent lines must start with a space. charset names the character set to use to encode the header. It defaults to iso-8859-1. End-of-line characters (\\r, \\n, \\r\\n) will be automatically converted to the canonical email line separator \\r\\n unless the keep_eols parameter is True (the default is False). Each line of the header will be terminated in the value of eol, which defaults to "\\n". Set this to "\\r\\n" if you are using the result of this function directly in email. The resulting string will be in the form: "=?charset?b?WW/5ciBtYXp66XLrIHf8eiBhIGhhbXBzdGHuciBBIFlv+XIgbWF6euly?=\\n =?charset?b?6yB3/HogYSBoYW1wc3Rh7nIgQkMgWW/5ciBtYXp66XLrIHf8eiBhIGhh?=" with each line wrapped at, at most, maxlinelen characters (defaults to 76 characters). """ # Return empty headers unchanged if not header: return header if not keep_eols: header = fix_eols(header) # Base64 encode each line, in encoded chunks no greater than maxlinelen in # length, after the RFC chrome is added in. base64ed = [] max_encoded = maxlinelen - len(charset) - MISC_LEN max_unencoded = max_encoded * 3 // 4 for i in range(0, len(header), max_unencoded): base64ed.append(b2a_base64(header[i:i+max_unencoded])) # Now add the RFC chrome to each encoded chunk lines = [] for line in base64ed: # Ignore the last character of each line if it is a newline if line.endswith(NL): line = line[:-1] # Add the chrome lines.append('=?%s?b?%s?=' % (charset, line)) # Glue the lines together and return it. BAW: should we be able to # specify the leading whitespace in the joiner? joiner = eol + ' ' return joiner.join(lines) def encode(s, binary=True, maxlinelen=76, eol=NL): """Encode a string with base64. Each line will be wrapped at, at most, maxlinelen characters (defaults to 76 characters). If binary is False, end-of-line characters will be converted to the canonical email end-of-line sequence \\r\\n. Otherwise they will be left verbatim (this is the default). Each line of encoded text will end with eol, which defaults to "\\n". Set this to "\\r\\n" if you will be using the result of this function directly in an email. """ if not s: return s if not binary: s = fix_eols(s) encvec = [] max_unencoded = maxlinelen * 3 // 4 for i in range(0, len(s), max_unencoded): # BAW: should encode() inherit b2a_base64()'s dubious behavior in # adding a newline to the encoded string? enc = b2a_base64(s[i:i + max_unencoded]) if enc.endswith(NL) and eol != NL: enc = enc[:-1] + eol encvec.append(enc) return EMPTYSTRING.join(encvec) # For convenience and backwards compatibility w/ standard base64 module body_encode = encode encodestring = encode def decode(s, convert_eols=None): """Decode a raw base64 string. If convert_eols is set to a string value, all canonical email linefeeds, e.g. "\\r\\n", in the decoded text will be converted to the value of convert_eols. os.linesep is a good choice for convert_eols if you are decoding a text attachment. This function does not parse a full MIME header value encoded with base64 (like =?iso-8859-1?b?bmloISBuaWgh?=) -- please use the high level email.header class for that functionality. """ if not s: return s dec = a2b_base64(s) if convert_eols: return dec.replace(CRLF, convert_eols) return dec # For convenience and backwards compatibility w/ standard base64 module body_decode = decode decodestring = decode mime/application.py000064400000002350152526700310010351 0ustar00# Copyright (C) 2001-2006 Python Software Foundation # Author: Keith Dart # Contact: email-sig@python.org """Class representing application/* type MIME documents.""" __all__ = ["MIMEApplication"] from email import encoders from email.mime.nonmultipart import MIMENonMultipart class MIMEApplication(MIMENonMultipart): """Class for generating application/* MIME documents.""" def __init__(self, _data, _subtype='octet-stream', _encoder=encoders.encode_base64, **_params): """Create an application/* type MIME document. _data is a string containing the raw application data. _subtype is the MIME content type subtype, defaulting to 'octet-stream'. _encoder is a function which will perform the actual encoding for transport of the application data, defaulting to base64 encoding. Any additional keyword arguments are passed to the base class constructor, which turns them into parameters on the Content-Type header. """ if _subtype is None: raise TypeError('Invalid application MIME subtype') MIMENonMultipart.__init__(self, 'application', _subtype, **_params) self.set_payload(_data) _encoder(self) mime/base.py000064400000001432152526700310006760 0ustar00# Copyright (C) 2001-2006 Python Software Foundation # Author: Barry Warsaw # Contact: email-sig@python.org """Base class for MIME specializations.""" __all__ = ['MIMEBase'] from email import message class MIMEBase(message.Message): """Base class for MIME specializations.""" def __init__(self, _maintype, _subtype, **_params): """This constructor adds a Content-Type: and a MIME-Version: header. The Content-Type: header is taken from the _maintype and _subtype arguments. Additional parameters for this header are taken from the keyword arguments. """ message.Message.__init__(self) ctype = '%s/%s' % (_maintype, _subtype) self.add_header('Content-Type', ctype, **_params) self['MIME-Version'] = '1.0' mime/__pycache__/message.cpython-312.opt-1.pyc000064400000003034152526700310014772 0ustar00 {|j#<dZdgZddlmZddlmZGddeZy),Class representing message/* MIME documents. MIMEMessage)message)MIMENonMultipartceZdZdZddddZy)rrNpolicyctj|d||t|tjs t dtjj |||jdy)aCreate a message/* type MIME document. _msg is a message object and must be an instance of Message, or a derived class of Message, otherwise a TypeError is raised. Optional _subtype defines the subtype of the contained message. The default is "rfc822" (this is defined by the MIME standard, even though the term "rfc822" is technically outdated by RFC 2822). rrz&Argument is not an instance of Messagezmessage/rfc822N)r__init__ isinstancerMessage TypeErrorattachset_default_type)self_msg_subtyper s +/usr/lib64/python3.12/email/mime/message.pyr zMIMEMessage.__init__sW !!$ 8FK$0DE E tT* ./)rfc822)__name__ __module__ __qualname____doc__r rrrr s60$0rN)r__all__emailremail.mime.nonmultipartrrrrrrs$ 3 /40"0rmime/__pycache__/text.cpython-312.opt-1.pyc000064400000002733152526700310014337 0ustar00 {|jr0dZdgZddlmZGddeZy)z.Class representing text/* type MIME documents.MIMEText)MIMENonMultipartceZdZdZddddZy)rz0Class for generating text/* type MIME documents.N)policyc | |jdd}tj|d||t ||j ||y#t$rd}YCwxYw)a~Create a text/* type MIME document. _text is the string for this message object. _subtype is the MIME sub content type, defaulting to "plain". _charset is the character set parameter added to the Content-Type header. This defaults to "us-ascii". Note that as a side-effect, the Content-Transfer-Encoding header will also be set. Nzus-asciizutf-8text)rcharset)encodeUnicodeEncodeErrorr__init__str set_payload)self_text_subtype_charsetrs (/usr/lib64/python3.12/email/mime/text.pyr zMIMEText.__init__sg   # Z(% !!$*-h- 9 ) & #" #sA AA)plainN)__name__ __module__ __qualname____doc__r rrr s:**rN)r__all__email.mime.nonmultipartrrrrrrs! 5 ,4**rmime/__pycache__/application.cpython-312.opt-1.pyc000064400000003203152526700310015647 0ustar00 {|j)<dZdgZddlmZddlmZGddeZy)z5Class representing application/* type MIME documents.MIMEApplication)encoders)MIMENonMultipartc6eZdZdZdej fdddZy)rz2Class for generating application/* MIME documents.z octet-streamN)policyc | tdtj|d|fd|i||j|||y)aCreate an application/* type MIME document. _data contains the bytes for the raw application data. _subtype is the MIME content type subtype, defaulting to 'octet-stream'. _encoder is a function which will perform the actual encoding for transport of the application data, defaulting to base64 encoding. Any additional keyword arguments are passed to the base class constructor, which turns them into parameters on the Content-Type header. Nz Invalid application MIME subtype applicationr) TypeErrorr__init__ set_payload)self_data_subtype_encoderr_paramss //usr/lib64/python3.12/email/mime/application.pyr zMIMEApplication.__init__sN  >? ?!!$ x - -$+ - )__name__ __module__ __qualname____doc__r encode_base64r rrrr s<'5"00<@rN)r__all__emailremail.mime.nonmultipartrrrrrrs% <  4&rmime/__pycache__/audio.cpython-312.pyc000064400000006567152526700310013526 0ustar00 {|j dZdgZddlmZddlmZddlmZGddeZgZ dZ dZ e d Z e d Z e d Zy ) z/Class representing audio/* type MIME documents. MIMEAudio)BytesIO)encoders)MIMENonMultipartc6eZdZdZdej fdddZy)rz,Class for generating audio/* MIME documents.N)policyc | t|}| tdtj|d|fd|i||j |||y)aCreate an audio/* type MIME document. _audiodata contains the bytes for the raw audio data. If this data can be decoded as au, wav, aiff, or aifc, then the subtype will be automatically included in the Content-Type header. Otherwise, you can specify the specific audio subtype via the _subtype parameter. If _subtype is not given, and no subtype can be guessed, a TypeError is raised. _encoder is a function which will perform the actual encoding for transport of the image data. It takes one argument, which is this Image instance. It should use get_payload() and set_payload() to change the payload to the encoded form. It should also add any Content-Transfer-Encoding or other headers to the message as necessary. The default encoding is Base64. Any additional keyword arguments are passed to the base class constructor, which turns them into parameters on the Content-Type header. Nz!Could not find audio MIME subtypeaudior)_what TypeErrorr__init__ set_payload)self _audiodata_subtype_encoderr_paramss )/usr/lib64/python3.12/email/mime/audio.pyr zMIMEAudio.__init__s^,  Z(H  ?@ @!!$ -& -$+ - $)__name__ __module__ __qualname____doc__r encode_base64r rrrrs6,0"00<@rcX|dd}t|}tD]}|||x}s|cSy)Ni)r_rules)datahdrfakefiletestfnress rr r 8s> t*Cs|Hh' '3 'Jrc0tj||S)N)rappend)rulefuncs rruler&Gs MM( Orc8|jdsy|dddvryy)NsFORM >AIFCAIFFzx-aiff startswithhfs r_aiffr1Ls& << 2w$$rc(|jdryy)Ns.sndbasicr,r.s r_aur4Vs||GrcH|jdr|dddk7s|dddk7ryy)NsRIFFr(r)sWAVEsfmt zx-wavr,r.s r_wavr7^s0 << AaGw$6!Br(g:MrN)r__all__ioremailremail.mime.nonmultipartrrrr r&r1r4r7rrrr<su 6 -4  F   rmime/__pycache__/multipart.cpython-312.pyc000064400000003253152526700310014433 0ustar00 {|jS0dZdgZddlmZGddeZy).Base class for MIME multipart/* type messages. MIMEMultipart)MIMEBaseceZdZdZddddZy)rrN)policyc tj|d|fd|i|g|_|r|D]}|j||r|j |yy)aCreates a multipart/* type message. By default, creates a multipart/mixed message, with proper Content-Type and MIME-Version headers. _subtype is the subtype of the multipart content type, defaulting to `mixed'. boundary is the multipart boundary string. By default it is calculated as needed. _subparts is a sequence of initial subparts for the payload. It must be an iterable object, such as a list. You can always attach new subparts to the message by using the attach() method. Additional parameters for the Content-Type header are taken from the keyword arguments (or passed into the _params argument). multipartrN)r__init___payloadattach set_boundary)self_subtypeboundary _subpartsr_paramsps -/usr/lib64/python3.12/email/mime/multipart.pyr zMIMEMultipart.__init__sW* $ XPfPP   A    h ' )mixedNN)__name__ __module__ __qualname____doc__r rrrr s8 ( (rN)r__all__email.mime.baserrrrrrs! 5  $#(H#(rmime/__pycache__/__init__.cpython-312.pyc000064400000000215152526700310014144 0ustar00 gjy)Nr,/usr/lib64/python3.12/email/mime/__init__.pyrsrmime/__pycache__/audio.cpython-312.opt-1.pyc000064400000006567152526700310014465 0ustar00 {|j dZdgZddlmZddlmZddlmZGddeZgZ dZ dZ e d Z e d Z e d Zy ) z/Class representing audio/* type MIME documents. MIMEAudio)BytesIO)encoders)MIMENonMultipartc6eZdZdZdej fdddZy)rz,Class for generating audio/* MIME documents.N)policyc | t|}| tdtj|d|fd|i||j |||y)aCreate an audio/* type MIME document. _audiodata contains the bytes for the raw audio data. If this data can be decoded as au, wav, aiff, or aifc, then the subtype will be automatically included in the Content-Type header. Otherwise, you can specify the specific audio subtype via the _subtype parameter. If _subtype is not given, and no subtype can be guessed, a TypeError is raised. _encoder is a function which will perform the actual encoding for transport of the image data. It takes one argument, which is this Image instance. It should use get_payload() and set_payload() to change the payload to the encoded form. It should also add any Content-Transfer-Encoding or other headers to the message as necessary. The default encoding is Base64. Any additional keyword arguments are passed to the base class constructor, which turns them into parameters on the Content-Type header. Nz!Could not find audio MIME subtypeaudior)_what TypeErrorr__init__ set_payload)self _audiodata_subtype_encoderr_paramss )/usr/lib64/python3.12/email/mime/audio.pyr zMIMEAudio.__init__s^,  Z(H  ?@ @!!$ -& -$+ - $)__name__ __module__ __qualname____doc__r encode_base64r rrrrs6,0"00<@rcX|dd}t|}tD]}|||x}s|cSy)Ni)r_rules)datahdrfakefiletestfnress rr r 8s> t*Cs|Hh' '3 'Jrc0tj||S)N)rappend)rulefuncs rruler&Gs MM( Orc8|jdsy|dddvryy)NsFORM >AIFCAIFFzx-aiff startswithhfs r_aiffr1Ls& << 2w$$rc(|jdryy)Ns.sndbasicr,r.s r_aur4Vs||GrcH|jdr|dddk7s|dddk7ryy)NsRIFFr(r)sWAVEsfmt zx-wavr,r.s r_wavr7^s0 << AaGw$6!Br(g:MrN)r__all__ioremailremail.mime.nonmultipartrrrr r&r1r4r7rrrr<su 6 -4  F   rmime/__pycache__/image.cpython-312.opt-1.pyc000064400000013117152526700310014433 0ustar00 {|jdZdgZddlmZddlmZGddeZgZdZdZ e dZ e d Z e d Z e d Z e d Ze d Ze dZe dZe dZe dZe dZe dZe dZy)z/Class representing image/* type MIME documents. MIMEImage)encoders)MIMENonMultipartc6eZdZdZdej fdddZy)rz1Class for generating image/* type MIME documents.N)policyc | t|n|}| tdtj|d|fd|i||j |||y)aCreate an image/* type MIME document. _imagedata contains the bytes for the raw image data. If the data type can be detected (jpeg, png, gif, tiff, rgb, pbm, pgm, ppm, rast, xbm, bmp, webp, and exr attempted), then the subtype will be automatically included in the Content-Type header. Otherwise, you can specify the specific image subtype via the _subtype parameter. _encoder is a function which will perform the actual encoding for transport of the image data. It takes one argument, which is this Image instance. It should use get_payload() and set_payload() to change the payload to the encoded form. It should also add any Content-Transfer-Encoding or other headers to the message as necessary. The default encoding is Base64. Any additional keyword arguments are passed to the base class constructor, which turns them into parameters on the Content-Type header. Nz"Could not guess image MIME subtypeimager)_what TypeErrorr__init__ set_payload)self _imagedata_subtype_encoderr_paramss )/usr/lib64/python3.12/email/mime/image.pyr zMIMEImage.__init__s_*)1(85$h  @A A!!$ -& -$+ - $)__name__ __module__ __qualname____doc__r encode_base64r rrrr s;,0"00<@rc6tD]}||x}s|cSyN)_rules)dataruleress rr r 2s%t* 3 Jrc0tj||Sr)rappend)rulefuncs rrr:s MM( Orc&|dddvry|dddk(ryy)z1JPEG data with JFIF or Exif markers; and raw JPEG )sJFIFsExifjpegNsrhs r_jpegr+?s- 2w$$ 2A% % &rc(|jdryy)NsPNG  png startswithr)s r_pngr0Hs||()*rc|dddvryy)zGIF ('87 and '89 variants)Nr%)sGIF87asGIF89agifrr)s r_gifr3Ns !u&&'rc|dddvryy)z-TIFF (can be in Motorola or Intel byte order)N)sMMsIItiffrr)s r_tiffr7Us !urc(|jdryy)zSGI image librarysrgbNr.r)s r_rgbr:\ ||K !rcft|dk\r#|dtdk(r|ddvr |ddvryy y y y ) zPBM (portable bitmap)rPs14r5 pbmNlenordr)s r_pbmrEcG 1v{ aDCI !A$%-AaDJ4F5G- rcft|dk\r#|dtdk(r|ddvr |ddvryy y y y ) zPGM (portable graymap)r=rr>r?s25r5r@pgmNrBr)s r_pgmrIkrFrcft|dk\r#|dtdk(r|ddvr |ddvryy y y y ) zPPM (portable pixmap)r=rr>r?s36r5r@ppmNrBr)s r_ppmrLsrFrc(|jdryy)zSun raster filesYjrastNr.r)s r_rastrO{s ||'()rc(|jdryy)zX bitmap (X10 or X11)s#define xbmNr.r)s r_xbmrRr;rc(|jdryy)NsBMbmpr.r)s r_bmprUs||Erc:|jdr |dddk(ryyy)NsRIFF sWEBPwebpr.r)s r_webprZs&||G1RG!3"4rc(|jdryy)Nsv/1exrr.r)s r_exrr]s||'()rN)r__all__emailremail.mime.nonmultipartrrrr rr+r0r3r7r:rErIrLrOrRrUrZr]rrrras: 6 -4 B          rmime/__pycache__/application.cpython-312.opt-2.pyc000064400000002004152526700310015646 0ustar00 {|j): dgZddlmZddlmZGddeZy)MIMEApplication)encoders)MIMENonMultipartc4eZdZ dejfdddZy)rz octet-streamN)policyc | tdtj|d|fd|i||j|||y)Nz Invalid application MIME subtype applicationr) TypeErrorr__init__ set_payload)self_data_subtype_encoderr_paramss //usr/lib64/python3.12/email/mime/application.pyr zMIMEApplication.__init__sS   >? ?!!$ x - -$+ - )__name__ __module__ __qualname__r encode_base64r rrrr s<'5"00<@rN)__all__emailremail.mime.nonmultipartrrrrrrs% <  4&rmime/__pycache__/base.cpython-312.opt-1.pyc000064400000002424152526700310014262 0ustar00 {|jLdZdgZddlZddlmZGddej Zy)$Base class for MIME specializations.MIMEBaseN)messageceZdZdZdddZy)rrNpolicyc |tjj}tjj |||d|}|j d|fi|d|d<y)zThis constructor adds a Content-Type: and a MIME-Version: header. The Content-Type: header is taken from the _maintype and _subtype arguments. Additional parameters for this header are taken from the keyword arguments. Nr/z Content-Typez1.0z MIME-Version)emailrcompat32rMessage__init__ add_header)self _maintype_subtyper_paramsctypes (/usr/lib64/python3.12/email/mime/base.pyrzMIMEBase.__init__sX >\\**F  f 5$h/99$^)__name__ __module__ __qualname____doc__rrrrrs .6: %r)r__all__ email.policyr rr rrrrrs' + ,%w%rmime/__pycache__/text.cpython-312.opt-2.pyc000064400000001753152526700310014341 0ustar00 {|jr. dgZddlmZGddeZy)MIMEText)MIMENonMultipartceZdZ ddddZy)rN)policyc  | |jdd}tj|d||t ||j ||y#t$rd}YCwxYw)Nzus-asciizutf-8text)rcharset)encodeUnicodeEncodeErrorr__init__str set_payload)self_text_subtype_charsetrs (/usr/lib64/python3.12/email/mime/text.pyr zMIMEText.__init__sl    # Z(% !!$*-h- 9 ) & #" #sA AA)plainN)__name__ __module__ __qualname__r rrr s:**rN)__all__email.mime.nonmultipartrrrrrrs! 5 ,4**rmime/__pycache__/application.cpython-312.pyc000064400000003203152526700310014710 0ustar00 {|j)<dZdgZddlmZddlmZGddeZy)z5Class representing application/* type MIME documents.MIMEApplication)encoders)MIMENonMultipartc6eZdZdZdej fdddZy)rz2Class for generating application/* MIME documents.z octet-streamN)policyc | tdtj|d|fd|i||j|||y)aCreate an application/* type MIME document. _data contains the bytes for the raw application data. _subtype is the MIME content type subtype, defaulting to 'octet-stream'. _encoder is a function which will perform the actual encoding for transport of the application data, defaulting to base64 encoding. Any additional keyword arguments are passed to the base class constructor, which turns them into parameters on the Content-Type header. Nz Invalid application MIME subtype applicationr) TypeErrorr__init__ set_payload)self_data_subtype_encoderr_paramss //usr/lib64/python3.12/email/mime/application.pyr zMIMEApplication.__init__sN  >? ?!!$ x - -$+ - )__name__ __module__ __qualname____doc__r encode_base64r rrrr s<'5"00<@rN)r__all__emailremail.mime.nonmultipartrrrrrrs% <  4&rmime/__pycache__/base.cpython-312.opt-2.pyc000064400000001737152526700310014271 0ustar00 {|jJ dgZddlZddlmZGddejZy)MIMEBaseN)messageceZdZ dddZy)rNpolicyc |tjj}tjj |||d|}|j d|fi|d|d<y)Nr/z Content-Typez1.0z MIME-Version)emailrcompat32rMessage__init__ add_header)self _maintype_subtyper_paramsctypes (/usr/lib64/python3.12/email/mime/base.pyr zMIMEBase.__init__s] >\\**F  f 5$h/99$^)__name__ __module__ __qualname__r rrrrs .6: %r)__all__ email.policyr rr rrrrrs' + ,%w%rmime/__pycache__/multipart.cpython-312.opt-2.pyc000064400000001636152526700310015376 0ustar00 {|jS. dgZddlmZGddeZy) MIMEMultipart)MIMEBaseceZdZ ddddZy)rN)policyc tj|d|fd|i|g|_|r|D]}|j||r|j |yy)N multipartr)r__init___payloadattach set_boundary)self_subtypeboundary _subpartsr_paramsps -/usr/lib64/python3.12/email/mime/multipart.pyr zMIMEMultipart.__init__s\ $ $ XPfPP   A    h ' )mixedNN)__name__ __module__ __qualname__r rrrr s8 ( (rN)__all__email.mime.baserrrrrrs! 5  $#(H#(rmime/__pycache__/multipart.cpython-312.opt-1.pyc000064400000003253152526700310015372 0ustar00 {|jS0dZdgZddlmZGddeZy).Base class for MIME multipart/* type messages. MIMEMultipart)MIMEBaseceZdZdZddddZy)rrN)policyc tj|d|fd|i|g|_|r|D]}|j||r|j |yy)aCreates a multipart/* type message. By default, creates a multipart/mixed message, with proper Content-Type and MIME-Version headers. _subtype is the subtype of the multipart content type, defaulting to `mixed'. boundary is the multipart boundary string. By default it is calculated as needed. _subparts is a sequence of initial subparts for the payload. It must be an iterable object, such as a list. You can always attach new subparts to the message by using the attach() method. Additional parameters for the Content-Type header are taken from the keyword arguments (or passed into the _params argument). multipartrN)r__init___payloadattach set_boundary)self_subtypeboundary _subpartsr_paramsps -/usr/lib64/python3.12/email/mime/multipart.pyr zMIMEMultipart.__init__sW* $ XPfPP   A    h ' )mixedNN)__name__ __module__ __qualname____doc__r rrrr s8 ( (rN)r__all__email.mime.baserrrrrrs! 5  $#(H#(rmime/__pycache__/text.cpython-312.pyc000064400000002733152526700310013400 0ustar00 {|jr0dZdgZddlmZGddeZy)z.Class representing text/* type MIME documents.MIMEText)MIMENonMultipartceZdZdZddddZy)rz0Class for generating text/* type MIME documents.N)policyc | |jdd}tj|d||t ||j ||y#t$rd}YCwxYw)a~Create a text/* type MIME document. _text is the string for this message object. _subtype is the MIME sub content type, defaulting to "plain". _charset is the character set parameter added to the Content-Type header. This defaults to "us-ascii". Note that as a side-effect, the Content-Transfer-Encoding header will also be set. Nzus-asciizutf-8text)rcharset)encodeUnicodeEncodeErrorr__init__str set_payload)self_text_subtype_charsetrs (/usr/lib64/python3.12/email/mime/text.pyr zMIMEText.__init__sg   # Z(% !!$*-h- 9 ) & #" #sA AA)plainN)__name__ __module__ __qualname____doc__r rrr s:**rN)r__all__email.mime.nonmultipartrrrrrrs! 5 ,4**rmime/__pycache__/image.cpython-312.pyc000064400000013117152526700310013474 0ustar00 {|jdZdgZddlmZddlmZGddeZgZdZdZ e dZ e d Z e d Z e d Z e d Ze d Ze dZe dZe dZe dZe dZe dZe dZy)z/Class representing image/* type MIME documents. MIMEImage)encoders)MIMENonMultipartc6eZdZdZdej fdddZy)rz1Class for generating image/* type MIME documents.N)policyc | t|n|}| tdtj|d|fd|i||j |||y)aCreate an image/* type MIME document. _imagedata contains the bytes for the raw image data. If the data type can be detected (jpeg, png, gif, tiff, rgb, pbm, pgm, ppm, rast, xbm, bmp, webp, and exr attempted), then the subtype will be automatically included in the Content-Type header. Otherwise, you can specify the specific image subtype via the _subtype parameter. _encoder is a function which will perform the actual encoding for transport of the image data. It takes one argument, which is this Image instance. It should use get_payload() and set_payload() to change the payload to the encoded form. It should also add any Content-Transfer-Encoding or other headers to the message as necessary. The default encoding is Base64. Any additional keyword arguments are passed to the base class constructor, which turns them into parameters on the Content-Type header. Nz"Could not guess image MIME subtypeimager)_what TypeErrorr__init__ set_payload)self _imagedata_subtype_encoderr_paramss )/usr/lib64/python3.12/email/mime/image.pyr zMIMEImage.__init__s_*)1(85$h  @A A!!$ -& -$+ - $)__name__ __module__ __qualname____doc__r encode_base64r rrrr s;,0"00<@rc6tD]}||x}s|cSyN)_rules)dataruleress rr r 2s%t* 3 Jrc0tj||Sr)rappend)rulefuncs rrr:s MM( Orc&|dddvry|dddk(ryy)z1JPEG data with JFIF or Exif markers; and raw JPEG )sJFIFsExifjpegNsrhs r_jpegr+?s- 2w$$ 2A% % &rc(|jdryy)NsPNG  png startswithr)s r_pngr0Hs||()*rc|dddvryy)zGIF ('87 and '89 variants)Nr%)sGIF87asGIF89agifrr)s r_gifr3Ns !u&&'rc|dddvryy)z-TIFF (can be in Motorola or Intel byte order)N)sMMsIItiffrr)s r_tiffr7Us !urc(|jdryy)zSGI image librarysrgbNr.r)s r_rgbr:\ ||K !rcft|dk\r#|dtdk(r|ddvr |ddvryy y y y ) zPBM (portable bitmap)rPs14r5 pbmNlenordr)s r_pbmrEcG 1v{ aDCI !A$%-AaDJ4F5G- rcft|dk\r#|dtdk(r|ddvr |ddvryy y y y ) zPGM (portable graymap)r=rr>r?s25r5r@pgmNrBr)s r_pgmrIkrFrcft|dk\r#|dtdk(r|ddvr |ddvryy y y y ) zPPM (portable pixmap)r=rr>r?s36r5r@ppmNrBr)s r_ppmrLsrFrc(|jdryy)zSun raster filesYjrastNr.r)s r_rastrO{s ||'()rc(|jdryy)zX bitmap (X10 or X11)s#define xbmNr.r)s r_xbmrRr;rc(|jdryy)NsBMbmpr.r)s r_bmprUs||Erc:|jdr |dddk(ryyy)NsRIFF sWEBPwebpr.r)s r_webprZs&||G1RG!3"4rc(|jdryy)Nsv/1exrr.r)s r_exrr]s||'()rN)r__all__emailremail.mime.nonmultipartrrrr rr+r0r3r7r:rErIrLrOrRrUrZr]rrrras: 6 -4 B          rmime/__pycache__/image.cpython-312.opt-2.pyc000064400000010561152526700310014434 0ustar00 {|j dgZddlmZddlmZGddeZgZdZdZedZ edZ ed Z ed Z ed Z ed Zed ZedZedZedZedZedZedZy) MIMEImage)encoders)MIMENonMultipartc4eZdZ dejfdddZy)rN)policyc | t|n|}| tdtj|d|fd|i||j |||y)Nz"Could not guess image MIME subtypeimager)_what TypeErrorr__init__ set_payload)self _imagedata_subtype_encoderr_paramss )/usr/lib64/python3.12/email/mime/image.pyr zMIMEImage.__init__sd &)1(85$h  @A A!!$ -& -$+ - $)__name__ __module__ __qualname__r encode_base64r rrrr s;,0"00<@rc6tD]}||x}s|cSyN)_rules)dataruleress rr r 2s%t* 3 Jrc0tj||Sr)rappend)rulefuncs rrr:s MM( Orc( |dddvry|dddk(ryy)N )sJFIFsExifjpegsrhs r_jpegr*?s.;2w$$ 2A% % &rc(|jdryy)NsPNG  png startswithr(s r_pngr/Hs||()*rc |dddvryy)Nr$)sGIF87asGIF89agifrr(s r_gifr2Ns$!u&&'rc |dddvryy)N)sMMsIItiffrr(s r_tiffr6Us7!urc* |jdryy)Nsrgbr-r(s r_rgbr9\s||K !rch t|dk\r#|dtdk(r|ddvr |ddvryyyyy) NrPs14r4 pbmlenordr(s r_pbmrCcH 1v{ aDCI !A$%-AaDJ4F5G- rch t|dk\r#|dtdk(r|ddvr |ddvryyyyy) Nr;rr<r=s25r4r>pgmr@r(s r_pgmrGksH  1v{ aDCI !A$%-AaDJ4F5G- rch t|dk\r#|dtdk(r|ddvr |ddvryyyyy) Nr;rr<r=s36r4r>ppmr@r(s r_ppmrJsrDrc* |jdryy)NsYjrastr-r(s r_rastrM{s||'()rc* |jdryy)Ns#define xbmr-r(s r_xbmrPs||K !rc(|jdryy)NsBMbmpr-r(s r_bmprSs||Erc:|jdr |dddk(ryyy)NsRIFF sWEBPwebpr-r(s r_webprXs&||G1RG!3"4rc(|jdryy)Nsv/1exrr-r(s r_exrr[s||'()rN)__all__emailremail.mime.nonmultipartrrrr rr*r/r2r6r9rCrGrJrMrPrSrXr[rrrr_s: 6 -4 B          rmime/__pycache__/nonmultipart.cpython-312.opt-2.pyc000064400000001336152526700320016107 0ustar00 {|j: dgZddlmZddlmZGddeZy)MIMENonMultipart)errors)MIMEBaseceZdZ dZy)rc,tjd)Nz4Cannot attach additional subparts to non-multipart/*)rMultipartConversionError)selfpayloads 0/usr/lib64/python3.12/email/mime/nonmultipart.pyattachzMIMENonMultipart.attachs-- BD DN)__name__ __module__ __qualname__r r r rr s :Dr N)__all__emailremail.mime.baserrrr r rs' @  $DxDr mime/__pycache__/nonmultipart.cpython-312.pyc000064400000001535152526700320015150 0ustar00 {|j<dZdgZddlmZddlmZGddeZy)z9Base class for MIME type messages that are not multipart.MIMENonMultipart)errors)MIMEBaseceZdZdZdZy)rz0Base class for MIME non-multipart type messages.c,tjd)Nz4Cannot attach additional subparts to non-multipart/*)rMultipartConversionError)selfpayloads 0/usr/lib64/python3.12/email/mime/nonmultipart.pyattachzMIMENonMultipart.attachs-- BD DN)__name__ __module__ __qualname____doc__r r r rr s :Dr N)r__all__emailremail.mime.baserrrr r rs' @  $DxDr mime/__pycache__/base.cpython-312.pyc000064400000002424152526700320013324 0ustar00 {|jLdZdgZddlZddlmZGddej Zy)$Base class for MIME specializations.MIMEBaseN)messageceZdZdZdddZy)rrNpolicyc |tjj}tjj |||d|}|j d|fi|d|d<y)zThis constructor adds a Content-Type: and a MIME-Version: header. The Content-Type: header is taken from the _maintype and _subtype arguments. Additional parameters for this header are taken from the keyword arguments. Nr/z Content-Typez1.0z MIME-Version)emailrcompat32rMessage__init__ add_header)self _maintype_subtyper_paramsctypes (/usr/lib64/python3.12/email/mime/base.pyrzMIMEBase.__init__sX >\\**F  f 5$h/99$^)__name__ __module__ __qualname____doc__rrrrrs .6: %r)r__all__ email.policyr rr rrrrrs' + ,%w%rmime/__pycache__/__init__.cpython-312.opt-1.pyc000064400000000215152526700320015104 0ustar00 gjy)Nr,/usr/lib64/python3.12/email/mime/__init__.pyrsrmime/__pycache__/message.cpython-312.pyc000064400000003034152526700320014034 0ustar00 {|j#<dZdgZddlmZddlmZGddeZy),Class representing message/* MIME documents. MIMEMessage)message)MIMENonMultipartceZdZdZddddZy)rrNpolicyctj|d||t|tjs t dtjj |||jdy)aCreate a message/* type MIME document. _msg is a message object and must be an instance of Message, or a derived class of Message, otherwise a TypeError is raised. Optional _subtype defines the subtype of the contained message. The default is "rfc822" (this is defined by the MIME standard, even though the term "rfc822" is technically outdated by RFC 2822). rrz&Argument is not an instance of Messagezmessage/rfc822N)r__init__ isinstancerMessage TypeErrorattachset_default_type)self_msg_subtyper s +/usr/lib64/python3.12/email/mime/message.pyr zMIMEMessage.__init__sW !!$ 8FK$0DE E tT* ./)rfc822)__name__ __module__ __qualname____doc__r rrrr s60$0rN)r__all__emailremail.mime.nonmultipartrrrrrrs$ 3 /40"0rmime/__pycache__/__init__.cpython-312.opt-2.pyc000064400000000215152526700320015105 0ustar00 gjy)Nr,/usr/lib64/python3.12/email/mime/__init__.pyrsrmime/__pycache__/message.cpython-312.opt-2.pyc000064400000002077152526700320015002 0ustar00 {|j#: dgZddlmZddlmZGddeZy) MIMEMessage)message)MIMENonMultipartceZdZ ddddZy)rNpolicyc tj|d||t|tjs t dtjj |||jdy)Nrrz&Argument is not an instance of Messagezmessage/rfc822)r__init__ isinstancerMessage TypeErrorattachset_default_type)self_msg_subtypers +/usr/lib64/python3.12/email/mime/message.pyr zMIMEMessage.__init__s\  !!$ 8FK$0DE E tT* ./)rfc822)__name__ __module__ __qualname__r rrrr s60$0rN)__all__emailremail.mime.nonmultipartrrrrrrs$ 3 /40"0rmime/__pycache__/audio.cpython-312.opt-2.pyc000064400000004411152526700320014451 0ustar00 {|j  dgZddlmZddlmZddlmZGddeZgZdZ dZ e dZ e d Z e d Z y ) MIMEAudio)BytesIO)encoders)MIMENonMultipartc4eZdZ dejfdddZy)rN)policyc | t|}| tdtj|d|fd|i||j |||y)Nz!Could not find audio MIME subtypeaudior)_what TypeErrorr__init__ set_payload)self _audiodata_subtype_encoderr_paramss )/usr/lib64/python3.12/email/mime/audio.pyr zMIMEAudio.__init__sc (  Z(H  ?@ @!!$ -& -$+ - $)__name__ __module__ __qualname__r encode_base64r rrrrs6,0"00<@rcX|dd}t|}tD]}|||x}s|cSy)Ni)r_rules)datahdrfakefiletestfnress rr r 8s> t*Cs|Hh' '3 'Jrc0tj||S)N)rappend)rulefuncs rruler%Gs MM( Orc8|jdsy|dddvryy)NsFORM >AIFCAIFFzx-aiff startswithhfs r_aiffr0Ls& << 2w$$rc(|jdryy)Ns.sndbasicr+r-s r_aur3Vs||GrcH|jdr|dddk7s|dddk7ryy)NsRIFFr'r(sWAVEsfmt zx-wavr+r-s r_wavr6^s0 << AaGw$6!Br(g:MrN)__all__ioremailremail.mime.nonmultipartrrrr r%r0r3r6rrrr;su 6 -4  F   rmime/__pycache__/nonmultipart.cpython-312.opt-1.pyc000064400000001535152526700320016107 0ustar00 {|j<dZdgZddlmZddlmZGddeZy)z9Base class for MIME type messages that are not multipart.MIMENonMultipart)errors)MIMEBaseceZdZdZdZy)rz0Base class for MIME non-multipart type messages.c,tjd)Nz4Cannot attach additional subparts to non-multipart/*)rMultipartConversionError)selfpayloads 0/usr/lib64/python3.12/email/mime/nonmultipart.pyattachzMIMENonMultipart.attachs-- BD DN)__name__ __module__ __qualname____doc__r r r rr s :Dr N)r__all__emailremail.mime.baserrrr r rs' @  $DxDr mime/multipart.py000064400000003045152526700320010072 0ustar00# Copyright (C) 2002-2006 Python Software Foundation # Author: Barry Warsaw # Contact: email-sig@python.org """Base class for MIME multipart/* type messages.""" __all__ = ['MIMEMultipart'] from email.mime.base import MIMEBase class MIMEMultipart(MIMEBase): """Base class for MIME multipart/* type messages.""" def __init__(self, _subtype='mixed', boundary=None, _subparts=None, **_params): """Creates a multipart/* type message. By default, creates a multipart/mixed message, with proper Content-Type and MIME-Version headers. _subtype is the subtype of the multipart content type, defaulting to `mixed'. boundary is the multipart boundary string. By default it is calculated as needed. _subparts is a sequence of initial subparts for the payload. It must be an iterable object, such as a list. You can always attach new subparts to the message by using the attach() method. Additional parameters for the Content-Type header are taken from the keyword arguments (or passed into the _params argument). """ MIMEBase.__init__(self, 'multipart', _subtype, **_params) # Initialise _payload to an empty list as the Message superclass's # implementation of is_multipart assumes that _payload is a list for # multipart messages. self._payload = [] if _subparts: for p in _subparts: self.attach(p) if boundary: self.set_boundary(boundary) mime/text.py000064400000001756152526700320007044 0ustar00# Copyright (C) 2001-2006 Python Software Foundation # Author: Barry Warsaw # Contact: email-sig@python.org """Class representing text/* type MIME documents.""" __all__ = ['MIMEText'] from email.encoders import encode_7or8bit from email.mime.nonmultipart import MIMENonMultipart class MIMEText(MIMENonMultipart): """Class for generating text/* type MIME documents.""" def __init__(self, _text, _subtype='plain', _charset='us-ascii'): """Create a text/* type MIME document. _text is the string for this message object. _subtype is the MIME sub content type, defaulting to "plain". _charset is the character set parameter added to the Content-Type header. This defaults to "us-ascii". Note that as a side-effect, the Content-Transfer-Encoding header will also be set. """ MIMENonMultipart.__init__(self, 'text', _subtype, **{'charset': _charset}) self.set_payload(_text, _charset) mime/audio.py000064400000005173152526700320007156 0ustar00# Copyright (C) 2001-2006 Python Software Foundation # Author: Anthony Baxter # Contact: email-sig@python.org """Class representing audio/* type MIME documents.""" __all__ = ['MIMEAudio'] import sndhdr from cStringIO import StringIO from email import encoders from email.mime.nonmultipart import MIMENonMultipart _sndhdr_MIMEmap = {'au' : 'basic', 'wav' :'x-wav', 'aiff':'x-aiff', 'aifc':'x-aiff', } # There are others in sndhdr that don't have MIME types. :( # Additional ones to be added to sndhdr? midi, mp3, realaudio, wma?? def _whatsnd(data): """Try to identify a sound file type. sndhdr.what() has a pretty cruddy interface, unfortunately. This is why we re-do it here. It would be easier to reverse engineer the Unix 'file' command and use the standard 'magic' file, as shipped with a modern Unix. """ hdr = data[:512] fakefile = StringIO(hdr) for testfn in sndhdr.tests: res = testfn(hdr, fakefile) if res is not None: return _sndhdr_MIMEmap.get(res[0]) return None class MIMEAudio(MIMENonMultipart): """Class for generating audio/* MIME documents.""" def __init__(self, _audiodata, _subtype=None, _encoder=encoders.encode_base64, **_params): """Create an audio/* type MIME document. _audiodata is a string containing the raw audio data. If this data can be decoded by the standard Python `sndhdr' module, then the subtype will be automatically included in the Content-Type header. Otherwise, you can specify the specific audio subtype via the _subtype parameter. If _subtype is not given, and no subtype can be guessed, a TypeError is raised. _encoder is a function which will perform the actual encoding for transport of the image data. It takes one argument, which is this Image instance. It should use get_payload() and set_payload() to change the payload to the encoded form. It should also add any Content-Transfer-Encoding or other headers to the message as necessary. The default encoding is Base64. Any additional keyword arguments are passed to the base class constructor, which turns them into parameters on the Content-Type header. """ if _subtype is None: _subtype = _whatsnd(_audiodata) if _subtype is None: raise TypeError('Could not find audio MIME subtype') MIMENonMultipart.__init__(self, 'audio', _subtype, **_params) self.set_payload(_audiodata) _encoder(self) mime/image.py000064400000003344152526700320007135 0ustar00# Copyright (C) 2001-2006 Python Software Foundation # Author: Barry Warsaw # Contact: email-sig@python.org """Class representing image/* type MIME documents.""" __all__ = ['MIMEImage'] import imghdr from email import encoders from email.mime.nonmultipart import MIMENonMultipart class MIMEImage(MIMENonMultipart): """Class for generating image/* type MIME documents.""" def __init__(self, _imagedata, _subtype=None, _encoder=encoders.encode_base64, **_params): """Create an image/* type MIME document. _imagedata is a string containing the raw image data. If this data can be decoded by the standard Python `imghdr' module, then the subtype will be automatically included in the Content-Type header. Otherwise, you can specify the specific image subtype via the _subtype parameter. _encoder is a function which will perform the actual encoding for transport of the image data. It takes one argument, which is this Image instance. It should use get_payload() and set_payload() to change the payload to the encoded form. It should also add any Content-Transfer-Encoding or other headers to the message as necessary. The default encoding is Base64. Any additional keyword arguments are passed to the base class constructor, which turns them into parameters on the Content-Type header. """ if _subtype is None: _subtype = imghdr.what(None, _imagedata) if _subtype is None: raise TypeError('Could not guess image MIME subtype') MIMENonMultipart.__init__(self, 'image', _subtype, **_params) self.set_payload(_imagedata) _encoder(self) mime/nonmultipart.py000064400000001263152526700320010605 0ustar00# Copyright (C) 2002-2006 Python Software Foundation # Author: Barry Warsaw # Contact: email-sig@python.org """Base class for MIME type messages that are not multipart.""" __all__ = ['MIMENonMultipart'] from email import errors from email.mime.base import MIMEBase class MIMENonMultipart(MIMEBase): """Base class for MIME non-multipart type messages.""" def attach(self, payload): # The public API prohibits attaching multiple subparts to MIMEBase # derived subtypes since none of them are, by definition, of content # type multipart/* raise errors.MultipartConversionError( 'Cannot attach additional subparts to non-multipart/*') mime/__init__.py000064400000000000152526700320007574 0ustar00mime/message.py000064400000002406152526700320007475 0ustar00# Copyright (C) 2001-2006 Python Software Foundation # Author: Barry Warsaw # Contact: email-sig@python.org """Class representing message/* MIME documents.""" __all__ = ['MIMEMessage'] from email import message from email.mime.nonmultipart import MIMENonMultipart class MIMEMessage(MIMENonMultipart): """Class representing message/* MIME documents.""" def __init__(self, _msg, _subtype='rfc822'): """Create a message/* type MIME document. _msg is a message object and must be an instance of Message, or a derived class of Message, otherwise a TypeError is raised. Optional _subtype defines the subtype of the contained message. The default is "rfc822" (this is defined by the MIME standard, even though the term "rfc822" is technically outdated by RFC 2822). """ MIMENonMultipart.__init__(self, 'message', _subtype) if not isinstance(_msg, message.Message): raise TypeError('Argument is not an instance of Message') # It's convenient to use this base class method. We need to do it # this way or we'll get an exception message.Message.attach(self, _msg) # And be sure our default type is set correctly self.set_default_type('message/rfc822') contentmanager.py000064400000024534152526700320010135 0ustar00import binascii import email.charset import email.message import email.errors from email import quoprimime class ContentManager: def __init__(self): self.get_handlers = {} self.set_handlers = {} def add_get_handler(self, key, handler): self.get_handlers[key] = handler def get_content(self, msg, *args, **kw): content_type = msg.get_content_type() if content_type in self.get_handlers: return self.get_handlers[content_type](msg, *args, **kw) maintype = msg.get_content_maintype() if maintype in self.get_handlers: return self.get_handlers[maintype](msg, *args, **kw) if '' in self.get_handlers: return self.get_handlers[''](msg, *args, **kw) raise KeyError(content_type) def add_set_handler(self, typekey, handler): self.set_handlers[typekey] = handler def set_content(self, msg, obj, *args, **kw): if msg.get_content_maintype() == 'multipart': # XXX: is this error a good idea or not? We can remove it later, # but we can't add it later, so do it for now. raise TypeError("set_content not valid on multipart") handler = self._find_set_handler(msg, obj) msg.clear_content() handler(msg, obj, *args, **kw) def _find_set_handler(self, msg, obj): full_path_for_error = None for typ in type(obj).__mro__: if typ in self.set_handlers: return self.set_handlers[typ] qname = typ.__qualname__ modname = getattr(typ, '__module__', '') full_path = '.'.join((modname, qname)) if modname else qname if full_path_for_error is None: full_path_for_error = full_path if full_path in self.set_handlers: return self.set_handlers[full_path] if qname in self.set_handlers: return self.set_handlers[qname] name = typ.__name__ if name in self.set_handlers: return self.set_handlers[name] if None in self.set_handlers: return self.set_handlers[None] raise KeyError(full_path_for_error) raw_data_manager = ContentManager() def get_text_content(msg, errors='replace'): content = msg.get_payload(decode=True) charset = msg.get_param('charset', 'ASCII') return content.decode(charset, errors=errors) raw_data_manager.add_get_handler('text', get_text_content) def get_non_text_content(msg): return msg.get_payload(decode=True) for maintype in 'audio image video application'.split(): raw_data_manager.add_get_handler(maintype, get_non_text_content) del maintype def get_message_content(msg): return msg.get_payload(0) for subtype in 'rfc822 external-body'.split(): raw_data_manager.add_get_handler('message/'+subtype, get_message_content) del subtype def get_and_fixup_unknown_message_content(msg): # If we don't understand a message subtype, we are supposed to treat it as # if it were application/octet-stream, per # tools.ietf.org/html/rfc2046#section-5.2.4. Feedparser doesn't do that, # so do our best to fix things up. Note that it is *not* appropriate to # model message/partial content as Message objects, so they are handled # here as well. (How to reassemble them is out of scope for this comment :) return bytes(msg.get_payload(0)) raw_data_manager.add_get_handler('message', get_and_fixup_unknown_message_content) def _prepare_set(msg, maintype, subtype, headers): msg['Content-Type'] = '/'.join((maintype, subtype)) if headers: if not hasattr(headers[0], 'name'): mp = msg.policy headers = [mp.header_factory(*mp.header_source_parse([header])) for header in headers] try: for header in headers: if header.defects: raise header.defects[0] msg[header.name] = header except email.errors.HeaderDefect as exc: raise ValueError("Invalid header: {}".format( header.fold(policy=msg.policy))) from exc def _finalize_set(msg, disposition, filename, cid, params): if disposition is None and filename is not None: disposition = 'attachment' if disposition is not None: msg['Content-Disposition'] = disposition if filename is not None: msg.set_param('filename', filename, header='Content-Disposition', replace=True) if cid is not None: msg['Content-ID'] = cid if params is not None: for key, value in params.items(): msg.set_param(key, value) # XXX: This is a cleaned-up version of base64mime.body_encode (including a bug # fix in the calculation of unencoded_bytes_per_line). It would be nice to # drop both this and quoprimime.body_encode in favor of enhanced binascii # routines that accepted a max_line_length parameter. def _encode_base64(data, max_line_length): encoded_lines = [] unencoded_bytes_per_line = max_line_length // 4 * 3 for i in range(0, len(data), unencoded_bytes_per_line): thisline = data[i:i+unencoded_bytes_per_line] encoded_lines.append(binascii.b2a_base64(thisline).decode('ascii')) return ''.join(encoded_lines) def _encode_text(string, charset, cte, policy): lines = string.encode(charset).splitlines() linesep = policy.linesep.encode('ascii') def embedded_body(lines): return linesep.join(lines) + linesep def normal_body(lines): return b'\n'.join(lines) + b'\n' if cte is None: # Use heuristics to decide on the "best" encoding. if max((len(x) for x in lines), default=0) <= policy.max_line_length: try: return '7bit', normal_body(lines).decode('ascii') except UnicodeDecodeError: pass if policy.cte_type == '8bit': return '8bit', normal_body(lines).decode('ascii', 'surrogateescape') sniff = embedded_body(lines[:10]) sniff_qp = quoprimime.body_encode(sniff.decode('latin-1'), policy.max_line_length) sniff_base64 = binascii.b2a_base64(sniff) # This is a little unfair to qp; it includes lineseps, base64 doesn't. if len(sniff_qp) > len(sniff_base64): cte = 'base64' else: cte = 'quoted-printable' if len(lines) <= 10: return cte, sniff_qp if cte == '7bit': data = normal_body(lines).decode('ascii') elif cte == '8bit': data = normal_body(lines).decode('ascii', 'surrogateescape') elif cte == 'quoted-printable': data = quoprimime.body_encode(normal_body(lines).decode('latin-1'), policy.max_line_length) elif cte == 'base64': data = _encode_base64(embedded_body(lines), policy.max_line_length) else: raise ValueError("Unknown content transfer encoding {}".format(cte)) return cte, data def set_text_content(msg, string, subtype="plain", charset='utf-8', cte=None, disposition=None, filename=None, cid=None, params=None, headers=None): _prepare_set(msg, 'text', subtype, headers) cte, payload = _encode_text(string, charset, cte, msg.policy) msg.set_payload(payload) msg.set_param('charset', email.charset.ALIASES.get(charset, charset), replace=True) msg['Content-Transfer-Encoding'] = cte _finalize_set(msg, disposition, filename, cid, params) raw_data_manager.add_set_handler(str, set_text_content) def set_message_content(msg, message, subtype="rfc822", cte=None, disposition=None, filename=None, cid=None, params=None, headers=None): if subtype == 'partial': raise ValueError("message/partial is not supported for Message objects") if subtype == 'rfc822': if cte not in (None, '7bit', '8bit', 'binary'): # http://tools.ietf.org/html/rfc2046#section-5.2.1 mandate. raise ValueError( "message/rfc822 parts do not support cte={}".format(cte)) # 8bit will get coerced on serialization if policy.cte_type='7bit'. We # may end up claiming 8bit when it isn't needed, but the only negative # result of that should be a gateway that needs to coerce to 7bit # having to look through the whole embedded message to discover whether # or not it actually has to do anything. cte = '8bit' if cte is None else cte elif subtype == 'external-body': if cte not in (None, '7bit'): # http://tools.ietf.org/html/rfc2046#section-5.2.3 mandate. raise ValueError( "message/external-body parts do not support cte={}".format(cte)) cte = '7bit' elif cte is None: # http://tools.ietf.org/html/rfc2046#section-5.2.4 says all future # subtypes should be restricted to 7bit, so assume that. cte = '7bit' _prepare_set(msg, 'message', subtype, headers) msg.set_payload([message]) msg['Content-Transfer-Encoding'] = cte _finalize_set(msg, disposition, filename, cid, params) raw_data_manager.add_set_handler(email.message.Message, set_message_content) def set_bytes_content(msg, data, maintype, subtype, cte='base64', disposition=None, filename=None, cid=None, params=None, headers=None): _prepare_set(msg, maintype, subtype, headers) if cte == 'base64': data = _encode_base64(data, max_line_length=msg.policy.max_line_length) elif cte == 'quoted-printable': # XXX: quoprimime.body_encode won't encode newline characters in data, # so we can't use it. This means max_line_length is ignored. Another # bug to fix later. (Note: encoders.quopri is broken on line ends.) data = binascii.b2a_qp(data, istext=False, header=False, quotetabs=True) data = data.decode('ascii') elif cte == '7bit': data = data.decode('ascii') elif cte in ('8bit', 'binary'): data = data.decode('ascii', 'surrogateescape') msg.set_payload(data) msg['Content-Transfer-Encoding'] = cte _finalize_set(msg, disposition, filename, cid, params) for typ in (bytes, bytearray, memoryview): raw_data_manager.add_set_handler(typ, set_bytes_content) del typ headerregistry.py000064400000050523152526700320010146 0ustar00"""Representing and manipulating email headers via custom objects. This module provides an implementation of the HeaderRegistry API. The implementation is designed to flexibly follow RFC5322 rules. """ from types import MappingProxyType from email import utils from email import errors from email import _header_value_parser as parser class Address: def __init__(self, display_name='', username='', domain='', addr_spec=None): """Create an object representing a full email address. An address can have a 'display_name', a 'username', and a 'domain'. In addition to specifying the username and domain separately, they may be specified together by using the addr_spec keyword *instead of* the username and domain keywords. If an addr_spec string is specified it must be properly quoted according to RFC 5322 rules; an error will be raised if it is not. An Address object has display_name, username, domain, and addr_spec attributes, all of which are read-only. The addr_spec and the string value of the object are both quoted according to RFC5322 rules, but without any Content Transfer Encoding. """ inputs = ''.join(filter(None, (display_name, username, domain, addr_spec))) if '\r' in inputs or '\n' in inputs: raise ValueError("invalid arguments; address parts cannot contain CR or LF") # This clause with its potential 'raise' may only happen when an # application program creates an Address object using an addr_spec # keyword. The email library code itself must always supply username # and domain. if addr_spec is not None: if username or domain: raise TypeError("addrspec specified when username and/or " "domain also specified") a_s, rest = parser.get_addr_spec(addr_spec) if rest: raise ValueError("Invalid addr_spec; only '{}' " "could be parsed from '{}'".format( a_s, addr_spec)) if a_s.all_defects: raise a_s.all_defects[0] username = a_s.local_part domain = a_s.domain self._display_name = display_name self._username = username self._domain = domain @property def display_name(self): return self._display_name @property def username(self): return self._username @property def domain(self): return self._domain @property def addr_spec(self): """The addr_spec (username@domain) portion of the address, quoted according to RFC 5322 rules, but with no Content Transfer Encoding. """ lp = self.username if not parser.DOT_ATOM_ENDS.isdisjoint(lp): lp = parser.quote_string(lp) if self.domain: return lp + '@' + self.domain if not lp: return '<>' return lp def __repr__(self): return "{}(display_name={!r}, username={!r}, domain={!r})".format( self.__class__.__name__, self.display_name, self.username, self.domain) def __str__(self): disp = self.display_name if not parser.SPECIALS.isdisjoint(disp): disp = parser.quote_string(disp) if disp: addr_spec = '' if self.addr_spec=='<>' else self.addr_spec return "{} <{}>".format(disp, addr_spec) return self.addr_spec def __eq__(self, other): if not isinstance(other, Address): return NotImplemented return (self.display_name == other.display_name and self.username == other.username and self.domain == other.domain) class Group: def __init__(self, display_name=None, addresses=None): """Create an object representing an address group. An address group consists of a display_name followed by colon and a list of addresses (see Address) terminated by a semi-colon. The Group is created by specifying a display_name and a possibly empty list of Address objects. A Group can also be used to represent a single address that is not in a group, which is convenient when manipulating lists that are a combination of Groups and individual Addresses. In this case the display_name should be set to None. In particular, the string representation of a Group whose display_name is None is the same as the Address object, if there is one and only one Address object in the addresses list. """ self._display_name = display_name self._addresses = tuple(addresses) if addresses else tuple() @property def display_name(self): return self._display_name @property def addresses(self): return self._addresses def __repr__(self): return "{}(display_name={!r}, addresses={!r}".format( self.__class__.__name__, self.display_name, self.addresses) def __str__(self): if self.display_name is None and len(self.addresses)==1: return str(self.addresses[0]) disp = self.display_name if disp is not None and not parser.SPECIALS.isdisjoint(disp): disp = parser.quote_string(disp) adrstr = ", ".join(str(x) for x in self.addresses) adrstr = ' ' + adrstr if adrstr else adrstr return "{}:{};".format(disp, adrstr) def __eq__(self, other): if not isinstance(other, Group): return NotImplemented return (self.display_name == other.display_name and self.addresses == other.addresses) # Header Classes # class BaseHeader(str): """Base class for message headers. Implements generic behavior and provides tools for subclasses. A subclass must define a classmethod named 'parse' that takes an unfolded value string and a dictionary as its arguments. The dictionary will contain one key, 'defects', initialized to an empty list. After the call the dictionary must contain two additional keys: parse_tree, set to the parse tree obtained from parsing the header, and 'decoded', set to the string value of the idealized representation of the data from the value. (That is, encoded words are decoded, and values that have canonical representations are so represented.) The defects key is intended to collect parsing defects, which the message parser will subsequently dispose of as appropriate. The parser should not, insofar as practical, raise any errors. Defects should be added to the list instead. The standard header parsers register defects for RFC compliance issues, for obsolete RFC syntax, and for unrecoverable parsing errors. The parse method may add additional keys to the dictionary. In this case the subclass must define an 'init' method, which will be passed the dictionary as its keyword arguments. The method should use (usually by setting them as the value of similarly named attributes) and remove all the extra keys added by its parse method, and then use super to call its parent class with the remaining arguments and keywords. The subclass should also make sure that a 'max_count' attribute is defined that is either None or 1. XXX: need to better define this API. """ def __new__(cls, name, value): kwds = {'defects': []} cls.parse(value, kwds) if utils._has_surrogates(kwds['decoded']): kwds['decoded'] = utils._sanitize(kwds['decoded']) self = str.__new__(cls, kwds['decoded']) del kwds['decoded'] self.init(name, **kwds) return self def init(self, name, *, parse_tree, defects): self._name = name self._parse_tree = parse_tree self._defects = defects @property def name(self): return self._name @property def defects(self): return tuple(self._defects) def __reduce__(self): return ( _reconstruct_header, ( self.__class__.__name__, self.__class__.__bases__, str(self), ), self.__getstate__()) @classmethod def _reconstruct(cls, value): return str.__new__(cls, value) def fold(self, *, policy): """Fold header according to policy. The parsed representation of the header is folded according to RFC5322 rules, as modified by the policy. If the parse tree contains surrogateescaped bytes, the bytes are CTE encoded using the charset 'unknown-8bit". Any non-ASCII characters in the parse tree are CTE encoded using charset utf-8. XXX: make this a policy setting. The returned value is an ASCII-only string possibly containing linesep characters, and ending with a linesep character. The string includes the header name and the ': ' separator. """ # At some point we need to put fws here if it was in the source. header = parser.Header([ parser.HeaderLabel([ parser.ValueTerminal(self.name, 'header-name'), parser.ValueTerminal(':', 'header-sep')]), ]) if self._parse_tree: header.append( parser.CFWSList([parser.WhiteSpaceTerminal(' ', 'fws')])) header.append(self._parse_tree) return header.fold(policy=policy) def _reconstruct_header(cls_name, bases, value): return type(cls_name, bases, {})._reconstruct(value) class UnstructuredHeader: max_count = None value_parser = staticmethod(parser.get_unstructured) @classmethod def parse(cls, value, kwds): kwds['parse_tree'] = cls.value_parser(value) kwds['decoded'] = str(kwds['parse_tree']) class UniqueUnstructuredHeader(UnstructuredHeader): max_count = 1 class DateHeader: """Header whose value consists of a single timestamp. Provides an additional attribute, datetime, which is either an aware datetime using a timezone, or a naive datetime if the timezone in the input string is -0000. Also accepts a datetime as input. The 'value' attribute is the normalized form of the timestamp, which means it is the output of format_datetime on the datetime. """ max_count = None # This is used only for folding, not for creating 'decoded'. value_parser = staticmethod(parser.get_unstructured) @classmethod def parse(cls, value, kwds): if not value: kwds['defects'].append(errors.HeaderMissingRequiredValue()) kwds['datetime'] = None kwds['decoded'] = '' kwds['parse_tree'] = parser.TokenList() return if isinstance(value, str): kwds['decoded'] = value try: value = utils.parsedate_to_datetime(value) except ValueError: kwds['defects'].append(errors.InvalidDateDefect('Invalid date value or format')) kwds['datetime'] = None kwds['parse_tree'] = parser.TokenList() return kwds['datetime'] = value kwds['decoded'] = utils.format_datetime(kwds['datetime']) kwds['parse_tree'] = cls.value_parser(kwds['decoded']) def init(self, *args, **kw): self._datetime = kw.pop('datetime') super().init(*args, **kw) @property def datetime(self): return self._datetime class UniqueDateHeader(DateHeader): max_count = 1 class AddressHeader: max_count = None @staticmethod def value_parser(value): address_list, value = parser.get_address_list(value) assert not value, 'this should not happen' return address_list @classmethod def parse(cls, value, kwds): if isinstance(value, str): # We are translating here from the RFC language (address/mailbox) # to our API language (group/address). kwds['parse_tree'] = address_list = cls.value_parser(value) groups = [] for addr in address_list.addresses: groups.append(Group(addr.display_name, [Address(mb.display_name or '', mb.local_part or '', mb.domain or '') for mb in addr.all_mailboxes])) defects = list(address_list.all_defects) else: # Assume it is Address/Group stuff if not hasattr(value, '__iter__'): value = [value] groups = [Group(None, [item]) if not hasattr(item, 'addresses') else item for item in value] defects = [] kwds['groups'] = groups kwds['defects'] = defects kwds['decoded'] = ', '.join([str(item) for item in groups]) if 'parse_tree' not in kwds: kwds['parse_tree'] = cls.value_parser(kwds['decoded']) def init(self, *args, **kw): self._groups = tuple(kw.pop('groups')) self._addresses = None super().init(*args, **kw) @property def groups(self): return self._groups @property def addresses(self): if self._addresses is None: self._addresses = tuple(address for group in self._groups for address in group.addresses) return self._addresses class UniqueAddressHeader(AddressHeader): max_count = 1 class SingleAddressHeader(AddressHeader): @property def address(self): if len(self.addresses)!=1: raise ValueError(("value of single address header {} is not " "a single address").format(self.name)) return self.addresses[0] class UniqueSingleAddressHeader(SingleAddressHeader): max_count = 1 class MIMEVersionHeader: max_count = 1 value_parser = staticmethod(parser.parse_mime_version) @classmethod def parse(cls, value, kwds): kwds['parse_tree'] = parse_tree = cls.value_parser(value) kwds['decoded'] = str(parse_tree) kwds['defects'].extend(parse_tree.all_defects) kwds['major'] = None if parse_tree.minor is None else parse_tree.major kwds['minor'] = parse_tree.minor if parse_tree.minor is not None: kwds['version'] = '{}.{}'.format(kwds['major'], kwds['minor']) else: kwds['version'] = None def init(self, *args, **kw): self._version = kw.pop('version') self._major = kw.pop('major') self._minor = kw.pop('minor') super().init(*args, **kw) @property def major(self): return self._major @property def minor(self): return self._minor @property def version(self): return self._version class ParameterizedMIMEHeader: # Mixin that handles the params dict. Must be subclassed and # a property value_parser for the specific header provided. max_count = 1 @classmethod def parse(cls, value, kwds): kwds['parse_tree'] = parse_tree = cls.value_parser(value) kwds['decoded'] = str(parse_tree) kwds['defects'].extend(parse_tree.all_defects) if parse_tree.params is None: kwds['params'] = {} else: # The MIME RFCs specify that parameter ordering is arbitrary. kwds['params'] = {utils._sanitize(name).lower(): utils._sanitize(value) for name, value in parse_tree.params} def init(self, *args, **kw): self._params = kw.pop('params') super().init(*args, **kw) @property def params(self): return MappingProxyType(self._params) class ContentTypeHeader(ParameterizedMIMEHeader): value_parser = staticmethod(parser.parse_content_type_header) def init(self, *args, **kw): super().init(*args, **kw) self._maintype = utils._sanitize(self._parse_tree.maintype) self._subtype = utils._sanitize(self._parse_tree.subtype) @property def maintype(self): return self._maintype @property def subtype(self): return self._subtype @property def content_type(self): return self.maintype + '/' + self.subtype class ContentDispositionHeader(ParameterizedMIMEHeader): value_parser = staticmethod(parser.parse_content_disposition_header) def init(self, *args, **kw): super().init(*args, **kw) cd = self._parse_tree.content_disposition self._content_disposition = cd if cd is None else utils._sanitize(cd) @property def content_disposition(self): return self._content_disposition class ContentTransferEncodingHeader: max_count = 1 value_parser = staticmethod(parser.parse_content_transfer_encoding_header) @classmethod def parse(cls, value, kwds): kwds['parse_tree'] = parse_tree = cls.value_parser(value) kwds['decoded'] = str(parse_tree) kwds['defects'].extend(parse_tree.all_defects) def init(self, *args, **kw): super().init(*args, **kw) self._cte = utils._sanitize(self._parse_tree.cte) @property def cte(self): return self._cte class MessageIDHeader: max_count = 1 value_parser = staticmethod(parser.parse_message_id) @classmethod def parse(cls, value, kwds): kwds['parse_tree'] = parse_tree = cls.value_parser(value) kwds['decoded'] = str(parse_tree) kwds['defects'].extend(parse_tree.all_defects) # The header factory # _default_header_map = { 'subject': UniqueUnstructuredHeader, 'date': UniqueDateHeader, 'resent-date': DateHeader, 'orig-date': UniqueDateHeader, 'sender': UniqueSingleAddressHeader, 'resent-sender': SingleAddressHeader, 'to': UniqueAddressHeader, 'resent-to': AddressHeader, 'cc': UniqueAddressHeader, 'resent-cc': AddressHeader, 'bcc': UniqueAddressHeader, 'resent-bcc': AddressHeader, 'from': UniqueAddressHeader, 'resent-from': AddressHeader, 'reply-to': UniqueAddressHeader, 'mime-version': MIMEVersionHeader, 'content-type': ContentTypeHeader, 'content-disposition': ContentDispositionHeader, 'content-transfer-encoding': ContentTransferEncodingHeader, 'message-id': MessageIDHeader, } class HeaderRegistry: """A header_factory and header registry.""" def __init__(self, base_class=BaseHeader, default_class=UnstructuredHeader, use_default_map=True): """Create a header_factory that works with the Policy API. base_class is the class that will be the last class in the created header class's __bases__ list. default_class is the class that will be used if "name" (see __call__) does not appear in the registry. use_default_map controls whether or not the default mapping of names to specialized classes is copied in to the registry when the factory is created. The default is True. """ self.registry = {} self.base_class = base_class self.default_class = default_class if use_default_map: self.registry.update(_default_header_map) def map_to_type(self, name, cls): """Register cls as the specialized class for handling "name" headers. """ self.registry[name.lower()] = cls def __getitem__(self, name): cls = self.registry.get(name.lower(), self.default_class) return type('_'+cls.__name__, (cls, self.base_class), {}) def __call__(self, name, value): """Create a header instance for header 'name' from 'value'. Creates a header instance by creating a specialized class for parsing and representing the specified header by combining the factory base_class with a specialized class from the registry or the default_class, and passing the name and value to the constructed class's constructor. """ return self[name](name, value) __pycache__/message.cpython-312.opt-1.pyc000064400000147567152526700320014070 0ustar00 {|j dZddgZddlZddlZddlZddlmZmZddlm Z ddlm Z ddl m Z dd lm Zdd lmZej"Zd Zej&d Zd ZddZdZdZdZGddZGddeZGddeZy)z8Basic message object for the email package object model.Message EmailMessageN)BytesIOStringIO)utils)errors)compat32charset)decode_bz; z[ \(\)<>@,;:\\"/\[\]\?=]ct|jd\}}}|s|jdfS|j|jfS)N;)str partitionstrip)paramasepbs &/usr/lib64/python3.12/email/message.py _splitparamrsH E $$S)IAsA wwy$ 779aggi c|t|dkDrt|tr,|dz }tj|d|d|d}|d|S |j d|stj|r|d tj|d S|d|S|S#t $r&|dz }tj|dd}|d|cYSwxYw) a~Convenience function to format and return a key=value pair. This will quote the value if needed or if quote is true. If value is a three tuple (charset, language, value), it will be encoded according to RFC2231 rules. If it contains non-ascii characters it will likewise be encoded according to RFC2231 rules, using the utf-8 charset and a null language. r*=asciizutf-8z="") len isinstancetuplerencode_rfc2231encodeUnicodeEncodeError tspecialssearchquote)rvaluer)s r _formatparamr+'s SZ!^ eU # SLE((q58U1XFE#U+ + 0 W% I$$U+ %u{{5'9: :#U+ + & 0 ,,UGR@"'// 0sB,C C cxdt|z}g}d}|jd||k(r|dz }|jd|}|d}}|dkDrP||jd|||jd||z z }|dzdk(rn||jd|dz}}|dkDrP|dkr t|}|jd||}|dk(r|||}n;|||j j dz||dz|j z}|j|j|}|jd||k(r|S) Nrrrr z\"rr) rfindcountr!rstriplowerlstripappendr)spliststartendinddiffifs r _parseparamr<IsP c!f A E E &&e  %  ffS% 1TAg AGGCc*QWWUC-EE EDax1}AFF3a0C Ag 7a&C FF3s # 7% A% !!#))+c1Aac#J4E4E4GGA QWWY# &&e  %$ Lrct|tr!|d|dtj|dfStj|S)Nrrr)r"r#runquote)r*s r _unquotevaluer?cs? %Qxq5==q#:::}}U##rcRg}t|j}|D]G}|jds|jdj d\}}} t |dn t d|D]L}|s t d|jddk(rn) tj|}|j|Ndj|S#t $rYwxYw#tj$r/|d d z d zd zd zdz}tj|d|}YtwxYw)zDecode uuencoded data.sbegin  )basez`begin` line not foundzTruncated inputs sendr ?Nr) iter splitlines startswith removeprefixrint ValueErrorrbinasciia2b_uuErrorr3join) encoded decoded_linesencoded_lines_iterlinemode_path decoded_linenbytess r _decode_uur\ns2Mg0023" ??9 % --i8BB4HMD!T Dq!#122"./ / ZZ % /  :#??40L \*# 88M ""'  ~~ :Q b(A-1a7F#??4=9L :s$ CC$ C! C!$?D&%D&cTeZdZdZefdZdZd2dZdZd3dZ d Z d Z d Z d Z d4d Zd5dZdZdZdZdZdZdZdZdZdZdZdZd5dZdZdZd5dZdZdZ d Z!d!Z"d"Z#d#Z$d$Z%d%Z&d6d&Z' d6d'Z( d7d(Z)d8d)Z*d9d*Z+d5d+Z,d5d,Z-d-Z.d5d.Z/d5d/Z0d0Z1dd1l2m3Z3y):raBasic message object. A message object is defined as something that has a bunch of RFC 2822 headers and a payload. It may optionally have an envelope header (a.k.a. Unix-From or From_ header). If the message is a container (i.e. a multipart or a message/rfc822), then the payload is a list of Message objects, otherwise it is a string. Message objects implement part of the `mapping' interface, which assumes there is exactly one occurrence of the header per message. Some headers do in fact appear multiple times (e.g. Received) and for those headers, you must use the explicit API to set or get all the headers. Not all of the mapping methods are implemented. c||_g|_d|_d|_d|_dx|_|_g|_d|_y)N text/plain) policy_headers _unixfrom_payload_charsetpreambleepiloguedefects _default_type)selfr`s r__init__zMessage.__init__sB    (,,   )rc"|jS)z9Return the entire formatted message as a string. ) as_stringris r__str__zMessage.__str__s~~rrNcddlm}| |jn|}t}||d||}|j |||j S)aReturn the entire formatted message as a string. Optional 'unixfrom', when true, means include the Unix From_ envelope header. For backward compatibility reasons, if maxheaderlen is not specified it defaults to 0, so you must override it explicitly if you want a different maxheaderlen. 'policy' is passed to the Generator instance used to serialize the message; if it is not specified the policy associated with the message instance is used. If the message object contains binary data that is not encoded according to RFC standards, the non-compliant data will be replaced by unicode "unknown character" code points. r) GeneratorF) mangle_from_ maxheaderlenr`unixfrom)email.generatorrpr`rflattengetvalue)rirtrrr`rpfpgs rrlzMessage.as_stringsP . &F Z b#(#/# % $ *{{}rc"|jS)z?Return the entire formatted message as a bytes object. )as_bytesrms r __bytes__zMessage.__bytes__s}}rcddlm}| |jn|}t}||d|}|j |||j S)aJReturn the entire formatted message as a bytes object. Optional 'unixfrom', when true, means include the Unix From_ envelope header. 'policy' is passed to the BytesGenerator instance used to serialize the message; if not specified the policy associated with the message instance is used. r)BytesGeneratorF)rqr`rs)rur~r`rrvrw)rirtr`r~rxrys rr{zMessage.as_bytessG 3 &F Y 2E& A $ *{{}rc6t|jtS)z6Return True if the message consists of multiple parts.)r"rclistrms r is_multipartzMessage.is_multiparts$--..rc||_yNrb)rirts r set_unixfromzMessage.set_unixfroms !rc|jSrrrms r get_unixfromzMessage.get_unixfroms ~~rc|j |g|_y |jj|y#t$r tdwxYw)zAdd the given payload to the current payload. The current payload will always be a list of objects after this method is called. If you want to set the payload to a scalar object, use set_payload() instead. Nz=Attach is not valid on a message with a non-multipart payload)rcr3AttributeError TypeError)ripayloads rattachzMessage.attachsO == $IDM : $$W-! :!9:: :s 3Ac|jr |ry| |jS|j|S|;t|jts!t dt |jz|j}|j dd}t|dr |j}n't|jj}|s^t|trLtj|r7 |jdd} |j|j!dd}|S|St|tr |jdd}|d k(rt'j(S|d k(rPt+d j-j/\}}|D]}|j0j3|| |S|d vr t5St|trS|S#t"$r|jdd}Y|SwxYw#t$$rY|SwxYw#t$$r|jd }YwxYw#t6$rcYSwxYw)aZReturn a reference to the payload. The payload will either be a list object or a string. If you mutate the list object, you modify the message's payload in place. Optional i returns that index into the payload. Optional decode is a flag indicating whether the payload should be decoded or not, according to the Content-Transfer-Encoding header (default is False). When True and the message is not a multipart, the payload will be decoded if this header's value is `quoted-printable' or `base64'. If some other encoding is used, or the header is missing, or if the payload has bogus data (i.e. bogus base64 or uuencoded data), the payload is returned as-is. If the message is a multipart and the decode flag is True, then None is returned. NzExpected list, got %szcontent-transfer-encodingrctersurrogateescapereplaceraw-unicode-escapezquoted-printablebase64r)z x-uuencodeuuencodeuuezx-uue)rrcr"rrtypegethasattrrrrr1r_has_surrogatesr%decodeget_content_charset LookupErrorr&quopri decodestringr rRrJr` handle_defectr\rN) rir:rrrbpayloadr*rgdefects r get_payloadzMessage.get_payloads8D    y}}$}}Q'' =DMM4!@3d4==6IIJ J--hh2B7 3 ''Cc(.."((*C'3'E,A,A',J&~~g7HIHF"*//$2J2J72SU^"_ N7N gs # @">>'3DE $ $&&x0 0 H_&chhx/B/B/D&EFNE7! ))$7"L > > !(++ gs #O?'F"*//'9"EN F)N & @ #>>*>?  @$  sT4H!G"=H H4"H=HHH HHH10H14 IIct|drA|||_yt|ts t|}|j |j d}t|dr|j dd|_n||_||j|yy)zSet the payload to the given value. Optional charset sets the message's default character set. See set_charset() for details. r%Nrrr)rrcr"Charsetr%output_charsetr set_charset)rirr s r set_payloadzMessage.set_payloadUs 7H % ' gw/!'*nnW%;%;=NOG 7H %#NN74EFDM#DM     W % rc||jdd|_yt|ts t|}||_d|vr|j ddd|vr#|j dd|j n |j d|j ||j k7r |j|j|_d|vr|j} ||yy#t$rw|j}|r> |jd d }n*#t$r|j|j}YnwxYw|j||_|j d|YywxYw) aSet the charset of the payload to a given character set. charset can be a Charset instance, a string naming a character set, or None. If it is a string it will be converted to a Charset instance. If charset is None, the charset parameter will be removed from the Content-Type field. Anything else will generate a TypeError. The message will be assumed to be of type text/* encoded with charset.input_charset. It will be converted to charset.output_charset and encoded properly, if needed, when generating the plain text representation of the message. MIME headers (MIME-Version, Content-Type, Content-Transfer-Encoding) will be added as needed. Nr MIME-Version1.0 Content-Typer_r zContent-Transfer-Encodingrr) del_paramrdr"r add_headerget_output_charset set_param body_encodercget_body_encodingrr% UnicodeErrorr)rir rrs rrzMessage.set_charsetis` ? NN9 % DM '7+g&G  % OONE 2  % OONL$+$>$>$@  B NN9g&@&@&B C g002 2#// >DM &d 2++-C BD  3 B--I")..:K"L'I")..1G1G"HI ' 3 3G <  ;SA Bs6#C--E-DE-$D?<E->D??+E-,E-c|jS)zKReturn the Charset instance associated with the message's payload. )rdrms r get_charsetzMessage.get_charsets}}rc,t|jS)z9Return the total number of headers, including duplicates.)r!rarms r__len__zMessage.__len__s4==!!rc$|j|S)a-Get a header value. Return None if the header is missing instead of raising an exception. Note that if the header appeared multiple times, exactly which occurrence gets returned is undefined. Use get_all() to get all the values matching a header field name. )r)rinames r __getitem__zMessage.__getitem__sxx~rcf|jj|}|r_|j}d}|jD]>\}}|j|k(s|dz }||k\s%t dj |||jj |jj||y)zSet the value of a header. Note: this does not overwrite an existing header with the same field name. Use __delitem__() first to delete any existing headers. rrz/There may be at most {} {} headers in a messageN)r`header_max_countr1rarNformatr3header_store_parse)rirval max_countlnamefoundkvs r __setitem__zMessage.__setitem__s KK006 JJLEE 1779%QJE )(*88>y$8OQQ & T[[;;D#FGrc|j}g}|jD],\}}|j|k7s|j||f.||_y)zwDelete all occurrences of a header, if present. Does not raise an exception if the header is missing. N)r1rar3)rir newheadersrrs r __delitem__zMessage.__delitem__sO zz| MMDAqwwyD !!1a&)"# rcv|j}|jD]\}}||jk(syy)NTF)r1ra)rir name_lowerrrs r __contains__zMessage.__contains__s5ZZ\ MMDAqQWWY&"rc#<K|jD] \}}| ywrra)rifieldr*s r__iter__zMessage.__iter__s MMLE5K*scL|jDcgc]\}}| c}}Scc}}w)a.Return a list of all the message's header field names. These will be sorted in the order they appeared in the original message, or were added to the message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. rrirrs rkeysz Message.keyss$#mm,mdam,,,s c|jDcgc]!\}}|jj||#c}}Scc}}w)a)Return a list of all the message's header values. These will be sorted in the order they appeared in the original message, or were added to the message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. rar`header_fetch_parsers rvalueszMessage.valuessB!MM+)DAq ..q!4)+ ++s&:c |jDcgc]#\}}||jj||f%c}}Scc}}w)a'Get all the message's header fields and values. These will be sorted in the order they appeared in the original message, or were added to the message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. rrs ritemsz Message.itemssG!MM+)DAqDKK221a89)+ ++s(<c|j}|jD]6\}}|j|k(s|jj||cS|S)z~Get a header value. Like __getitem__() but return failobj instead of None when the field is missing. )r1rar`r)rirfailobjrrs rrz Message.getsM zz|MMDAqwwyD {{55a;;"rc>|jj||fy)zStore name and value in the model without modification. This is an "internal" API, intended only for use by a parser. N)rar3)rirr*s rset_rawzMessage.set_raw s dE]+rcHt|jjS)zReturn the (name, value) header pairs without modification. This is an "internal" API, intended only for use by a generator. )rIracopyrms r raw_itemszMessage.raw_itemss DMM&&())rcg}|j}|jD]D\}}|j|k(s|j|jj ||F|s|S|S)aQReturn a list of all the values for the named field. These will be sorted in the order they appeared in the original message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. If no such fields exist, failobj is returned (defaults to None). )r1rar3r`r)rirrrrrs rget_allzMessage.get_alls`zz|MMDAqwwyD  dkk<rrs r get_paramzMessage.get_paramsZ0  N--gv>DAqwwyEKKM)(++H ? rcft|ts|r|||f}||vr|jdk(rd}n|j|}|j ||s3|st |||}nt j|t |||g}nwd}|j||D]_\} } d} | j|jk(rt |||} n t | | |} |s| }It j|| g}a||j|k7r|r|j||y||=|||<yy)aSet a parameter in the Content-Type header. If the parameter already exists in the header, its value will be replaced with the new value. If header is Content-Type and has not yet been defined for this message, it will be set to "text/plain" and the new parameter and value will be appended as per RFC 2045. An alternate header can be specified in the header argument, and all parameters will be quoted as necessary unless requote is False. If charset is specified, the parameter will be encoded according to RFC 2231. Optional language specifies the RFC 2231 language, defaulting to the empty string. Both charset and language should be strings. rr_)rrrr>N) r"r#r1rr r+rrRrr) rirr*rrequoter languagerr old_param old_value append_params rrzMessage.set_params<$%'Gh.E  &,,.N"B EHHV$E~~eF~3$UE7;!Lw?@BE(,v@G)8)I$ 9! ??$ 5#/ug#FL#/ 9g#NL(E%NNE<+@AE)I DHHV$ $##FE2L$V %rc *||vryd}|j||D]Y\}}|j|jk7s(|st|||}8tj |t|||g}[||j |k7r ||=|||<yy)a>Remove the given parameter completely from the Content-Type header. The header will be re-written in place without the parameter or its value. All values will be quoted as necessary unless requote is False. Optional header specifies an alternative to the Content-Type header. Nrr )rr1r+rrRr)rirrr  new_ctyperrs rrzMessage.del_params    OO67OCDAqwwyEKKM) ,Q7 ;I ) 0^ +^$#(D  DL @ LV 12JDAq NN1a 1rct}|jd|d}||ur|jd|d}||ur|Stj|j S)a@Return the filename associated with the payload if present. The filename is extracted from the Content-Disposition header's `filename' parameter, and it is unquoted. If that header is missing the `filename' parameter, this method falls back to looking for the `name' parameter. filenamecontent-dispositionrr)rr rcollapse_rfc2231_valuer)rirrrs r get_filenamezMessage.get_filenamePs_(>>*g7LM w ~~fg~FH w N++H5;;==rct}|jd|}||ur|Stj|j S)zReturn the boundary associated with the payload if present. The boundary is extracted from the Content-Type header's `boundary' parameter, and it is unquoted. boundary)rr rrr0)rirrrs r get_boundaryzMessage.get_boundary`sB (>>*g6 w N++H5<<>>rct}|j|d}||urtjdg}d}|D]D\}}|j dk(r|j dd|zfd}2|j ||fF|s|j dd|zfg}|j D]\} } | j dk(rzg} |D]2\} } | dk(r| j | | j | d| 4tj| } |j |jj| | |j | | f||_y ) aSet the boundary parameter in Content-Type to 'boundary'. This is subtly different than deleting the Content-Type header and adding a new one with a new boundary parameter via add_header(). The main difference is that using the set_boundary() method preserves the order of the Content-Type header in the original message. HeaderParseError is raised if the message has no Content-Type header. rzNo Content-Type header foundFrz"%s"TrrN) rrrHeaderParseErrorr1r3rarrRr`r)rirrr newparamsfoundppkpvrhrrrrs r set_boundaryzMessage.set_boundarymsT(**7NC W ))*HI I FBxxzZ'  *fx.?!@A  "b*     j&8*;< = MMDAqwwyN*%DAqBw Q 1%56 &  nnU+!!$++"@"@C"HI!!1a&)"# rcTt}|jd|}||ur|St|tr*|dxsd} |dj d}t ||} |j d|jS#t tf$r|d}Y8wxYw#t$r|cYSwxYw)zReturn the charset parameter of the Content-Type header. The returned string is always coerced to lower case. If there is no Content-Type header, or if that header has no charset parameter, failobj is returned. r rzus-asciirr) rr r"r#r%rrrr1)rirrr pcharsetr{s rrzMessage.get_content_charsets(..G4 g N gu %qz/ZH %#1:,,-ABh1  NN: &}} . %!!* %  N s# A?B?BB B'&B'cf|jDcgc]}|j|c}Scc}w)aReturn a list containing the charset(s) used in this message. The returned list of items describes the Content-Type headers' charset parameter for this message and all the subparts in its payload. Each item will either be a string (the value of the charset parameter in the Content-Type header of that part) or the value of the 'failobj' parameter (defaults to None), if the part does not have a main MIME type of "text", or the charset is not defined. The list will contain one string for each part of the message, plus one for the container message (i.e. self), so that a non-multipart message will still return a list of length 1. )walkr)rirparts r get_charsetszMessage.get_charsetss. ?CiikJkd((1kJJJs.cf|jd}|yt|dj}|S)zReturn the message's content-disposition if it exists, or None. The return values can be either 'inline', 'attachment' or None according to the rfc2183. rNr)rrr1)rir*c_ds rget_content_dispositionzMessage.get_content_dispositions8 ./ =% #))+ r)r))FrN)FN)NFr)NrT)rTNrF)rT)rT)4__name__ __module__ __qualname____doc__r rjrnrlr|r{rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr rrrrrr%rr+r.email.iteratorsr)rrrrs ' * 0 /" : Zx&(-B^" H$ #- + + ",*$,< "&0##"#*,5C DFJ5:1%f%,2@> ?,#\<K$ %rceZdZdfd Zdfd ZdZdZdZddZhdZ d Z d Z dd d Z dd d Z dZddZddZddZdddZdZdZdZdZdZxZS)MIMEPartNc8|ddlm}|}t| |y)Nr)default) email.policyr8superrj)rir`r8 __class__s rrjzMIMEPart.__init__s > ,F  rcb| |jn|}| |j}t| |||S)aReturn the entire formatted message as a string. Optional 'unixfrom', when true, means include the Unix From_ envelope header. maxheaderlen is retained for backward compatibility with the base Message class, but defaults to None, meaning that the policy value for max_line_length controls the header maximum length. 'policy' is passed to the Generator instance used to serialize the message; if it is not specified the policy associated with the message instance is used. )r`max_line_lengthr:rl)rirtrrr`r;s rrlzMIMEPart.as_strings9!'F  !11Lw <@@rcZ|j|jjdS)NT)utf8r`)rlr`clonerms rrnzMIMEPart.__str__s%~~T[[%6%6D%6%A~BBrcJ|jd}|dS|jdk(S)NrF attachment)rcontent_disposition)rir-s r is_attachmentzMIMEPart.is_attachments+hh,- uP)@)@L)PPrc#\K|jry|jjd\}}|dk(r||vr|j||fy|dk7s|j sy|dk7r0|j D]}|j ||Ed{yd|vr|jd|fd}|jd}|r!|j D]}|d|k(s |}n||j}|r|dnd}||j ||Ed{yy77w)Nrtext multipartrelatedr6 content-idr) rErrindexr iter_parts _find_bodyr r) rir*preferencelistmaintypesubtypesubpart candidater6subpartss rrMzMIMEPart._find_bodysK      11399#>' v .(%++G4d;;  { "$*;*;*=  i ??,??7NCCC-   &!'' 2D9 9 w' ??,<(E1 'I-  '')H'/ TI  y.A A A !D Bs+BD,D(AD,*7D,!D*"D,*D,cxt|}d}|j||D]\}}||ks |}|}|dk(s|S|S)aReturn best candidate mime part for display as 'body' of message. Do a depth first search, starting with self, looking for the first part matching each of the items in preferencelist, and return the part corresponding to the first item that has a match, or None if no items have a match. If 'related' is not included in preferencelist, consider the root part of any multipart/related encountered as a candidate match. Ignore parts with 'Content-Disposition: attachment'. Nr)r!rM)rirN best_priobodyprior*s rget_bodyzMIMEPart.get_bodysU' //$?JD$i 19 @  r>rGhtmlrGplainrHrIrH alternativec#K|jjd\}}|dk7s|dk(ry|j} |j}|dk(rt|dk(ro|j d}|r@d}g}|D]*}|j d|k(rd }|j|,|r |Ed{y|jd |Ed{yg} |D]^}|jjd\}}||f|jvr&|js|| vr| j|[|`y#t$rYywxYw77|w) aReturn an iterator over the non-main parts of a multipart. Skip the first of each occurrence of text/plain, text/html, multipart/related, or multipart/alternative in the multipart (unless they have a 'Content-Disposition: attachment' header) and include all remaining subparts in the returned iterator. When applied to a multipart/related, return all parts except the root part. Return an empty iterator when applied to a multipart/alternative or a non-multipart. rrHr_NrIr6FrJTr) rrrrrr rr3pop _body_typesrE) rirOrPrrr6r attachmentsr*seens riter_attachmentszMIMEPart.iter_attachments0sb!11399#>' { "g&> ""$ LLNE { "w)';NN7+E !Dxx -6 $#**40 " *** IIaL   D $ 5 5 7 = =c B Hg7#t'7'77**,1D G$J 7   $+ sI>ED0AE(D?)EEA+E0 D<9E;D<<EEc#bK|jr|jEd{yy7w)z~Return an iterator over all immediate subparts of a multipart. Return an empty iterator for a non-multipart. N)rrrms rrLzMIMEPart.iter_partsgs.    '') ) )  )s $/-/)content_managerc^||jj}|j|g|i|Sr)r`rg get_contentrirgargskws rrizMIMEPart.get_contentos4  ""kk99O***4=$="==rc`||jj}|j|g|i|yr)r`rg set_contentrjs rrnzMIMEPart.set_contentts1  ""kk99O###D64626rc$|jdk(r5|j}||fz}||vrtdj||g}g}|jD]K\}}|j j dr|j||f9|j||fM|r=t||j} || _|j| _ | g|_ ng|_ ||_d|z|d<||jd|yy)NrHzCannot convert {} to {}content-r@z multipart/rr) rrrNrrar1rKr3rr`rcr) rirPdisallowed_subtypesrexisting_subtype keep_headers part_headersrr*r*s r_make_multipartzMIMEPart._make_multipartys  $ $ &+ 5#779 "5 "B #66 !:!A!A$g"/00  ==KD%zz|&&z2##T5M2##T5M2 ) 4:T[[1D(DM MMDM!FDMDM$ +g5^   NN:x 0 rc*|jdd|y)NrI)r_mixedrurirs r make_relatedzMIMEPart.make_relateds Y(@(Krc*|jdd|y)Nr_)rwrxrys rmake_alternativezMIMEPart.make_alternatives ]JArc*|jdd|y)Nrwr4rxrys r make_mixedzMIMEPart.make_mixeds Wb(3r)_dispc |jdk7s|j|k7rt|d|zt||j}|j |i||r d|vr||d<|j |y)NrHmake_r@rzContent-Disposition)rrgetattrrr`rnr)ri_subtyperrkrlr*s r_add_multipartzMIMEPart._add_multiparts  % % '; 6((*h6 -GD'H, - /tDz-$%"% *$6*/D& ' Drc4|jdg|ddi|y)NrIrinlinerrirkrls r add_relatedzMIMEPart.add_relateds!ICCHCCrc0|jdg|i|y)Nr_rrs radd_alternativezMIMEPart.add_alternativesM7D7B7rc4|jdg|ddi|y)NrwrrCrrs radd_attachmentzMIMEPart.add_attachments!GEdE,E"Erc g|_d|_yr)rarcrms rclearzMIMEPart.clears  rc|jDcgc](\}}|jjds||f*c}}|_d|_ycc}}w)Nrp)rar1rKrc)rinrs r clear_contentzMIMEPart.clear_contentsN,0MMBMDAq ! 4 4Z @QMB  Bs-Ar)FNN))rIrZr\)r/r0r1rjrlrnrErMrXrbrerLrirnrurzr|r~rrrrrr __classcell__r;s@rr6r6s!A CQB:(1K5n*26> 267 16LB459D8Frr6ceZdZfdZxZS)rc8t||i|d|vrd|d<yy)Nrr)r:rn)rirkrlr;s rrnzEmailMessage.set_contents, T(R(  %#(D  &r)r/r0r1rnrrs@rrrs ))r)NT)r2__all__rOreriorremailrremail._policybaser r rdemail._encoded_wordsr rrcompiler'rr+r<r?r\rr6rr4rrrs ? n % &%)      BJJ2 3   D4$#>K %K %\\w\~)8)r__pycache__/base64mime.cpython-312.opt-2.pyc000064400000004231152526700320014355 0ustar00 {|j b gdZddlmZddlmZmZdZdZdZdZ dZ dd Z d efd Z d Z e Ze Zy )) body_decode body_encodedecode decodestring header_encode header_length) b64encode) b2a_base64 a2b_base64z  cP tt|d\}}|dz}|r|dz }|S)N)divmodlen) bytearray groups_of_3leftoverns )/usr/lib64/python3.12/email/base64mime.pyrr1s4@"3y>15KaA Q Hc |syt|tr|j|}t|j d}d|d|dS)Nr asciiz=?z?b?z?=) isinstancestrencoder r) header_bytescharsetencodeds rrr;sI ,$#**73  %,,W5G#W --rLc, |syg}|dzdz}tdt||D]Y}t||||zjd}|j t r|t k7r|dd|z}|j |[tj|S)Nr rrrr) rangerr rendswithNLappend EMPTYSTRINGjoin)s maxlineleneolencvec max_unencodediencs rrrIs  FNa'M 1c!fm ,1Q./077@ << r cr(S.C c -   F ##rc |s tSt|trt|j dSt|S)Nzraw-unicode-escape)bytesrrr r)strings rrrbs= w FC &--(<=>>&!!rN)z iso-8859-1)__all__base64r binasciir r CRLFr'r)MISC_LENrrrrrrrrr;sV , +      .!b$2 "   r__pycache__/_parseaddr.cpython-312.opt-2.pyc000064400000047670152526700320014543 0ustar00 {|jE gdZddlZddlZdZdZdZgdZgdZdddddd d dd d d d d d dZdZ dZ dZ dZ dZ GddZGddeZy)) mktime_tz parsedate parsedate_tzquoteN z, )janfebmaraprmayjunjulaugsepoctnovdecjanuaryfebruarymarchaprilr junejulyaugust septemberoctobernovemberdecember)montuewedthufrisatsunipii iiDi)UTUTCGMTZASTADTESTEDTCSTCDTMSTMDTPSTPDTcJ t|}|sy|dd|d<t|S)N r) _parsedate_tztuple)dataress )/usr/lib64/python3.12/email/_parseaddr.pyrr-s5  C  1v~A :c  |sy|j}|sy|djds|djtvr|d=n'|dj d}|dk\r|d|dzd|d<t |dk(r*|djd}t |dk(r||ddz}t |dk(rP|d}|j d}|dk(r|j d}|dkDr|d|||dg|ddn|jd t |d kry|dd }|\}}}}}|r|r|sy|j}|tvr||j}}|tvrytj|dz}|d kDr|d z}|ddk(r|dd}|j d }|dkDr||}}|ddk(r|dd}|sy|djs||}}|ddk(r|dd}|jd }t |d k(r|\} } d} nkt |dk(r|\} } } nVt |dk(rGd|dvr@|djd}t |d k(r|\} } d} nt |dk(r|\} } } nyy t|}t|}t| } t| } t| } |dkr|dkDr|dz }n|dz }d} |j}|tvr t|} n$ t|} | dk(r|jdrd} | r!| dkrd} | } nd} | | dzdz| dzdzzz} |||| | | ddd| g S#t$rYywxYw#t$rYawxYw)Nr,-+r :0.dDilii<)splitendswithlower _daynamesrfindlenfindappend _monthnamesindexisdigitint ValueErrorupper _timezones startswith)r9istuffsddmmyytmtzthhtmmtsstzoffsettzsigns r;r7r79s  :: 2wH Q;2==-H a<F yHFx}d2hnb5HHI BS#q!R ::E *   s$,7L/ L>/ L;:L;> M  M cH t|}t|tr|ddS|S)Nr6)r isinstancer8r9ts r;rrs)0TA!U!u r<c~ |dtj|dddzStj|}||dz S)Nr6)rD)timemktimecalendartimegmrms r;rrsDO Aw{{48e+,, OOD !47{r<cH |jddjddS)N\z\\"z\")replace)strs r;rrs' ;;tV $ , ,S% 88r<c`eZdZ dZdZdZdZdZdZdZ ddZ d Z d Z d Z dd ZdZy ) AddrlistClassc. d|_d|_d|_d|_|j|jz|_|j|jz|jz|_|j j dd|_||_g|_ y)Nz ()<>@,:;."[]rz z rJr) specialsposLWSCRFWSatomendsrx phraseendsfield commentlistselfrs r;__init__zAddrlistClass.__init__s ( 88dgg% 0477: --//R8 r<cL g}|jt|jkr|j|j|jdzvrY|j|jdvr(|j |j|j|xjdz c_nG|j|jdk(r*|j j |j nn#|jt|jkrtj|S)Nz r?() r~rSrrrUr getcomment EMPTYSTRINGjoin)rwslists r;gotonextzAddrlistClass.gotonexts4hhTZZ(zz$((#txx&'88::dhh'v5MM$**TXX"67A DHH%,  ''(9:hhTZZ(''r<c g}|jt|jkrL|j}|r||z }n|j d|jt|jkrL|S)N)rr)r~rSr getaddressrU)rresultads r; getaddrlistzAddrlistClass.getaddrlistsc hhTZZ("B"  h' hhTZZ(  r<c g|_|j|j}|j}|j}|jg}|jt |j k\r*|rft j|j|dfg}n?|j |jdvrB||_||_|j}t j|j|fg}n|j |jdk(rg}t |j }|xjdz c_|jt |j krw|j|j|kr3|j |jdk(r|xjdz c_n%||jz}|jt |j krn|j |jdk(rp|j}|jr;t j|dzdj|jzd z|fg}n{t j||fg}nb|r&t j|j|dfg}n:|j |j|jvr|xjdz c_|j|jt |j kr1|j |jd k(r|xjdz c_|S) Nrz.@rGr?;) rrr~ getphraselistrSrSPACEr getaddrspecr getrouteaddrr})roldposoldclplist returnlistaddrspecfieldlen routeaddrs r;rzAddrlistClass.getaddress s%   ""$  88s4:: &$zz$*:*:;U1XFG ZZ !T )DH$D '')H ::d&6&67BCJ ZZ !S (J4::H HHMH((S_, 88h&4::dhh+?3+FHHMH'$//*;; ((S_,ZZ !S ())+I$zz%047"xx(8(89 :#*E HHMHr<c |j|jdk7ryd}|xjdz c_|jd}|jt|jkr |r|j d}n|j|jdk(r|xjdz c_ |S|j|jdk(r|xjdz c_d}nZ|j|jdk(r|xjdz c_n(|j }|xjdz c_ |S|j|jt|jkr |S) NrFr?r>@TrG)rr~rrS getdomainr)r expectrouteadlists r;rzAddrlistClass.getrouteaddrGs+  ::dhh 3 &   A  hhTZZ( # DHH%,A  DHH%,A " DHH%,A ))+A   MMO!hhTZZ($ r<c g}|j|jt|jkrgd}|j|jdk(rN|r#|dj s|j |j d|xjdz c_d}n|j|jdk(r,|j dt|jznj|j|j|jvr&|r#|dj s|j nh|j |j|j}|r|r|j ||jt|jkrg|jt|jk\s|j|jdk7rtj|S|j d|xjdz c_|j|j}|stStj||zS) NTrJrDr?Frwz"%s"r)rr~rSrstrippoprUrgetquotergetatomrrr)raslist preserve_wswsdomains r;rzAddrlistClass.getaddrspecgs* hhTZZ(Kzz$((#s*&*"2"2"4JJL c"A # DHH%, fuT]]_'==>DHH%6&*"2"2"4JJL dlln-Br b!%hhTZZ(( 88s4:: &$**TXX*>#*E##F+ + c A  ! '&00r<c g}|jt|jkr|j|j|jvr|xjdz c_n,|j|jdk(r*|jj |j n|j|jdk(r |j |jn|j|jdk(r'|xjdz c_|j dng|j|jdk(rtS|j|j|jvrnC|j |j|jt|jkrtj|S)Nr?r[rJr) r~rSrrrrUrgetdomainliteralrrrr)rsdlists r;rzAddrlistClass.getdomains@;hhTZZ(zz$((#txx/A DHH%,  ''(9:DHH%, d3356DHH%,A  c"DHH%,#"DHH%6 dlln-#hhTZZ($''r<c |j|j|k7rydg}d}|xjdz c_|jt|jkr|r+|j|j|jd}n|j|j|vr|xjdz c_n|r<|j|jdk(r |j|j |j|jdk(rd}n(|j|j|j|xjdz c_|jt|jkrt j |S)NrFr?rrvT)rr~rSrUrrr)r begincharendchars allowcommentsslistrs r; getdelimitedzAddrlistClass.getdelimiteds*  ::dhh 9 , A hhTZZ( TZZ12DHH%1A 4::dhh#73#> T__./DHH%- TZZ12 HHMHhhTZZ( &&r<c* |jdddS)Nrwz" Frrs r;rzAddrlistClass.getquotes?  eU33r<c* |jdddS)Nrz) Trrs r;rzAddrlistClass.getcommentsE  eT22r<c0 d|jdddzS)Nz[%s]rz] Frrs r;rzAddrlistClass.getdomainliterals/))#ue<<rs     I > AQA$$$$$   z;z9kkZ -'--'r<__pycache__/charset.cpython-312.opt-1.pyc000064400000035512152526700320014057 0ustar00 {|jB gdZddlmZddlZddlZddlmZddlmZdZ dZ dZ d Z d Z d Zd Zid e e dfde e dfde e dfde e dfde e dfde e dfde e dfde e dfde e dfde e dfde e dfde e dfd dde e dfde e dfde ddfde ddfe ddfe e dfe e dfd Zid!d d"d d#dd$dd%dd&dd'dd(dd)dd*dd+dd,dd-dd.dd/dd0dd1ddddd2dd3d d4Zd5d6dd7Zdd8Zd9Zd:Zd;ZGd<d=Zy)>)Charset add_alias add_charset add_codec)partialN)errors)encode_7or8bitus-asciiz unknown-8bitz iso-8859-1z iso-8859-2z iso-8859-3z iso-8859-4z iso-8859-9z iso-8859-10z iso-8859-13z iso-8859-14z iso-8859-15z iso-8859-16z windows-1252viscii)NNNbig5gb2312zeuc-jp iso-2022-jp shift_jisutf-8)rzkoi8-rrlatin_1zlatin-1latin_2zlatin-2latin_3zlatin-3latin_4zlatin-4latin_5zlatin-5latin_6zlatin-6latin_7zlatin-7latin_8zlatin-8latin_9zks_c_5601-1987zeuc-kr)zlatin-9latin_10zlatin-10cp949euc_jpeuc_krascii eucgb2312_cnbig5_tw)rrrcD|tk(r td|||ft|<y)a>Add character set properties to the global registry. charset is the input character set, and must be the canonical name of a character set. Optional header_enc and body_enc is either charset.QP for quoted-printable, charset.BASE64 for base64 encoding, charset.SHORTEST for the shortest of qp or base64 encoding, or None for no encoding. SHORTEST is only valid for header_enc. It describes how message headers and message bodies in the input charset are to be encoded. Default is no encoding. Optional output_charset is the character set that the output should be in. Conversions will proceed from input charset, to Unicode, to the output charset when the method Charset.convert() is called. The default is to output in the same character set as the input. Both input_charset and output_charset must have Unicode codec entries in the module's charset-to-codec mapping; use add_codec(charset, codecname) to add codecs the module does not know about. See the codecs module's documentation for more information. z!SHORTEST not allowed for body_encN)SHORTEST ValueErrorCHARSETS)charset header_encbody_encoutput_charsets &/usr/lib64/python3.12/email/charset.pyrrjs).8<==#X~>HWc|t|<y)zAdd a character set alias. alias is the alias name, e.g. latin-1 canonical is the character set's canonical name, e.g. iso-8859-1 N)ALIASES)alias canonicals r.rrs GENr/c|t|<y)a$Add a codec that map characters in the given charset to/from Unicode. charset is the canonical name of a character set. codecname is the name of a Python codec, as appropriate for the second argument to the unicode() built-in, or to the encode() method of a Unicode string. N) CODEC_MAP)r* codecnames r.rrs#Igr/cZ|tk(r|jddS|j|S)Nr#surrogateescape) UNKNOWN8BITencode)stringcodecs r._encoder=s+ }}W&788}}U##r/cJeZdZdZefdZdZdZdZdZ dZ dZ d Z d Z y ) ra@ Map character sets to their email properties. This class provides information about the requirements imposed on email for a specific character set. It also provides convenience routines for converting between character sets, given the availability of the applicable codecs. Given a character set, it will do its best to provide information on how to use that character set in an email in an RFC-compliant way. Certain character sets must be encoded with quoted-printable or base64 when used in email headers or bodies. Certain character sets must be converted outright, and are not allowed in email. Instances of this module expose the following information about a character set: input_charset: The initial character set specified. Common aliases are converted to their `official' email names (e.g. latin_1 is converted to iso-8859-1). Defaults to 7-bit us-ascii. header_encoding: If the character set must be encoded before it can be used in an email header, this attribute will be set to charset.QP (for quoted-printable), charset.BASE64 (for base64 encoding), or charset.SHORTEST for the shortest of QP or BASE64 encoding. Otherwise, it will be None. body_encoding: Same as header_encoding, but describes the encoding for the mail message's body, which indeed may be different than the header encoding. charset.SHORTEST is not allowed for body_encoding. output_charset: Some character sets must be converted before they can be used in email headers or bodies. If the input_charset is one of them, this attribute will contain the name of the charset output will be converted to. Otherwise, it will be None. input_codec: The name of the Python codec used to convert the input_charset to Unicode. If no conversion codec is necessary, this attribute will be None. output_codec: The name of the Python codec used to convert Unicode to the output_charset. If no conversion codec is necessary, this attribute will have the same value as the input_codec. c t|tr|jdn t|d}|j }tj|||_ tj|jttdf\}}}|s |j}||_ ||_tj|||_t j|j|j|_t j|j|j|_y#t$rt j |wxYw)Nr#) isinstancestrr: UnicodeErrorr CharsetErrorlowerr1get input_charsetr)r'BASE64header_encoding body_encodingr-r5 input_codec output_codec)selfrFhencbencconvs r.__init__zCharset.__init__s  5--$$W- #M7 ; &++- $[[ F$<<(:(:)164(@BdD%%D#!%kk$5%==););)-););=%MM$*=*=*.*=*=?) 5%%m4 4 5s .D D?c6|jjSN)rFrDrLs r.__repr__zCharset.__repr__s!!''))r/cLt|t|jk(SrR)rArD)rLothers r.__eq__zCharset.__eq__s4yCJ,,...r/c^|jtk(ry|jtk(rytS)aPReturn the content-transfer-encoding used for body encoding. This is either the string `quoted-printable' or `base64' depending on the encoding used, or it is a function in which case you should call the function with a single argument, the Message object being encoded. The function should then set the Content-Transfer-Encoding header itself to whatever is appropriate. Returns "quoted-printable" if self.body_encoding is QP. Returns "base64" if self.body_encoding is BASE64. Returns conversion function otherwise. zquoted-printablebase64)rIQPrGr rSs r.get_body_encodingzCharset.get_body_encodings,    #%   6 )! !r/c6|jxs |jS)zReturn the output character set. This is self.output_charset if that is not None, otherwise it is self.input_charset. )r-rFrSs r.get_output_charsetzCharset.get_output_charset s ""8d&8&88r/c|jxsd}t||}|j|}||S|j||S)aHeader-encode a string by converting it first to bytes. The type of encoding (base64 or quoted-printable) will be based on this charset's `header_encoding`. :param string: A unicode string for the header. It must be possible to encode this string to bytes using the character set's output codec. :return: The encoded string, with RFC 2047 chrome. r)rKr= _get_encoder header_encode)rLr;r< header_bytesencoder_modules r.r`zCharset.header_encodesN!!/Zvu- **<8  !M++L%@@r/c|jxsd}t||}|j|}t|j|}|j }t |tz}g} g} t||z } |D]} | j| tj| } |jt| |}|| kDsJ| j| s| s| jdn8tj| }t||}| j||| g} t||z } tj| }t||}| j||| S)afHeader-encode a string by converting it first to bytes. This is similar to `header_encode()` except that the string is fit into maximum line lengths as given by the argument. :param string: A unicode string for the header. It must be possible to encode this string to bytes using the character set's output codec. :param maxlengths: Maximum line length iterator. Each element returned from this iterator will provide the next maximum line length. This parameter is used as an argument to built-in next() and should never be exhausted. The maximum line lengths should not count the RFC 2047 chrome. These line lengths are only a hint; the splitter does the best it can. :return: Lines of encoded strings, each with RFC 2047 chrome. r)r*N)rKr=r_rr`r]lenRFC2047_CHROME_LENnextappend EMPTYSTRINGjoin header_lengthpop)rLr; maxlengthsr<rarbencoderr*extralines current_linemaxlen character this_linelength joined_lines r.header_encode_lineszCharset.header_encode_lines%sV$!!/Zvu- **<8.66F))+G 11 j!E)I    *#((6I#11')W2MNF  "\LL&"-"2"2<"@K#*;#>LLL!67 ){ j)E1 "&&|4 {E2  W\*+ r/c||jtk(rtjS|jtk(rtj S|jt k(rctjj|}tj j|}||krtjStj SyrR)rHrGemail base64mimerZ quoprimimer'rj)rLralen64lenqps r.r_zCharset._get_encoderbs   6 )## #  ! !R '## #  ! !X -$$22<@E$$22<@Eu}''''''r/c|s|S|jturJt|tr|j |j }t jj|S|jtur[t|tr|j |j }|jd}t jj|St|tr*|j |j jd}|S)avBody-encode a string by converting it first to bytes. The type of encoding (base64 or quoted-printable) will be based on self.body_encoding. If body_encoding is None, we assume the output charset is a 7bit encoding, so re-encoding the decoded string using the ascii codec produces the correct string version of the content. latin1r#) rIrGr@rAr:r-rxry body_encoderZdecoderz)rLr;s r.rzCharset.body_encodeqsM    '&#&t':':;##//7 7   2 %&#&t':':;]]8,F##//7 7&#&t':':;BB7KMr/N)__name__ __module__ __qualname____doc__DEFAULT_CHARSETrPrTrWr[r]r`rvr_rr/r.rrs=*V&5?B*/"*9A&;z r/r)__all__ functoolsremail.base64mimerxemail.quoprimimeremail.encodersr rZrGr'rerr9rhr)r1r5rrrr=rrr/r.rs  )   Br- Br- Br-   Br-  Br- Br- Br- Br- Br-  Br-! "Br-# $ Br-% &-' ( Fv-) * Fv-+ , Ft 6- .Ft 6/ 0t-v-vw/5 >  |  | | |   |   |  | | | | } } } } }  }! "}# $1 <"   ?8#$llr/__pycache__/utils.cpython-312.pyc000064400000037144152526700320012632 0ustar00 {|j>dZgdZddlZddlZddlZddlZddlZddlZddlZ ddl m Z ddl m Z ddl mZddl mZmZmZddlmZd Zd Zd Zd Zd Zej2d Zej2dZdZdZd'dZdZdZ dZ!dddZ"dZ#dZ$dZ%dZ&d(dZ'd)dZ(d*dZ)dZ*dddZ+d Z,d!Z-d*d"Z.ej2d#ej^Z0d$Z1 d+d%Z2d*d&Z3y),zMiscellaneous utilities.)collapse_rfc2231_value decode_paramsdecode_rfc2231encode_rfc2231 formataddr formatdateformat_datetime getaddresses make_msgid mktime_tz parseaddr parsedate parsedate_tzparsedate_to_datetimeunquoteN)quote) AddressList)r )r r _parsedate_tz)Charsetz, z 'z[][\\()<>@,:;".]z[\\"]cD |jy#t$rYywxYw)z;Return True if s may contain surrogate-escaped binary data.FT)encodeUnicodeEncodeError)ss $/usr/lib64/python3.12/email/utils.py_has_surrogatesr4s%    s  cJ|jdd}|jddS)Nutf-8surrogateescapereplace)rdecode)stringoriginal_bytess r _sanitizer%As( ]]7,=>N  ) 44cV|\}}|jd|rM |jdd}tj|rd}tj d|}|||d|dS|S#t $r7t |tr t|}|j|}|d|dcYSwxYw)aThe inverse of parseaddr(), this takes a 2-tuple of the form (realname, email_address) and returns the string value suitable for an RFC 2822 From, To or Cc header. If the first element of pair is false, then the second element is returned unmodified. The optional charset is the character set that is used to encode realname in case realname is not ASCII safe. Can be an instance of str or a Charset-like object which has a header_encode method. Default is 'utf-8'. asciir"z\\\g<0>z <>) r specialsresearch escapesresubr isinstancestrr header_encode)paircharsetnameaddressquotes encoded_names rrrMsMD' NN7  C KK F  &==T2D$*D&'B B N" 7'3'!'*"006L ,g6 6  7sA((=B('B(c#Kd}d}t|D]!\}}|r |d|zfd}|dk(rd}||f#|r|dfyyw)NrF\T) enumerate)addrposescapechs r_iter_escaped_charsr?nsb C FT?R r " "F 4ZF)O#Dks>Acd|vr|Sd}d}g}t|D]0\}}|dk(s ||}||k7r|j||||dz}d}2|t|kr|j||ddj|S)z Strip real names between quotes.r)rNr)r?appendlenjoin)r;startopen_posresultr<r>s r_strip_quoted_realnamesrH}s $ EH F&t,R 9H$MM$uX"67a- s4y d56l# 776?r&T)strictc|s3tjd|D}t|}|jS|Dcgc] }t |}}t |}tj|}t|}t |j}d}|D]$}t|}|d|jdzz }&t||k7rdgS|Scc}w)zReturn a list of (REALNAME, EMAIL) or ('','') for each fieldvalue. When parsing fails for a fieldvalue, a 2-tuple of ('', '') is returned in its place. If strict is true, use a strict parser which rejects malformed inputs. c32K|]}t|yw)Nr0).0vs r zgetaddresses..s:kc!fksrrA,rr) COMMASPACErD _AddressList addresslistr0_pre_parse_validation_post_parse_validationrHcountrC) fieldvaluesrIallarNr;rGns rr r s$ oo:k::  }}#./;a3q6;K/' 4K ??; 'DTA #AMM 2F A  $A & Q    6{az M%0sC ct|}d}t|D]"\}}|dk(r|dz }|dk(s|dz}|dks"y|dk(S)Nr(rA)F)rHr?)r;opensr<r>s r_check_parenthesisr`sZ "4 (D E&t,R 9 QJE 3Y QJEqy - QJr&cTg}|D] }t|sd}|j|"|S)Nz('', ''))r`rB)email_header_fieldsaccepted_valuesrNs rrUrUs4O !!$Aq!! r&cLg}|D]}d|dvrd}|j||S)N[rArQ)rB)parsed_email_header_tuplesrcrNs rrVrVs9O( !A$;Aq!( r&c `dgd|d|dgd|ddz |d|d|d |d |fzS) Nz"%s, %02d %s %04d %02d:%02d:%02d %s)MonTueWedThuFriSatSun) JanFebMarAprMayJunJulAugSepOctNovDecrAr) timetuplezones r_format_timetuple_and_zonersZ /9)A,G!  33->-B-B BDE E  {{4  %c4 00r&cttjdz}tj}t j d}|d}nd|z}|t j}d|||||fz}|S)a{Returns a string suitable for RFC 2822 compliant Message-ID, e.g: <142480216486.20800.16526388040877946887@nightshade.la.mastaler.com> Optional idstring if given is a string used to strengthen the uniqueness of the message id. Optional domain if given provides the portion of the message id after the '@'. It defaults to the locally defined hostname. d@r.z<%d.%d.%d%s@%s>)introsgetpidrandom getrandbitssocketgetfqdn)idstringdomainrpidrandintmsgids rr r "sr$))+c/"G ))+C  $G> ~! #w& I IE Lr&c t|}|tdt|z|^}}|tj|ddStj|dddtjtj |iS)Nz!Invalid date value or format "%s"ror)seconds)rrr0rr timedelta)dataparsed_date_tzdtupletzs rrr9s"4(N># 3<<#4q9$$VT2::5#F F >># 3<<#4q9  Jr&cX|jtd}t|dkrdd|fS|S)z#Decode string according to RFC 2231rpN)splitTICKrC)rpartss rrros. GGD! E 5zQT1} Lr&cvtjj|d|xsd}|||S|d}|d|d|S)zEncode string according to RFC 2231. If neither charset nor language is given, then s is returned as-is. If charset is given but not language, the string is encoded using the empty string for language. rr()safeencodingr)urllibparser)rr3languages rrrwsK  120B7CA8+ (A ..r&z&^(?P\w+)\*((?P[0-9]+)\*?)?$c|dg}i}|ddD]\}}|jd}t|}tj|}|rG|j dd\}}| t |}|j |gj|||f|j|dt|zf|r|jD]\}}g}d} |j|D]<\}} }|r#tjj| d } d } |j| >ttj|}| r)t|\} } }|j|| | d|zff|j|d|zf|S) zDecode parameters list according to RFC 2231. params is a sequence of 2-tuples containing (param name, string value). rrAN*r4numz"%s"Fzlatin-1)rT)rrrfc2231_continuationmatchgroupr setdefaultrBritemssortrr EMPTYSTRINGrDr) params new_paramsrfc2231_paramsr4valueencodedmor continuationsextendedrr3rs rrrs )JNabz e--$ ! ' ' - /ID##h  % %dB / 6 6UG7L M   tVeEl%:; <"#1#7#7#9 D-EH    $1Q ,,Q,CA#H Q$1+**512E+9%+@(5!!4'8Ve^)L"MN!!4%"89/$:0 r&ct|trt|dk7r t|S|\}}}||}t |d} t |||S#t $rt|cYSwxYw)Nr}zraw-unicode-escape)r/tuplerCrbytesr0 LookupError)rerrorsfallback_charsetr3rtextrawbytess rrrst eU #s5zQu~$GXt#T/0H8Wf-- t}s AA%$A%c|ddl}|jddd|tjj}|j S)a}Return local time as an aware datetime object. If called without arguments, return current time. Otherwise *dt* argument should be a datetime instance, and it is converted to the local time zone according to the system time zone database. If *dt* is naive (that is, dt.tzinfo is None), it is assumed to be in local time. The isdst parameter is ignored. Nrz$The 'isdst' parameter to 'localtime'z>{name} is deprecated and slated for removal in Python {remove})r})messageremove)warnings _deprecatedrrr)risdstrs rrrsP  2T    z    " " $ ==?r&)r)NFF)F)NN)r!zus-ascii)4__doc____all__rrerrrr urllib.parseremail._parseaddrrrrSr r rr email.charsetrrRr UEMPTYSTRINGCRLFrcompiler+r-rr%rr?rHsupports_strict_parsingr r`rUrVrrrr rr rrrASCIIrrrrrr&rrs  $ "8&CC"       RZZ+ , BJJx  5B 2(,)X  ':1&.F#> /"rzz"KHH.`*3,64r&__pycache__/policy.cpython-312.opt-1.pyc000064400000027034152526700320013725 0ustar00 {|jv)PdZddlZddlZddlmZmZmZmZddlm Z ddl m Z ddl m Z ddlmZgdZej"d ZeGd d eZeZe`ej-d Zej-dZej-ddZej-d Zy)zcThis will be the home for the policy that hooks in the new code that adds all the email6 features. N)PolicyCompat32compat32_extend_docstrings)_has_surrogates)HeaderRegistry)raw_data_manager) EmailMessage)rrr EmailPolicydefaultstrictSMTPHTTPz\n|\r\n?cleZdZdZeZdZdZeZ e Z fdZ dZ dZdZdZd Zd Zd d ZxZS) r aQ + PROVISIONAL The API extensions enabled by this policy are currently provisional. Refer to the documentation for details. This policy adds new header parsing and folding algorithms. Instead of simple strings, headers are custom objects with custom attributes depending on the type of the field. The folding algorithm fully implements RFCs 2047 and 5322. In addition to the settable attributes listed above that apply to all Policies, this policy adds the following additional attributes: utf8 -- if False (the default) message headers will be serialized as ASCII, using encoded words to encode any non-ASCII characters in the source strings. If True, the message headers will be serialized using utf8 and will not contain encoded words (see RFC 6532 for more on this serialization format). refold_source -- if the value for a header in the Message object came from the parsing of some source, this attribute indicates whether or not a generator should refold that value when transforming the message back into stream form. The possible values are: none -- all source values use original folding long -- source values that have any line that is longer than max_line_length will be refolded all -- all values are refolded. The default is 'long'. header_factory -- a callable that takes two arguments, 'name' and 'value', where 'name' is a header field name and 'value' is an unfolded header field value, and returns a string-like object that represents that header. A default header_factory is provided that understands some of the RFC5322 header field types. (Currently address fields and date fields have special treatment, while all other fields are treated as unstructured. This list will be completed before the extension is marked stable.) content_manager -- an object with at least two methods: get_content and set_content. When the get_content or set_content method of a Message object is called, it calls the corresponding method of this object, passing it the message object as its first argument, and any arguments or keywords that were passed to it as additional arguments. The default content_manager is :data:`~email.contentmanager.raw_data_manager`. Flongc jd|vrtj|dtt|di|y)Nheader_factory)object __setattr__rsuper__init__)selfkw __class__s %/usr/lib64/python3.12/email/policy.pyrzEmailPolicy.__init__]s3 2 %   t%5~7G H 2c4|j|jS)z+ The implementation for this class returns the max_count attribute from the specialized header class that would be used to construct a header of type 'name'. )r max_count)rnames rheader_max_countzEmailPolicy.header_max_countds ""4(222rc|djdd\}}dj|g|ddjd}||jdfS)a]+ The name is parsed as everything up to the ':' and returned unmodified. The value is determined by stripping leading whitespace off the remainder of the first line joined with all subsequent lines, and stripping any trailing carriage return or linefeed characters. (This is the same as Compat32). r:Nz  )splitjoinlstriprstrip)r sourcelinesr values rheader_source_parsezEmailPolicy.header_source_parsevsY"!n**32 e1QR1299)Dell6*++rct|dr/|jj|jk(r||fSt|tr't |j dkDr td||j||fS)a+ The name is returned unchanged. If the input value has a 'name' attribute and it matches the name ignoring case, the value is returned unchanged. Otherwise the name and value are passed to header_factory method, and the resulting custom header object is returned as the value. In this case a ValueError is raised if the input value contains CR or LF characters. r r$zDHeader values may not contain linefeed or carriage return characters) hasattrr lower isinstancestrlen splitlines ValueErrorrrr r,s rheader_store_parsezEmailPolicy.header_store_parses} 5& !ejj&6&6&8DJJL&H%= eS !c%*:*:*<&=a&?=> >d))$677rct|dr|Sdjtj|}|j ||S)ai+ If the value has a 'name' attribute, it is returned to unmodified. Otherwise the name and the value with any linesep characters removed are passed to the header_factory method, and the resulting custom header object is returned. Any surrogateescaped bytes get turned into the unicode unknown-character glyph. r r%)r/r(linesep_splitterr'rr6s rheader_fetch_parsezEmailPolicy.header_fetch_parses@ 5& !L(..u56""4//rc*|j||dS)a + Header folding is controlled by the refold_source policy setting. A value is considered to be a 'source value' if and only if it does not have a 'name' attribute (having a 'name' attribute means it is a header object of some sort). If a source value needs to be refolded according to the policy, it is converted into a custom header object by passing the name and the value with any linesep characters removed to the header_factory method. Folding of a custom header object is done by calling its fold method with the current policy. Source values are split into lines using splitlines. If the value is not to be refolded, the lines are rejoined using the linesep from the policy and returned. The exception is lines containing non-ascii binary data. In that case the value is refolded regardless of the refold_source setting, which causes the binary data to be CTE encoded using the unknown-8bit charset. T refold_binary)_foldr6s rfoldzEmailPolicy.folds&zz$Tz::rc|j|||jdk(}|jrdnd}|j|dS)a+ The same as fold if cte_type is 7bit, except that the returned value is bytes. If cte_type is 8bit, non-ASCII binary data is converted back into bytes. Headers with binary data are not refolded, regardless of the refold_header setting, since there is no way to know whether the binary data consists of single byte characters or multibyte characters. If utf8 is true, headers are encoded to utf8, otherwise to ascii with non-ASCII unicode rendered as encoded words. 7bitr<utf8asciisurrogateescape)r>cte_typerBencode)rr r,foldedcharsets r fold_binaryzEmailPolicy.fold_binarys@D%t}}f7LM II&7}}W&788rct|dr|j|S|jr |jntjt j |}|jdk(xsN|jdk(xr=|xr t|dt|zdzkDxstfd|ddD}|s+|js|j }n |r t|}|r1|j|d j|j|S|d z|jj|z|jzS) Nr )policyallrrc3:K|]}t|kDyw)N)r3).0xmaxlens r z$EmailPolicy._fold..s<)QQ&)sr$r%z: )r/r?max_line_lengthsysmaxsizer9r' refold_sourcer3anyrBisasciirrr(linesep)rr r,r=linesrefoldrQs @rr>zEmailPolicy._folds( 5& !::T:* *)-)=)=%%3;; &&u-$$->$$.>As58}SY6q86A=<%)<<  99"]]_,(/ &&tRWWU^<AAAN Nd{T\\..u55 DDr)F)__name__ __module__ __qualname____doc__r message_factoryrBrVrrr content_managerrr!r-r7r:r?rIr> __classcell__)rs@rr r sP8t#O DM#%N&O3$ ,8& 0;*9$Err T)raise_on_defectr&)rY)rYrS)rB)r_rerTemail._policybaserrrr email.utilsremail.headerregistryremail.contentmanagerr email.messager __all__compiler9r r rcloner rrSMTPUTF8rrrrns LL'A1& 2::k*DE&DEDEN -  t ,}}V}$}}VT}: ::4: r__pycache__/__init__.cpython-312.pyc000064400000003601152526700320013220 0ustar00 {|j(dZgdZdZdZdZdZy)z?A package for parsing, handling, and generating email messages.) base64mimecharsetencoderserrors feedparser generatorheader iteratorsmessagemessage_from_filemessage_from_binary_filemessage_from_stringmessage_from_bytesmimeparser quoprimimeutilsc<ddlm}||i|j|S)zvParse a string into a Message object model. Optional _class and strict are passed to the Parser constructor. Parser) email.parserrparsestr)sargskwsrs '/usr/lib64/python3.12/email/__init__.pyr r s" $ 4 3  ( ( ++c<ddlm}||i|j|S)z|Parse a bytes string into a Message object model. Optional _class and strict are passed to the Parser constructor. r BytesParser)rr parsebytes)rrrr s rrr's" )  $ $ / / 22rc<ddlm}||i|j|S)zRead a file and parse its contents into a Message object model. Optional _class and strict are passed to the Parser constructor. rr)rrparse)fprrrs rr r /s" $ 4 3  % %b ))rc<ddlm}||i|j|S)zRead a binary file and parse its contents into a Message object model. Optional _class and strict are passed to the Parser constructor. rr)rr r#)r$rrr s rr r 7s" )  $ $ * *2 ..rN)__doc____all__r rr r rrr)s& F 0,3*/r__pycache__/_parseaddr.cpython-312.opt-1.pyc000064400000055317152526700320014537 0ustar00 {|jEdZgdZddlZddlZdZdZdZgdZgdZddddd d d d d d d d dd dZ dZ dZ dZ dZ dZGddZGddeZy)zcEmail address parsing code. Lifted directly from rfc822.py. This should eventually be rewritten. ) mktime_tz parsedate parsedate_tzquoteN z, )janfebmaraprmayjunjulaugsepoctnovdecjanuaryfebruarymarchaprilr junejulyaugust septemberoctobernovemberdecember)montuewedthufrisatsunipii iiDi)UTUTCGMTZASTADTESTEDTCSTCDTMSTMDTPSTPDTcHt|}|sy|dd|d<t|S)zQConvert a date string to a time tuple. Accounts for military timezones. N r) _parsedate_tztuple)dataress )/usr/lib64/python3.12/email/_parseaddr.pyrr-s0  C  1v~A :c |sy|j}|sy|djds|djtvr|d=n'|dj d}|dk\r|d|dzd|d<t |dk(r*|djd}t |dk(r||ddz}t |dk(rP|d}|j d}|d k(r|j d}|dkDr|d|||dg|ddn|jd t |d kry|dd }|\}}}}}|r|r|sy|j}|tvr||j}}|tvrytj|dz}|d kDr|d z}|d dk(r|dd }|j d }|dkDr||}}|d dk(r|dd }|sy|djs||}}|d dk(r|dd }|jd }t |dk(r|\} } d} nkt |dk(r|\} } } nVt |dk(rGd|dvr@|djd}t |dk(r|\} } d} nt |dk(r|\} } } nyy t|}t|}t| } t| } t| } |dkr|dkDr|dz }n|dz }d} |j}|tvr t|} n$ t|} | dk(r|jdrd} | r!| dkrd } | } nd} | | dzdz| dzdzzz} |||| | | ddd | g S#t$rYywxYw#t$rYawxYw)aConvert date to extended time tuple. The last (additional) element is the time zone offset in seconds, except if the timezone was specified as -0000. In that case the last element is None. This indicates a UTC timestamp that explicitly declaims knowledge of the source timezone, as opposed to a +0000 timestamp that indicates the source timezone really was UTC. Nr,-+r :0.dDilii<)splitendswithlower _daynamesrfindlenfindappend _monthnamesindexisdigitint ValueErrorupper _timezones startswith)r9istuffsddmmyytmtzthhtmmtsstzoffsettzsigns r;r7r79s  :: 2wH Q;2==-H a<F yHFx}d2hnb5HHI BS#q!R ::E *   s$+7L. L=. L:9L:= M M cFt|}t|tr|ddS|S)z&Convert a time string to a time tuple.Nr6)r isinstancer8r9ts r;rrs&TA!U!u r<c||dtj|dddzStj|}||dz S)zETurn a 10-tuple as returned by parsedate_tz() into a POSIX timestamp.r6N)rD)timemktimecalendartimegmrms r;rrsA Aw{{48e+,, OOD !47{r<cF|jddjddS)zPrepare string to be used in a quoted string. Turns backslash and double quote characters into quoted pairs. These are the only characters that need to be quoted inside a quoted string. Does not add the surrounding double quotes. \z\\"z\")replace)strs r;rrs" ;;tV $ , ,S% 88r<cbeZdZdZdZdZdZdZdZdZ dZ dd Z d Z d Z d ZddZdZy ) AddrlistClassaAddress parser class by Ben Escoto. To understand what this class does, it helps to have a copy of RFC 2822 in front of you. Note: this class interface is deprecated and may be removed in the future. Use email.utils.AddressList instead. c,d|_d|_d|_d|_|j|jz|_|j|jz|jz|_|j j dd|_||_g|_ y)zInitialize a new instance. `field' is an unparsed address header field, containing one or more addresses. z ()<>@,:;."[]rz z rJrN) specialsposLWSCRFWSatomendsrx phraseendsfield commentlistselfrs r;__init__zAddrlistClass.__init__sz ( 88dgg% 0477: --//R8 r<cJg}|jt|jkr|j|j|jdzvrY|j|jdvr(|j |j|j|xjdz c_nG|j|jdk(r*|j j |j nn#|jt|jkrtj|S)z&Skip white space and extract comments.z r?() r~rSrrrUr getcomment EMPTYSTRINGjoin)rwslists r;gotonextzAddrlistClass.gotonextshhTZZ(zz$((#txx&'88::dhh'v5MM$**TXX"67A DHH%,  ''(9:hhTZZ(''r<cg}|jt|jkrL|j}|r||z }n|j d|jt|jkrL|S)zVParse all addresses. Returns a list containing all of the addresses. )rr)r~rSr getaddressrU)rresultads r; getaddrlistzAddrlistClass.getaddrlists^ hhTZZ("B"  h' hhTZZ(  r<cg|_|j|j}|j}|j}|jg}|jt |j k\r*|rft j|j|dfg}n?|j |jdvrB||_||_|j}t j|j|fg}n|j |jdk(rg}t |j }|xjdz c_|jt |j krw|j|j|kr3|j |jdk(r|xjdz c_n%||jz}|jt |j krn|j |jdk(rp|j}|jr;t j|dzdj|jzd z|fg}n{t j||fg}nb|r&t j|j|dfg}n:|j |j|jvr|xjdz c_|j|jt |j kr1|j |jd k(r|xjdz c_|S) zParse the next address.rz.@rGr?;) rrr~ getphraselistrSrSPACEr getaddrspecr getrouteaddrr})roldposoldclplist returnlistaddrspecfieldlen routeaddrs r;rzAddrlistClass.getaddress s   ""$  88s4:: &$zz$*:*:;U1XFG ZZ !T )DH$D '')H ::d&6&67BCJ ZZ !S (J4::H HHMH((S_, 88h&4::dhh+?3+FHHMH'$//*;; ((S_,ZZ !S ())+I$zz%047"xx(8(89 :#*E HHMHr<c|j|jdk7ryd}|xjdz c_|jd}|jt|jkr |r|j d}n|j|jdk(r|xjdz c_ |S|j|jdk(r|xjdz c_d}nZ|j|jd k(r|xjdz c_n(|j }|xjdz c_ |S|j|jt|jkr |S) zParse a route address (Return-path value). This method just skips all the route stuff and returns the addrspec. rNFr?r>@TrG)rr~rrS getdomainr)r expectrouteadlists r;rzAddrlistClass.getrouteaddrGs& ::dhh 3 &   A  hhTZZ( # DHH%,A  DHH%,A " DHH%,A ))+A   MMO!hhTZZ($ r<cg}|j|jt|jkrgd}|j|jdk(rN|r#|dj s|j |j d|xjdz c_d}n|j|jdk(r,|j dt|jznj|j|j|jvr&|r#|dj s|j nh|j |j|j}|r|r|j ||jt|jkrg|jt|jk\s|j|jdk7rtj|S|j d|xjdz c_|j|j}|stStj||zS) zParse an RFC 2822 addr-spec.TrJrDr?Frwz"%s"r)rr~rSrstrippoprUrgetquotergetatomrrr)raslist preserve_wswsdomains r;rzAddrlistClass.getaddrspecgs hhTZZ(Kzz$((#s*&*"2"2"4JJL c"A # DHH%, fuT]]_'==>DHH%6&*"2"2"4JJL dlln-Br b!%hhTZZ(( 88s4:: &$**TXX*>#*E##F+ + c A  ! '&00r<cg}|jt|jkr|j|j|jvr|xjdz c_n,|j|jdk(r*|jj |j n|j|jdk(r |j |jn|j|jdk(r'|xjdz c_|j dng|j|jdk(rtS|j|j|jvrnC|j |j|jt|jkrtj|S)z-Get the complete domain name from an address.r?r[rJr) r~rSrrrrUrgetdomainliteralrrrr)rsdlists r;rzAddrlistClass.getdomains=hhTZZ(zz$((#txx/A DHH%,  ''(9:DHH%, d3356DHH%,A  c"DHH%,#"DHH%6 dlln-#hhTZZ($''r<c|j|j|k7rydg}d}|xjdz c_|jt|jkr|r+|j|j|jd}n|j|j|vr|xjdz c_n|r<|j|jdk(r |j|j |j|jdk(rd}n(|j|j|j|xjdz c_|jt|jkrt j |S)aParse a header fragment delimited by special characters. `beginchar' is the start character for the fragment. If self is not looking at an instance of `beginchar' then getdelimited returns the empty string. `endchars' is a sequence of allowable end-delimiting characters. Parsing stops when one of these is encountered. If `allowcomments' is non-zero, embedded RFC 2822 comments are allowed within the parsed fragment. rFr?rrvT)rr~rSrUrrr)r begincharendchars allowcommentsslistrs r; getdelimitedzAddrlistClass.getdelimiteds% ::dhh 9 , A hhTZZ( TZZ12DHH%1A 4::dhh#73#> T__./DHH%- TZZ12 HHMHhhTZZ( &&r<c(|jdddS)z1Get a quote-delimited fragment from self's field.rwz" Frrs r;rzAddrlistClass.getquotes  eU33r<c(|jdddS)z7Get a parenthesis-delimited fragment from self's field.rz) Trrs r;rzAddrlistClass.getcomments  eT22r<c.d|jdddzS)z!Parse an RFC 2822 domain-literal.z[%s]rz] Frrs r;rzAddrlistClass.getdomainliterals))#ue<<rs     I > AQA$$$$$   z;z9kkZ -'--'r<__pycache__/_policybase.cpython-312.pyc000064400000044314152526700320013760 0ustar00 {|j<dZddlZddlmZddlmZddlmZgdZGddZ d Z d Z Gd d e ej Z e Gdde ZeZy)zwPolicy framework for the email package. Allows fine grained feature control of how the package parses and emits data. N)header)charset)_has_surrogates)PolicyCompat32compat32c:eZdZdZfdZdZdZdZdZxZ S) _PolicyBaseaPolicy Object basic framework. This class is useless unless subclassed. A subclass should define class attributes with defaults for any values that are to be managed by the Policy object. The constructor will then allow non-default values to be set for these attributes at instance creation time. The instance will be callable, taking these same attributes keyword arguments, and returning a new instance identical to the called instance except for those values changed by the keyword arguments. Instances may be added, yielding new instances with any non-default values from the right hand operand overriding those in the left hand operand. That is, A + B == A() The repr of an instance can be used to reconstruct the object if and only if the repr of the values can be used to reconstruct those values. c |jD]T\}}t||rtt|||'t dj ||jjy)zCreate new Policy, possibly overriding some defaults. See class docstring for a list of overridable attributes. *{!r} is an invalid keyword argument for {}N) itemshasattrsuperr __setattr__ TypeErrorformat __class____name__)selfkwnamevaluers */usr/lib64/python3.12/email/_policybase.py__init__z_PolicyBase.__init__)s^ 88:KD%tT"k$3D%@@GGdnn55788 &c|jjDcgc]\}}dj||}}}dj|jjdj |Scc}}w)Nz{}={!r}z{}({})z, )__dict__r rrrjoin)rrrargss r__repr__z_PolicyBase.__repr__7sh$(MM$7$7$9<$9[T5!!$.$9 <t~~66 $HH>: ==..0KD%   y$ 6188:KD%4&@GGdnn55788   y$ 6 & rct||rd}nd}t|j|jj|)Nz'{!r} object attribute {!r} is read-onlyz!{!r} object has no attribute {!r})rAttributeErrorrrr)rrrmsgs rrz_PolicyBase.__setattr__Ns6 4 ;C5CSZZ(?(?FGGrc:|jdi|jS)zNon-default values from right operand override those from left. The object returned is a new instance of the subclass. )r&r)rothers r__add__z_PolicyBase.__add__Us tzz+ENN++r) r __module__ __qualname____doc__rr r&rr- __classcell__)rs@rr r s#* 8I $H,rr cf|jddd}|jddd}|dz|zS)N r)rsplitsplit)doc added_docs r _append_docr9^s; **T1 a Ca(+I : !!rc|jrM|jjdr2t|jdj|j|_|jj D]{\}}|js|jjds/d|jDD]7}t t ||d}|st||j|_{}|S)N+rc3JK|]}|jD]}|yw)N)mro).0basecs r z%_extend_docstrings..hsFMD488:aa:aMs!#r0)r0 startswithr9 __bases__rr getattr)clsrr%r@r7s r_extend_docstringsrFcs {{s{{--c2!#--"2":":CKKH ll((* d <' in front of them. This is used when the message is being serialized by a generator. Default: False. message_factory -- the class to use to create new message objects. If the value is None, the default is Message. verify_generated_headers -- if true, the generator verifies that each header they are properly folded, so that a parser won't treat it as multiple headers, start-of-body, or part of another header. This is a check against custom Header & fold() implementations. Fr38bitNNTcD|jr||j||y)aZBased on policy, either raise defect or call register_defect. handle_defect(obj, defect) defect should be a Defect subclass, but in any case must be an Exception subclass. obj is the object on which the defect should be registered if it is not raised. If the raise_on_defect is True, the defect is raised as an error, otherwise the object and the defect are passed to register_defect. This method is intended to be called by parsers that discover defects. The email package parsers always call it with Defect instances. N)raise_on_defectregister_defectrobjdefects r handle_defectzPolicy.handle_defects"   L S&)rc:|jj|y)aRecord 'defect' on 'obj'. Called by handle_defect if raise_on_defect is False. This method is part of the Policy API so that Policy subclasses can implement custom defect handling. The default implementation calls the append method of the defects attribute of obj. The objects used by the email package by default that get passed to this method will always have a defects attribute with an append method. N)defectsappendrMs rrLzPolicy.register_defects 6"rcy)a[Return the maximum allowed number of headers named 'name'. Called when a header is added to a Message object. If the returned value is not 0 or None, and there are already a number of headers with the name 'name' equal to the value returned, a ValueError is raised. Because the default behavior of Message's __setitem__ is to append the value to the list of headers, it is easy to create duplicate headers without realizing it. This method allows certain headers to be limited in the number of instances of that header that may be added to a Message programmatically. (The limit is not observed by the parser, which will faithfully produce as many headers as exist in the message being parsed.) The default implementation returns None for all header names. Nr+)rrs rheader_max_countzPolicy.header_max_counts"rct)aZGiven a list of linesep terminated strings constituting the lines of a single header, return the (name, value) tuple that should be stored in the model. The input lines should retain their terminating linesep characters. The lines passed in by the email package may contain surrogateescaped binary data. NotImplementedError)r sourceliness rheader_source_parsezPolicy.header_source_parse "!rct)zGiven the header name and the value provided by the application program, return the (name, value) that should be stored in the model. rWrrrs rheader_store_parsezPolicy.header_store_parses "!rct)awGiven the header name and the value from the model, return the value to be returned to the application program that is requesting that header. The value passed in by the email package may contain surrogateescaped binary data if the lines were parsed by a BytesParser. The returned value should not contain any surrogateescaped data. rWr]s rheader_fetch_parsezPolicy.header_fetch_parses "!rct)aGiven the header name and the value from the model, return a string containing linesep characters that implement the folding of the header according to the policy controls. The value passed in by the email package may contain surrogateescaped binary data if the lines were parsed by a BytesParser. The returned value should not contain any surrogateescaped data. rWr]s rfoldz Policy.folds "!rct)a%Given the header name and the value from the model, return binary data containing linesep characters that implement the folding of the header according to the policy controls. The value passed in by the email package may contain surrogateescaped binary data. rWr]s r fold_binaryzPolicy.fold_binary r[r)rr.r/r0rKlinesepcte_typemax_line_length mangle_from_message_factoryverify_generated_headersrPrLrUabcabstractmethodrZr^r`rbrdr+rrrrps5nOGHOLO#*& #& "" ""  ""  " " ""rr) metaclassc>eZdZdZdZdZdZdZdZdZ dZ d Z y ) rz+ This particular policy is the backward compatibility Policy. It replicates the behavior of the email package version 5.1. Tct|ts|St|r&tj|t j |S|S)Nr header_name) isinstancestrrrHeader_charset UNKNOWN8BITr]s r_sanitize_headerzCompat32._sanitize_header!s@%%L 5 !==0D0D-13 3Lrc|djdd\}}dj|g|ddjd}||jdfS)a4+ The name is parsed as everything up to the ':' and returned unmodified. The value is determined by stripping leading whitespace off the remainder of the first line joined with all subsequent lines, and stripping any trailing carriage return or linefeed characters. r:r4Nz z )r6rlstriprstrip)rrYrrs rrZzCompat32.header_source_parse-sY"!n**32 e1QR1299)Dell6*++rc ||fS)z>+ The name and value are returned unmodified. r+r]s rr^zCompat32.header_store_parse9se}rc&|j||S)z+ If the value contains binary data, it is converted into a Header object using the unknown-8bit charset. Otherwise it is returned unmodified. )rwr]s rr`zCompat32.header_fetch_parse?s $$T511rc*|j||dS)a+ Headers are folded using the Header folding algorithm, which preserves existing line breaks in the value, and wraps each resulting line to the max_line_length. Non-ASCII binary data are CTE encoded using the unknown-8bit charset. Tsanitize)_foldr]s rrbz Compat32.foldFszz$z55rch|j|||jdk(}|jddS)a+ Headers are folded using the Header folding algorithm, which preserves existing line breaks in the value, and wraps each resulting line to the max_line_length. If cte_type is 7bit, non-ascii binary data is CTE encoded using the unknown-8bit charset. Otherwise the original source header is used, with its existing line breaks and/or binary data. 7bitrasciisurrogateescape)rrfencode)rrrfoldeds rrdzCompat32.fold_binaryPs3D%$--2GH}}W&788rcg}|jd|zt|tr`t|r=|r't j |t j|}n.|j|d}nt j ||}n|}|Fd}|j |j}|j|j|j||j|jdj|S)Nz%s: rp)rqr)re maxlinelenrz) rSrrrsrrrtrurvrgrrer)rrrrpartshrs rrzCompat32._fold\s Vd]# eS !u% e.6.B.B268ALL'AMM%T:A =J##/!11 LL$,,:N O T\\"wwu~rN) rr.r/r0rhrwrZr^r`rbrdrr+rrrrs1 L  , 26 9rr)r0rkemailrrru email.utilsr__all__r r9rFABCMetarrrr+rrrss  %' I,I,X" d"[CKKd"NcvccL :r__pycache__/policy.cpython-312.pyc000064400000027034152526700320012766 0ustar00 {|jv)PdZddlZddlZddlmZmZmZmZddlm Z ddl m Z ddl m Z ddlmZgdZej"d ZeGd d eZeZe`ej-d Zej-dZej-ddZej-d Zy)zcThis will be the home for the policy that hooks in the new code that adds all the email6 features. N)PolicyCompat32compat32_extend_docstrings)_has_surrogates)HeaderRegistry)raw_data_manager) EmailMessage)rrr EmailPolicydefaultstrictSMTPHTTPz\n|\r\n?cleZdZdZeZdZdZeZ e Z fdZ dZ dZdZdZd Zd Zd d ZxZS) r aQ + PROVISIONAL The API extensions enabled by this policy are currently provisional. Refer to the documentation for details. This policy adds new header parsing and folding algorithms. Instead of simple strings, headers are custom objects with custom attributes depending on the type of the field. The folding algorithm fully implements RFCs 2047 and 5322. In addition to the settable attributes listed above that apply to all Policies, this policy adds the following additional attributes: utf8 -- if False (the default) message headers will be serialized as ASCII, using encoded words to encode any non-ASCII characters in the source strings. If True, the message headers will be serialized using utf8 and will not contain encoded words (see RFC 6532 for more on this serialization format). refold_source -- if the value for a header in the Message object came from the parsing of some source, this attribute indicates whether or not a generator should refold that value when transforming the message back into stream form. The possible values are: none -- all source values use original folding long -- source values that have any line that is longer than max_line_length will be refolded all -- all values are refolded. The default is 'long'. header_factory -- a callable that takes two arguments, 'name' and 'value', where 'name' is a header field name and 'value' is an unfolded header field value, and returns a string-like object that represents that header. A default header_factory is provided that understands some of the RFC5322 header field types. (Currently address fields and date fields have special treatment, while all other fields are treated as unstructured. This list will be completed before the extension is marked stable.) content_manager -- an object with at least two methods: get_content and set_content. When the get_content or set_content method of a Message object is called, it calls the corresponding method of this object, passing it the message object as its first argument, and any arguments or keywords that were passed to it as additional arguments. The default content_manager is :data:`~email.contentmanager.raw_data_manager`. Flongc jd|vrtj|dtt|di|y)Nheader_factory)object __setattr__rsuper__init__)selfkw __class__s %/usr/lib64/python3.12/email/policy.pyrzEmailPolicy.__init__]s3 2 %   t%5~7G H 2c4|j|jS)z+ The implementation for this class returns the max_count attribute from the specialized header class that would be used to construct a header of type 'name'. )r max_count)rnames rheader_max_countzEmailPolicy.header_max_countds ""4(222rc|djdd\}}dj|g|ddjd}||jdfS)a]+ The name is parsed as everything up to the ':' and returned unmodified. The value is determined by stripping leading whitespace off the remainder of the first line joined with all subsequent lines, and stripping any trailing carriage return or linefeed characters. (This is the same as Compat32). r:Nz  )splitjoinlstriprstrip)r sourcelinesr values rheader_source_parsezEmailPolicy.header_source_parsevsY"!n**32 e1QR1299)Dell6*++rct|dr/|jj|jk(r||fSt|tr't |j dkDr td||j||fS)a+ The name is returned unchanged. If the input value has a 'name' attribute and it matches the name ignoring case, the value is returned unchanged. Otherwise the name and value are passed to header_factory method, and the resulting custom header object is returned as the value. In this case a ValueError is raised if the input value contains CR or LF characters. r r$zDHeader values may not contain linefeed or carriage return characters) hasattrr lower isinstancestrlen splitlines ValueErrorrrr r,s rheader_store_parsezEmailPolicy.header_store_parses} 5& !ejj&6&6&8DJJL&H%= eS !c%*:*:*<&=a&?=> >d))$677rct|dr|Sdjtj|}|j ||S)ai+ If the value has a 'name' attribute, it is returned to unmodified. Otherwise the name and the value with any linesep characters removed are passed to the header_factory method, and the resulting custom header object is returned. Any surrogateescaped bytes get turned into the unicode unknown-character glyph. r r%)r/r(linesep_splitterr'rr6s rheader_fetch_parsezEmailPolicy.header_fetch_parses@ 5& !L(..u56""4//rc*|j||dS)a + Header folding is controlled by the refold_source policy setting. A value is considered to be a 'source value' if and only if it does not have a 'name' attribute (having a 'name' attribute means it is a header object of some sort). If a source value needs to be refolded according to the policy, it is converted into a custom header object by passing the name and the value with any linesep characters removed to the header_factory method. Folding of a custom header object is done by calling its fold method with the current policy. Source values are split into lines using splitlines. If the value is not to be refolded, the lines are rejoined using the linesep from the policy and returned. The exception is lines containing non-ascii binary data. In that case the value is refolded regardless of the refold_source setting, which causes the binary data to be CTE encoded using the unknown-8bit charset. T refold_binary)_foldr6s rfoldzEmailPolicy.folds&zz$Tz::rc|j|||jdk(}|jrdnd}|j|dS)a+ The same as fold if cte_type is 7bit, except that the returned value is bytes. If cte_type is 8bit, non-ASCII binary data is converted back into bytes. Headers with binary data are not refolded, regardless of the refold_header setting, since there is no way to know whether the binary data consists of single byte characters or multibyte characters. If utf8 is true, headers are encoded to utf8, otherwise to ascii with non-ASCII unicode rendered as encoded words. 7bitr<utf8asciisurrogateescape)r>cte_typerBencode)rr r,foldedcharsets r fold_binaryzEmailPolicy.fold_binarys@D%t}}f7LM II&7}}W&788rct|dr|j|S|jr |jntjt j |}|jdk(xsN|jdk(xr=|xr t|dt|zdzkDxstfd|ddD}|s+|js|j }n |r t|}|r1|j|d j|j|S|d z|jj|z|jzS) Nr )policyallrrc3:K|]}t|kDyw)N)r3).0xmaxlens r z$EmailPolicy._fold..s<)QQ&)sr$r%z: )r/r?max_line_lengthsysmaxsizer9r' refold_sourcer3anyrBisasciirrr(linesep)rr r,r=linesrefoldrQs @rr>zEmailPolicy._folds( 5& !::T:* *)-)=)=%%3;; &&u-$$->$$.>As58}SY6q86A=<%)<<  99"]]_,(/ &&tRWWU^<AAAN Nd{T\\..u55 DDr)F)__name__ __module__ __qualname____doc__r message_factoryrBrVrrr content_managerrr!r-r7r:r?rIr> __classcell__)rs@rr r sP8t#O DM#%N&O3$ ,8& 0;*9$Err T)raise_on_defectr&)rY)rYrS)rB)r_rerTemail._policybaserrrr email.utilsremail.headerregistryremail.contentmanagerr email.messager __all__compiler9r r rcloner rrSMTPUTF8rrrrns LL'A1& 2::k*DE&DEDEN -  t ,}}V}$}}VT}: ::4: r__pycache__/quoprimime.cpython-312.pyc000064400000023340152526700320013652 0ustar00 {|j&dZgdZddlZddlmZmZmZdZdZdZ e dDcgc]}d |z c}Z e ddZ e ddZ d ejd zejd zD] Zeee e<d e ed <dD] Zeee e<dZdZdZdZddZdZdZddZe ddZdD] Zeeee<[defdZefdZeZeZdZdZ ycc}w)aFQuoted-printable content transfer encoding per RFCs 2045-2047. This module handles the content transfer encoding method defined in RFC 2045 to encode US ASCII-like 8-bit data called `quoted-printable'. It is used to safely encode text that is in a character set similar to the 7-bit US ASCII character set, but that includes some 8-bit characters that are normally not allowed in email bodies or headers. Quoted-printable is very space-inefficient for encoding binary files; use the email.base64mime module for that instead. This module provides an interface to encode and decode both headers and bodies with quoted-printable encoding. RFC 2045 defines a method for including character set information in an `encoded-word' in a header. This method is commonly used for 8-bit real names in To:/From:/Cc: etc. fields, as well as Subject: lines. This module does not do the line wrapping or end-of-line character conversion necessary for proper internationalized headers; it only does dumb encoding and decoding. To deal with the various line wrapping issues, use the email.header module. ) body_decode body_encode body_lengthdecode decodestring header_decode header_encode header_lengthquoteunquoteN) ascii_lettersdigits hexdigits  z=%02Xs-!*+/ascii_ s_ !"#$%&'()*+,-./0123456789:;<>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ c,t|t|k7S)z>Return True if the octet should be escaped with header quopri.)chr_QUOPRI_HEADER_MAPoctets )/usr/lib64/python3.12/email/quoprimime.py header_checkrJs u:+E2 22c,t|t|k7S)zz header_length..^sE9%s%e,-9sum bytearrays rr r Ts E9E EErc&td|DS)zReturn a body quoted-printable encoding length. :param bytearray: An array of bytes (a.k.a. octets). :return: The length in bytes of the byte array when it is encoded with quoted-printable for bodies. c3@K|]}tt|ywr$)r%r r&s rr(zbody_length..hsCs#E*+r)r*r,s rrras CC CCrct|ts t|}|s |j|j yt |dt |z|kr|dxx||zz cc<y|j|j y)N) isinstancestrrappendlstripr%)Lsmaxlenextras r _max_appendr:ksg a  F   QrUc!f  & " rc2tt|dddS)zDTurn a string in the form =AB to the ASCII character with value 0xab)rintr7s rr r vs s1Qq62 rc&tt|Sr$) _QUOPRI_MAPordcs rr r {s s1v rcb|sy|jdjt}d|d|dS)aEncode a single header line with quoted-printable (like) encoding. Defined in RFC 2045, this `Q' encoding is similar to quoted-printable, but used specifically for email header fields to allow charsets with mostly 7 bit characters (and some 8 bit) to remain more or less readable in non-RFC 2045 aware mail clients. charset names the character set to use in the RFC 2046 header. It defaults to iso-8859-1. rlatin1z=?z?q?z?=)r translater) header_bytescharsetencodeds rrrs3 !!(+556HIG$W --rs Lc|dkr td|s|S|jt}d|z}|dz }g}|j}|j D]}d}t |dz |z } || krV||z} || dz dk(r|||| dz | dz }n,|| dz dk(r|||| | dz }n|||| dz| }|| krV|rN|ddvrG|| z } | d k\rt |d} n| dk(r |d|z} n|t |dz} |||d| z|||d |dtvr|d |j|S) aEncode with quoted-printable, wrapping at maxlinelen characters. Each line of encoded text will end with eol, which defaults to "\n". Set this to "\r\n" if you will be using the result of this function directly in an email. Each line will be wrapped at, at most, maxlinelen characters before the eol string (maxlinelen defaults to 76 characters, the maximum value permitted by RFC 2045). Long lines will have the 'soft line break' quoted-printable character "=" appended to them, so the decoded text will be identical to the original text. The minimum maxlinelen is 4 to have room for a quoted character ("=XX") followed by a soft line break. Smaller values will generate a ValueError. zmaxlinelen must be at least 4=r<r r1z r=Nr) ValueErrorrH_QUOPRI_BODY_ENCODE_MAPr4 splitlinesr%r CRLFjoin) body maxlineleneol soft_break maxlinelen1 encoded_bodyr4linestart laststartstoproomqs rrrs&A~899   >>1 2DsJq.KL  F!IMJ. y ;&DD1H~$tE$(+,qdQh3&tE$'(qtE$'#-.y  DH%9$Dqy$r(OHz)tBx0 4b>A% & 4< C"H Bx4r 88L !!rc|s|Sd}|jD]}|j}|s||z }d}t|}||ks.||}|dk7r ||z }|dz }nV|dz|k(r|dz })|dz|kr6||dztvr(||dztvr|t |||dzz }|dz }n ||z }|dz }||k(r||z }||kr{|ddvr|j |r|d d}|S) z_Decode a quoted-printable string. Lines are separated with eol, which defaults to \n. rr rOr<rPr=r1rN)rSrstripr%rr endswith)rKrXdecodedr\inrEs rrrs3 G""${{} sNG   I!eQACx1 Q1Q1qT!A#Y)3QqS Y8N74!A#;//Q1 QAv3)!e%<r{& W%5%5c%:#2, Nrc:|jd}t|S)zCTurn a match in the form =AB to the ASCII character with value 0xabr )groupr )matchr7s r_unquote_matchrks AA 1:rc||jdd}tjdt|tjS)aDecode a string encoded with RFC 2045 MIME header `Q' encoding. This function does not parse a full MIME header value encoded with quoted-printable (like =?iso-8859-1?q?Hello_World?=) -- please use the high level email.header class for that functionality. rrz=[a-fA-F0-9]{2})flags)replaceresubrkASCIIr@s rrr$s. #sA 66$narxx HHr)r)z iso-8859-1)!__doc____all__rostringr rrrTNL EMPTYSTRINGrangerBrr encoderErrCrr!r rr:r r rrRrrrrrkrrDs0rrysQ 0  33   %*#J/Jqw{J/  ^q> (M((1 1MFMM'4J JAFq K #3s8 .Aa&Q .3 1 FD .*+1- A!$QA !#I"^,`  I[0s C__pycache__/headerregistry.cpython-312.pyc000064400000074367152526700320014523 0ustar00 {|jSQ,dZddlmZddlmZddlmZddlmZGddZGdd Z Gd d e Z d Z Gd dZ Gdde ZGddZGddeZGddZGddeZGddeZGddeZGddZGdd ZGd!d"eZGd#d$eZGd%d&ZGd'd(Zid)ed*ed+ed,ed-ed.ed/ed0ed1ed2ed3ed4ed5ed6ed7ed8ed9eeeed:ZGd;d<Zy=)>zRepresenting and manipulating email headers via custom objects. This module provides an implementation of the HeaderRegistry API. The implementation is designed to flexibly follow RFC5322 rules. )MappingProxyType)utils)errors)_header_value_parsercfeZdZd dZedZedZedZedZdZ dZ d Z y) AddressNc djtd||||f}d|vsd|vr td|w|s|r tdt j |\}}|rtdj |||jr|jd|j}|j}||_ ||_ ||_ y) aCreate an object representing a full email address. An address can have a 'display_name', a 'username', and a 'domain'. In addition to specifying the username and domain separately, they may be specified together by using the addr_spec keyword *instead of* the username and domain keywords. If an addr_spec string is specified it must be properly quoted according to RFC 5322 rules; an error will be raised if it is not. An Address object has display_name, username, domain, and addr_spec attributes, all of which are read-only. The addr_spec and the string value of the object are both quoted according to RFC5322 rules, but without any Content Transfer Encoding. N  z8invalid arguments; address parts cannot contain CR or LFz=addrspec specified when username and/or domain also specifiedz6Invalid addr_spec; only '{}' could be parsed from '{}'r) joinfilter ValueError TypeErrorparser get_addr_specformat all_defects local_partdomain _display_name _username_domain)self display_nameusernamer addr_specinputsa_srests -/usr/lib64/python3.12/email/headerregistry.py__init__zAddress.__init__s"|Xvy&QRS 6>TV^WX X  6!899,,Y7IC "==CV$'>455ooa((~~HZZF)! c|jSNrrs r!rzAddress.display_name8!!!r#c|jSr%)rr's r!rzAddress.username< ~~r#c|jSr%)rr's r!rzAddress.domain@ ||r#c|j}tjj|stj|}|j r|dz|j zS|sy|S)zThe addr_spec (username@domain) portion of the address, quoted according to RFC 5322 rules, but with no Content Transfer Encoding. @<>)rr DOT_ATOM_ENDS isdisjoint quote_stringr)rlps r!rzAddress.addr_specDsV ]]##..r2$$R(B ;;8dkk) ) r#cdj|jj|j|j|j S)Nz1{}(display_name={!r}, username={!r}, domain={!r}))r __class____name__rrrr's r!__repr__zAddress.__repr__Rs9BII//))4==$++G Gr#c|j}tjj|stj|}|r/|j dk(rdn |j }dj ||S|j S)Nr/r z{} <{}>)rrSPECIALSr1r2rr)rdisprs r!__str__zAddress.__str__Wse  ))$/&&t,D "nnd2I##D)4 4~~r#ct|tstS|j|jk(xr4|j|jk(xr|j |j k(Sr%) isinstancerNotImplementedrrrrothers r!__eq__zAddress.__eq__`sU%)! !!!U%7%77, /, u||+ -r#)r r r N) r6 __module__ __qualname__r"propertyrrrrr7r;rAr#r!rr sh(T""  G -r#rcFeZdZddZedZedZdZdZdZ y) GroupNcV||_|rt||_yt|_y)aCreate an object representing an address group. An address group consists of a display_name followed by colon and a list of addresses (see Address) terminated by a semi-colon. The Group is created by specifying a display_name and a possibly empty list of Address objects. A Group can also be used to represent a single address that is not in a group, which is convenient when manipulating lists that are a combination of Groups and individual Addresses. In this case the display_name should be set to None. In particular, the string representation of a Group whose display_name is None is the same as the Address object, if there is one and only one Address object in the addresses list. N)rtuple _addresses)rr addressess r!r"zGroup.__init__js"*.7% *UWr#c|jSr%r&r's r!rzGroup.display_name|r(r#c|jSr%)rJr's r!rKzGroup.addressess r#cxdj|jj|j|jS)Nz${}(display_name={!r}, addresses={!r})rr5r6rrKr's r!r7zGroup.__repr__s15<<((""DNN4 4r#cx|j0t|jdk(rt|jdS|j}|4tj j |st j|}djd|jD}|rd|zn|}dj||S)Nr, c32K|]}t|ywr%)str).0xs r! z Group.__str__..s:>a3q6>s z{}:{};) rlenrKrSrr9r1r2r r)rr:adrstrs r!r;z Group.__str__s    $T^^)$>t$D&&t,D:4>>::!'vVtV,,r#ct|tstS|j|jk(xr|j|jk(Sr%)r=rGr>rrKr?s r!rAz Group.__eq__s@%'! !!!U%7%772%//1 3r#)NN) r6rBrCr"rDrrKr7r;rArEr#r!rGrGhs?E$""4 -3r#rGcXeZdZdZdZdZedZedZdZ e dZ dZ y ) BaseHeadera|Base class for message headers. Implements generic behavior and provides tools for subclasses. A subclass must define a classmethod named 'parse' that takes an unfolded value string and a dictionary as its arguments. The dictionary will contain one key, 'defects', initialized to an empty list. After the call the dictionary must contain two additional keys: parse_tree, set to the parse tree obtained from parsing the header, and 'decoded', set to the string value of the idealized representation of the data from the value. (That is, encoded words are decoded, and values that have canonical representations are so represented.) The defects key is intended to collect parsing defects, which the message parser will subsequently dispose of as appropriate. The parser should not, insofar as practical, raise any errors. Defects should be added to the list instead. The standard header parsers register defects for RFC compliance issues, for obsolete RFC syntax, and for unrecoverable parsing errors. The parse method may add additional keys to the dictionary. In this case the subclass must define an 'init' method, which will be passed the dictionary as its keyword arguments. The method should use (usually by setting them as the value of similarly named attributes) and remove all the extra keys added by its parse method, and then use super to call its parent class with the remaining arguments and keywords. The subclass should also make sure that a 'max_count' attribute is defined that is either None or 1. XXX: need to better define this API. cdgi}|j||tj|drtj|d|d<tj ||d}|d=|j |fi||S)Ndefectsdecoded)parser_has_surrogates _sanitizerS__new__init)clsnamevaluekwdsrs r!rczBaseHeader.__new__st2 %  i 1#ood9o>DO{{3Y0 O $$ r#c.||_||_||_yr%)_name _parse_tree_defects)rrf parse_treer^s r!rdzBaseHeader.inits % r#c|jSr%)rjr's r!rfzBaseHeader.names zzr#c,t|jSr%)rIrlr's r!r^zBaseHeader.defectssT]]##r#ct|jj|jjt |f|j fSr%)_reconstruct_headerr5r6 __bases__rS __getstate__r's r! __reduce__zBaseHeader.__reduce__sC ''((D      ! !r#c.tj||Sr%)rSrc)rergs r! _reconstructzBaseHeader._reconstructs{{3&&r#c tjtjtj|jdtjddgg}|j r9|j tjtjddg|j |j |j|S)atFold header according to policy. The parsed representation of the header is folded according to RFC5322 rules, as modified by the policy. If the parse tree contains surrogateescaped bytes, the bytes are CTE encoded using the charset 'unknown-8bit". Any non-ASCII characters in the parse tree are CTE encoded using charset utf-8. XXX: make this a policy setting. The returned value is an ASCII-only string possibly containing linesep characters, and ending with a linesep character. The string includes the header name and the ': ' separator. z header-name:z header-seprWfws)policy) rHeader HeaderLabel ValueTerminalrfrkappendCFWSListWhiteSpaceTerminalfold)rrzheaders r!rzBaseHeader.folds"   $$TYY >$$S,7 9 :     MM!:!:3!F GH J d&&'{{&{))r#N) r6rBrC__doc__rcrdrDrfr^rt classmethodrvrrEr#r!r\r\sX@ $$!''*r#r\c:t||ij|Sr%)typerv)cls_namebasesrgs r!rqrqs % $ 1 1% 88r#cDeZdZdZeej ZedZ y)UnstructuredHeaderNcN|j||d<t|d|d<y)Nrmr_) value_parserrSrergrhs r!r`zUnstructuredHeader.parse s* --e4\d<01Yr#) r6rBrC max_count staticmethodrget_unstructuredrrr`rEr#r!rrs)I 7 78L22r#rceZdZdZy)UniqueUnstructuredHeaderrPNr6rBrCrrEr#r!rrIr#rcjeZdZdZdZeejZe dZ fdZ e dZ xZS) DateHeaderaHeader whose value consists of a single timestamp. Provides an additional attribute, datetime, which is either an aware datetime using a timezone, or a naive datetime if the timezone in the input string is -0000. Also accepts a datetime as input. The 'value' attribute is the normalized form of the timestamp, which means it is the output of format_datetime on the datetime. Nc|sH|djtjd|d<d|d<tj|d<yt |t r||d< tj|}||d<tj|d|d<|j|d|d<y#t$rF|djtjdd|d<tj|d<YywxYw)Nr^datetimer r_rmzInvalid date value or format) r~rHeaderMissingRequiredValuer TokenListr=rSrparsedate_to_datetimerInvalidDateDefectformat_datetimerrs r!r`zDateHeader.parse$s O " "6#D#D#F G#D  DO!'!1!1!3D   eS !#DO 33E: !Z//Z0@AY --d9o>\ Y&&v'?'?@^'_`#'Z %+%5%5%7\"  s!B..A C=<C=cP|jd|_t| |i|y)Nr)pop _datetimesuperrdrargskwr5s r!rdzDateHeader.init9s$ +  d!b!r#c|jSr%)rr's r!rzDateHeader.datetime=r*r#)r6rBrCrrrrrrrr`rdrDr __classcell__r5s@r!rrsLI  7 78L??("r#rceZdZdZy)UniqueDateHeaderrPNrrEr#r!rrBrr#rcbeZdZdZedZedZfdZe dZ e dZ xZ S) AddressHeaderNcHtj|\}}|rJd|S)Nzthis should not happen)rget_address_list)rg address_lists r!rzAddressHeader.value_parserKs+$55e< e222yr#ct|tr|j|x|d<}g}|jD]t}|j t |j |jDcgc]9}t|j xsd|jxsd|jxsd;c}vt|j}n9t|ds|g}|Dcgc]}t|ds t d|gn|}}g}||d<||d<dj|Dcgc] }t|c}|d<d|vr|j|d|d<yycc}wcc}wcc}w) Nrmr __iter__rKgroupsr^rQr_)r=rSrrKr~rGr all_mailboxesrrrlistrhasattrr ) rergrhrraddrmbr^items r!r`zAddressHeader.parseQs eS !140@0@0G GD F$.. eD$5$504/A/A%C0B&-R__-B-/]]-@b-/YY_"&>0B%CDE/ <334G5*-1670529{1KeD4&)/3405 7GX!Y))6$B64SY6$BCY t #!$!1!1$y/!BD  $!%C7 %Cs!>E "EEcpt|jd|_d|_t ||i|y)Nr)rIr_groupsrJrrdrs r!rdzAddressHeader.initms0RVVH-.   d!b!r#c|jSr%)rr's r!rzAddressHeader.groupsrr,r#ct|j!td|jD|_|jS)Nc3BK|]}|jD]}|ywr%)rK)rTgroupaddresss r!rVz*AddressHeader.addresses..ys($L;@??%,;J%,s)rJrIrr's r!rKzAddressHeader.addressesvs5 ?? "#$L$LLDOr#) r6rBrCrrrrr`rdrDrrKrrs@r!rrGs]I CC6" r#rceZdZdZy)UniqueAddressHeaderrPNrrEr#r!rr~rr#rceZdZedZy)SingleAddressHeaderct|jdk7r$tdj|j|jdS)NrPz9value of single address header {} is not a single addressr)rXrKrrrfr's r!rzSingleAddressHeader.addresssB t~~  !#$*F499$57 7~~a  r#N)r6rBrCrDrrEr#r!rrs !!r#rceZdZdZy)UniqueSingleAddressHeaderrPNrrEr#r!rrrr#rceZdZdZeej ZedZ fdZ e dZ e dZ e dZxZS)MIMEVersionHeaderrPc:|j|x|d<}t||d<|dj|j|jdn |j |d<|j|d<|jdj |d|d|d<yd|d<y)Nrmr_r^majorminorz{}.{}version)rrSextendrrrrrergrhrms r!r`zMIMEVersionHeader.parses*-*:*:5*AA\Zj/Y Yz556 * 0 0 8j>N>NW "((W    '%nnT']DMJDO"DOr#c|jd|_|jd|_|jd|_t ||i|y)Nrrr)r_version_major_minorrrdrs r!rdzMIMEVersionHeader.initsBy) ffWo ffWo   d!b!r#c|jSr%)rr's r!rzMIMEVersionHeader.major {{r#c|jSr%)rr's r!rzMIMEVersionHeader.minorrr#c|jSr%)rr's r!rzMIMEVersionHeader.version }}r#)r6rBrCrrrparse_mime_versionrrr`rdrDrrrrrs@r!rrskI 9 9:L # #" r#rcBeZdZdZedZfdZedZxZ S)ParameterizedMIMEHeaderrPcf|j|x|d<}t||d<|dj|j|ji|d<y|jDcic]<\}}t j |jt j |>c}}|d<ycc}}w)Nrmr_r^params)rrSrrrrrblower)rergrhrmrfs r!r`zParameterizedMIMEHeader.parses*-*:*:5*AA\Zj/Y Yz556    $DN 3=2C2CE2C;4$ood399;$)OOE$:;2CEDNEs$AB-cP|jd|_t| |i|y)Nr)r_paramsrrdrs r!rdzParameterizedMIMEHeader.inits$vvh'   d!b!r#c,t|jSr%)rrr's r!rzParameterizedMIMEHeader.paramss --r#) r6rBrCrrr`rdrDrrrs@r!rrs7 I E E"..r#rcreZdZeej ZfdZedZ edZ edZ xZ S)ContentTypeHeaderct||i|tj|jj |_tj|jj|_yr%) rrdrrbrkmaintype _maintypesubtype_subtypers r!rdzContentTypeHeader.initsL  d!b!)9)9)B)BC(8(8(@(@A r#c|jSr%)rr's r!rzContentTypeHeader.maintyper*r#c|jSr%)rr's r!rzContentTypeHeader.subtyperr#c:|jdz|jzS)N/)rrr's r! content_typezContentTypeHeader.content_types}}s"T\\11r#) r6rBrCrrparse_content_type_headerrrdrDrrrrrs@r!rrsU @ @ALB 22r#rcReZdZeej ZfdZedZ xZ S)ContentDispositionHeaderct||i||jj}|||_yt j ||_yr%)rrdrkcontent_dispositionrrb_content_disposition)rrrcdr5s r!rdzContentDispositionHeader.initsA  d!b!    1 1*,*B!%//":M!r#c|jSr%)rr's r!rz,ContentDispositionHeader.content_dispositions(((r#) r6rBrCrr parse_content_disposition_headerrrdrDrrrs@r!rrs- G GHLN ))r#rcfeZdZdZeej ZedZ fdZ e dZ xZ S)ContentTransferEncodingHeaderrPc|j|x|d<}t||d<|dj|jyNrmr_r^rrSrrrs r!r`z#ContentTransferEncodingHeader.parseA*-*:*:5*AA\Zj/Y Yz556r#ct||i|tj|jj |_yr%)rrdrrbrkcte_cters r!rdz"ContentTransferEncodingHeader.inits0  d!b!OOD$4$4$8$89 r#c|jSr%)rr's r!rz!ContentTransferEncodingHeader.ctes yyr#)r6rBrCrrr&parse_content_transfer_encoding_headerrrr`rdrDrrrs@r!rrsCI M MNL77 :r#rcDeZdZdZeej ZedZ y)MessageIDHeaderrPc|j|x|d<}t||d<|dj|jyrrrs r!r`zMessageIDHeader.parserr#N) r6rBrCrrrparse_message_idrrr`rEr#r!rr s)I 7 78L77r#rsubjectdatez resent-datez orig-datesenderz resent-sendertoz resent-toccz resent-ccbccz resent-bccfromz resent-fromzreply-toz mime-versionz content-type)zcontent-dispositionzcontent-transfer-encodingz message-idc0eZdZdZeedfdZdZdZdZ y)HeaderRegistryz%A header_factory and header registry.Tcri|_||_||_|r |jjtyy)aCreate a header_factory that works with the Policy API. base_class is the class that will be the last class in the created header class's __bases__ list. default_class is the class that will be used if "name" (see __call__) does not appear in the registry. use_default_map controls whether or not the default mapping of names to specialized classes is copied in to the registry when the factory is created. The default is True. N)registry base_class default_classupdate_default_header_map)rrruse_default_maps r!r"zHeaderRegistry.__init__6s5 $*  MM !4 5 r#c>||j|j<y)zLRegister cls as the specialized class for handling "name" headers. N)rrrrfres r! map_to_typezHeaderRegistry.map_to_typeHs'* djjl#r#c|jj|j|j}t d|j z||j fiS)N_)rgetrrrr6rrs r! __getitem__zHeaderRegistry.__getitem__NsEmm d.@.@AC $sDOO&rs #0Y-Y-x/3/3ha*a*H9221 ++\z 44n- !-! 3 ""J..:2/2, )6 )* 7 7 $< $4J$4   $=  $7  $7M $7M $7M $7M$7 $5!"$5#$%=$A$3).*'*'r#__pycache__/iterators.cpython-312.pyc000064400000005361152526700320013502 0ustar00 {|jQBdZgdZddlZddlmZdZd dZd dZd dZy) z1Various types of useful iterators and generators.)body_line_iteratortyped_subpart_iteratorwalkN)StringIOc#K||jr.|jD]}|jEd{yy7w)zWalk over the message tree, yielding each subpart. The walk is performed in depth-first order. This method is a generator. N) is_multipart get_payloadr)selfsubparts (/usr/lib64/python3.12/email/iterators.pyrrsC J '')G||~ % %* %s;AA Ac#K|jD]8}|j|}t|ts&t |Ed{:y7w)zIterate over the parts, returning string payloads line-by-line. Optional decode (default False) is passed through to .get_payload(). )decodeN)rr isinstancestrr)msgrr payloads r rr sH 88:%%V%4 gs #( ( ( )s6AAAAc#K|jD]0}|j|k(s||j|k(s-|2yw)zIterate over the subparts with a given MIME type. Use `maintype' as the main MIME type to match against; this defaults to "text". Optional `subtype' is the MIME subtype to match against; if omitted, only the main type is matched. N)rget_content_maintypeget_content_subtype)rmaintypesubtyper s r rr+sC88:  ' ' )X 5'"="="?7"J s'AAAc>|tj}d|dzz}t||jzd||rtd|j z|n t||j r'|j D]}t|||dz|yy) zA handy debugging aidN )endfilez [%s])r)sysstdoutprintget_content_typeget_default_typerr _structure)rfplevelinclude_defaulttabr s r r$r$8s z ZZ  C #$$& &BR8 g,,..R8 2 (G wE!G_ =))F)textN)NrF) __doc____all__riorrrrr$r)r r/s- 8   &)  >r)__pycache__/_header_value_parser.cpython-312.opt-2.pyc000064400000345040152526700320016566 0ustar00 {|jE ddlZddlZddlZddlmZddlmZddlmZ ddlm Z ddlm Z e dZ e e dzZe d Zee zZee d z Zee d z Zee d ze d z Zee zZee d zZee zZee dz ZddhZeezZdZdZdZej:dej<ej>zZ Gdde!Z"Gdde"Z#Gdde"Z$Gdde"Z%Gdde"Z&Gdd e#Z'Gd!d"e"Z(Gd#d$e"Z)Gd%d&e"Z*Gd'd(e"Z+Gd)d*e+Z,Gd+d,e#Z-Gd-d.e"Z.Gd/d0e"Z/Gd1d2e"Z0Gd3d4e"Z1Gd5d6e"Z2Gd7d8e"Z3Gd9d:e"Z4Gd;de"Z6Gd?d@e"Z7GdAdBe"Z8GdCdDe"Z9GdEdFe"Z:GdGdHe"Z;GdIdJe"Z<GdKdLe"Z=GdMdNe%Z>GdOdPe"Z?GdQdRe"Z@GdSdTe"ZAGdUdVe"ZBGdWdXeBZCGdYdZe"ZDGd[d\e"ZEGd]d^e"ZFGd_d`e"ZGGdadbe"ZHGdcddeHZIGdedfeHZJGdgdhe"ZKGdidje"ZLGdkdle"ZMGdmdneMZNGdodpeNZOGdqdre"ZPGdsdteQZRGdudveRZSGdwdxeRZTGdydzeSZUGd{d|e jZWeTd d}ZXeTd~dZYdeY_ZdeY_[eTddZ\ej:djdje jZ`ej:djejdjejZcej:djZeej:djejdjejZfej:djejdjejZgej:djejdjejZhdZidZjdZkddZldZmdZndZodZpdZqdZrdZsdZtdZudZvdZwdZxdZydZzdZ{dZ|dZ}dZ~dZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZy)N) hexdigits) itemgetter)_encoded_words)errors)utilsz (z ()<>@,:;.\"[].z."(z/?=z*'%%  cZ t|jddjddS)N\\\"z\"strreplacevalues 3/usr/lib64/python3.12/email/_header_value_parser.pymake_quoted_pairsrcs)E u:  dF + 3 3C ??cz t|jddjddjddS)Nrrr\()\)rrs rmake_parenthesis_pairsrhs5D u:  dF + e WWS%01rc$t|}d|dS)Nr)r)rescapeds r quote_stringr ns&G wiq>rz =\? # literal =? [^?]* # charset \? # literal ? [qQbB] # literal 'q' or 'b', case insensitive \? # literal ? .*? # encoded word \?= # literal ?= ceZdZdZdZdZfdZdZfdZe dZ e dZ dZ e d Z e d Zd Zdd Zdd ZddZxZS) TokenListNTc2t||i|g|_yN)super__init__defects)selfargskw __class__s rr&zTokenList.__init__s $%"% rc2djd|DS)Nc32K|]}t|ywr$r.0xs r z$TokenList.__str__..,t!s1vtjoinr(s r__str__zTokenList.__str__sww,t,,,rchdj|jjt|SNz{}({})formatr+__name__r%__repr__r(r+s rr?zTokenList.__repr__s+t~~66"W-/1 1rc2djd|DS)Nr-c3NK|]}|js|jywr$rr0s rr3z"TokenList.value..s81qwws%%r6r8s rrzTokenList.valuesww8888rc<td|D|jS)Nc34K|]}|jywr$) all_defectsr0s rr3z(TokenList.all_defects..s04aAMM4)sumr'r8s rrEzTokenList.all_defectss040$,,??rc(|djSNr)startswith_fwsr8s rrJzTokenList.startswith_fwssAw%%''rc( td|DS)Nc34K|]}|jywr$) as_ew_allowed)r1parts rr3z*TokenList.as_ew_allowed..s7$$4%%$rF)allr8s rrMzTokenList.as_ew_allowedsO7$777rcNg}|D]}|j|j|Sr$)extendcomments)r(rRtokens rrRzTokenList.commentss&E OOENN +rct||S)Npolicy)_refold_parse_treer(rVs rfoldzTokenList.folds!$v66rc:t|j|y)Nindent)printppstrr(r\s rpprintzTokenList.pprints djjj'(rcDdj|j|S)Nr r[)r7_ppr_s rr^zTokenList.ppstrsyy011rc#~Kdj||jj|j|D]A}t |ds|dj|z&|j |dzEd{C|j rdj|j }nd}dj||y7Ew)Nz{}{}/{}(rbz* !! invalid element in token list: {!r}z z Defects: {}r-z{}){})r=r+r> token_typehasattrrbr')r(r\rSextras rrbz TokenList._pps  NN # # OO E5%(!55;VE]CD!99VF]333  <<"))$,,7EEnnVU++ 4sA3B=5B;6AB=r-)r> __module__ __qualname__rdsyntactic_breakew_combine_allowedr&r9r?propertyrrErJrMrRrYr`r^rb __classcell__r+s@rr"r"sJO-199@@(88 7)2,rr"c,eZdZedZedZy)WhiteSpaceTokenListcyN r8s rrzWhiteSpaceTokenList.valuerc`|Dcgc]}|jdk(s|j c}Scc}w)Ncomment)rdcontentr(r2s rrRzWhiteSpaceTokenList.commentss)#'C4a1<<+B 4CCC++N)r>rhrirlrrRrtrrrprps* DDrrpceZdZdZy)UnstructuredTokenList unstructuredNr>rhrirdrtrrr|r|sJrr|ceZdZdZy)PhrasephraseNr~rtrrrrJrrceZdZdZy)WordwordNr~rtrrrrJrrceZdZdZy)CFWSListcfwsNr~rtrrrrrrrceZdZdZy)AtomatomNr~rtrrrrrrrceZdZdZdZy)TokenrSFN)r>rhrird encode_as_ewrtrrrrs JLrrceZdZdZdZdZdZy) EncodedWord encoded-wordN)r>rhrirdctecharsetlangrtrrrrsJ CG Drrc@eZdZdZedZedZedZy) QuotedString quoted-stringcL|D]}|jdk(s|jcSyNbare-quoted-stringrdrrys rrxzQuotedString.contents"A||33wwrcg}|D]G}|jdk(r|jt|-|j|jIdj |S)Nrr-)rdappendrrr7)r(resr2s r quoted_valuezQuotedString.quoted_valuesNA||33 3q6" 177#  wws|rcL|D]}|jdk(s|jcSyrrr(rSs rstripped_valuezQuotedString.stripped_values%E#77{{"rN)r>rhrirdrlrxrrrtrrrrsA J  ##rrc&eZdZdZdZedZy)BareQuotedStringrcDtdjd|DS)Nr-c32K|]}t|ywr$r/r0s rr3z+BareQuotedString.__str__..s#9DqCFDr5)r r7r8s rr9zBareQuotedString.__str__sBGG#9D#99::rc2djd|DS)Nr-c32K|]}t|ywr$r/r0s rr3z)BareQuotedString.value..r4r5r6r8s rrzBareQuotedString.valueww,t,,,rN)r>rhrirdr9rlrrtrrrr s %J;--rrc<eZdZdZdZdZedZedZy)Commentrwc djtdg|Dcgc]}|j|c}dgggScc}w)Nr-rr)r7rGquoterys rr9zComment.__str__sKwws E489DqTZZ]D9 E " #$ $9s>c|jdk(r t|St|jddjddjddS)Nrwrrrrrr)rdrr)r(rs rrz Comment.quote"sR   y (u: 5z!!$/77"%u..5g"%u/. .rc2djd|DS)Nr-c32K|]}t|ywr$r/r0s rr3z"Comment.content..+r4r5r6r8s rrxzComment.content)rrc|jgSr$)rxr8s rrRzComment.comments-s ~rN) r>rhrirdr9rrlrxrRrtrrrrs9J$.--rrc@eZdZdZedZedZedZy) AddressListz address-listcL|Dcgc]}|jdk(s|c}Scc}w)Naddressrdrys r addresseszAddressList.addresses5%;4a1<<#:4;;;!!c(td|DgS)Nc3RK|]}|jdk(r|j!ywrNrd mailboxesr0s rr3z(AddressList.mailboxes..;s'>!Q\\9%<KK!%'rGr8s rrzAddressList.mailboxes9!>!>?AC Crc(td|DgS)Nc3RK|]}|jdk(r|j!ywrrd all_mailboxesr0s rr3z,AddressList.all_mailboxes..@s'>!Q\\9%<OO!rrr8s rrzAddressList.all_mailboxes>rrN)r>rhrirdrlrrrrtrrrr1sEJ <<CCCCrrc@eZdZdZedZedZedZy)AddressrcF|djdk(r|djSy)Nrgrouprd display_namer8s rrzAddress.display_nameHs) 7   (7'' ' )rcx|djdk(r|dgS|djdk(rgS|djSNrmailboxinvalid-mailboxrr8s rrzAddress.mailboxesMsH 7   *G9  !W  #4 4IAw   rc|djdk(r|dgS|djdk(r|dgS|djSrrr8s rrzAddress.all_mailboxesUsO 7   *G9  !W  #4 4G9 Aw$$$rN)r>rhrirdrlrrrrtrrrrDsAJ ((!!%%rrc0eZdZdZedZedZy) MailboxList mailbox-listcL|Dcgc]}|jdk(s|c}Scc}w)Nrrrys rrzMailboxList.mailboxesarrcH|Dcgc]}|jdvr|c}Scc}w)N)rrrrys rrzMailboxList.all_mailboxeses2?4a||==4? ??sNr>rhrirdrlrrrtrrrr]s-J <<??rrc0eZdZdZedZedZy) GroupList group-listcL|r|djdk7rgS|djSNrrrr8s rrzGroupList.mailboxesos+tAw))^;IAw   rcL|r|djdk7rgS|djSrrr8s rrzGroupList.all_mailboxesus+tAw))^;IAw$$$rNrrtrrrrks-J !! %%rrc@eZdZdZedZedZedZy)GrouprcH|djdk7rgS|djSNrrr8s rrzGroup.mailboxess) 7   -IAw   rcH|djdk7rgS|djSrrr8s rrzGroup.all_mailboxess) 7   -IAw$$$rc |djSrI)rr8s rrzGroup.display_namesAw###rN)r>rhrirdrlrrrrtrrrr|sAJ !! %% $$rrc`eZdZdZedZedZedZedZedZ y)NameAddr name-addrc>t|dk(ry|djSNr)lenrr8s rrzNameAddr.display_names t9>Aw###rc |djSN local_partr8s rrzNameAddr.local_partsBx"""rc |djSrdomainr8s rrzNameAddr.domainsBxrc |djSr)router8s rrzNameAddr.routesBx~~rc |djSr addr_specr8s rrzNameAddr.addr_specsBx!!!rN r>rhrirdrlrrrrrrtrrrrsiJ $$ ##""rrcPeZdZdZedZedZedZedZy) AngleAddrz angle-addrcL|D]}|jdk(s|jcSyN addr-spec)rdrrys rrzAngleAddr.local_parts"A||{*||#rcL|D]}|jdk(s|jcSyrrdrrys rrzAngleAddr.domains!A||{*xxrcL|D]}|jdk(s|jcSy)N obs-route)rddomainsrys rrzAngleAddr.routes"A||{*yy rc|D]O}|jdk(s|jr|jcSt|j|jzcSy)Nrz<>)rdrrr rys rrzAngleAddr.addr_specsFA||{*<<;;&' 5 CC rN) r>rhrirdrlrrrrrtrrrrsUJ $$   !! rrc eZdZdZedZy)ObsRouterc`|Dcgc]}|jdk(s|j c}Scc}w)Nrrrys rrzObsRoute.domainss)"&C$Q!,,(*B$CCCrzN)r>rhrirdrlrrtrrrrsJ DDrrc`eZdZdZedZedZedZedZedZ y)MailboxrcF|djdk(r|djSyNrrrr8s rrzMailbox.display_names) 7   ,7'' ' -rc |djSrIrr8s rrzMailbox.local_partAw!!!rc |djSrIrr8s rrzMailbox.domainsAw~~rcF|djdk(r|djSyr )rdrr8s rrz Mailbox.routes' 7   ,7==  -rc |djSrIrr8s rrzMailbox.addr_specsAw   rNrrtrrr r siJ ((""!!!!rr c0eZdZdZedZexZxZxZZ y)InvalidMailboxrcyr$rtr8s rrzInvalidMailbox.display_namerNrrtrrrrs/"J /;:J::%)rrc0eZdZdZdZefdZxZS)DomainrFcRdjt|jSNr-r7r%rsplitr@s rrz Domain.domainwwuw}**,--r)r>rhrirdrMrlrrmrns@rrrsJM ..rrceZdZdZy)DotAtomdot-atomNr~rtrrrrsJrrceZdZdZdZy) DotAtomTextz dot-atom-textTNr>rhrirdrMrtrrr r  s  JMrr ceZdZdZdZy) NoFoldLiteralzno-fold-literalFNr!rtrrr#r#s "JMrr#cTeZdZdZdZedZedZedZedZ y)AddrSpecrFc |djSrIrr8s rrzAddrSpec.local_partr rc>t|dkry|djS)Nr)rrr8s rrzAddrSpec.domains t9q=Bxrct|dkr|djS|djj|djz|djjzS)Nr(rrr)rrrstriplstripr8s rrzAddrSpec.value$sU t9q=7== Aw}}##%d1gmm3DGMM4H4H4JJJrct|j}t|t|tz kDrt |j}n |j}|j |dz|j zS|S)N@)setrr DOT_ATOM_ENDSr r)r(namesetlps rrzAddrSpec.addr_spec*s_doo& w<#gm34 4doo.BB ;; "8dkk) ) rN) r>rhrirdrMrlrrrrrtrrr%r%s\JM "" KK rr%ceZdZdZdZy) ObsLocalPartzobs-local-partFNr!rtrrr3r36s !JMrr3c@eZdZdZdZedZefdZxZS) DisplayNamez display-nameFct|}t|dk(r |jS|djdk(r|j dneOC$Q""f,47I.Q %%/R##v-48Y/R ''61|D$5$566t; ;7= r) r>rhrirdrkrlrrrmrns@rr5r5<s4J $!!rr5c4eZdZdZdZedZedZy) LocalPartz local-partFcb|djdk(r|djS|djS)Nrr)rdrrr8s rrzLocalPart.valueqs2 7   07'' '7== rctg}t}d}|dtgzD]}|jdk(r|r2|jdk(r#|djdk(rt|dd|d<t|t}|r?|jdk(r0|djdk(r|j t|ddn|j ||d}|}t|dd}|j S)NFrrdotrr)DOTrdr"r8rr)r(rlast last_is_tltokis_tls rrzLocalPart.local_partxse 7cU?C~~'s~~6H''61#D"I.BsI.E$//U2F%%/ 9SW-. 3r7DJ#Ab "yyrN)r>rhrirdrMrlrrrtrrr=r=ls2JM !! rr=c@eZdZdZdZefdZedZxZS) DomainLiteralzdomain-literalFcRdjt|jSrrr@s rrzDomainLiteral.domainrrcL|D]}|jdk(s|jcSy)Nptextrrys ripzDomainLiteral.ips!A||w&wwr) r>rhrirdrMrlrrKrmrns@rrGrGs3!JM ..rrGceZdZdZdZdZy) MIMEVersionz mime-versionN)r>rhrirdmajorminorrtrrrMrMsJ E ErrMc<eZdZdZdZdZdZedZedZ y) Parameter parameterFus-asciic<|jr|djSdSr) sectionednumberr8s rsection_numberzParameter.section_numbers"&tAw~~6Q6rc|D]n}|jdk(r|jcS|jdk(s0|D]:}|jdk(s|D]#}|jdk(s|jcccS<py)Nrrrr-)rdrrs r param_valuezParameter.param_valuesxE7*+++?2"E''+??%*E$//7:',';'; ;&+# rN) r>rhrirdrUextendedrrlrWrYrtrrrQrQs<JIHG 77   rrQceZdZdZy)InvalidParameterinvalid-parameterNr~rtrrr\r\s$Jrr\c eZdZdZedZy) Attribute attributecd|D]+}|jjds|jcSy)Nattrtext)rdendswithrrs rrzAttribute.stripped_values*E((4{{"rNr>rhrirdrlrrtrrr_r_sJ ##rr_ceZdZdZdZy)SectionsectionN)r>rhrirdrVrtrrrfrfs J Frrfc eZdZdZedZy)Valuerc|d}|jdk(r|d}|jjdr |jS|jS)Nrrr)rr`zextended-attribute)rdrcrrrs rrzValue.stripped_valuesPQ   v %GE    $ $D F'' 'zzrNrdrtrrririsJ rric*eZdZdZdZedZdZy)MimeParametersmime-parametersFc#lKi}|D]w}|jjds|djdk7r2|djj}||vrg||<||j |j |fy|j D]\}}t|td}|dd}|j}|jsRt|dkDrD|dddk(r9|ddjj tjd|dd}g}d}|D]\} } | |k7ri| js/| jj tjdG| jj tjd|dz }| j} | jrv t j"j%| } | j'|d } t-j.| r.| jj tj0 |j | d j5|} || fy#t(t*f$r| j'd d } YwxYw#t*$r$t j"j3| d } YwxYww)NrRrr`)keyrz.duplicate parameter name; duplicate(s) ignoredz+duplicate parameter name; duplicate ignoredz(inconsistent RFC2231 parameter numberingsurrogateescaperSzlatin-1)encodingr-)rdrcrstriprrWitemssortedrrrZrr'rInvalidHeaderDefectrYurllibparseunquote_to_bytesdecode LookupErrorUnicodeEncodeErrorr_has_surrogatesUndecodableBytesDefectunquoter7) r(paramsrSnameparts first_paramr value_partsirWparamrs rrzMimeParameters.paramssE##,,[9Qx""k18>>'')D6!!t 4L  !5!5u = >"<<>KD%5jm4E(1+K!))G''CJN8A;!#!HQK''..v/I/IH0JK!"1IEKA).%!Q&!>> ,,V-G-GI.KL  ,,V-G-GF.HIQ))>>R & = =e DP$)LL:K$LE!007!MM001N1N1PQ""5)C*/DGGK(E+ g*R!,-?@P %*LL=N$OE P.P!' 4 4UY 4 O PsIF6J49JI+A2J4!J>J4JJ4*J1.J40J11J4c g}|jD]C\}}|r+|jdj|t|3|j|Edj |}|rd|zSdS)N{}={}z; rsr-)rrr=r r7)r(rrrs rr9zMimeParameters.__str__2se;;KD% gnnT<3FGH d# ' 6"%sV|-2-rN)r>rhrirdrjrlrr9rtrrrlrls&"JO CCJ.rrlc eZdZdZedZy)ParameterizedHeaderValueFc`t|D]}|jdk(s|jcSiS)Nrm)reversedrdrrs rrzParameterizedHeaderValue.paramsCs0d^E#44||#$ rN)r>rhrirjrlrrtrrrr=sO rrceZdZdZdZdZdZy) ContentTypez content-typeFtextplainN)r>rhrirdrMmaintypesubtypertrrrrKsJMHGrrceZdZdZdZdZy)ContentDispositionzcontent-dispositionFN)r>rhrirdrMcontent_dispositionrtrrrrRs&JMrrceZdZdZdZdZy)ContentTransferEncodingzcontent-transfer-encodingF7bitN)r>rhrirdrMrrtrrrrXs,JM CrrceZdZdZdZy) HeaderLabelz header-labelFNr!rtrrrr^s JMrrceZdZdZdZdZy)MsgIDzmsg-idFc2t||jzSr$)rlineseprXs rrYz MsgID.foldgs4y6>>))rN)r>rhrirdrMrYrtrrrrcsJM*rrceZdZdZy) MessageIDz message-idNr~rtrrrrlsJrrceZdZdZy)InvalidMessageIDzinvalid-message-idNr~rtrrrrps%JrrceZdZdZy)HeaderheaderNr~rtrrrrtrrrcreZdZdZdZdZfdZfdZdZe dZ d fd Z dZ e dZ d ZxZS) TerminalTcDt|||}||_g|_|Sr$)r%__new__rdr')clsrrdr(r+s rrzTerminal.__new__s&wsE*$  rchdj|jjt|Sr;r<r@s rr?zTerminal.__repr__s&t~~668H8JKKrcbt|jjdz|jzy)N/)r]r+r>rdr8s rr`zTerminal.pprints" dnn%%+doo=>rc,t|jSr$)listr'r8s rrEzTerminal.all_defectssDLL!!rc dj||jj|jt||j sdgSdj|j gS)Nz {}{}/{}({}){}r-z {})r=r+r>rdr%r?r')r(r\r+s rrbz Terminal._ppsg&&  NN # # OO G  llB   ). T\\(B  rcyr$rtr8s rpop_trailing_wszTerminal.pop_trailing_wsrrcgSr$rtr8s rrRzTerminal.commentss rc0t||jfSr$)rrdr8s r__getnewargs__zTerminal.__getnewargs__s4y$//**rrg)r>rhrirMrkrjrr?r`rlrErbrrRrrmrns@rrr|sZMO L?""+rrc"eZdZedZdZy)WhiteSpaceTerminalcyrrrtr8s rrzWhiteSpaceTerminal.valuerurc |xr |dtvSrIWSPr8s rrJz!WhiteSpaceTerminal.startswith_fwss&Q3&rNr>rhrirlrrJrtrrrrs 'rrc"eZdZedZdZy) ValueTerminalc|Sr$rtr8s rrzValueTerminal.values rcy)NFrtr8s rrJzValueTerminal.startswith_fwssrNrrtrrrrs rrc"eZdZedZdZy)EWWhiteSpaceTerminalcyrrtr8s rrzEWWhiteSpaceTerminal.valuesrcyrrtr8s rr9zEWWhiteSpaceTerminal.__str__srN)r>rhrirlrr9rtrrrrs rrc eZdZy)_InvalidEwErrorN)r>rhrirtrrrrs;rrr@,zlist-separatorFr-zroute-component-markerz([{}]+)r-z[^{}]+z[\x00-\x20\x7F]c t|}|r.|jjtj|t j |r/|jjtjdyy)Nz*Non-ASCII characters found in header token)_non_printable_finderr'rrNonPrintableDefectrr|r})xtextnon_printabless r_validate_xtextrsdJ*51N V66~FG U# V:: 8: ;$rc$ t|d^}}g}d}d}tt|D]6}||dk(r |rd}d}nd}|rd}n |||vrn|j||8dz}dj |dj ||dg|z|fS)NrFrTr-) _wsp_splitterrangerrr7)rendcharsfragment remaindervcharsescapehad_qpposs r_get_ptext_to_endcharsrs)2Hy F F FS]# C=D  F c]h &  hsm$$Ag 776?BGGXcd^$4y$@A6 IIrct |j}t|dt|t|z d}||fS)Nfws)r+rr)rnewvaluers rget_fwsrs?||~H U#@ @ABioodA.OC) eABi%% 0 7 7 >@ @ WWY F F aq Yq Y #!<<a0yDj4 399;! &44 ,. / BF GGI E@'*zz$*t2C'D$gtWBJBGJJg  7c>!$-KE4 IIe  )$2 e]3 %wwy!  q$ &44 <> ? u9)  !@ / 6 6rvv >@ @@s I 4I?c" t}|r[|dtvr t|\}}|j|.d}|j dr t |d\}}d}t |dkDrB|djdk7r0|jjtjdd}|r2t |d kDr$|d jd k(rt|dd|d<|j|t|d ^}}|r(tj!|r|j#d^}}t%|d}t'||j|d j)|}|r[|S#t$rd}Ytj$rYwxYw) NrTrutextrrz&missing whitespace before encoded wordFrrr-)r|rrrrrrrdr'rrurrrrrfc2047_matchersearch partitionrrr7)rr}rSvalid_ewhave_wsrDrrs rget_unstructuredrWs,)*L  8s?"5>LE5    &    D ! /w? u|$q(#B'22e;$,,33F4N4ND5FG"'s<014#B'22nD+?(,e,5 R(##E*'q1i ..s3#ood3OC)c7+E" "Q R A# ! **  sE,, F9F FcZ t|d\}}}t|d}t|||fS)Nz()rJ)rrrrrJ_s r get_qp_ctextrs9 -UD9OE5! ug .EE %<rcZ t|d\}}}t|d}t|||fS)NrrJ)rrrrs r get_qcontentrs9-UC8OE5! % )EE %<rc t|}|s$tjdj||j }|t |d}t |d}t|||fS)Nzexpected atext but found '{}'atext)_non_atom_end_matcherrrr=rrrr)rmrs r get_atextrsp e$A %% + 2 25 9; ; GGIE #e*+ E % )EE %<rcP |r|ddk7r$tjdj|t}|dd}|r'|ddk(rt |\}}|j ||r|ddk7r|dt vrt|\}}n|dddk(rd} t|\}}|jj tjdd }|rSt|dkDrE|d jd k(r3|d jd k(r!t|d d |d <nt |\}}|j ||r |ddk7r|s2|jj tjd||fS||ddfS#tj$rt |\}}YwxYw)Nrrzexpected '"' but found '{}'rrrFz!encoded word inside quoted stringTrrrrz"end of header inside quoted string)rrr=rrrrrrr'rurrdr)rbare_quoted_stringrSrs rget_bare_quoted_stringrs E!HO%% * 1 1% 8: :)+ !"IE qS#E* u!!%( E!HO 8s?"5>LE5 2AY$ H 3/6 u"**11&2L2L739: C 23a7&r*55>*2.99^K-A*2..7&r*(.LE5!!%(+ E!HO, ""))&*D*D 0+2 3!5(( uQRy ((!** 3+E2 u 3s>F!F%$F%c |r,|ddk7r$tjdj|t}|dd}|rc|ddk7r[|dtvrt |\}}n%|ddk(rt |\}}nt|\}}|j||r |ddk7r[|s2|jjtjd||fS||ddfS)Nrrzexpected '(' but found '{}'rrzend of header inside comment) rrr=rrr get_commentrrr'ru)rrwrSs rrrs  qS%% ) 0 0 79 9iG !"IE E!HO 8s?"5>LE5 1X_&u-LE5'.LE5u E!HO v99 * , -~ E!"I rc t}|rR|dtvrG|dtvrt|\}}nt |\}}|j ||r |dtvrG||fSrI)r CFWS_LEADERrrrr)rrrSs rget_cfwsrsl :D E!H + 8s?"5>LE5&u-LE5 E E!H + ;rc t}|r*|dtvrt|\}}|j|t |\}}|j||r*|dtvrt|\}}|j|||fSrI)rrrrr)r quoted_stringrSs rget_quoted_stringr s !NM q[( uU#)%0LE5 q[( uU# % rc t}|r*|dtvrt|\}}|j||r/|dtvr$t j dj||jdr t|\}}nt|\}}|j||r*|dtvrt|\}}|j|||fS#t j $rt|\}}YdwxYw)Nrzexpected atom but found '{}'r) rrrr ATOM_ENDSrrr=rrr)rrrSs rget_atomr -s 6D q[( u E qY&%% * 1 1% 8: :  ,+E2LE5 !' uKK q[( u E ;&& ,%U+LE5 ,s;C!C=<C=c t}|r |dtvr$tjdj ||r\|dtvrQt |\}}|j ||r"|ddk(r|j t|dd}|r |dtvrQ|dtur'tjdj d|z||fS)Nrz8expected atom at a start of dot-atom-text but found '{}'r rrz4expected atom at end of dot-atom-text but found '{}')r r rrr=rrrA)r dot_atom_textrSs rget_dot_atom_textrHs MM E!H )%%'++16%=: : E!HI- ' uU# U1X_   %!"IE E!HI- RC%%'#VCI.0 0 % rc t}|dtvrt|\}}|j||j dr t |\}}nt|\}}|j||r*|dtvrt|\}}|j|||fS#t j$rt|\}}YdwxYw)Nrr) rrrrrrrrr)rdot_atomrSs r get_dot_atomr[s yH Qx; u  4+E2LE5 )/ u OOE q[( u U?&& 4-U3LE5 4sB&&!C  C c* |dtvrt|\}}nd}|stjd|ddk(rt |\}}n=|dt vr$tjdj |t|\}}||g|dd||fS)Nrz5Expected 'atom' or 'quoted-string' but found nothing.rz1Expected 'atom' or 'quoted-string' but found '{}')rrrrr SPECIALSr=r )rleaderrSs rget_wordrts Qx;   %% CE E Qx}(/ u qX %%'77=ve}F F  u Hbq %<rc t} t|\}}|j||r|dtvr|ddk(rI|jt|j jtjd|dd}n t|\}}|j||r |dtvr||fS#tj$r1|j jtj dYwxYw#tj$rL|dtvr=t|\}}|j jtjdnYwxYw)Nzphrase does not start with wordrr zperiod in 'phrase'rzcomment found without atom) rrrrrr'ru PHRASE_ENDSrAObsoleteHeaderDefectrr)rrrSs r get_phrasersR XF0 u e E!HK/ 8S= MM#  NN ! !&"="=$#& '!"IE ' u MM% ! E!HK/" 5=)  " "0f88 -/ 00** 8{*#+E?LE5NN))&*E*E4+677 s%B< D@ @ #E* uHbq e %(D.E!HK$? 23z?U3J K  $ $(@ @    % %f&@&@N'P Q    % %f&A&A>'@ A& 1 >( u 1  " "  #E?LE5&& Qx4E!H $;KE  * >!!&"@"@;#= > u >sHD7F7F EF1F F FFF7GGcP t}d}|rB|ddk(s |dtvr.|ddk(rM|r.|jjt j d|jt d}|dd}l|ddk(rT|jt|dd|dd}|jjt j d d}|r@|d jd k7r.|jjt j d  t|\}}d}|j||r|ddk(r!|dtvr.|s$t jd j||djd k(s2|djdk(rNt|dkDr@|djd k(r.|jjt j d|d jd k(s2|d jdk(rNt|dkDr@|djd k(r.|jjt j d|jrd|_||fS#tj$r|dtvrt|\}}Y{wxYw)NFrrr zinvalid repeated '.'Trmisplaced-specialz/'\' character outside of quoted-string/ccontentrr@zmissing '.' between wordsz&expected obs-local-part but found '{}'rz!Invalid leading '.' in local partrz"Invalid trailing '.' in local partr)r3rr'rrrurArrdrrrrr=r)rr"last_non_ws_was_dotrSs rrrs!^N U1Xt^uQx{'B 8s?"&&--f.H.H*/,-  ! !# &"& !"IE  1Xt^  ! !-a0C#E F!"IE  " " ) )&*D*DB+D E"'   nR0;;uD  " " ) )&*D*D++- . +#E?LE5"'  e$7 U1Xt^uQx{'B8 %% 4 ; ;E BD Dq$$- 1  ( (& 0  ! # 1  ( (% /%%f&@&@ /'1 2r%%. 2  ) )6 1  ! # 2  ) )5 0%%f&@&@ 0'2 3$<! 5  -&& +Qx{*#E?LE5 +sI44-J%$J%c t|d\}}}t|d}|r.|jjt j dt |||fS)Nz[]rJz(quoted printable found in domain-literal)rrr'rrrr)rrJrs r get_dtextr(s_ 2%>E5& % )E  V88 68 9E %<rc|ry|jtjd|jtddy)NFz"end of input inside domain-literal]domain-literal-endT)rrrur)rdomain_literals r_check_for_early_dl_endr-+s? &44,./--ABC rcp t}|dtvrt|\}}|j||st j d|ddk7r$t j dj ||dd}t||r||fS|jtdd|dtvrt|\}}|j|t|\}}|j|t||r||fS|dtvrt|\}}|j|t||r||fS|ddk7r$t j dj ||jtdd |dd}|r*|dtvrt|\}}|j|||fS) Nrzexpected domain-literal[z6expected '[' at start of domain-literal but found '{}'rzdomain-literal-startr*z4expected ']' at end of domain-literal but found '{}'r+) rGrrrrrr=r-rrrr()rr,rSs rget_domain_literalr03s#_N Qx; ue$ %%&?@@ Qx3%%'!!'0 0 !"IEun5u$$--CDE Qx3u~ ue$U#LE5% un5u$$ Qx3u~ ue$un5u$$ Qx3%%'!!'0 0--ABC !"IE q[( ue$ 5  rc$ t}d}|r|dtvrt|\}}|s$tjdj ||ddk(r+t |\}}||g|dd|j|||fS t|\}}|r|ddk(rtjd||g|dd|j||r|ddk(r|jjtjd|djdk(r|d|dd|rJ|ddk(rB|jtt|d d\}}|j||r |ddk(rB||fS#tj$rt|\}}YwxYw) Nrzexpected domain but found '{}'r/r-zInvalid Domainr z(domain is not a dot-atom (contains CFWS)rr)rrrrrr=r0rrr r'rrdrA)rrrrSs r get_domainr2ZsXF F q[(   %% , 3 3E :< < Qx3)%0 u  E"1I eu}'#E* u qS%%&677 Hbq  MM% qSf99 68 9 !9  : -q F1IaC MM# #E!"I.LE5 MM% aC 5=!  " "' u'sE++!FFcP t}t|\}}|j||r|ddk7r2|jjt j d||fS|jt ddt|dd\}}|j|||fS)Nrr-z#addr-spec local part with no domainaddress-at-symbolr)r%r#rr'rrurr2)rrrSs r get_addr_specr5s I!%(LE5 U E!HO  !;!; 1"3 4% ]3(;<=eABi(LE5 U e rc t}|rw|ddk(s |dtvrd|dtvr t|\}}|j|n"|ddk(r|jt|dd}|r|ddk(rX|dtvrd|r|ddk7r$t j dj||jtt|dd\}}|j||r|ddk(r|jt|dd}|snw|dtvrt|\}}|j||snJ|ddk(r7|jtt|dd\}}|j||r |ddk(r|st j d|ddk7r$t j dj||jtdd ||ddfS) Nrrrr-z(expected obs-route domain but found '{}'z%end of header while parsing obs-route:z4expected ':' marking end of obs-route but found '{}'zend-of-obs-route-marker) rrrr ListSeparatorrrr=RouteComponentMarkerr2r)r obs_routerSs r get_obs_router;s  I U1Xs]eAh+&= 8{ "#E?LE5   U # 1X_   ] +!"IE U1Xs]eAh+&= E!HO%% 6 = =e DF F )*eABi(LE5 U E!HcM'ab   8{ "#E?LE5   U #  8s?   1 2%eABi0LE5   U # E!HcM %%&MNN Qx3%%(''-ve}6 6 ]3(ABC eABi rcz t}|r*|dtvrt|\}}|j||r|ddk7r$t j dj ||jtdd|dd}|rZ|ddk(rR|jtdd|jjt jd|dd}||fS t|\}}|j||r|ddk(r|dd}n.|jjt jd |jtdd|r*|dtvrt|\}}|j|||fS#tj $r t|\}}|jjt jd n;#tj $r%t j d j |wxYw|j|t|\}}YHwxYw) Nrzangle-addr-endznull addr-spec in angle-addrz*obsolete route specification in angle-addrz.expected addr-spec or obs-route but found '{}'z"missing trailing '>' on angle-addr) rrrrrrr=rr'rur5r;r)r angle_addrrSs rget_angle_addrr@s9J q[( u% E!HO%% 0 7 7 >@ @mC);<= !"IE qS--=>?!!&"<"< *#, -ab 5   ,$U+ ue qSab !!&"<"< 0#2 3mC)9:; q[( u% u )  " " , P(/LE5    % %f&A&A<'> ?&& P))@GGNP P P % $U+ u ,s*#F H:.+s% 3 11 a33 4 1$&r) r rErrr5r=anyrErdr)rrrSs r get_mailboxrJs iGA$U+ u  3 % 1 1 33. NN5 E>  " "A A(/LE5&& A))188?A A AAs)AB4'A65B468B..B43B4c t}|r_|d|vrX|dtvr$|jt|dd|dd}nt |\}}|j||r|d|vrX||fS)Nrr%r)rrrrr)rrinvalid_mailboxrSs rget_invalid_mailboxrM1s %&O E!HH, 8{ "  " "=q1D$F G!"IE%e,LE5  " "5 ) E!HH, E !!rc^ t}|r|ddk7r t|\}}|j||ra|ddvrZ|d}d|_ t|d\}}|j||jjtjd|r"|ddk(r|jt|d d}|r |ddk7r||fS#tj$rLd}|dt vrt |\}}|r|ddvr@|j||jjtjdnt|d\}}||g|dd|j||jjtjdn|ddk(r/|jjtjdnVt|d\}}||g|dd|j||jjtjdYwxYw) Nr;z,;zempty element in mailbox-listzinvalid mailbox in mailbox-listrrrr)rrJrrrrrr'rrMrurdrQr8)r mailbox_listrSrrs rget_mailbox_listrQCs: =L E!HO 8&u-LE5    &4 U1XT)#2&G!2G .ud;LE5 NN5 !  ' '(B(B1)3 4 U1X_    .!"IEQ E!HOR  K&& 8FQx;& ( aD 0 ''/ ((//0K0K719:$7ud#CLE5)%+Hbq  ''. ((//0J0J91;<qS$$++F,G,G3-56 35$? u%!'E"1I##E*$$++F,F,F5-78/ 8sC EH,+H,c t}|s2|jjtjd||fSd}|r{|dt vrpt |\}}|sC|jjtjd|j|||fS|ddk(r|j|||fSt|\}}t|jdk(rV||j||j||jjtjd||fS||g|dd|j|||fS)Nzend of header before group-listrzend of header in group-listrOzgroup-list with empty entries) rr'rrrurrrQrrrQr)r group_listrrSs rget_group_listrT|sfJ !!&"<"< -#/ 05  F q[(      % %f&@&@-'/ 0   f %u$ $ 8s?   f %u$ $#E*LE5 5  "     f %% !!&"="= +#- .5   Hbq e u rc t}t|\}}|r|ddk7r$tjdj ||j ||j t dd|dd}|r*|ddk(r"|j t dd||ddfSt|\}}|j ||s/|jj tjdn,|ddk7r$tjd j ||j t dd|dd}|r*|dtvrt|\}}|j |||fS) Nrr7z8expected ':' at end of group display name but found '{}'zgroup-display-name-terminatorrrOzgroup-terminatorzend of header in groupz)expected ';' at end of group but found {}) rrBrrr=rrrTr'rurr)rrrSs r get_grouprVsf GE#E*LE5 E!HO%%'**0&-9 9 LL LLs$CDE !"IE qS ]3(:;<eABi!%(LE5 LL  V77 $& ' qS%% 7 > >u EG G LLs$678 !"IE q[( u U %<rc( t} t|\}}|j |||fS#tj$rN t |\}}n;#tj$r%tjdj |wxYwYuwxYw)Nzexpected address but found '{}')rrVrrrJr=r)rrrSs r get_addressrXs iGA ' u NN5 E>  " "A A&u-LE5&& A))188?A A AAs'0BAB8B  BBc` t}|r t|\}}|j||re|ddk7r]|dd}d|_ t|d\}}|j||jjtjd|r|jt|dd}|r||fS#tj$rad}|dt vrt |\}}|r|ddk(r@|j||jjtjdnt|d\}}||g|dd|jt|g|jjtjdn|ddk(r/|jjtjdn`t|d\}}||g|dd|jt|g|jjtjdYwxYw) Nrrz"address-list entry with no contentzinvalid address in address-listzempty element in address-listrrr)rrXrrrrrr'rrMrrurdrQr8)r address_listrSrrs rget_address_listr[s-=L  8&u-LE5    &4 U1X_#2&q)G!2G .uc:LE5 NN5 !  ' '(B(B1)3 4     .!"IEQ R  K&& 8FQx;& ( aC ''/ ((//0K0K<1>?$7uc#BLE5)%+Hbq  ''(89 ((//0J0J91;<qS$$++F,G,G3-56 35#> u%!'E"1I##GUG$45$$++F,F,F5-78/ 8sB88E1H-,H-c t}|s$tjdj||ddk7r$tjdj||j t dd|dd}t |\}}|j ||r|ddk7r$tjdj||j t dd ||ddfS) Nz'expected no-fold-literal but found '{}'rr/z;expected '[' at the start of no-fold-literal but found '{}'zno-fold-literal-startrr*z9expected ']' at the end of no-fold-literal but found '{}'zno-fold-literal-end)r#rrr=rrr()rno_fold_literalrSs rget_no_fold_literalr^s#oO %% 5 < z msg-id-endr4zobsolete id-right in msg-idzFexpected dot-atom-text, no-fold-literal or obs-id-right but found '{}'zmissing trailing '>' on msg-id)rrrrrrr=rrrr'rrur^r2)rmsg_idrSs r get_msg_idra)s WF q[( u e E!HO%% , 3 3E :< < MM-^45 !"IE 1(/ u MM% E!HOf88 %' ( U1X_ MM-\: ;!"IEu} MM-%89: !"IE 5(/ u MM% qSab f88 ,. / MM-\23 q[( u e 5=a  " " 1 1-e4LE5 NN ! !&"="=,#. /&& 1))""(&-1 1 1 / 14  " " 5 5.u5LE5&& 5 5)%0 u%%f&A&A1'34** 5--&&,fUm55 54 5 5sxG-I(I%)> ##F$>$> ? F Fv N%P QM&':; [ M&(;< q[( uE" E!HO    )  ' '(B(BB)D E     eW = > c+>?@ !"IE q[( uE"     )  ' '(B(BB)D E F E!HK/%(ab  E!HK/ >> ##F$>$> ? F Fv N%P QM&':; [ M&(;< q[( uE" ##F$>$> 5%7 8M%9: rc t}|ra|ddk7rY|dtvr$|jt|dd|dd}nt |\}}|j||r |ddk7rY||fS)NrrOr%r)r\rrrr)rinvalid_parameterrSs rget_invalid_parameterros )* E!HO 8{ "  $ $]583F&H I!"IE%e,LE5  $ $U + E!HO e ##rc t|}|s$tjdj||j }|t |d}t |d}t|||fS)Nzexpected ttext but found '{}'ttext)_non_token_end_matcherrrr=rrrr)rrrqs r get_ttextrssp u%A %% + 2 25 9; ; GGIE #e*+ E % )EE %<rcp t}|r*|dtvrt|\}}|j||r/|dtvr$t j dj|t|\}}|j||r*|dtvrt|\}}|j|||fSNrzexpected token but found '{}') rrrr TOKEN_ENDSrrr=rs)rmtokenrSs r get_tokenrxsWF q[( u e qZ'%% + 2 25 9; ;U#LE5 MM% q[( u e 5=rc t|}|s$tjdj||j }|t |d}t |d}t|||fS)Nz expected attrtext but found {!r}rb)_non_attribute_end_matcherrrr=rrrrrrrbs r get_attrtextr| sp #5)A %% . 5 5e <> >wwyH #h-. !EXz2HH U?rcp t}|r*|dtvrt|\}}|j||r/|dtvr$t j dj|t|\}}|j||r*|dtvrt|\}}|j|||fSru) r_rrrATTRIBUTE_ENDSrrr=r|rr`rSs r get_attributer s I q[( u q^+%% + 2 25 9; ;&LE5 U q[( u e rc t|}|s$tjdj||j }|t |d}t |d}t|||fS)Nz)expected extended attrtext but found {!r}extended-attrtext)#_non_extended_attribute_end_matcherrrr=rrrrr{s rget_extended_attrtextr4 ss ,E2A %% 7 > >u EG GwwyH #h-. !EX':;HH U?rcp t}|r*|dtvrt|\}}|j||r/|dtvr$t j dj|t|\}}|j||r*|dtvrt|\}}|j|||fSru) r_rrrEXTENDED_ATTRIBUTE_ENDSrrr=rrs rget_extended_attributerF s I q[( u q44%% + 2 25 9; ;(/LE5 U q[( u e rcn t}|r|ddk7r$tjdj||j t dd|dd}|r|dj s$tjdj|d}|r6|dj r#||dz }|dd}|r|dj r#|ddk(r3|dk7r.|jj tjd t||_ |j t |d ||fS) Nr*zExpected section but found {}zsection-markerrz$Expected section number but found {}r-0z'section number has an invalid leading 0rg) rfrrr=rrrir'rurjrV)rrgrgs r get_sectionr\ s7iG E!HO%%&E&L&L(-'/0 0 NN=&678 !"IE a((*%%'117@ @ F E!H$$&%(ab  E!H$$&ayCFcMv999 ; <[GN NN=23 E>rcL t}|stjdd}|dtvrt |\}}|s$tjdj ||ddk(rt |\}}nt|\}}||g|dd|j|||fS)Nz&Expected value but found end of stringrz Expected value but found only {}r) rirrrrr=r rr)rvrrSs r get_valuerz s A %%&NOO F Qx;   %%'006v@ @ Qx3(/ u-e4 u Hbq HHUO e8Orc t}t|\}}|j||r|ddk(rA|jjt j dj |||fS|ddk(rm t|\}}d|_|j||st jd|ddk(r'|jtdd|dd}d|_ |dd k7rt jd |jtd d |dd}|r*|dtvrt|\}}|j|d}|}|jr|r|dd k(rt|\}}|j}d }|j dk(r(|r |ddk(rd}n/t#|\}}|r|ddk(rd}n t%|\}}|sd} |ra|jjt j d|j||D]} | j&dk(sg| dd| }n|}n0d}|jjt j d|r |ddk(rd}nt)|\}}|jr|j dkDrQ|r|ddk7r|j|||}||fS|jjt j d|sF|jjt j d|j||#||fS|I|D]} | j&dk(sn j&dk(|j| | j*|_|ddk7r$t jdj ||jtdd|dd}|rf|ddk7r^t#|\}}|j||j*|_|r|ddk7r$t jdj ||jtdd|dd}|et1} |rV|dt2vrt5|\}}n(|dd k(rtd d}|dd}nt7|\}}| j||rV| }nt)|\}}|j|||}||fS#tj$rYWwxYw#Y.xYw)NrrOz)Parameter contains name ({}) but no valuerTzIncomplete parameterzextended-parameter-markerr=zParameter not followed by '='parameter-separatorrF'z5Quoted string value for extended parameter is invalidrzZParameter marked as extended but appears to have a quoted string value that is non-encodedzcApparent initial-extended-value but attribute was not marked as extended or was not initial sectionz(Missing required charset/lang delimitersrrbz=Expected RFC2231 char/lang encoding delimiter, but found {!r}zRFC2231-delimiterz;Expected RFC2231 char/lang encoding delimiter, but found {}DQUOTE)rQrrr'rrur=rrUrrrZrrr rrWr|rrdrrrrrirrr) rrrSrappendtoqstring inner_value semi_validrtrs r get_parameterr s KE 'LE5 LL E!HO V779%%+VE]4 5e| Qx3 &u-LE5"EO LL ))*@A A 8s? LLs,GH I!"IE!EN Qx3%%&EFF LLs$9:; !"IE q[( u UIH ~~%E!HO/u5,,    1 ${1~4! *;7 tDGsN!%J &3K@ t!%J  MM !;!;G"I J LL !<<#77AaD H   EI MM !;!;:"; < qS ' u >>U11A5aC OOE "$!%<  V77 DE F  V77 68 9  %<   <<#66 LLJ & OOA GGEM 8s?))+FFLfUmU U c+>?@ab  U1X_'.LE5 OOE "EJE!HO--/<?@ab  GQx3&u~ uqS%c84ab +E2 u HHUO ' u OOE %<i&&   D s?&S&T&S=<S=Tc t}|r t|\}}|j||rp|ddk7rh|d}d|_ t|\}}|j||jjtjdj||r |jtdd|d d}|r|S#tj$rd}|dt vrt |\}}|s|j||cYS|ddk(rB||j||jjtjdndt|\}}|r|g|dd|j||jjtjdj|YwxYw) NrrOzparameter entry with no contentzinvalid parameter {!r}rr]z)parameter with invalid trailing text {!r}rr)rlrrrrrrr'ruror=rdrQr)rmime_parametersrSrrs rparse_mime_parametersr s %&O  =(/LE5  " "5 )( U1X_$B'E2E 07LE5 LL   # # * *6+E+E;BB5I,K L   " "=6K#L M!"IEG H A&& =FQx;& ( &&v.&&Qx3%#**62''..v/I/I5078 5U; u!'E"1I&&u-''..v/I/I,33E:0<=# =sCAF> B.F>=F>cB |ra|ddk7rY|dtvr$|jt|dd|dd}nt|\}}|j||r |ddk7rY|sy|jtdd|jt |ddy)NrrOr%rr)rrrrr) tokenlistrrSs r_find_mime_parametersrQ s E!HO 8{ "   ]585HI J!"IE%e,LE5   U # E!HO  ]3(=>? *5956rc: t}|s0|jjtjd|S t |\}}|j||r|ddk7r>|jjtjd|r t|||S|jjj|_ |jtdd|dd} t |\}}|j||jjj|_|s|S|dd k7rO|jjtjd j||` |`t|||S|jtd d |jt!|dd|S#tj $rN|jjtjdj|t|||cYSwxYw#tj $rN|jjtjdj|t|||cYSwxYw) Nz"Missing content type specificationz(Expected content maintype but found {!r}rrzInvalid content typezcontent-type-separatorrz'Expected content subtype but found {!r}rOz> 02 3  ' u  LL E!HO V77 "$ %  !% / [[&&(..0EN LLs$<=> !"IE ' u  LLKK%%'--/EM   Qx3 V77 ( ) NEMeU+  LLs$9:; LL&uQRy12 LQ  " " V77 6 = =e DF GeU+ &  " " V77 5 < . s%.,qa!>!>?,rH unknown-8bitTrmrUrr rrrJrwrr)"max_line_lengthsysmaxsizeutf8rrr7rrd SPECIALSNL isdisjointNLSETr r{rIrE_fold_mime_parametersrMrjrYrrrrre _fold_as_ewrkrJrr7rrrinsert) parse_treerVmaxlenrqrleading_whitespacelast_ew last_charsetr want_encodingend_ew_not_allowedrrNtstrr encoded_partnewlinewhitespace_accumulatorcharnewpartsps rrWrW s # # 2s{{F ++w:H DEGLM!"&:;  E yy| % % ! #  4y"44$.$9$9$$? ? %*$4$4T$: :  ! KK !G ??/ / !$vx @  !3%% % ''#'99F9#;Q=Q#RL~~\9|,vE"I/FF&CE&JG!LL1b \1  4*T U* % ##'|+!^3!W,J1F"G%dE67&*&=&=wHZ\&("& %  %  t9U2Y/ / "I I     D A '3E:G$--/  Wt^,)+&!"ID3*11$7&&(WW-C%D"tX&DzH"66 #301&(&##4Q#7A&((#3012 )+"301'(& /##9!#>  u % 66}" !. ,,..(" M !B( (s;P*$Q2-Q"*,QQc  |+|r)tt|d|d|z}|dd||d<nM|dtvrB|d}|dd}t|d|k(r|j t ||dxx|z cc<d}|dtvr |d}|dd}|t|dn|} |dk(rdn|} t| dz} | dz|k\rt jd|r!|t|dz } | | z t|z } | dkr|j d  b [ L} } crN $+O#eBi.K"j0gIY!#JQ6!%% AC C  3uRy>1$z1C8J4KK ? LL   u:>c%)n16H::&8)LL "I %I!# ";J/zz.)D \"_4qj,CR0N::niHL&8F qj b \! c.123   LL eBi.K? @ "II,;6$6rc  |jD]\}}|djjds |dxxdz cc<|}d} |j|d}|r6tjj|d | } d j||| } nd j|t|} t|dt| zd z|kr|ddz| z|d<t| dz|kr|jd| zd} |dz} |st|tt| zdzt| z} || dzkrd}|| z dz x}} |d|}tjj|d | } t| |krn|d z}<|jdj|| | | d } | d z } ||d}|r |dxxdz cc<|ry#t$r"d}t j |rd}d}nd}YwxYw)NrrOstrictFTrrprr-)saferz {}*={}''{}rrrsrrz''r(Nz {}*{}*={}{})rr*rcr r{rr|rvrwrr=r rrr)rNrrrqrrr error_handlerencoding_required encoded_valuerrg extra_chromer splitpointmaxcharspartials rrr sF{{ e Ry!**3/ "I I  " LL " %  "LL..B}/6M&&tWmDD>>$ U(;CI % )F 2b C$.E"I  Y]f $ LLt $ ~ TSW%66:S=NNJa' $*Z$7!$; ;J , & 2 2"]!3!< }%1a  LL..g|]< =L qLG*+&Eb S -I#" " $ $$U+( 1 !  "s G'G?>G?)r)rerrvstringroperatorremailrrrrr.rrrr r/r TSPECIALSrv ASPECIALSr~rrrrrr compileVERBOSE MULTILINErrr"rpr|rrrrrrrrrrrrrrrrrr rrrr r#r%r3r5r=rGrMrQr\r_rfrirlrrrrrrrrrrrrrrrrrAr8rMrjr9r=r7rrrmatchrfindallrrrrzrrrrrrrrrrrrr r rrrrr#rr(r-r0r2r5r;r@rBrErJrMrQrTrVrXr[r^rarerlrorsrxr|rrrrrrrrrrrrrWrrrtrrrs:CJ '  %jCHn   sN CH$ U# E "c#h . _ E " S(3s83 t    @ 1  "**ZZ",, @,@,FD)D I Y9"9I )#9#6 -| -!4C)C&%i%2 ?) ?% %"$I$*"y"6 DDyD!i!6;Y;.Y.i) I yB9 -!&-!`! !H I  ) 8%y% # #i I S.YS.l y *1 i ) *I*&y&Y(+s(+V''H->#I$4$4 BIIbggj!"%$%%*U'RZZ (8(8 BIIbggn%&)()).&0bjj1A1A BIIbgg-./21'227%$;J< /bAF"  ))V2  $6 &2 D$L%N2!h(%!N$L ) V,\ "H*"$6r#J<:4n&,BJ8BH$$&.&.$,<,KZ2h7 6p<^`7DJ7XI!r__pycache__/feedparser.cpython-312.opt-2.pyc000064400000043100152526700320014537 0ustar00 {|j YP ddgZddlZddlmZddlmZddlmZddlm Z ejdZ ejd Z ejd Z ejd Zejd Zd Zd ZeZGddeZGddZGddeZy) FeedParserBytesFeedParserN)errors)compat32)deque)StringIOz \r\n|\r|\nz (\r\n|\r|\n)z(\r\n|\r|\n)\Zz%^(From |[\041-\071\073-\176]*:|[\t ]) cJeZdZ dZdZdZdZdZdZdZ dZ d Z d Z y ) BufferedSubFilec`td|_t|_g|_d|_y)Nr )newlineF)r_partialr_lines _eofstack_closedselfs )/usr/lib64/python3.12/email/feedparser.py__init__zBufferedSubFile.__init__4s'!, g  c:|jj|yN)rappend)rpreds rpush_eof_matcherz BufferedSubFile.push_eof_matcher?s d#rc6|jjSr)rpoprs rpop_eof_matcherzBufferedSubFile.pop_eof_matcherBs~~!!##rc|jjd|j|jj|jjd|jj d|_y)NrT)rseek pushlines readlinestruncaterrs rclosezBufferedSubFile.closeEsV 1 t}}..01 1   rc|js|jrytS|jj}t |j D]'}||s |jj |y|SNr )rr NeedMoreDatapopleftreversedr appendleft)rlineateofs rreadlinezBufferedSubFile.readlineMse{{|| {{""$dnn-ET{ &&t, .  rc:|jj|yr)rr+rr,s r unreadlinezBufferedSubFile.unreadline_s t$rc |jj|d|vrd|vry|jjd|jj}|jjd|jj |dj ds)|jj|j |j|y)Nr  r)rwriter!r#r$endswithrr")rdatapartss rpushzBufferedSubFile.pushds2 D! t D 0  1 '') 1  Ry!!$' MM   , urc:|jj|yr)rextend)rliness rr"zBufferedSubFile.pushlinesys 5!rc|Srrs r__iter__zBufferedSubFile.__iter__|s rc<|j}|dk(rt|Sr')r. StopIterationr0s r__next__zBufferedSubFile.__next__s}} 2:  rN) __name__ __module__ __qualname__rrrr%r.r1r9r"r?rBr>rrr r ,s9 $$$% *"rr cLeZdZ d eddZdZdZdZdZdZ d Z d Z d Z y) rNpolicyct ||_d|_|,|jddlm}||_n-|j|_n||_ ||jt|_g|_ |jj|_ d|_ d|_d|_y#t $r d|_Y]wxYw)NFr)MessagerGT)rH_old_style_factorymessage_factory email.messagerJ_factory TypeErrorr _input _msgstack _parsegenrB_parse_cur_last _headersonly)rrNrHrJs rrzFeedParser.__init__s  "'  %%-1 ' & 6 6 $DM / ,&' nn&//   ! /*.' /sB$$B76B7cd|_y)NT)rVrs r_set_headersonlyzFeedParser._set_headersonlys  rc\ |jj||jyr)rPr9 _call_parse)rr7s rfeedzFeedParser.feeds#-  rcD |jy#t$rYywxYwr)rSrArs rrZzFeedParser._call_parses"  KKM   s  c: |jj|j|j}|j dk(rL|j s<|j s0tj}|jj|||S)N multipart) rPr%rZ _pop_messageget_content_maintype is_multipartrVr!MultipartInvariantViolationDefectrH handle_defect)rrootdefects rr%zFeedParser.closes}J    "  $ $ &+ 5((*43D3D==?F KK % %dF 3 rc|jr|j}n|j|j}|jr.|jj dk(r|j d|j r|j dj||j j|||_||_ y)NrGzmultipart/digestzmessage/rfc822r4) rKrNrHrTget_content_typeset_default_typerQattachrrU)rmsgs r _new_messagezFeedParser._new_messages  " "--/C--t{{-3C 993359KK  !1 2 >> NN2  % %c * c"  rc|jj}|jr|jd|_|Sd|_|S)Nr4)rQrrT)rretvals rr_zFeedParser._pop_messages@##% >>r*DI DI rc#BK|jg}|jD]}|tur ttj |slt j |sUt j}|jj|j||jj|n|j||j||jrug} |jj}|tur t,|dk(rn|j|C|jj!t"j%|y|jj'dk(r |jj)t j|j+D]}|tur tn|j-|jj/ |jj}|tur t, |jj}|tur t, |dk(r y|jj||jj1dk(r8|j+D]}|tur tn|j-y|jj1dk(r|jj3}|t j4}|jj|j|g}|jD]$}|tur t|j|&|jj!t"j%|yt7|jj9ddj;dvr:t j<}|jj|j|d |z}t?j@d t?jB|zd z}d} g} d } d } |jj}|tur t,|dk(rn|j |} | r| jEd rd} | jEd} ny| r| ra| d}tFjI|}|r!|dtK|jEd | d<t"j%| |j_&d } |jj| |jj}|tur t,|j |} | s|jj|n[|jj)|j|j+D]}|tur tn|jNj1dk(rv|jNjP}|dk(rd|jN_(n|tFjI|} | rtK| jEd}|d| |jN_(nl|jNjR}tU|t6rFtFjI|} | r/|dtK| jEd }||jN_)|jj/|j-|j|_'n| j|| rt jV}|jj|j||jj!t"j%| g}|jD]}|tus tt"j%||j_(y| s;t jX}|jj|j|y| rdg}ng}|jD]$}|tur t|j|&|r<|d}tZj |}|r |tK|jEdd|d<t"j%||j_(yg}|jD]$}|tur t|j|&|jj!t"j%|yw)NTr zmessage/delivery-statusmessager^zcontent-transfer-encoding8bit)7bitrpbinaryz--z(?Pz4)(?P--)?(?P[ \t]*)(?P\r\n|\r|\n)?$Fendlinesepr4r).rkrPr(headerREmatchNLCREr MissingHeaderBodySeparatorDefectrHrcrTr1r_parse_headersrVr. set_payload EMPTYSTRINGjoinrgrrRr_rr` get_boundaryNoBoundaryInMultipartDefectstrgetlower-InvalidMultipartContentTransferEncodingDefectrecompileescapegroup NLCRE_eolsearchlenpreamblerUepilogue_payload isinstanceStartBoundaryNotFoundDefectCloseBoundaryNotFoundDefect NLCRE_bol)rheadersr,rer<rmboundary separator boundaryrecapturing_preamblerrtclose_boundary_seenmolastlineeolmorrspayload firstlinebolmos rrRzFeedParser._parsegens KKD|#"">>$'{{4(#DDFFKK--dii@KK**40 NN4  G$   E{{++-<'&&2: T" II ! !+"2"25"9 :  99 % % '+D D  ,,U[[9"nn.F-**  / !!# ++- ;;//1D|+** ;;//1D|+** 2:  &&t,?B 99 ) ) +y 8..*\)&& +      99 ) ) +{ :yy--/H  ;;= ))$))V< KKD|+** LL& (  %%k&6&6u&=>DIIMM"=vFGMMO56MMO ))$))V< xIRYYy11GHIJ"& HG"' {{++-<'&&2:%%d+ xx.2+"$((9"5)#(0|H$-$4$4X$>E$/78M#ekk!n:M9M/N 1<1A1A(1KDII.-2* ..t4 #{{335</"..$'--d3! KK2248!KK001A1AB"&.."2!\1"..$ #3zz668KG#'::#6#6#r>26DJJ/%1!*!1!1(!;B!&)"((1+&66>uo 3"&**"5"5%gs3!*!1!1'!:B!*12DC 4D3D*E6= 3KK//1%%'"&DJOOD)_f";;= ))$))V< %%k&6&6x&@A KKD|+** (&1%5%5h%? "';;= ))$))V<4 <'&&% $$QK ! 2"+C A,?,@"AHQK!,!1!1(!;DII  KKD|#"" LL   k..u56s ^.d1E.dcd}g}t|D]\}}|ddvrP|s>yI J rr) rCrDrErrrXr[rZr%rkr_rRryr>rrrrs<'"">!   {7z:Krc eZdZ fdZxZS)rcDt||jddy)Nasciisurrogateescape)superr[decode)rr7 __class__s rr[zBytesFeedParser.feeds  T[[*;<=r)rCrDrEr[ __classcell__)rs@rrrs2>>r)__all__remailremail._policybaser collectionsriorrrwrr NLCRE_crackrur{NLobjectr(r rrr>rrrs " * + & =! BJJ ' BJJ( ) bjj)  2::> ?  x WfWtIKIKX >j>r__pycache__/headerregistry.cpython-312.opt-2.pyc000064400000061371152526700320015452 0ustar00 {|jSQ* ddlmZddlmZddlmZddlmZGddZGddZGd d e Z d Z Gd d Z Gdde Z GddZGddeZGddZGddeZGddeZGddeZGddZGddZGd d!eZGd"d#eZGd$d%ZGd&d'Zid(e d)ed*ed+ed,ed-ed.ed/ed0ed1ed2ed3ed4ed5ed6ed7ed8eeeed9ZGd:d;Zy<)=)MappingProxyType)utils)errors)_header_value_parsercfeZdZd dZedZedZedZedZdZ dZ d Z y) AddressNc  djtd||||f}d|vsd|vr td|w|s|r tdt j |\}}|rtdj |||jr|jd|j}|j}||_ ||_ ||_ y)N  z8invalid arguments; address parts cannot contain CR or LFz=addrspec specified when username and/or domain also specifiedz6Invalid addr_spec; only '{}' could be parsed from '{}'r) joinfilter ValueError TypeErrorparser get_addr_specformat all_defects local_partdomain _display_name _username_domain)self display_nameusernamer addr_specinputsa_srests -/usr/lib64/python3.12/email/headerregistry.py__init__zAddress.__init__s |Xvy&QRS 6>TV^WX X  6!899,,Y7IC "==CV$'>455ooa((~~HZZF)! c|jSNrrs r!rzAddress.display_name8!!!r#c|jSr%)rr's r!rzAddress.username< ~~r#c|jSr%)rr's r!rzAddress.domain@ ||r#c |j}tjj|stj|}|j r|dz|j zS|sy|S)N@<>)rr DOT_ATOM_ENDS isdisjoint quote_stringr)rlps r!rzAddress.addr_specDs[ ]]##..r2$$R(B ;;8dkk) ) r#cdj|jj|j|j|j S)Nz1{}(display_name={!r}, username={!r}, domain={!r}))r __class____name__rrrr's r!__repr__zAddress.__repr__Rs9BII//))4==$++G Gr#c|j}tjj|stj|}|r/|j dk(rdn |j }dj ||S|j S)Nr/r z{} <{}>)rrSPECIALSr1r2rr)rdisprs r!__str__zAddress.__str__Wse  ))$/&&t,D "nnd2I##D)4 4~~r#ct|tstS|j|jk(xr4|j|jk(xr|j |j k(Sr%) isinstancerNotImplementedrrrrothers r!__eq__zAddress.__eq__`sU%)! !!!U%7%77, /, u||+ -r#)r r r N) r6 __module__ __qualname__r"propertyrrrrr7r;rAr#r!rr sh(T""  G -r#rcFeZdZddZedZedZdZdZdZ y) GroupNcX ||_|rt||_yt|_yr%)rtuple _addresses)rr addressess r!r"zGroup.__init__js' *.7% *UWr#c|jSr%r&r's r!rzGroup.display_name|r(r#c|jSr%)rJr's r!rKzGroup.addressess r#cxdj|jj|j|jS)Nz${}(display_name={!r}, addresses={!r})rr5r6rrKr's r!r7zGroup.__repr__s15<<((""DNN4 4r#cx|j0t|jdk(rt|jdS|j}|4tj j |st j|}djd|jD}|rd|zn|}dj||S)Nr, c32K|]}t|ywr%)str).0xs r! z Group.__str__..s:>a3q6>s z{}:{};) rlenrKrSrr9r1r2r r)rr:adrstrs r!r;z Group.__str__s    $T^^)$>t$D&&t,D:4>>::!'vVtV,,r#ct|tstS|j|jk(xr|j|jk(Sr%)r=rGr>rrKr?s r!rAz Group.__eq__s@%'! !!!U%7%772%//1 3r#)NN) r6rBrCr"rDrrKr7r;rArEr#r!rGrGhs?E$""4 -3r#rGcVeZdZ dZdZedZedZdZe dZ dZ y) BaseHeadercdgi}|j||tj|drtj|d|d<tj ||d}|d=|j |fi||S)Ndefectsdecoded)parser_has_surrogates _sanitizerS__new__init)clsnamevaluekwdsrs r!rczBaseHeader.__new__st2 %  i 1#ood9o>DO{{3Y0 O $$ r#c.||_||_||_yr%)_name _parse_tree_defects)rrf parse_treer^s r!rdzBaseHeader.inits % r#c|jSr%)rjr's r!rfzBaseHeader.names zzr#c,t|jSr%)rIrlr's r!r^zBaseHeader.defectssT]]##r#ct|jj|jjt |f|j fSr%)_reconstruct_headerr5r6 __bases__rS __getstate__r's r! __reduce__zBaseHeader.__reduce__sC ''((D      ! !r#c.tj||Sr%)rSrc)rergs r! _reconstructzBaseHeader._reconstructs{{3&&r#c  tjtjtj|jdtjddgg}|j r9|j tjtjddg|j |j |j|S)Nz header-name:z header-seprWfws)policy) rHeader HeaderLabel ValueTerminalrfrkappendCFWSListWhiteSpaceTerminalfold)rrzheaders r!rzBaseHeader.folds    $$TYY >$$S,7 9 :     MM!:!:3!F GH J d&&'{{&{))r#N) r6rBrCrcrdrDrfr^rt classmethodrvrrEr#r!r\r\sX@ $$!''*r#r\c:t||ij|Sr%)typerv)cls_namebasesrgs r!rqrqs % $ 1 1% 88r#cDeZdZdZeej ZedZ y)UnstructuredHeaderNcN|j||d<t|d|d<y)Nrmr_) value_parserrSrergrhs r!r`zUnstructuredHeader.parse s* --e4\d<01Yr#) r6rBrC max_count staticmethodrget_unstructuredrrr`rEr#r!rrs)I 7 78L22r#rceZdZdZy)UniqueUnstructuredHeaderrPNr6rBrCrrEr#r!rrIr#rcheZdZ dZeej ZedZ fdZ e dZ xZ S) DateHeaderNc|sH|djtjd|d<d|d<tj|d<yt |t r||d< tj|}||d<tj|d|d<|j|d|d<y#t$rF|djtjdd|d<tj|d<YywxYw)Nr^datetimer r_rmzInvalid date value or format) r~rHeaderMissingRequiredValuer TokenListr=rSrparsedate_to_datetimerInvalidDateDefectformat_datetimerrs r!r`zDateHeader.parse$s O " "6#D#D#F G#D  DO!'!1!1!3D   eS !#DO 33E: !Z//Z0@AY --d9o>\ Y&&v'?'?@^'_`#'Z %+%5%5%7\"  s!B..A C=<C=cP|jd|_t| |i|y)Nr)pop _datetimesuperrdrargskwr5s r!rdzDateHeader.init9s$ +  d!b!r#c|jSr%)rr's r!rzDateHeader.datetime=r*r#)r6rBrCrrrrrrr`rdrDr __classcell__r5s@r!rrsLI  7 78L??("r#rceZdZdZy)UniqueDateHeaderrPNrrEr#r!rrBrr#rcbeZdZdZedZedZfdZe dZ e dZ xZ S) AddressHeaderNc6tj|\}}|Sr%)rget_address_list)rg address_lists r!rzAddressHeader.value_parserKs$55e< er#ct|tr|j|x|d<}g}|jD]t}|j t |j |jDcgc]9}t|j xsd|jxsd|jxsd;c}vt|j}n9t|ds|g}|Dcgc]}t|ds t d|gn|}}g}||d<||d<dj|Dcgc] }t|c}|d<d|vr|j|d|d<yycc}wcc}wcc}w) Nrmr __iter__rKgroupsr^rQr_)r=rSrrKr~rGr all_mailboxesrrrlistrhasattrr ) rergrhrraddrmbr^items r!r`zAddressHeader.parseQs eS !140@0@0G GD F$.. eD$5$504/A/A%C0B&-R__-B-/]]-@b-/YY_"&>0B%CDE/ <334G5*-1670529{1KeD4&)/3405 7GX!Y))6$B64SY6$BCY t #!$!1!1$y/!BD  $!%C7 %Cs!>E "EEcpt|jd|_d|_t ||i|y)Nr)rIr_groupsrJrrdrs r!rdzAddressHeader.initms0RVVH-.   d!b!r#c|jSr%)rr's r!rzAddressHeader.groupsrr,r#ct|j!td|jD|_|jS)Nc3BK|]}|jD]}|ywr%)rK)rTgroupaddresss r!rVz*AddressHeader.addresses..ys($L;@??%,;J%,s)rJrIrr's r!rKzAddressHeader.addressesvs5 ?? "#$L$LLDOr#) r6rBrCrrrrr`rdrDrrKrrs@r!rrGs]I CC6" r#rceZdZdZy)UniqueAddressHeaderrPNrrEr#r!rr~rr#rceZdZedZy)SingleAddressHeaderct|jdk7r$tdj|j|jdS)NrPz9value of single address header {} is not a single addressr)rXrKrrrfr's r!rzSingleAddressHeader.addresssB t~~  !#$*F499$57 7~~a  r#N)r6rBrCrDrrEr#r!rrs !!r#rceZdZdZy)UniqueSingleAddressHeaderrPNrrEr#r!rrrr#rceZdZdZeej ZedZ fdZ e dZ e dZ e dZxZS)MIMEVersionHeaderrPc:|j|x|d<}t||d<|dj|j|jdn |j |d<|j|d<|jdj |d|d|d<yd|d<y)Nrmr_r^majorminorz{}.{}version)rrSextendrrrrrergrhrms r!r`zMIMEVersionHeader.parses*-*:*:5*AA\Zj/Y Yz556 * 0 0 8j>N>NW "((W    '%nnT']DMJDO"DOr#c|jd|_|jd|_|jd|_t ||i|y)Nrrr)r_version_major_minorrrdrs r!rdzMIMEVersionHeader.initsBy) ffWo ffWo   d!b!r#c|jSr%)rr's r!rzMIMEVersionHeader.major {{r#c|jSr%)rr's r!rzMIMEVersionHeader.minorrr#c|jSr%)rr's r!rzMIMEVersionHeader.version }}r#)r6rBrCrrrparse_mime_versionrrr`rdrDrrrrrs@r!rrskI 9 9:L # #" r#rcBeZdZdZedZfdZedZxZ S)ParameterizedMIMEHeaderrPcf|j|x|d<}t||d<|dj|j|ji|d<y|jDcic]<\}}t j |jt j |>c}}|d<ycc}}w)Nrmr_r^params)rrSrrrrrblower)rergrhrmrfs r!r`zParameterizedMIMEHeader.parses*-*:*:5*AA\Zj/Y Yz556    $DN 3=2C2CE2C;4$ood399;$)OOE$:;2CEDNEs$AB-cP|jd|_t| |i|y)Nr)r_paramsrrdrs r!rdzParameterizedMIMEHeader.inits$vvh'   d!b!r#c,t|jSr%)rrr's r!rzParameterizedMIMEHeader.paramss --r#) r6rBrCrrr`rdrDrrrs@r!rrs7 I E E"..r#rcreZdZeej ZfdZedZ edZ edZ xZ S)ContentTypeHeaderct||i|tj|jj |_tj|jj|_yr%) rrdrrbrkmaintype _maintypesubtype_subtypers r!rdzContentTypeHeader.initsL  d!b!)9)9)B)BC(8(8(@(@A r#c|jSr%)rr's r!rzContentTypeHeader.maintyper*r#c|jSr%)rr's r!rzContentTypeHeader.subtyperr#c:|jdz|jzS)N/)rrr's r! content_typezContentTypeHeader.content_types}}s"T\\11r#) r6rBrCrrparse_content_type_headerrrdrDrrrrrs@r!rrsU @ @ALB 22r#rcReZdZeej ZfdZedZ xZ S)ContentDispositionHeaderct||i||jj}|||_yt j ||_yr%)rrdrkcontent_dispositionrrb_content_disposition)rrrcdr5s r!rdzContentDispositionHeader.initsA  d!b!    1 1*,*B!%//":M!r#c|jSr%)rr's r!rz,ContentDispositionHeader.content_dispositions(((r#) r6rBrCrr parse_content_disposition_headerrrdrDrrrs@r!rrs- G GHLN ))r#rcfeZdZdZeej ZedZ fdZ e dZ xZ S)ContentTransferEncodingHeaderrPc|j|x|d<}t||d<|dj|jyNrmr_r^rrSrrrs r!r`z#ContentTransferEncodingHeader.parseA*-*:*:5*AA\Zj/Y Yz556r#ct||i|tj|jj |_yr%)rrdrrbrkcte_cters r!rdz"ContentTransferEncodingHeader.inits0  d!b!OOD$4$4$8$89 r#c|jSr%)rr's r!rz!ContentTransferEncodingHeader.ctes yyr#)r6rBrCrrr&parse_content_transfer_encoding_headerrrr`rdrDrrrs@r!rrsCI M MNL77 :r#rcDeZdZdZeej ZedZ y)MessageIDHeaderrPc|j|x|d<}t||d<|dj|jyrrrs r!r`zMessageIDHeader.parserr#N) r6rBrCrrrparse_message_idrrr`rEr#r!rr s)I 7 78L77r#rsubjectdatez resent-datez orig-datesenderz resent-sendertoz resent-toccz resent-ccbccz resent-bccfromz resent-fromzreply-toz mime-versionz content-type)zcontent-dispositionzcontent-transfer-encodingz message-idc.eZdZ eedfdZdZdZdZy)HeaderRegistryTct i|_||_||_|r |jjtyyr%)registry base_class default_classupdate_default_header_map)rrruse_default_maps r!r"zHeaderRegistry.__init__6s:  $*  MM !4 5 r#c@ ||j|j<yr%)r rrrfres r! map_to_typezHeaderRegistry.map_to_typeHs '* djjl#r#c|jj|j|j}t d|j z||j fiS)N_)r getrrrr6rrs r! __getitem__zHeaderRegistry.__getitem__NsEmm d.@.@AC $sDOO&rs #0Y-Y-x/3/3ha*a*H9221 ++\z 44n- !-! 3 ""J..:2/2, )6 )* 7 7 $< $4J$4   $=  $7  $7M $7M $7M $7M$7 $5!"$5#$%=$A$3).*'*'r#__pycache__/generator.cpython-312.pyc000064400000051362152526700320013456 0ustar00 {|jSdZgdZddlZddlZddlZddlZddlmZddlm Z m Z ddl m Z ddl mZdZd Zej"d Zej"d ej&Zej"d Zej"d ZGddZGddeZdZGddeZeeej:dz ZdezZej@Z y)z:Classes to generate plain text from a message object tree.) GeneratorDecodedGeneratorBytesGeneratorN)deepcopy)StringIOBytesIO)_has_surrogates)HeaderWriteError_ z \r\n|\r|\nz^From z\r\n[^ \t]|\r[^ \n\t]|\n[^ \t]s\r\n[^ \t]|\r[^ \n\t]|\n[^ \t]ceZdZdZddddZdZddZdZdZd Z d Z d Z d Z d Z dZeZdZdZdZdZeddZedZy)rzGenerates output from a Message object tree. This basic generator writes the message to the given file object as plain text. Npolicyc`||dn |j}||_||_||_||_y)aCreate the generator for message flattening. outfp is the output file-like object for writing the message to. It must have a write() method. Optional mangle_from_ is a flag that, when True (the default if policy is not set), escapes From_ lines in the body of the message by putting a `>' in front of them. Optional maxheaderlen specifies the longest length for a non-continued header. When a header line is longer (in characters, with tabs expanded to 8 spaces) than maxheaderlen, the header will split as defined in the Header class. Set maxheaderlen to zero to disable header wrapping. The default is 78, as recommended (but not required) by RFC 2822. The policy keyword specifies a policy object that controls a number of aspects of the generator's operation. If no policy is specified, the policy associated with the Message object passed to the flatten method is used. NT) mangle_from__fp _mangle_from_ maxheaderlenr)selfoutfprrrs (/usr/lib64/python3.12/email/generator.py__init__zGenerator.__init__&s92  #)>4v7J7JL)( c:|jj|yN)rwriterss rrzGenerator.writeFs qrc|j |jn |j}||j|}|j|j|j}|j|_|j |j|_d|_|j |j|_|j}|j} ||_||_|rZ|j}|s*dtjtjz}|j||jz|j|||_||_y#||_||_wxYw)aPrint the message object tree rooted at msg to the output file specified when the Generator instance was created. unixfrom is a flag that forces the printing of a Unix From_ delimiter before the first object in the message tree. If the original message has no From_ delimiter, a `standard' one is crafted. By default, this is False to inhibit the printing of any From_ delimiter. Note that for subobjects, no From_ line is printed. linesep specifies the characters used to indicate a new line in the output. The default value is determined by the policy specified when the Generator instance was created or, if none was specified, from the policy associated with the msg. N)linesepmax_line_lengthz From nobody )rclonerr _NL_encode _encoded_NL_EMPTY_encoded_EMPTY get_unixfromtimectimer_write)rmsgunixfromr rold_gen_policyold_msg_policyufroms rflattenzGenerator.flattenJs%* ${{2   \\'\2F    (\\$2C2C\DF>><<1 "ll4;;7  ( DKCJ((**TZZ -DDE 5488+, KK (DK'CJ)DK'CJs A;EE,cT|j||jd|jS)z1Clone this generator with the exact same options.Nr) __class__rr)rfps rr$zGenerator.clone{s-~~b"00"%)[[2 2rctSr)rrs r _new_bufferzGenerator._new_buffers zrc|Srrs rr&zGenerator._encodesrc|sytj|}|ddD].}|j||j|j0|dr|j|dyy)N)NLCREsplitrr%)rlineslines r _write_lineszGenerator._write_liness`  E"#2JD JJt  JJtxx  9 JJuRy ! rc |j} d|_|jx|_}|j|||_|j}|`|rOt |}|j d |d|d<n|j d|d|j d|dt|dd}||j|n|||jj|jy#||_|j}|`wxYw)Ncontent-transfer-encodingrContent-Transfer-Encoding content-type_write_headers) r _munge_cter9 _dispatchrgetreplace_headergetattrrHrgetvalue)rr.oldfpsfp munge_ctemeths rr-zGenerator._writes "DO!--/ /DHs NN3 DHI 3-Cww23;3 ! M   ~y| <s,d3 <    $ J s||~&'DHIs /C66D c&|j}|j}tj||fj dd}t |d|zd}|0|j dd}t |d|zd}| |j }||y)N-r _handle_)get_content_maintypeget_content_subtype UNDERSCOREjoinreplacerM _writeBody)rr.mainsubspecificrRgenerics rrJzGenerator._dispatchs '')%%'??D#;/77SAtZ(2D9 <ll3,G4g!5tFrom ) get_payload isinstancestr TypeErrortyper _payload get_paramr set_payloadrIrfcrer]rB)rr.payloadrns r _handle_textzGenerator._handle_texts//# ? '3'9DMIJ J 3<< (mmI.G"sm34 g6//+#&'B#C#&~#6#8   hhx1G '"rc0g}|j}|g}n5t|tr|j|yt|ts|g}|D]`}|j }|j |}|j|d|j|j|jb|j}|s=|jj|}|j|}|j||j e|j"r!t$j'd|j } n |j } |j)| |j|j|jd|z|jz|r*|j*j|j-d|D]K} |j|jdz|z|jz|j*j| M|j|jdz|zdz|jz|j.K|j"r!t$j'd|j.} n |j.} |j)| yy)NFr/r roz--r)rprqrrrlistr9r$r3r%appendrN get_boundaryr'rY_make_boundary set_boundarypreamblerrxr]rBrpopepilogue) rr.msgtextssubpartspartrgboundaryalltextr body_partrs r_handle_multipartzGenerator._handle_multipart s ??$  H # & JJx Hd+ zHD  "A 1 A IIdUDHHI = OOAJJL )  ##%&&++H5G**73H   X & << #!!88Hcll;<<   h ' JJtxx  4(?TXX-.  HHNN8<<? +"I JJtxx$1DHH< = HHNN9 % " 488d?X-4txx?@ << #!!88Hcll;<<   h ' $rc|j}|jd|_ |j|||_y#||_wxYw)Nrr!)rr$r)rr.ps r_handle_multipart_signedz"Generator._handle_multipart_signedGsA KKggag0    " "3 'DK!DKs > Acg}|jD]}|j}|j|}|j|d|j|j }|j |j}|r@|d|jk(r.|j|jj|dd|j||jj|jj|y)NFr|r=) rpr9r$r3r%rNr?r'r)r~rYrr)rr.blocksrrrtextr@s r_handle_message_delivery_statusz)Generator._handle_message_delivery_statusRsOO%D  "A 1 A IIdUDHHI =::|j |j dd|j|j}n|j|}|jj|y)NrFr|) r9r$rurqr}r3rpr%rNr&rr)rr.rrrys r_handle_messagezGenerator._handle_messagegsz     JJqM,, gt $ IIcooa(5$((I KjjlGll7+G wrc@tjtj}dt|zzdz}||S|}d} |j dt j|zdzt j}|j|s |S|dzt|z}|dz }d)Nz===============z==rz^--z(--)?$.rG) random randrangesysmaxsize_fmt _compile_rereescape MULTILINErgrr)clsrtokenrbcountercres rrzGenerator._make_boundarys  -.5 <O //%"))A,"6"A2<<PC::d#3W-A qLG rc.tj||Sr)rcompilerrflagss rrzGenerator._compile_reszz!U##r)NN)FNr)__name__ __module__ __qualname____doc__rrr3r$r9r&rBr-rJrHrzr[rrrr classmethodrrr;rrrrs@/(b2( " %'N( &#,J8(t 6* 2"$$rrcNeZdZdZdZdZdZdZfdZeZ e dZ xZ S)raGenerates a bytes version of a Message object tree. Functionally identical to the base Generator except that the output is bytes and not string. When surrogates were used in the input to encode bytes, these are decoded back to bytes for output. If the policy has cte_type set to 7bit, then the message is transformed such that the non-ASCII bytes are properly content transfer encoded, using the charset unknown-8bit. The outfp object must accept bytes in its write method. cZ|jj|jddy)Nasciisurrogateescape)rrencoders rrzBytesGenerator.writes qxx):;#'#;#;#=#'#4#4_#E#'88,A,>$@#'88,G,;$= # ! "r)NNN)rrrrrrJr;rrrrs <"rrrGz%%0%dd)!r__all__rrr+rcopyriorr email.utilsr email.errorsr rXNLrr>rrxrfrrrrrlenreprr_widthrrr;rrrs A =  ')    =!rzz)R\\*!rzz"CD'RZZ(JKx$x$v 84Y84vN6"y6"t T#++a- !&))r__pycache__/base64mime.cpython-312.pyc000064400000007553152526700320013427 0ustar00 {|j ddZgdZddlmZddlmZmZdZdZdZ dZ d Z dd Z d efd Z d ZeZeZy)aBase64 content transfer encoding per RFCs 2045-2047. This module handles the content transfer encoding method defined in RFC 2045 to encode arbitrary 8-bit data using the three 8-bit bytes in four 7-bit characters encoding known as Base64. It is used in the MIME standards for email to attach images, audio, and text using some 8-bit character sets to messages. This module provides an interface to encode and decode both headers and bodies with Base64 encoding. RFC 2045 defines a method for including character set information in an `encoded-word' in a header. This method is commonly used for 8-bit real names in To:, From:, Cc:, etc. fields, as well as Subject: lines. This module does not do the line wrapping or end-of-line character conversion necessary for proper internationalized headers; it only does dumb encoding and decoding. To deal with the various line wrapping issues, use the email.header module. ) body_decode body_encodedecode decodestring header_encode header_length) b64encode) b2a_base64 a2b_base64z  cNtt|d\}}|dz}|r|dz }|S)z6Return the length of s when it is encoded with base64.)divmodlen) bytearray groups_of_3leftoverns )/usr/lib64/python3.12/email/base64mime.pyrr1s1"3y>15KaA Q Hc|syt|tr|j|}t|j d}d|d|dS)zEncode a single header line with Base64 encoding in a given charset. charset names the character set to use to encode the header. It defaults to iso-8859-1. Base64 encoding is defined in RFC 2045. r asciiz=?z?b?z?=) isinstancestrencoder r) header_bytescharsetencodeds rrr;sD ,$#**73  %,,W5G#W --rLc*|syg}|dzdz}tdt||D]Y}t||||zjd}|j t r|t k7r|dd|z}|j |[tj|S)a1Encode a string with base64. Each line will be wrapped at, at most, maxlinelen characters (defaults to 76 characters). Each line of encoded text will end with eol, which defaults to "\n". Set this to "\r\n" if you will be using the result of this function directly in an email. r rrrrN) rangerr rendswithNLappend EMPTYSTRINGjoin)s maxlineleneolencvec max_unencodediencs rrrIs  FNa'M 1c!fm ,1Q./077@ << r cr(S.C c -   F ##rc|s tSt|trt|j dSt|S)zDecode a raw base64 string, returning a bytes object. This function does not parse a full MIME header value encoded with base64 (like =?iso-8859-1?b?bmloISBuaWgh?=) -- please use the high level email.header class for that functionality. zraw-unicode-escape)bytesrrr r)strings rrrbs8 w FC &--(<=>>&!!rN)z iso-8859-1)__doc____all__base64r binasciir r CRLFr'r)MISC_LENrrrrrrrrr<sV , +      .!b$2 "   r__pycache__/contentmanager.cpython-312.pyc000064400000030114152526700320014465 0ustar00 {|j\)FddlZddlZddlZddlZddlmZGddZeZddZejdedZ djD]Z eje e [ d Z d jD]Zejd eze [d Zejd edZdZdZdZ ddZej+ee ddZej+ej0j2e ddZeeefD]Zej+ee[y)N) quoprimimec0eZdZdZdZdZdZdZdZy)ContentManagerc i|_i|_yN) get_handlers set_handlers)selfs -/usr/lib64/python3.12/email/contentmanager.py__init__zContentManager.__init__ sc"||j|<yr)r)r keyhandlers r add_get_handlerzContentManager.add_get_handler s!(#r cB|j}||jvr|j||g|i|S|j}||jvr|j||g|i|Sd|jvr|jd|g|i|St|)N)get_content_typerget_content_maintypeKeyError)r msgargskw content_typemaintypes r get_contentzContentManager.get_contents++- 4,, ,24$$\23DDD D++- t(( (.4$$X.s@T@R@ @ "" "(4$$R(:t:r: :|$$r c"||j|<yr)r )r typekeyrs r add_set_handlerzContentManager.add_set_handlers%,'"r c|jdk(r td|j||}|j|||g|i|y)N multipartz"set_content not valid on multipart)r TypeError_find_set_handler clear_content)r robjrrrs r set_contentzContentManager.set_contentsS  # # % 4@A A((c2 S&4&2&r cd}t|jD]}||jvr|j|cS|j}t |dd}|rdj ||fn|}||}||jvr|j|cS||jvr|j|cS|j }||jvs|j|cSd|jvr|jdSt|)N __module__r.)type__mro__r __qualname__getattrjoin__name__r) r rr%full_path_for_errortypqnamemodname full_pathnames r r#z ContentManager._find_set_handler's "9$$Cd'''((--$$Ec<4G6='5!125I"*&/#D---((33)))((//<>'&> 11r textc&|jdS)NTr8r=rs r get_non_text_contentrEGs ??$? ''r zaudio image video applicationc$|jdSNrrCrDs r get_message_contentrHNs ??1 r zrfc822 external-bodyzmessage/c6t|jdSrG)bytesr=rDs r %get_and_fixup_unknown_message_contentrKUs # $$r messagecdj||f|d<|rzt|dds8|j}|Dcgc]!}|j|j |g#}} |D],}|j r|j d|||j <.yycc}w#tjj$r:}tdjj|j|d}~wwxYw)N/z Content-Typerr5zInvalid header: {})policy) r.hasattrrOheader_factoryheader_source_parsedefectsr5emailr< HeaderDefect ValueErrorformatfold)rrsubtypeheadersmpheaderexcs r _prepare_setr^as((Hg#67Cwqz6*B%,.%,6)r(("*@*@&*JK%, . J!>> ..++#)FKK " .||(( J188 & 3:: >@AFI J Js&B!1BC065C++C0c||d}|||d<||jd|dd|||d<|+|jD]\}}|j||yy)N attachmentzContent-DispositionfilenameT)r\replacez Content-ID) set_paramitems)r dispositionracidparamsrvalues r _finalize_setrirsx3" %0 !" j2"  $ L  ,,.JC MM#u %)r cg}|dzdz}tdt||D]=}||||z}|jtj|j d?dj |S)Nrasciir)rangelenappendbinascii b2a_base64r9r.)datamax_line_length encoded_linesunencoded_bytes_per_lineithislines r _encode_base64rysvM.!3a7 1c$i!9 :!445X00:AA'JK; 77= !!r c |j|j}|jjd fd}d}|td|Dd|jkr d||j dfS||dd }tj|j d |j}tj|} t|t| kDrd }nd }t|d kr||fS|dk(r||j d} || fS|dk(r||j dd } || fS|d k(r9tj||j d |j} || fS|d k(r t|||j} || fStdj|#t $rYnwxYw|jdk(s[d||j dd fS)Nrmc,j|zSrr.)lineslineseps r embedded_bodyz#_encode_text..embedded_bodysW\\%%87%BBr c*dj|dzS)N r|)r}s r normal_bodyz!_encode_text..normal_bodys5::e#4u#<z_encode_text..s&1Asr)default7bit8bitsurrogateescape zlatin-1base64quoted-printablez$Unknown content transfer encoding {})encode splitlinesr~maxrtr9UnicodeDecodeErrorcte_typer body_encoderqrrroryrVrW) stringr:cterOr}rrsniffsniff_qp sniff_base64rsr~s @r _encode_textrs MM' " - - /Enn##G,GB< { && 2f6L6L L {5188AAA eCRj)))%,,y*A*0*@*@B**51 x=3|, ,C$C5zRH}$ f}5!((1 9 5!((2CD 9 " "%%k%&8&?&? &J&,&<&<> 9 mE2F4J4JK 9?FFsKLL3&  &({5188BSTTTs(F<< GGc t|d|| t||||j\}} |j| |j dt j jj||d||d<t|||||y)NrAr:TrbContent-Transfer-Encoding) r^rrO set_payloadrcrTr:ALIASESgetri) rrrYr:rrerarfrgrZpayloads r set_text_contentrsfgw/cjjALCOOGMM)--''++GW= (+C#$#{Hc6:r c 4|dk(r td|dk(r%|dvrtdj||dn|}n*|dk(r!|dvrtd j|d }n|d }t|d |||j|g||d <t |||||y) Npartialz4message/partial is not supported for Message objectsrfc822)Nrrbinaryz*message/rfc822 parts do not support cte={}rz external-body)Nrz1message/external-body parts do not support cte={}rrLr)rVrWr^rri) rrLrYrrerarfrgrZs r set_message_contentrs)OPP( 6 6<CCCHJ J f O # n $CJJ3OQ Q i'2OOWI'*C#$#{Hc6:r c rt|||| |dk(r"t||jj}n]|dk(r+t j |ddd}|j d}n-|dk(r|j d}n|d vr|j dd }|j|||d <t|||||y) Nr)rtrFT)istextr\ quotetabsrmr)rrrr) r^ryrOrtrqb2a_qpr9rri) rrsrrYrrerarfrgrZs r set_bytes_contentrsh1 hdCJJ4N4NO " "tE%4P{{7# {{7# " "{{7$56OOD'*C#$#{Hc6:r r)plainzutf-8NNNNNN)rNNNNNN)rNNNNN)rq email.charsetrT email.message email.errorsrrraw_data_managerr@rrEsplitrrHrYrKr^riryrrrstrrrLMessagerrJ bytearray memoryviewr1r6r r rs[3,3,l"#2 )9:(/557H$$X/CD8 %++-G$$Z%79LM. % !FHJ"&*"$NIM:>*. ; &67=A<@,0;< !6!68KL9A:>*.;& 9j )C$$S*;< *r __pycache__/contentmanager.cpython-312.opt-2.pyc000064400000030114152526700320015425 0ustar00 {|j\)FddlZddlZddlZddlZddlmZGddZeZddZejdedZ djD]Z eje e [ d Z d jD]Zejd eze [d Zejd edZdZdZdZ ddZej+ee ddZej+ej0j2e ddZeeefD]Zej+ee[y)N) quoprimimec0eZdZdZdZdZdZdZdZy)ContentManagerc i|_i|_yN) get_handlers set_handlers)selfs -/usr/lib64/python3.12/email/contentmanager.py__init__zContentManager.__init__ sc"||j|<yr)r)r keyhandlers r add_get_handlerzContentManager.add_get_handler s!(#r cB|j}||jvr|j||g|i|S|j}||jvr|j||g|i|Sd|jvr|jd|g|i|St|)N)get_content_typerget_content_maintypeKeyError)r msgargskw content_typemaintypes r get_contentzContentManager.get_contents++- 4,, ,24$$\23DDD D++- t(( (.4$$X.s@T@R@ @ "" "(4$$R(:t:r: :|$$r c"||j|<yr)r )r typekeyrs r add_set_handlerzContentManager.add_set_handlers%,'"r c|jdk(r td|j||}|j|||g|i|y)N multipartz"set_content not valid on multipart)r TypeError_find_set_handler clear_content)r robjrrrs r set_contentzContentManager.set_contentsS  # # % 4@A A((c2 S&4&2&r cd}t|jD]}||jvr|j|cS|j}t |dd}|rdj ||fn|}||}||jvr|j|cS||jvr|j|cS|j }||jvs|j|cSd|jvr|jdSt|)N __module__r.)type__mro__r __qualname__getattrjoin__name__r) r rr%full_path_for_errortypqnamemodname full_pathnames r r#z ContentManager._find_set_handler's "9$$Cd'''((--$$Ec<4G6='5!125I"*&/#D---((33)))((//<>'&> 11r textc&|jdS)NTr8r=rs r get_non_text_contentrEGs ??$? ''r zaudio image video applicationc$|jdSNrrCrDs r get_message_contentrHNs ??1 r zrfc822 external-bodyzmessage/c6t|jdSrG)bytesr=rDs r %get_and_fixup_unknown_message_contentrKUs # $$r messagecdj||f|d<|rzt|dds8|j}|Dcgc]!}|j|j |g#}} |D],}|j r|j d|||j <.yycc}w#tjj$r:}tdjj|j|d}~wwxYw)N/z Content-Typerr5zInvalid header: {})policy) r.hasattrrOheader_factoryheader_source_parsedefectsr5emailr< HeaderDefect ValueErrorformatfold)rrsubtypeheadersmpheaderexcs r _prepare_setr^as((Hg#67Cwqz6*B%,.%,6)r(("*@*@&*JK%, . J!>> ..++#)FKK " .||(( J188 & 3:: >@AFI J Js&B!1BC065C++C0c||d}|||d<||jd|dd|||d<|+|jD]\}}|j||yy)N attachmentzContent-DispositionfilenameT)r\replacez Content-ID) set_paramitems)r dispositionracidparamsrvalues r _finalize_setrirsx3" %0 !" j2"  $ L  ,,.JC MM#u %)r cg}|dzdz}tdt||D]=}||||z}|jtj|j d?dj |S)Nrasciir)rangelenappendbinascii b2a_base64r9r.)datamax_line_length encoded_linesunencoded_bytes_per_lineithislines r _encode_base64rysvM.!3a7 1c$i!9 :!445X00:AA'JK; 77= !!r c |j|j}|jjd fd}d}|td|Dd|jkr d||j dfS||dd }tj|j d |j}tj|} t|t| kDrd }nd }t|d kr||fS|dk(r||j d} || fS|dk(r||j dd } || fS|d k(r9tj||j d |j} || fS|d k(r t|||j} || fStdj|#t $rYnwxYw|jdk(s[d||j dd fS)Nrmc,j|zSrr.)lineslineseps r embedded_bodyz#_encode_text..embedded_bodysW\\%%87%BBr c*dj|dzS)N r|)r}s r normal_bodyz!_encode_text..normal_bodys5::e#4u#<z_encode_text..s&1Asr)default7bit8bitsurrogateescape zlatin-1base64quoted-printablez$Unknown content transfer encoding {})encode splitlinesr~maxrtr9UnicodeDecodeErrorcte_typer body_encoderqrrroryrVrW) stringr:cterOr}rrsniffsniff_qp sniff_base64rsr~s @r _encode_textrs MM' " - - /Enn##G,GB< { && 2f6L6L L {5188AAA eCRj)))%,,y*A*0*@*@B**51 x=3|, ,C$C5zRH}$ f}5!((1 9 5!((2CD 9 " "%%k%&8&?&? &J&,&<&<> 9 mE2F4J4JK 9?FFsKLL3&  &({5188BSTTTs(F<< GGc t|d|| t||||j\}} |j| |j dt j jj||d||d<t|||||y)NrAr:TrbContent-Transfer-Encoding) r^rrO set_payloadrcrTr:ALIASESgetri) rrrYr:rrerarfrgrZpayloads r set_text_contentrsfgw/cjjALCOOGMM)--''++GW= (+C#$#{Hc6:r c 4|dk(r td|dk(r%|dvrtdj||dn|}n*|dk(r!|dvrtd j|d }n|d }t|d |||j|g||d <t |||||y) Npartialz4message/partial is not supported for Message objectsrfc822)Nrrbinaryz*message/rfc822 parts do not support cte={}rz external-body)Nrz1message/external-body parts do not support cte={}rrLr)rVrWr^rri) rrLrYrrerarfrgrZs r set_message_contentrs)OPP( 6 6<CCCHJ J f O # n $CJJ3OQ Q i'2OOWI'*C#$#{Hc6:r c rt|||| |dk(r"t||jj}n]|dk(r+t j |ddd}|j d}n-|dk(r|j d}n|d vr|j dd }|j|||d <t|||||y) Nr)rtrFT)istextr\ quotetabsrmr)rrrr) r^ryrOrtrqb2a_qpr9rri) rrsrrYrrerarfrgrZs r set_bytes_contentrsh1 hdCJJ4N4NO " "tE%4P{{7# {{7# " "{{7$56OOD'*C#$#{Hc6:r r)plainzutf-8NNNNNN)rNNNNNN)rNNNNN)rq email.charsetrT email.message email.errorsrrraw_data_managerr@rrEsplitrrHrYrKr^riryrrrstrrrLMessagerrJ bytearray memoryviewr1r6r r rs[3,3,l"#2 )9:(/557H$$X/CD8 %++-G$$Z%79LM. % !FHJ"&*"$NIM:>*. ; &67=A<@,0;< !6!68KL9A:>*.;& 9j )C$$S*;< *r __pycache__/utils.cpython-312.opt-2.pyc000064400000030735152526700320013571 0ustar00 {|j> gdZddlZddlZddlZddlZddlZddlZddlZddl m Z ddl m Z ddl m Z ddl mZmZmZddlmZdZd Zd Zd Zd Zej0d Zej0d ZdZdZd&dZdZdZdZ dddZ!dZ"dZ#dZ$dZ%d'dZ&d(dZ'd)dZ(dZ)dddZ*dZ+d Z,d)d!Z-ej0d"ej\Z/d#Z0 d*d$Z1d)d%Z2y)+)collapse_rfc2231_value decode_paramsdecode_rfc2231encode_rfc2231 formataddr formatdateformat_datetime getaddresses make_msgid mktime_tz parseaddr parsedate parsedate_tzparsedate_to_datetimeunquoteN)quote) AddressList)r )r r _parsedate_tz)Charsetz, z 'z[][\\()<>@,:;".]z[\\"]cF |jy#t$rYywxYw)NFT)encodeUnicodeEncodeError)ss $/usr/lib64/python3.12/email/utils.py_has_surrogatesr4s(E   s   cJ|jdd}|jddS)Nutf-8surrogateescapereplace)rdecode)stringoriginal_bytess r _sanitizer%As( ]]7,=>N  ) 44cX |\}}|jd|rM |jdd}tj|rd}tj d|}|||d|dS|S#t $r7t |tr t|}|j|}|d|dcYSwxYw)Nasciir"z\\\g<0>z <>) r specialsresearch escapesresubr isinstancestrr header_encode)paircharsetnameaddressquotes encoded_names rrrMs MD' NN7  C KK F  &==T2D$*D&'B B N" 7'3'!'*"006L ,g6 6  7sA))=B)(B)c#Kd}d}t|D]!\}}|r |d|zfd}|dk(rd}||f#|r|dfyyw)NrF\T) enumerate)addrposescapechs r_iter_escaped_charsr?nsb C FT?R r " "F 4ZF)O#Dks>Ac d|vr|Sd}d}g}t|D]0\}}|dk(s ||}||k7r|j||||dz}d}2|t|kr|j||ddj|S)Nr)rr)r?appendlenjoin)r;startopen_posresultr<r>s r_strip_quoted_realnamesrH}s* $ EH F&t,R 9H$MM$uX"67a- s4y d56l# 776?r&T)strictc |s3tjd|D}t|}|jS|Dcgc] }t |}}t |}tj|}t|}t |j}d}|D]$}t|}|d|jdzz }&t||k7rdgS|Scc}w)Nc32K|]}t|yw)Nr0).0vs r zgetaddresses..s:kc!fksrrA,rr) COMMASPACErD _AddressList addresslistr0_pre_parse_validation_post_parse_validationrHcountrC) fieldvaluesrIallarNr;rGns rr r s" oo:k::  }}#./;a3q6;K/' 4K ??; 'DTA #AMM 2F A  $A & Q    6{az M%0sC ct|}d}t|D]"\}}|dk(r|dz }|dk(s|dz}|dks"y|dk(S)Nr(rA)F)rHr?)r;opensr<r>s r_check_parenthesisr`sZ "4 (D E&t,R 9 QJE 3Y QJEqy - QJr&cTg}|D] }t|sd}|j|"|S)Nz('', ''))r`rB)email_header_fieldsaccepted_valuesrNs rrUrUs4O !!$Aq!! r&cLg}|D]}d|dvrd}|j||S)N[rArQ)rB)parsed_email_header_tuplesrcrNs rrVrVs9O( !A$;Aq!( r&c `dgd|d|dgd|ddz |d|d|d |d |fzS) Nz"%s, %02d %s %04d %02d:%02d:%02d %s)MonTueWedThuFriSatSun) JanFebMarAprMayJunJulAugSepOctNovDecrAr) timetuplezones r_format_timetuple_and_zonersZ /9)A,G!  33->-B-B BDE E  {{4  %c4 00r&c ttjdz}tj}t j d}|d}nd|z}|t j}d|||||fz}|S)Nd@r.z<%d.%d.%d%s@%s>)introsgetpidrandom getrandbitssocketgetfqdn)idstringdomainrpidrandintmsgids rr r "sw$))+c/"G ))+C  $G> ~! #w& I IE Lr&c t|}|tdt|z|^}}|tj|ddStj|dddtjtj |iS)Nz!Invalid date value or format "%s"ror)seconds)rrr0rr timedelta)dataparsed_date_tzdtupletzs rrr9s"4(N># 3<<#4q9$$VT2::5#F F >># 3<<#4q9  Jr&cZ |jtd}t|dkrdd|fS|S)Nrp)splitTICKrC)rpartss rrros1- GGD! E 5zQT1} Lr&cx tjj|d|xsd}|||S|d}|d|d|S)Nrr()safeencodingr)urllibparser)rr3languages rrrwsP  120B7CA8+ (A ..r&z&^(?P\w+)\*((?P[0-9]+)\*?)?$c |dg}i}|ddD]\}}|jd}t|}tj|}|rG|j dd\}}| t |}|j |gj|||f|j|dt|zf|r|jD]\}}g}d} |j|D]<\}} }|r#tjj| d } d } |j| >ttj|}| r)t|\} } }|j|| | d|zff|j|d|zf|S) NrrA*r4numz"%s"Fzlatin-1)rT)rrrfc2231_continuationmatchgroupr setdefaultrBritemssortrr EMPTYSTRINGrDr) params new_paramsrfc2231_paramsr4valueencodedmor continuationsextendedrr3rs rrrs)JNabz e--$ ! ' ' - /ID##h  % %dB / 6 6UG7L M   tVeEl%:; <"#1#7#7#9 D-EH    $1Q ,,Q,CA#H Q$1+**512E+9%+@(5!!4'8Ve^)L"MN!!4%"89/$:0 r&ct|trt|dk7r t|S|\}}}||}t |d} t |||S#t $rt|cYSwxYw)Nr}zraw-unicode-escape)r/tuplerCrbytesr0 LookupError)rerrorsfallback_charsetr3rtextrawbytess rrrst eU #s5zQu~$GXt#T/0H8Wf-- t}s AA%$A%c |ddl}|jddd|tjj}|j S)Nrz$The 'isdst' parameter to 'localtime'z>{name} is deprecated and slated for removal in Python {remove})r})messageremove)warnings _deprecatedrrr)risdstrs rrrsU  2T    z    " " $ ==?r&)r)NFF)F)NN)r!zus-ascii)3__all__rrerrrr urllib.parseremail._parseaddrrrrSr r rr email.charsetrrRr UEMPTYSTRINGCRLFrcompiler+r-rr%rr?rHsupports_strict_parsingr r`rUrVrrrr rr rrrASCIIrrrrrr&rrs  $ "8&CC"       RZZ+ , BJJx  5B 2(,)X  ':1&.F#> /"rzz"KHH.`*3,64r&__pycache__/utils.cpython-312.opt-1.pyc000064400000037144152526700320013571 0ustar00 {|j>dZgdZddlZddlZddlZddlZddlZddlZddlZ ddl m Z ddl m Z ddl mZddl mZmZmZddlmZd Zd Zd Zd Zd Zej2d Zej2dZdZdZd'dZdZdZ dZ!dddZ"dZ#dZ$dZ%dZ&d(dZ'd)dZ(d*dZ)dZ*dddZ+d Z,d!Z-d*d"Z.ej2d#ej^Z0d$Z1 d+d%Z2d*d&Z3y),zMiscellaneous utilities.)collapse_rfc2231_value decode_paramsdecode_rfc2231encode_rfc2231 formataddr formatdateformat_datetime getaddresses make_msgid mktime_tz parseaddr parsedate parsedate_tzparsedate_to_datetimeunquoteN)quote) AddressList)r )r r _parsedate_tz)Charsetz, z 'z[][\\()<>@,:;".]z[\\"]cD |jy#t$rYywxYw)z;Return True if s may contain surrogate-escaped binary data.FT)encodeUnicodeEncodeError)ss $/usr/lib64/python3.12/email/utils.py_has_surrogatesr4s%    s  cJ|jdd}|jddS)Nutf-8surrogateescapereplace)rdecode)stringoriginal_bytess r _sanitizer%As( ]]7,=>N  ) 44cV|\}}|jd|rM |jdd}tj|rd}tj d|}|||d|dS|S#t $r7t |tr t|}|j|}|d|dcYSwxYw)aThe inverse of parseaddr(), this takes a 2-tuple of the form (realname, email_address) and returns the string value suitable for an RFC 2822 From, To or Cc header. If the first element of pair is false, then the second element is returned unmodified. The optional charset is the character set that is used to encode realname in case realname is not ASCII safe. Can be an instance of str or a Charset-like object which has a header_encode method. Default is 'utf-8'. asciir"z\\\g<0>z <>) r specialsresearch escapesresubr isinstancestrr header_encode)paircharsetnameaddressquotes encoded_names rrrMsMD' NN7  C KK F  &==T2D$*D&'B B N" 7'3'!'*"006L ,g6 6  7sA((=B('B(c#Kd}d}t|D]!\}}|r |d|zfd}|dk(rd}||f#|r|dfyyw)NrF\T) enumerate)addrposescapechs r_iter_escaped_charsr?nsb C FT?R r " "F 4ZF)O#Dks>Acd|vr|Sd}d}g}t|D]0\}}|dk(s ||}||k7r|j||||dz}d}2|t|kr|j||ddj|S)z Strip real names between quotes.r)rNr)r?appendlenjoin)r;startopen_posresultr<r>s r_strip_quoted_realnamesrH}s $ EH F&t,R 9H$MM$uX"67a- s4y d56l# 776?r&T)strictc|s3tjd|D}t|}|jS|Dcgc] }t |}}t |}tj|}t|}t |j}d}|D]$}t|}|d|jdzz }&t||k7rdgS|Scc}w)zReturn a list of (REALNAME, EMAIL) or ('','') for each fieldvalue. When parsing fails for a fieldvalue, a 2-tuple of ('', '') is returned in its place. If strict is true, use a strict parser which rejects malformed inputs. c32K|]}t|yw)Nr0).0vs r zgetaddresses..s:kc!fksrrA,rr) COMMASPACErD _AddressList addresslistr0_pre_parse_validation_post_parse_validationrHcountrC) fieldvaluesrIallarNr;rGns rr r s$ oo:k::  }}#./;a3q6;K/' 4K ??; 'DTA #AMM 2F A  $A & Q    6{az M%0sC ct|}d}t|D]"\}}|dk(r|dz }|dk(s|dz}|dks"y|dk(S)Nr(rA)F)rHr?)r;opensr<r>s r_check_parenthesisr`sZ "4 (D E&t,R 9 QJE 3Y QJEqy - QJr&cTg}|D] }t|sd}|j|"|S)Nz('', ''))r`rB)email_header_fieldsaccepted_valuesrNs rrUrUs4O !!$Aq!! r&cLg}|D]}d|dvrd}|j||S)N[rArQ)rB)parsed_email_header_tuplesrcrNs rrVrVs9O( !A$;Aq!( r&c `dgd|d|dgd|ddz |d|d|d |d |fzS) Nz"%s, %02d %s %04d %02d:%02d:%02d %s)MonTueWedThuFriSatSun) JanFebMarAprMayJunJulAugSepOctNovDecrAr) timetuplezones r_format_timetuple_and_zonersZ /9)A,G!  33->-B-B BDE E  {{4  %c4 00r&cttjdz}tj}t j d}|d}nd|z}|t j}d|||||fz}|S)a{Returns a string suitable for RFC 2822 compliant Message-ID, e.g: <142480216486.20800.16526388040877946887@nightshade.la.mastaler.com> Optional idstring if given is a string used to strengthen the uniqueness of the message id. Optional domain if given provides the portion of the message id after the '@'. It defaults to the locally defined hostname. d@r.z<%d.%d.%d%s@%s>)introsgetpidrandom getrandbitssocketgetfqdn)idstringdomainrpidrandintmsgids rr r "sr$))+c/"G ))+C  $G> ~! #w& I IE Lr&c t|}|tdt|z|^}}|tj|ddStj|dddtjtj |iS)Nz!Invalid date value or format "%s"ror)seconds)rrr0rr timedelta)dataparsed_date_tzdtupletzs rrr9s"4(N># 3<<#4q9$$VT2::5#F F >># 3<<#4q9  Jr&cX|jtd}t|dkrdd|fS|S)z#Decode string according to RFC 2231rpN)splitTICKrC)rpartss rrros. GGD! E 5zQT1} Lr&cvtjj|d|xsd}|||S|d}|d|d|S)zEncode string according to RFC 2231. If neither charset nor language is given, then s is returned as-is. If charset is given but not language, the string is encoded using the empty string for language. rr()safeencodingr)urllibparser)rr3languages rrrwsK  120B7CA8+ (A ..r&z&^(?P\w+)\*((?P[0-9]+)\*?)?$c|dg}i}|ddD]\}}|jd}t|}tj|}|rG|j dd\}}| t |}|j |gj|||f|j|dt|zf|r|jD]\}}g}d} |j|D]<\}} }|r#tjj| d } d } |j| >ttj|}| r)t|\} } }|j|| | d|zff|j|d|zf|S) zDecode parameters list according to RFC 2231. params is a sequence of 2-tuples containing (param name, string value). rrAN*r4numz"%s"Fzlatin-1)rT)rrrfc2231_continuationmatchgroupr setdefaultrBritemssortrr EMPTYSTRINGrDr) params new_paramsrfc2231_paramsr4valueencodedmor continuationsextendedrr3rs rrrs )JNabz e--$ ! ' ' - /ID##h  % %dB / 6 6UG7L M   tVeEl%:; <"#1#7#7#9 D-EH    $1Q ,,Q,CA#H Q$1+**512E+9%+@(5!!4'8Ve^)L"MN!!4%"89/$:0 r&ct|trt|dk7r t|S|\}}}||}t |d} t |||S#t $rt|cYSwxYw)Nr}zraw-unicode-escape)r/tuplerCrbytesr0 LookupError)rerrorsfallback_charsetr3rtextrawbytess rrrst eU #s5zQu~$GXt#T/0H8Wf-- t}s AA%$A%c|ddl}|jddd|tjj}|j S)a}Return local time as an aware datetime object. If called without arguments, return current time. Otherwise *dt* argument should be a datetime instance, and it is converted to the local time zone according to the system time zone database. If *dt* is naive (that is, dt.tzinfo is None), it is assumed to be in local time. The isdst parameter is ignored. Nrz$The 'isdst' parameter to 'localtime'z>{name} is deprecated and slated for removal in Python {remove})r})messageremove)warnings _deprecatedrrr)risdstrs rrrsP  2T    z    " " $ ==?r&)r)NFF)F)NN)r!zus-ascii)4__doc____all__rrerrrr urllib.parseremail._parseaddrrrrSr r rr email.charsetrrRr UEMPTYSTRINGCRLFrcompiler+r-rr%rr?rHsupports_strict_parsingr r`rUrVrrrr rr rrrASCIIrrrrrr&rrs  $ "8&CC"       RZZ+ , BJJx  5B 2(,)X  ':1&.F#> /"rzz"KHH.`*3,64r&__pycache__/_encoded_words.cpython-312.opt-2.pyc000064400000014451152526700320015404 0ustar00 {|j]!0 ddlZddlZddlZddlZddlmZmZddlmZgdZ ejejdjdZ dZGdd eZeZd eed <d Zd ZdZdZdZeedZdZeedZeedZddZy)N) ascii_lettersdigits)errors)decode_qencode_qdecode_bencode_blen_qlen_bdecodeencodes=([a-fA-F0-9]{2})cftj|jdjS)N)bytesfromhexgroupr )ms -/usr/lib64/python3.12/email/_encoded_words.pyrAs%-- 1 1 34c@|jdd}t|gfS)N_ )replace_q_byte_subber)encodeds rrrCs"oodD)G ' "B &&rcbeZdZdejdzejdzZdZy) _QByteMaps-!*+/asciicv||jvrt|||<||Sdj|||<||S)Nz={:02X})safechrformat)selfkeys r __missing__z_QByteMap.__missing__MsG $)) CDICy"((-DICyrN)__name__ __module__ __qualname__rr rr!r&rrrrIs/ *m**73 3mfmmG6L LDrr_ c2djd|DS)Nc3.K|] }t|ywN) _q_byte_map.0xs r zencode_q..Zs37a;q>7s)joinbstrings rrrYs 77373 33rc&td|DS)Nc3@K|]}tt|ywr0)lenr1r2s rr5zlen_q..]s4Gqs;q>"Gs)sumr7s rr r \s 4G4 44rcPt|dz}|rddd|z nd} tj||zd|rtjgfSgfS#t j $r tj|dtjgfcYS#t j $r| tj|dzdtjtjgfcYcYS#t j $r|tjgfcYcYcYSwxYwwxYwwxYw)Ns===rT)validateFs==) r;base64 b64decoderInvalidBase64PaddingDefectbinasciiErrorInvalidBase64CharactersDefectInvalidBase64LengthDefect)rpad_errmissing_paddings rrrds7'lQG,3fZai(OE   W6 F5>E  E  595578 ~~ E E$$Wu_uE99;668: >> E !A!A!C DDD  E EEsZ0A AD%$+BD%D!&AC,'D!(D%,*DD!D%DD!!D%cJtj|jdS)Nr)r@ b64encoder r7s rr r s   G $ + +G 44rcNtt|d\}}|dz|rdzSdzS)Nr>r)divmodr;)r8 groups_of_3leftovers rr r s0"3w<3K ?8a 33 33r)qbc> |jd\}}}}}|jd\}}}|j}|jdd}t ||\}} |j |}||||fS#t $r=|jtjd|d|j |d}YKttf$rP|j dd}|jdk7r(|jtjd|d YwxYw) N?*rsurrogateescapez0Encoded word contains bytes not decodable using z charset unknown-8bitzUnknown charset z* in encoded word; decoded as unknown bytes) split partitionlowerr _cte_decodersr UnicodeDecodeErrorappendrUndecodableBytesDefect LookupErrorUnicodeEncodeError CharsetError) ewr+charsetcte cte_stringlangr8defectsstrings rr r s6(&(XXc]"AwZ((-GQ ))+C):;G$S)'2GW ?( 7D' )) <v446229H6FG H):; + ,?):; ==?n , NN6..1A'M<0=> ??s"A99AD>ADDc |dk(r|jdd}n|j|}|(td|}td|}||z dkrdnd}t||}|rd|z}dj||||S) NrVrrUrPrQrTz=?{}{}?{}?{}?=)r _cte_encode_length _cte_encodersr#)rgrbencodingrer8qlenblenrs rr r s . --):;--(!#&w/!#&w/+/3sH%g.G Tz  " "7D(G DDr)zutf-8Nr.)rer@rC functoolsrgrremailr__all__partialcompilesubrrdictrr1ordrr rr r rZr rkrjr r*rrrxsR ( #"":2::.C#D#H#H46'  k  CH45$EL54   '*V     Er__pycache__/_encoded_words.cpython-312.opt-1.pyc000064400000020164152526700320015401 0ustar00 {|j]!2dZddlZddlZddlZddlZddlmZmZddlm Z gdZ ejejdjdZdZGd d eZeZd eed <d ZdZdZdZdZeedZdZeedZeedZddZy)z Routines for manipulating RFC2047 encoded words. This is currently a package-private API, but will be considered for promotion to a public API if there is demand. N) ascii_lettersdigits)errors)decode_qencode_qdecode_bencode_blen_qlen_bdecodeencodes=([a-fA-F0-9]{2})cftj|jdjS)N)bytesfromhexgroupr )ms -/usr/lib64/python3.12/email/_encoded_words.pyrAs%-- 1 1 34c@|jdd}t|gfS)N_ )replace_q_byte_subber)encodeds rrrCs"oodD)G ' "B &&rcbeZdZdejdzejdzZdZy) _QByteMaps-!*+/asciicv||jvrt|||<||Sdj|||<||S)Nz={:02X})safechrformat)selfkeys r __missing__z_QByteMap.__missing__MsG $)) CDICy"((-DICyrN)__name__ __module__ __qualname__rr rr!r&rrrrIs/ *m**73 3mfmmG6L LDrr_ c2djd|DS)Nc3.K|] }t|ywN) _q_byte_map.0xs r zencode_q..Zs37a;q>7s)joinbstrings rrrYs 77373 33rc&td|DS)Nc3@K|]}tt|ywr0)lenr1r2s rr5zlen_q..]s4Gqs;q>"Gs)sumr7s rr r \s 4G4 44rcPt|dz}|rddd|z nd} tj||zd|rtjgfSgfS#t j $r tj|dtjgfcYS#t j $r| tj|dzdtjtjgfcYcYS#t j $r|tjgfcYcYcYSwxYwwxYwwxYw)Ns===rT)validateFs==) r;base64 b64decoderInvalidBase64PaddingDefectbinasciiErrorInvalidBase64CharactersDefectInvalidBase64LengthDefect)rpad_errmissing_paddings rrrds7'lQG,3fZai(OE   W6 F5>E  E  595578 ~~ E E$$Wu_uE99;668: >> E !A!A!C DDD  E EEsZ0A AD%$+BD%D!&AC,'D!(D%,*DD!D%DD!!D%cJtj|jdS)Nr)r@ b64encoder r7s rr r s   G $ + +G 44rcNtt|d\}}|dz|rdzSdzS)Nr>r)divmodr;)r8 groups_of_3leftovers rr r s0"3w<3K ?8a 33 33r)qbc<|jd\}}}}}|jd\}}}|j}|jdd}t ||\}} |j |}||||fS#t $r=|jtjd|d|j |d}YKttf$rP|j dd}|jdk7r(|jtjd|d YwxYw) aDecode encoded word and return (string, charset, lang, defects) tuple. An RFC 2047/2243 encoded word has the form: =?charset*lang?cte?encoded_string?= where '*lang' may be omitted but the other parts may not be. This function expects exactly such a string (that is, it does not check the syntax and may raise errors if the string is not well formed), and returns the encoded_string decoded first from its Content Transfer Encoding and then from the resulting bytes into unicode using the specified charset. If the cte-decoded string does not successfully decode using the specified character set, a defect is added to the defects list and the unknown octets are replaced by the unicode 'unknown' character \uFDFF. The specified charset and language are returned. The default for language, which is rarely if ever encountered, is the empty string. ?*rsurrogateescapez0Encoded word contains bytes not decodable using z charset unknown-8bitzUnknown charset z* in encoded word; decoded as unknown bytes) split partitionlowerr _cte_decodersr UnicodeDecodeErrorappendrUndecodableBytesDefect LookupErrorUnicodeEncodeError CharsetError) ewr+charsetcte cte_stringlangr8defectsstrings rr r s1*&(XXc]"AwZ((-GQ ))+C):;G$S)'2GW ?( 7D' )) <v446229H6FG H):; + ,?):; ==?n , NN6..1A'M<0=> ??s!A88AD=ADDc|dk(r|jdd}n|j|}|(td|}td|}||z dkrdnd}t||}|rd|z}dj||||S) aEncode string using the CTE encoding that produces the shorter result. Produces an RFC 2047/2243 encoded word of the form: =?charset*lang?cte?encoded_string?= where '*lang' is omitted unless the 'lang' parameter is given a value. Optional argument charset (defaults to utf-8) specifies the charset to use to encode the string to binary before CTE encoding it. Optional argument 'encoding' is the cte specifier for the encoding that should be used ('q' or 'b'); if it is None (the default) the encoding which produces the shortest encoded sequence is used, except that 'q' is preferred if it is up to five characters longer. Optional argument 'lang' (default '') gives the RFC 2243 language string to specify in the encoded word. rVrrUrPrQrTz=?{}{}?{}?{}?=)r _cte_encode_length _cte_encodersr#)rgrbencodingrer8qlenblenrs rr r s". --):;--(!#&w/!#&w/+/3sH%g.G Tz  " "7D(G DDr)zutf-8Nr.)__doc__rer@rC functoolsrgrremailr__all__partialcompilesubrrdictrr1ordrr rr r rZr rkrjr r*rrrysR ( #"":2::.C#D#H#H46'  k  CH45$EL54   '*V     Er__pycache__/_parseaddr.cpython-312.pyc000064400000055317152526700320013600 0ustar00 {|jEdZgdZddlZddlZdZdZdZgdZgdZddddd d d d d d d d dd dZ dZ dZ dZ dZ dZGddZGddeZy)zcEmail address parsing code. Lifted directly from rfc822.py. This should eventually be rewritten. ) mktime_tz parsedate parsedate_tzquoteN z, )janfebmaraprmayjunjulaugsepoctnovdecjanuaryfebruarymarchaprilr junejulyaugust septemberoctobernovemberdecember)montuewedthufrisatsunipii iiDi)UTUTCGMTZASTADTESTEDTCSTCDTMSTMDTPSTPDTcHt|}|sy|dd|d<t|S)zQConvert a date string to a time tuple. Accounts for military timezones. N r) _parsedate_tztuple)dataress )/usr/lib64/python3.12/email/_parseaddr.pyrr-s0  C  1v~A :c |sy|j}|sy|djds|djtvr|d=n'|dj d}|dk\r|d|dzd|d<t |dk(r*|djd}t |dk(r||ddz}t |dk(rP|d}|j d}|d k(r|j d}|dkDr|d|||dg|ddn|jd t |d kry|dd }|\}}}}}|r|r|sy|j}|tvr||j}}|tvrytj|dz}|d kDr|d z}|d dk(r|dd }|j d }|dkDr||}}|d dk(r|dd }|sy|djs||}}|d dk(r|dd }|jd }t |dk(r|\} } d} nkt |dk(r|\} } } nVt |dk(rGd|dvr@|djd}t |dk(r|\} } d} nt |dk(r|\} } } nyy t|}t|}t| } t| } t| } |dkr|dkDr|dz }n|dz }d} |j}|tvr t|} n$ t|} | dk(r|jdrd} | r!| dkrd } | } nd} | | dzdz| dzdzzz} |||| | | ddd | g S#t$rYywxYw#t$rYawxYw)aConvert date to extended time tuple. The last (additional) element is the time zone offset in seconds, except if the timezone was specified as -0000. In that case the last element is None. This indicates a UTC timestamp that explicitly declaims knowledge of the source timezone, as opposed to a +0000 timestamp that indicates the source timezone really was UTC. Nr,-+r :0.dDilii<)splitendswithlower _daynamesrfindlenfindappend _monthnamesindexisdigitint ValueErrorupper _timezones startswith)r9istuffsddmmyytmtzthhtmmtsstzoffsettzsigns r;r7r79s  :: 2wH Q;2==-H a<F yHFx}d2hnb5HHI BS#q!R ::E *   s$+7L. L=. L:9L:= M M cFt|}t|tr|ddS|S)z&Convert a time string to a time tuple.Nr6)r isinstancer8r9ts r;rrs&TA!U!u r<c||dtj|dddzStj|}||dz S)zETurn a 10-tuple as returned by parsedate_tz() into a POSIX timestamp.r6N)rD)timemktimecalendartimegmrms r;rrsA Aw{{48e+,, OOD !47{r<cF|jddjddS)zPrepare string to be used in a quoted string. Turns backslash and double quote characters into quoted pairs. These are the only characters that need to be quoted inside a quoted string. Does not add the surrounding double quotes. \z\\"z\")replace)strs r;rrs" ;;tV $ , ,S% 88r<cbeZdZdZdZdZdZdZdZdZ dZ dd Z d Z d Z d ZddZdZy ) AddrlistClassaAddress parser class by Ben Escoto. To understand what this class does, it helps to have a copy of RFC 2822 in front of you. Note: this class interface is deprecated and may be removed in the future. Use email.utils.AddressList instead. c,d|_d|_d|_d|_|j|jz|_|j|jz|jz|_|j j dd|_||_g|_ y)zInitialize a new instance. `field' is an unparsed address header field, containing one or more addresses. z ()<>@,:;."[]rz z rJrN) specialsposLWSCRFWSatomendsrx phraseendsfield commentlistselfrs r;__init__zAddrlistClass.__init__sz ( 88dgg% 0477: --//R8 r<cJg}|jt|jkr|j|j|jdzvrY|j|jdvr(|j |j|j|xjdz c_nG|j|jdk(r*|j j |j nn#|jt|jkrtj|S)z&Skip white space and extract comments.z r?() r~rSrrrUr getcomment EMPTYSTRINGjoin)rwslists r;gotonextzAddrlistClass.gotonextshhTZZ(zz$((#txx&'88::dhh'v5MM$**TXX"67A DHH%,  ''(9:hhTZZ(''r<cg}|jt|jkrL|j}|r||z }n|j d|jt|jkrL|S)zVParse all addresses. Returns a list containing all of the addresses. )rr)r~rSr getaddressrU)rresultads r; getaddrlistzAddrlistClass.getaddrlists^ hhTZZ("B"  h' hhTZZ(  r<cg|_|j|j}|j}|j}|jg}|jt |j k\r*|rft j|j|dfg}n?|j |jdvrB||_||_|j}t j|j|fg}n|j |jdk(rg}t |j }|xjdz c_|jt |j krw|j|j|kr3|j |jdk(r|xjdz c_n%||jz}|jt |j krn|j |jdk(rp|j}|jr;t j|dzdj|jzd z|fg}n{t j||fg}nb|r&t j|j|dfg}n:|j |j|jvr|xjdz c_|j|jt |j kr1|j |jd k(r|xjdz c_|S) zParse the next address.rz.@rGr?;) rrr~ getphraselistrSrSPACEr getaddrspecr getrouteaddrr})roldposoldclplist returnlistaddrspecfieldlen routeaddrs r;rzAddrlistClass.getaddress s   ""$  88s4:: &$zz$*:*:;U1XFG ZZ !T )DH$D '')H ::d&6&67BCJ ZZ !S (J4::H HHMH((S_, 88h&4::dhh+?3+FHHMH'$//*;; ((S_,ZZ !S ())+I$zz%047"xx(8(89 :#*E HHMHr<c|j|jdk7ryd}|xjdz c_|jd}|jt|jkr |r|j d}n|j|jdk(r|xjdz c_ |S|j|jdk(r|xjdz c_d}nZ|j|jd k(r|xjdz c_n(|j }|xjdz c_ |S|j|jt|jkr |S) zParse a route address (Return-path value). This method just skips all the route stuff and returns the addrspec. rNFr?r>@TrG)rr~rrS getdomainr)r expectrouteadlists r;rzAddrlistClass.getrouteaddrGs& ::dhh 3 &   A  hhTZZ( # DHH%,A  DHH%,A " DHH%,A ))+A   MMO!hhTZZ($ r<cg}|j|jt|jkrgd}|j|jdk(rN|r#|dj s|j |j d|xjdz c_d}n|j|jdk(r,|j dt|jznj|j|j|jvr&|r#|dj s|j nh|j |j|j}|r|r|j ||jt|jkrg|jt|jk\s|j|jdk7rtj|S|j d|xjdz c_|j|j}|stStj||zS) zParse an RFC 2822 addr-spec.TrJrDr?Frwz"%s"r)rr~rSrstrippoprUrgetquotergetatomrrr)raslist preserve_wswsdomains r;rzAddrlistClass.getaddrspecgs hhTZZ(Kzz$((#s*&*"2"2"4JJL c"A # DHH%, fuT]]_'==>DHH%6&*"2"2"4JJL dlln-Br b!%hhTZZ(( 88s4:: &$**TXX*>#*E##F+ + c A  ! '&00r<cg}|jt|jkr|j|j|jvr|xjdz c_n,|j|jdk(r*|jj |j n|j|jdk(r |j |jn|j|jdk(r'|xjdz c_|j dng|j|jdk(rtS|j|j|jvrnC|j |j|jt|jkrtj|S)z-Get the complete domain name from an address.r?r[rJr) r~rSrrrrUrgetdomainliteralrrrr)rsdlists r;rzAddrlistClass.getdomains=hhTZZ(zz$((#txx/A DHH%,  ''(9:DHH%, d3356DHH%,A  c"DHH%,#"DHH%6 dlln-#hhTZZ($''r<c|j|j|k7rydg}d}|xjdz c_|jt|jkr|r+|j|j|jd}n|j|j|vr|xjdz c_n|r<|j|jdk(r |j|j |j|jdk(rd}n(|j|j|j|xjdz c_|jt|jkrt j |S)aParse a header fragment delimited by special characters. `beginchar' is the start character for the fragment. If self is not looking at an instance of `beginchar' then getdelimited returns the empty string. `endchars' is a sequence of allowable end-delimiting characters. Parsing stops when one of these is encountered. If `allowcomments' is non-zero, embedded RFC 2822 comments are allowed within the parsed fragment. rFr?rrvT)rr~rSrUrrr)r begincharendchars allowcommentsslistrs r; getdelimitedzAddrlistClass.getdelimiteds% ::dhh 9 , A hhTZZ( TZZ12DHH%1A 4::dhh#73#> T__./DHH%- TZZ12 HHMHhhTZZ( &&r<c(|jdddS)z1Get a quote-delimited fragment from self's field.rwz" Frrs r;rzAddrlistClass.getquotes  eU33r<c(|jdddS)z7Get a parenthesis-delimited fragment from self's field.rz) Trrs r;rzAddrlistClass.getcomments  eT22r<c.d|jdddzS)z!Parse an RFC 2822 domain-literal.z[%s]rz] Frrs r;rzAddrlistClass.getdomainliterals))#ue<<rs     I > AQA$$$$$   z;z9kkZ -'--'r<__pycache__/feedparser.cpython-312.pyc000064400000046530152526700320013611 0ustar00 {|j YRdZddgZddlZddlmZddlmZddlmZddl m Z ejd Z ejd Z ejd Zejd Zejd Zd ZdZeZGddeZGddZGddeZy)aFeedParser - An email feed parser. The feed parser implements an interface for incrementally parsing an email message, line by line. This has advantages for certain applications, such as those reading email messages off a socket. FeedParser.feed() is the primary interface for pushing new data into the parser. It returns when there's nothing more it can do with the available data. When you have no more data to push into the parser, call .close(). This completes the parsing and returns the root message object. The other advantage of this parser is that it will never raise a parsing exception. Instead, when it finds something unexpected, it adds a 'defect' to the current message. Defects are just instances that live on the message object's .defects attribute. FeedParserBytesFeedParserN)errors)compat32)deque)StringIOz \r\n|\r|\nz (\r\n|\r|\n)z(\r\n|\r|\n)\Zz%^(From |[\041-\071\073-\176]*:|[\t ]) cLeZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z y ) BufferedSubFileakA file-ish object that can have new data loaded into it. You can also push and pop line-matching predicates onto a stack. When the current predicate matches the current line, a false EOF response (i.e. empty string) is returned instead. This lets the parser adhere to a simple abstraction -- it parses until EOF closes the current message. c`td|_t|_g|_d|_y)Nr )newlineF)r_partialr_lines _eofstack_closedselfs )/usr/lib64/python3.12/email/feedparser.py__init__zBufferedSubFile.__init__4s'!, g  c:|jj|yN)rappend)rpreds rpush_eof_matcherz BufferedSubFile.push_eof_matcher?s d#rc6|jjSr)rpoprs rpop_eof_matcherzBufferedSubFile.pop_eof_matcherBs~~!!##rc|jjd|j|jj|jjd|jj d|_y)NrT)rseek pushlines readlinestruncaterrs rclosezBufferedSubFile.closeEsV 1 t}}..01 1   rc|js|jrytS|jj}t |j D]'}||s |jj |y|SNr )rr NeedMoreDatapopleftreversedr appendleft)rlineateofs rreadlinezBufferedSubFile.readlineMse{{|| {{""$dnn-ET{ &&t, .  rcN|tusJ|jj|yr)r(rr+rr,s r unreadlinezBufferedSubFile.unreadline_s"<''' t$rc|jj|d|vrd|vry|jjd|jj}|jjd|jj |dj ds)|jj|j |j|y)z$Push some new data into this object.r  Nr)rwriter!r#r$endswithrr")rdatapartss rpushzBufferedSubFile.pushds D! t D 0  1 '') 1  Ry!!$' MM   , urc:|jj|yr)rextend)rliness rr"zBufferedSubFile.pushlinesys 5!rc|Srrs r__iter__zBufferedSubFile.__iter__|s rc<|j}|dk(rt|Sr')r. StopIterationr0s r__next__zBufferedSubFile.__next__s}} 2:  rN)__name__ __module__ __qualname____doc__rrrr%r.r1r9r"r?rBr>rrr r ,s9 $$$% *"rr cNeZdZdZd eddZdZdZdZdZ d Z d Z d Z d Z y)rzA feed-style parser of email.Npolicycr||_d|_|,|jddlm}||_n-|j|_n||_ ||jt|_g|_ |jj|_ d|_ d|_d|_y#t $r d|_Y]wxYw)a_factory is called with no arguments to create a new message obj The policy keyword specifies a policy object that controls a number of aspects of the parser's operation. The default policy maintains backward compatibility. FNr)MessagerHT)rI_old_style_factorymessage_factory email.messagerK_factory TypeErrorr _input _msgstack _parsegenrB_parse_cur_last _headersonly)rrOrIrKs rrzFeedParser.__init__s "'  %%-1 ' & 6 6 $DM / ,&' nn&//   ! /*.' /sB##B65B6cd|_y)NT)rWrs r_set_headersonlyzFeedParser._set_headersonlys  rcZ|jj||jy)zPush more data into the parser.N)rQr9 _call_parse)rr7s rfeedzFeedParser.feeds   rcD |jy#t$rYywxYwr)rTrArs rr[zFeedParser._call_parses"  KKM   s  cT|jj|j|j}|jrJ|j dk(rL|j s<|js0tj}|jj|||S)z>!!  $ $ &+ 5((*43D3D==?F KK % %dF 3 rc|jr|j}n|j|j}|jr.|jj dk(r|j d|j r|j dj||j j|||_||_ y)NrHzmultipart/digestzmessage/rfc822r4) rLrOrIrUget_content_typeset_default_typerRattachrrV)rmsgs r _new_messagezFeedParser._new_messages  " "--/C--t{{-3C 993359KK  !1 2 >> NN2  % %c * c"  rc|jj}|jr|jd|_|Sd|_|S)Nr4)rRrrU)rretvals rr`zFeedParser._pop_messages@##% >>r*DI DI rc#JK|jg}|jD]}|tur ttj |slt j |sUt j}|jj|j||jj|n|j||j||jrug} |jj}|tur t,|dk(rn|j|C|jj!t"j%|y|jj'dk(r |jj)t j|j+D]}|tur tn|j-|jj/ |jj}|tur t, |jj}|tur t, |dk(r y|jj||jj1dk(r8|j+D]}|tur tn|j-y|jj1dk(r|jj3}|t j4}|jj|j|g}|jD]$}|tur t|j|&|jj!t"j%|yt7|jj9ddj;dvr:t j<}|jj|j|d |z}t?j@d t?jB|zd z}d} g} d } d } |jj}|tur t,|dk(rn|j |} | r| jEd rd} | jEd} n}| r| ra| d}tFjI|}|r!|dtK|jEd | d<t"j%| |j_&d } |jj| |jj}|tur t,|j |} | s|jj|n[|jj)|j|j+D]}|tur tn|jNj1dk(rv|jNjP}|dk(rd|jN_(n|tFjI|} | rtK| jEd}|d| |jN_(nl|jNjR}tU|t6rFtFjI|} | r/|dtK| jEd }||jN_)|jj/|j-|j|_'n| sJ| j|| rt jV}|jj|j||jj!t"j%| g}|jD]}|tus tt"j%||j_(y| s;t jX}|jj|j|y| rdg}ng}|jD]$}|tur t|j|&|r<|d}tZj |}|r |tK|jEdd|d<t"j%||j_(yg}|jD]$}|tur t|j|&|jj!t"j%|yw)NTr zmessage/delivery-statusmessager_zcontent-transfer-encoding8bit)7bitrqbinaryz--z(?Pz4)(?P--)?(?P[ \t]*)(?P\r\n|\r|\n)?$Fendlinesepr4r).rlrQr(headerREmatchNLCREr MissingHeaderBodySeparatorDefectrIrdrUr1r_parse_headersrWr. set_payload EMPTYSTRINGjoinrhrrSr`rra get_boundaryNoBoundaryInMultipartDefectstrgetlower-InvalidMultipartContentTransferEncodingDefectrecompileescapegroup NLCRE_eolsearchlenpreamblerVepilogue_payload isinstanceStartBoundaryNotFoundDefectCloseBoundaryNotFoundDefect NLCRE_bol)rheadersr,rfr<rnboundary separator boundaryrecapturing_preamblerruclose_boundary_seenmolastlineeolmorrtpayload firstlinebolmos rrSzFeedParser._parsegens KKD|#"">>$'{{4(#DDFFKK--dii@KK**40 NN4  G$   E{{++-<'&&2: T" II ! !+"2"25"9 :  99 % % '+D D  ,,U[[9"nn.F-**  / !!# ++- ;;//1D|+** ;;//1D|+** 2:  &&t,?B 99 ) ) +y 8..*\)&& +      99 ) ) +{ :yy--/H  ;;= ))$))V< KKD|+** LL& (  %%k&6&6u&=>DIIMM"=vFGMMO56MMO ))$))V< xIRYYy11GHIJ"& HG"' {{++-<'&&2:%%d+ xx.2+"$((9"5)#(0|H$-$4$4X$>E$/78M#ekk!n:M9M/N 1<1A1A(1KDII.-2* ..t4 #{{335</"..$'--d3! KK2248!KK001A1AB"&.."2!\1"..$ #3zz668KG#'::#6#6#r>26DJJ/%1!*!1!1(!;B!&)"((1+&66>uo 3"&**"5"5%gs3!*!1!1'!:B!*12DC 4D3D*E6= 3KK//1%%'"&DJ.--OOD)_f";;= ))$))V< %%k&6&6x&@A KKD|+** (&1%5%5h%? "';;= ))$))V<4 <'&&% $$QK ! 2"+C A,?,@"AHQK!,!1!1(!;DII  KKD|#"" LL   k..u56s ^2d#5E.d#c,d}g}t|D]\}}|ddvrP|s>yI J rr)rCrDrErFrrrYr\r[r%rlr`rSrzr>rrrrs<'"">!   {7z:Krc"eZdZdZfdZxZS)rz(Like FeedParser, but feed accepts bytes.cDt||jddy)Nasciisurrogateescape)superr\decode)rr7 __class__s rr\zBytesFeedParser.feeds  T[[*;<=r)rCrDrErFr\ __classcell__)rs@rrrs2>>r)rF__all__remailremail._policybaser collectionsriorrrxrr NLCRE_crackrvr|NLobjectr(r rrr>rrrs " * + & =! BJJ ' BJJ( ) bjj)  2::> ?  x WfWtIKIKX >j>r__pycache__/header.cpython-312.opt-1.pyc000064400000057677152526700320013676 0ustar00 {|j^dZgdZddlZddlZddlZddlZddlmZddlm Z e jZ dZ dZ dZd Zd Zd Zd Ze d Ze dZej*dej,ej.zZej*dZej*dZej6j8ZdZ ddZGddZGddZ Gdde!Z"y)z+Header encoding and decoding functionality.)Header decode_header make_headerN)HeaderParseError)charset   z Nz us-asciizutf-8ai =\? # literal =? (?P[^?]*?) # non-greedy up to the next ? is the charset \? # literal ? (?P[qQbB]) # either a "q" or a "b", case insensitive \? # literal ? (?P.*?) # non-greedy up to the next ?= is the encoded string \?= # literal ?= z[\041-\176]+:$z \n[^ \t]+:c t|drG|jDcgc]/\}}tj|t |t |f1c}}St j |s|dfgSg}|jD]}t j|}d}|s|jd}|r|j}d}|r|j|ddf|rc|jdj}|jdj}|jd} |j| ||f|rg} t|D]K\} } | dkDs | ds|| dz ds|| dz djs8| j| dz Mt| D]} || =g}|D]\}}}||j||f|dk(r3t j"j%|}|j||fU|d k(rOt'|d z}|r |d dd |z z } t j(j+|}|j||ft3d |zg}dx}}|D]Y\}}t5|tr t7|d}||}|})||k7r|j||f|}|}F| |t8|zz }U||z }[|j||f|Scc}}w#t,j.$r t1d wxYw)a;Decode a message header value without converting charset. Returns a list of (string, charset) pairs containing each of the decoded parts of the header. Charset is None for non-encoded parts of the header, otherwise a lower-case string containing the name of the character set specified in the encoded string. header may be a string that may or may not contain RFC2047 encoded words, or it may be a Header object. An email.errors.HeaderParseError may be raised when certain decoding error occurs (e.g. a base64 decoding exception). _chunksNTrFqbz===zBase64 decoding errorzUnexpected encoding: zraw-unicode-escape)hasattrr_charset_encodestrecresearch splitlinessplitpoplstripappendlower enumerateisspacereversedemail quoprimime header_decodelen base64mimedecodebinasciiErrorrAssertionError isinstancebytesBSPACE)headerstringrwordslinepartsfirst unencodedencodingencodeddroplistnwd decoded_wordsencoded_stringwordpaderr collapsed last_word last_charsets %/usr/lib64/python3.12/email/header.pyrr;s8vy!+1>>;+9!!&#g,7WF+9; ; ;;v  E!!# 4  ! I%,,.  it45))A,,,. 99Q<--/))A, gx9:$"H% 1 Q31Q4E!A#JqMeAaCjm.C.C.E OOAaC !h  !H M-2)'    .'!: ; _##11.AD  $ 1 _(1,F% V"44 6''..~>$$dG_5 !88!CD D%.3*I##I & g dC 34D  I"L  $   i6 7I"L  ! $ &I  I'i./ W;d>> @&'>?? @s4K%*K++L ct|||}|D]4\}}|t|ts t|}|j||6|S)aCreate a Header from a sequence of pairs as returned by decode_header() decode_header() takes a header value string and returns a sequence of pairs of the format (decoded_string, charset) where charset is the string name of the character set. This function takes one of those sequence of pairs and returns a Header instance. Optional maxlinelen, header_name, and continuation_ws are as in the Header constructor. ) maxlinelen header_namecontinuation_ws)rr-Charsetr) decoded_seqrFrGrHhsrs rDrrsQ *+. 0A! 7  z'7'Cg&G G " HcBeZdZ d dZdZdZd dZdZd dZdZ y) rNc|t}nt|ts t|}||_||_g|_||j ||||t}||_|d|_ yt|dz|_ y)aDCreate a MIME-compliant header that can contain many character sets. Optional s is the initial header value. If None, the initial header value is not set. You can later append to the header with .append() method calls. s may be a byte string or a Unicode string, but see the .append() documentation for semantics. Optional charset serves two purposes: it has the same meaning as the charset argument to the .append() method. It also sets the default character set for all subsequent .append() calls that omit the charset argument. If charset is not provided in the constructor, the us-ascii charset is used both as s's initial charset and as the default for subsequent .append() calls. The maximum line length can be specified explicitly via maxlinelen. For splitting the first line to a shorter value (to account for the field header which isn't included in s, e.g. `Subject') pass in the name of the field in header_name. The default maxlinelen is 78 as recommended by RFC 2822. continuation_ws must be RFC 2822 compliant folding whitespace (usually either a space or a hard tab) which will be prepended to continuation lines. errors is passed through to the .append() call. Nrr) USASCIIr-rIr_continuation_wsrr MAXLINELEN _maxlinelen _headerlenr')selfrLrrFrGrHerrorss rD__init__zHeader.__init__s: ?GGW-g&G / = KK7F +  #J%  DO"+.2DOrMc|jg}d}d}|jD]\}}|}|tjk(r$|j dd}|j dd}|rU|xr|j |d}|dvr|dvr5|s3|jtd}n|dvr|s|jt|xr|j |d}|}|j|tj|S)z&Return the string value of the header.NasciisurrogateescapereplacerNr ) _normalizerr UNKNOWN8BITencoder) _nonctextrSPACE EMPTYSTRINGjoin) rUuchunkslastcs lastspacer1rnextcsoriginal_byteshasspaces rD__str__zHeader.__str__s  #||OFGF---!'w8I!J'..w B!?dnnVAY&?!33!33Hu-!%#55iNN5)=4>>&*#=IF NN6 "+ ,,((rMc|t|k(SN)r)rUothers rD__eq__z Header.__eq__sD !!rMc| |j}nt|ts t|}t|tsH|jxsd}|tj k(r|j dd}n|j ||}|jxsd}|tj k7r |j|||jj||fy#t$r|dk7rt}Y5wxYw)a.Append a string to the MIME header. Optional charset, if given, should be a Charset instance or the name of a character set (which will be converted to a Charset instance). A value of None (the default) means that the charset given in the constructor is used. s may be a byte string or a Unicode string. If it is a byte string (i.e. isinstance(s, str) is false), then charset is the encoding of that byte string, and a UnicodeError will be raised if the string cannot be decoded with that charset. If s is a Unicode string, then charset is a hint specifying the character set of the characters in the string. In either case, when producing an RFC 2822 compliant header using RFC 2047 rules, the string will be encoded using the output codec of the charset. If the string cannot be encoded to the output codec, a UnicodeError will be raised. Optional `errors' is passed as the errors argument to the decode call if s is a byte string. Nr rZ) rr-rIr input_codecr_r) output_codecr`UnicodeEncodeErrorUTF8rr)rUrLrrV input_charsetoutput_charsets rDrz Header.appends* ?mmGGW-g&G!S!#//=:M 4 44HHZ):;HH]F3!--; X11 1 0 QL) & !:- s'CC/.C/c.|jxs|dvS)z=True if string s is not a ctext character of RFC822. )()\)r")rUrLs rDrazHeader._nonctext0syy{3a#333rMc.|j| |j}|dk(rd}t|j||j|}d}dx}}|j D][\}} |I|xr|j |d}|dvr|r| dvr'|jn| dvr|s|j|xr|j |d}| }d}|j} | r|jd| d| n|jdd| | ddD]} |j| j/|j|jd | jz| N| j} | dt| t| z } |j| | | t| dkDsL|j^|j r|j|j|}tj!|rt#d j%||S) aEncode a message header into an RFC-compliant format. There are many issues involved in converting a given string for use in an email header. Only certain character sets are readable in most email clients, and as header strings can only contain a subset of 7-bit ASCII, care must be taken to properly convert and encode (with Base64 or quoted-printable) header strings. In addition, there is a 75-character length limit on any given encoded header field, so line-wrapping must be performed, even with double-byte character sets. Optional maxlinelen specifies the maximum length of each generated line, exclusive of the linesep string. Individual lines may be longer than maxlinelen if a folding point cannot be found. The first line will be shorter by the length of the header name plus ": " if a header name was specified at Header construction time. The default value for maxlinelen is determined at header construction time. Optional splitchars is a string containing characters which should be given extra weight by the splitting algorithm during normal header wrapping. This is in very rough support of RFC 2822's `higher level syntactic breaks': split points preceded by a splitchar are preferred during line splitting, with the characters preferred in the order in which they appear in the string. Space and tab may be included in the string to indicate whether preference should be given to one over the other as a split point when other split chars do not appear in the line being split. Splitchars does not affect RFC 2047 encoded lines. Optional linesep is a string to be used to separate the lines of the value. The default value is the most useful for typical Python applications, but it can be set to \r\n to produce RFC-compliant line separators when needed. Nri@Br\r]Fr rr z8header value appears to contain an embedded header: {!r})r^rS_ValueFormatterrTrQrraadd_transitionrfeednewlineheader_encodingrr'_str_embedded_headerrrformat)rU splitcharsrFlinesep formatterrfrjrgr1rlinesr3slinefwsvalues rDr`z Header.encode5sB   ))J ? J#DOOZ$($9$9:G ##9#||OFG#!?dnnVAY&?!33#w6H'H!002$66y,,.=4>>&*#=IFH%%'Er58W5r2w/ab !!#**6NN4#8#8# :M#*,!KKME4D #e* 45CNN3w7"5zA~!!#5 ,6 <<  $ $ &w'  " "5 )"$++16%=: : rMcg}d}g}|jD]I\}}||k(r|j||&|jtj||f|g}|}K|r&|jtj||f||_yrm)rrrbrd)rUchunksrC last_chunkr1rs rDr^zHeader._normalizes  #||OFG,&!!&)+MM5::j#9<"HI$X &  ,  MM5::j1<@ A rM)NNNNr strict)Nr)z;, Nr) __name__ __module__ __qualname__rWrkrorrar`r^rMrDrrs3'+.2-5-3^)@" )*V4 N`rMrcBeZdZdZdZdZdZdZdZdZ dZ d Z y ) r|c|||_||_t||_||_g|_t ||_yrm)_maxlenrQr'_continuation_ws_len _splitchars_lines _Accumulator _current_line)rU headerlenmaxlenrHrs rDrWz_ValueFormatter.__init__s: /$'$8!% ))4rMcX|j|j|jSrm)rrdr)rUrs rDrz_ValueFormatter._strs ||DKK((rMc,|jtSrm)rNLrUs rDrkz_ValueFormatter.__str__syy}rMc|jj}|dk7r|jj|t|jdkDr|jj r7|j r+|j dxxt |jz cc<n.|j jt |j|jjy)N)r r rr]) rrpushr' is_onlywsrrrreset)rU end_of_lines rDrz_ValueFormatter.newlines((,,. ) # #D   # #[ 1 t!! "Q &!!++-$++ B3t'9'9#:: ""3t'9'9#:;   "rMc<|jjddy)Nr r )rrrs rDr}z_ValueFormatter.add_transitions R(rMc |j|j|||jy|j||j } |j d}||j|| |j }|j|jj|j||D]*}|jj|j|z,y#t $rYywxYw#t $rYywxYwNr)r _ascii_splitrheader_encode_lines _maxlengthsr IndexError _append_chunkrrrrQrr)rUrr1r encoded_lines first_line last_liner3s rDr~z_ValueFormatter.feeds  " " *   c64+;+; <  33FDq@!RHAzz|"003A63q62:!#11!A#6q9HHRL"$4I'!..224 T%%33a7LLN"""''T2**33A6I KK  s4#5#56 7    $ $Y /9 2rMN) rrrrWrrkrr}r~rrrrrMrDr|r|s05) #)#=J; *,0rMr|c\eZdZd fd ZdZd dZfdZdZdZd dZ dZ fd Z xZ S) rc0||_t| yrm)rsuperrW)rU initial_size __class__s rDrWz_Accumulator.__init__s) rMc*|j||fyrm)r)rUrr1s rDrz_Accumulator.pushs S&M"rMc||d}g||d|Srmr)rUrpoppeds rDrz_Accumulator.pop_from!sabQR rMcH|jdk(ryt| S)Nr)r r )rrrrUrs rDrz_Accumulator.pop&s! ?? a w{}rMc<td|D|jS)Nc3PK|]\}}t|t|z ywrm)r'.0rrs rD z'_Accumulator.__len__..,s"=93CHSY&$&)sumrrs rD__len__z_Accumulator.__len__+s ==%%' 'rMc:tjd|DS)Nc3PK|]\}}tj||f ywrmrcrdrs rDrz'_Accumulator.__str__..0s+!715IC"-!1!13+!>15rrrs rDrkz_Accumulator.__str__/s"!715!78 8rMc$|g}||ddd|_yr)r)rUstartvals rDrz_Accumulator.reset3s  HQrMc`|jdk(xr| xst|jSr)rrr"rs rDrz_Accumulator.is_onlyws9s,!!1$Jd(*Ic$i6G6G6IJrMc t|Srm)rrrs rDrz_Accumulator.part_count<sw  rM)rrm) rrrrWrrrrrkrrr __classcell__)rs@rDrrs6#  '8 K!!rMr)NNr )#__doc____all__rr*email.quoprimimer$email.base64mime email.errorsrrrrIrrbr/SPACE8rcrRrrPrtcompileVERBOSE MULTILINErfcrerr% _max_appendrrrr|listrrrMrDrs 2   )%           * wrzz zzBLL "rzz#$2::m,** [|;? # ,ffR}0}0@%!4%!rM__pycache__/quoprimime.cpython-312.opt-2.pyc000064400000014621152526700320014614 0ustar00 {|j& gdZddlZddlmZmZmZdZdZdZe dDcgc]}d|z c}Z e ddZ e ddZ d ejd zejd zD] Zeee e<d e ed <d D] Zeee e<dZdZdZdZddZdZdZddZe ddZdD] Zeeee<[defdZefdZeZeZdZdZycc}w)) body_decode body_encode body_lengthdecode decodestring header_decode header_encode header_lengthquoteunquoteN) ascii_lettersdigits hexdigits  z=%02Xs-!*+/ascii_ s_ !"#$%&'()*+,-./0123456789:;<>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ c. t|t|k7SN)chr_QUOPRI_HEADER_MAPoctets )/usr/lib64/python3.12/email/quoprimime.py header_checkrJsH u:+E2 22c. t|t|k7Sr)r_QUOPRI_BODY_MAPrs r body_checkr"OsF u:)%0 00rc( td|DS)Nc3@K|]}tt|ywr)lenr.0rs r z header_length..^sE9%s%e,-9sum bytearrays rr r Ts E9E EErc( td|DS)Nc3@K|]}tt|ywr)r%r!r&s rr(zbody_length..hsCs#E*+r)r*r,s rrras CC CCrct|ts t|}|s |j|j yt |dt |z|kr|dxx||zz cc<y|j|j y)N) isinstancestrrappendlstripr%)Lsmaxlenextras r _max_appendr:ksg a  F   QrUc!f  & " rc4 tt|dddS)N)rintr7s rr r vsN s1Qq62 rc&tt|Sr) _QUOPRI_MAPordcs rr r {s s1v rcd |sy|jdjt}d|d|dS)Nrlatin1z=?z?q?z?=)r translater) header_bytescharsetencodeds rrrs8  !!(+556HIG$W --rs Lc |dkr td|s|S|jt}d|z}|dz }g}|j}|j D]}d}t |dz |z } || krV||z} || dz dk(r|||| dz | dz }n,|| dz dk(r|||| | dz }n|||| dz| }|| krV|rN|ddvrG|| z } | d k\rt |d} n| dk(r |d|z} n|t |dz} |||d| z|||d|dtvr|d |j|S) Nzmaxlinelen must be at least 4=r<r r1z r=r) ValueErrorrH_QUOPRI_BODY_ENCODE_MAPr4 splitlinesr%r CRLFjoin) body maxlineleneol soft_break maxlinelen1 encoded_bodyr4linestart laststartstoproomqs rrrs$A~899   >>1 2DsJq.KL  F!IMJ. y ;&DD1H~$tE$(+,qdQh3&tE$'(qtE$'#-.y  DH%9$Dqy$r(OHz)tBx0 4b>A% & 4< C"H Bx4r 88L !!rc |s|Sd}|jD]}|j}|s||z }d}t|}||ks.||}|dk7r ||z }|dz }nV|dz|k(r|dz })|dz|kr6||dztvr(||dztvr|t |||dzz }|dz }n ||z }|dz }||k(r||z }||kr{|ddvr|j |r|dd}|S) Nrr rOr<rPr=r1r)rSrstripr%rr endswith)rKrXdecodedr\inrEs rrrs8 G""${{} sNG   I!eQACx1 Q1Q1qT!A#Y)3QqS Y8N74!A#;//Q1 QAv3)!e%<r{& W%5%5c%:#2, Nrc< |jd}t|S)Nr )groupr )matchr7s r_unquote_matchrksM AA 1:rc~ |jdd}tjdt|tjS)Nrrz=[a-fA-F0-9]{2})flags)replaceresubrkASCIIr@s rrr$s3 #sA 66$narxx HHr)r)z iso-8859-1) __all__rostringr rrrTNL EMPTYSTRINGrangerBrr!encoderErrCrr"r rr:r r rrRrrrrrkrrDs0rrxsQ 0  33   %*#J/Jqw{J/  ^q> (M((1 1MFMM'4J JAFq K #3s8 .Aa&Q .3 1 FD .*+1- A!$QA !#I"^,`  I[0s C__pycache__/header.cpython-312.opt-2.pyc000064400000044771152526700320013666 0ustar00 {|j^ gdZddlZddlZddlZddlZddlmZddlmZ e jZ dZ dZ dZ dZd Zd Zd Ze d Ze d Zej(dej*ej,zZej(dZej(dZej4j6ZdZ ddZGddZGddZGdde Z!y))Header decode_header make_headerN)HeaderParseError)charset   z Nz us-asciizutf-8ai =\? # literal =? (?P[^?]*?) # non-greedy up to the next ? is the charset \? # literal ? (?P[qQbB]) # either a "q" or a "b", case insensitive \? # literal ? (?P.*?) # non-greedy up to the next ?= is the encoded string \?= # literal ?= z[\041-\176]+:$z \n[^ \t]+:c  t|drG|jDcgc]/\}}tj|t |t |f1c}}St j |s|dfgSg}|jD]}t j|}d}|s|jd}|r|j}d}|r|j|ddf|rc|jdj}|jdj}|jd} |j| ||f|rg} t|D]K\} } | dkDs | ds|| dz ds|| dz djs8| j| dz Mt| D]} || =g}|D]\}}}||j||f|dk(r3t j"j%|}|j||fU|dk(rOt'|d z}|r |d dd |z z } t j(j+|}|j||ft3d |zg}dx}}|D]Y\}}t5|tr t7|d }||}|})||k7r|j||f|}|}F| |t8|zz }U||z }[|j||f|Scc}}w#t,j.$r t1d wxYw)N_chunksTrFqbz===zBase64 decoding errorzUnexpected encoding: zraw-unicode-escape)hasattrr_charset_encodestrecresearch splitlinessplitpoplstripappendlower enumerateisspacereversedemail quoprimime header_decodelen base64mimedecodebinasciiErrorrAssertionError isinstancebytesBSPACE)headerstringrwordslinepartsfirst unencodedencodingencodeddroplistnwd decoded_wordsencoded_stringwordpaderr collapsed last_word last_charsets %/usr/lib64/python3.12/email/header.pyrr;s= vy!+1>>;+9!!&#g,7WF+9; ; ;;v  E!!# 4  ! I%,,.  it45))A,,,. 99Q<--/))A, gx9:$"H% 1 Q31Q4E!A#JqMeAaCjm.C.C.E OOAaC !h  !H M-2)'    .'!: ; _##11.AD  $ 1 _(1,F% V"44 6''..~>$$dG_5 !88!CD D%.3*I##I & g dC 34D  I"L  $   i6 7I"L  ! $ &I  I'i./ W;d>> @&'>?? @s4K&+K,,L c t|||}|D]4\}}|t|ts t|}|j||6|S)N) maxlinelen header_namecontinuation_ws)rr-Charsetr) decoded_seqrFrGrHhsrs rDrrsV  *+. 0A! 7  z'7'Cg&G G " HcBeZdZ d dZdZdZd dZdZd dZdZ y) rNc |t}nt|ts t|}||_||_g|_||j ||||t}||_|d|_ yt|dz|_ y)Nrr) USASCIIr-rIr_continuation_wsrr MAXLINELEN _maxlinelen _headerlenr')selfrLrrFrGrHerrorss rD__init__zHeader.__init__s 4 ?GGW-g&G / = KK7F +  #J%  DO"+.2DOrMc |jg}d}d}|jD]\}}|}|tjk(r$|j dd}|j dd}|rU|xr|j |d}|dvr|dvr5|s3|jtd}n|dvr|s|jt|xr|j |d}|}|j|tj|S)NasciisurrogateescapereplacerNr ) _normalizerr UNKNOWN8BITencoder) _nonctextrSPACE EMPTYSTRINGjoin) rUuchunkslastcs lastspacer1rnextcsoriginal_byteshasspaces rD__str__zHeader.__str__s4  #||OFGF---!'w8I!J'..w B!?dnnVAY&?!33!33Hu-!%#55iNN5)=4>>&*#=IF NN6 "+ ,,((rMc|t|k(SN)r)rUothers rD__eq__z Header.__eq__sD !!rMc | |j}nt|ts t|}t|tsH|jxsd}|tj k(r|j dd}n|j ||}|jxsd}|tj k7r |j|||jj||fy#t$r|dk7rt}Y5wxYw)Nr rZ) rr-rIr input_codecr_r) output_codecr`UnicodeEncodeErrorUTF8rr)rUrLrrV input_charsetoutput_charsets rDrz Header.appends ( ?mmGGW-g&G!S!#//=:M 4 44HHZ):;HH]F3!--; X11 1 0 QL) & !:- s(CC0/C0c0 |jxs|dvS)N)()\)r")rUrLs rDrazHeader._nonctext0s yy{3a#333rMc0 |j| |j}|dk(rd}t|j||j|}d}dx}}|j D][\}} |I|xr|j |d}|dvr|r| dvr'|jn| dvr|s|j|xr|j |d}| }d}|j} | r|jd| d| n|jdd| | ddD]} |j| j/|j|jd| jz| N| j} | dt| t| z } |j| | | t| dkDsL|j^|j r|j|j|}tj!|rt#d j%||S) Nri@Br\r]Fr rr z8header value appears to contain an embedded header: {!r})r^rS_ValueFormatterrTrQrraadd_transitionrfeednewlineheader_encodingrr'_str_embedded_headerrrformat)rU splitcharsrFlinesep formatterrfrjrgr1rlinesr3slinefwsvalues rDr`z Header.encode5s  @   ))J ? J#DOOZ$($9$9:G ##9#||OFG#!?dnnVAY&?!33#w6H'H!002$66y,,.=4>>&*#=IFH%%'Er58W5r2w/ab !!#**6NN4#8#8# :M#*,!KKME4D #e* 45CNN3w7"5zA~!!#5 ,6 <<  $ $ &w'  " "5 )"$++16%=: : rMcg}d}g}|jD]I\}}||k(r|j||&|jtj||f|g}|}K|r&|jtj||f||_yrm)rrrbrd)rUchunksrC last_chunkr1rs rDr^zHeader._normalizes  #||OFG,&!!&)+MM5::j#9<"HI$X &  ,  MM5::j1<@ A rM)NNNNr strict)Nr)z;, Nr) __name__ __module__ __qualname__rWrkrorrar`r^rMrDrrs3'+.2-5-3^)@" )*V4 N`rMrcBeZdZdZdZdZdZdZdZdZ dZ d Z y ) r|c|||_||_t||_||_g|_t ||_yrm)_maxlenrQr'_continuation_ws_len _splitchars_lines _Accumulator _current_line)rU headerlenmaxlenrHrs rDrWz_ValueFormatter.__init__s: /$'$8!% ))4rMcX|j|j|jSrm)rrdr)rUrs rDrz_ValueFormatter._strs ||DKK((rMc,|jtSrm)rNLrUs rDrkz_ValueFormatter.__str__syy}rMc|jj}|dk7r|jj|t|jdkDr|jj r7|j r+|j dxxt |jz cc<n.|j jt |j|jjy)N)r r rr]) rrpushr' is_onlywsrrrreset)rU end_of_lines rDrz_ValueFormatter.newlines((,,. ) # #D   # #[ 1 t!! "Q &!!++-$++ B3t'9'9#:: ""3t'9'9#:;   "rMc<|jjddy)Nr r )rrrs rDr}z_ValueFormatter.add_transitions R(rMc |j|j|||jy|j||j } |j d}||j|| |j }|j|jj|j||D]*}|jj|j|z,y#t $rYywxYw#t $rYywxYwNr)r _ascii_splitrheader_encode_lines _maxlengthsr IndexError _append_chunkrrrrQrr)rUrr1r encoded_lines first_line last_liner3s rDr~z_ValueFormatter.feeds  " " *   c64+;+; <  33FDq@!RHAzz|"003A63q62:!#11!A#6q9HHRL"$4I'!..224 T%%33a7LLN"""''T2**33A6I KK  s4#5#56 7    $ $Y /9 2rMN) rrrrWrrkrr}r~rrrrrMrDr|r|s05) #)#=J; *,0rMr|c\eZdZd fd ZdZd dZfdZdZdZd dZ dZ fd Z xZ S) rc0||_t| yrm)rsuperrW)rU initial_size __class__s rDrWz_Accumulator.__init__s) rMc*|j||fyrm)r)rUrr1s rDrz_Accumulator.pushs S&M"rMc||d}g||d|Srmr)rUrpoppeds rDrz_Accumulator.pop_from!sabQR rMcH|jdk(ryt| S)Nr)r r )rrrrUrs rDrz_Accumulator.pop&s! ?? a w{}rMc<td|D|jS)Nc3PK|]\}}t|t|z ywrm)r'.0rrs rD z'_Accumulator.__len__..,s"=93CHSY&$&)sumrrs rD__len__z_Accumulator.__len__+s ==%%' 'rMc:tjd|DS)Nc3PK|]\}}tj||f ywrmrcrdrs rDrz'_Accumulator.__str__..0s+!715IC"-!1!13+!>15rrrs rDrkz_Accumulator.__str__/s"!715!78 8rMc$|g}||ddd|_yr)r)rUstartvals rDrz_Accumulator.reset3s  HQrMc`|jdk(xr| xst|jSr)rrr"rs rDrz_Accumulator.is_onlyws9s,!!1$Jd(*Ic$i6G6G6IJrMc t|Srm)rrrs rDrz_Accumulator.part_count<sw  rM)rrm) rrrrWrrrrrkrrr __classcell__)rs@rDrrs6#  '8 K!!rMr)NNr )"__all__rr*email.quoprimimer$email.base64mime email.errorsrrrrIrrbr/SPACE8rcrRrrPrtcompileVERBOSE MULTILINErfcrerr% _max_appendrrrr|listrrrMrDrs 2   )%           * wrzz zzBLL "rzz#$2::m,** [|;? # ,ffR}0}0@%!4%!rM__pycache__/policy.cpython-312.opt-2.pyc000064400000013015152526700320013720 0ustar00 {|jv)N ddlZddlZddlmZmZmZmZddlmZddl m Z ddl m Z ddl mZgdZej dZeGd d eZeZe`ej+d Zej+d Zej+d dZej+d Zy)N)PolicyCompat32compat32_extend_docstrings)_has_surrogates)HeaderRegistry)raw_data_manager) EmailMessage)rrr EmailPolicydefaultstrictSMTPHTTPz\n|\r\n?cjeZdZ eZdZdZeZe Z fdZ dZ dZ dZdZdZd Zd d ZxZS) r Flongc jd|vrtj|dtt|di|y)Nheader_factory)object __setattr__rsuper__init__)selfkw __class__s %/usr/lib64/python3.12/email/policy.pyrzEmailPolicy.__init__]s3 2 %   t%5~7G H 2c6 |j|jSN)r max_count)rnames rheader_max_countzEmailPolicy.header_max_countds  ""4(222rc |djdd\}}dj|g|ddjd}||jdfS)Nr:z  )splitjoinlstriprstrip)r sourcelinesr!values rheader_source_parsezEmailPolicy.header_source_parsevs^ "!n**32 e1QR1299)Dell6*++rc t|dr/|jj|jk(r||fSt|tr't |j dkDr td||j||fS)Nr!r%zDHeader values may not contain linefeed or carriage return characters) hasattrr!lower isinstancestrlen splitlines ValueErrorrrr!r-s rheader_store_parsezEmailPolicy.header_store_parses  5& !ejj&6&6&8DJJL&H%= eS !c%*:*:*<&=a&?=> >d))$677rc t|dr|Sdjtj|}|j ||S)Nr!r&)r0r)linesep_splitterr(rr7s rheader_fetch_parsezEmailPolicy.header_fetch_parsesE  5& !L(..u56""4//rc, |j||dS)NT refold_binary)_foldr7s rfoldzEmailPolicy.folds $zz$Tz::rc |j|||jdk(}|jrdnd}|j|dS)N7bitr=utf8asciisurrogateescape)r?cte_typerCencode)rr!r-foldedcharsets r fold_binaryzEmailPolicy.fold_binarysE D%t}}f7LM II&7}}W&788rct|dr|j|S|jr |jntjt j |}|jdk(xsN|jdk(xr=|xr t|dt|zdzkDxstfd|ddD}|s+|js|j }n |r t|}|r1|j|d j|j|S|d z|jj|z|jzS) Nr!)policyallrrc3:K|]}t|kDywr)r4).0xmaxlens r z$EmailPolicy._fold..s<)QQ&)sr%r&z: )r0r@max_line_lengthsysmaxsizer:r( refold_sourcer4anyrCisasciirrr)linesep)rr!r-r>linesrefoldrRs @rr?zEmailPolicy._folds( 5& !::T:* *)-)=)=%%3;; &&u-$$->$$.>As58}SY6q86A=<%)<<  99"]]_,(/ &&tRWWU^<AAAN Nd{T\\..u55 DDr)F)__name__ __module__ __qualname__r message_factoryrCrWrrr content_managerrr"r.r8r;r@rJr? __classcell__)rs@rr r sP8t#O DM#%N&O3$ ,8& 0;*9$Err T)raise_on_defectr')rZ)rZrT)rC)rerUemail._policybaserrrr email.utilsremail.headerregistryremail.contentmanagerr email.messager __all__compiler:r r rcloner rrSMTPUTF8rrrrns LL'A1& 2::k*DE&DEDEN -  t ,}}V}$}}VT}: ::4: r__pycache__/base64mime.cpython-312.opt-1.pyc000064400000007553152526700320014366 0ustar00 {|j ddZgdZddlmZddlmZmZdZdZdZ dZ d Z dd Z d efd Z d ZeZeZy)aBase64 content transfer encoding per RFCs 2045-2047. This module handles the content transfer encoding method defined in RFC 2045 to encode arbitrary 8-bit data using the three 8-bit bytes in four 7-bit characters encoding known as Base64. It is used in the MIME standards for email to attach images, audio, and text using some 8-bit character sets to messages. This module provides an interface to encode and decode both headers and bodies with Base64 encoding. RFC 2045 defines a method for including character set information in an `encoded-word' in a header. This method is commonly used for 8-bit real names in To:, From:, Cc:, etc. fields, as well as Subject: lines. This module does not do the line wrapping or end-of-line character conversion necessary for proper internationalized headers; it only does dumb encoding and decoding. To deal with the various line wrapping issues, use the email.header module. ) body_decode body_encodedecode decodestring header_encode header_length) b64encode) b2a_base64 a2b_base64z  cNtt|d\}}|dz}|r|dz }|S)z6Return the length of s when it is encoded with base64.)divmodlen) bytearray groups_of_3leftoverns )/usr/lib64/python3.12/email/base64mime.pyrr1s1"3y>15KaA Q Hc|syt|tr|j|}t|j d}d|d|dS)zEncode a single header line with Base64 encoding in a given charset. charset names the character set to use to encode the header. It defaults to iso-8859-1. Base64 encoding is defined in RFC 2045. r asciiz=?z?b?z?=) isinstancestrencoder r) header_bytescharsetencodeds rrr;sD ,$#**73  %,,W5G#W --rLc*|syg}|dzdz}tdt||D]Y}t||||zjd}|j t r|t k7r|dd|z}|j |[tj|S)a1Encode a string with base64. Each line will be wrapped at, at most, maxlinelen characters (defaults to 76 characters). Each line of encoded text will end with eol, which defaults to "\n". Set this to "\r\n" if you will be using the result of this function directly in an email. r rrrrN) rangerr rendswithNLappend EMPTYSTRINGjoin)s maxlineleneolencvec max_unencodediencs rrrIs  FNa'M 1c!fm ,1Q./077@ << r cr(S.C c -   F ##rc|s tSt|trt|j dSt|S)zDecode a raw base64 string, returning a bytes object. This function does not parse a full MIME header value encoded with base64 (like =?iso-8859-1?b?bmloISBuaWgh?=) -- please use the high level email.header class for that functionality. zraw-unicode-escape)bytesrrr r)strings rrrbs8 w FC &--(<=>>&!!rN)z iso-8859-1)__doc____all__base64r binasciir r CRLFr'r)MISC_LENrrrrrrrrr<sV , +      .!b$2 "   r__pycache__/contentmanager.cpython-312.opt-1.pyc000064400000030114152526700320015424 0ustar00 {|j\)FddlZddlZddlZddlZddlmZGddZeZddZejdedZ djD]Z eje e [ d Z d jD]Zejd eze [d Zejd edZdZdZdZ ddZej+ee ddZej+ej0j2e ddZeeefD]Zej+ee[y)N) quoprimimec0eZdZdZdZdZdZdZdZy)ContentManagerc i|_i|_yN) get_handlers set_handlers)selfs -/usr/lib64/python3.12/email/contentmanager.py__init__zContentManager.__init__ sc"||j|<yr)r)r keyhandlers r add_get_handlerzContentManager.add_get_handler s!(#r cB|j}||jvr|j||g|i|S|j}||jvr|j||g|i|Sd|jvr|jd|g|i|St|)N)get_content_typerget_content_maintypeKeyError)r msgargskw content_typemaintypes r get_contentzContentManager.get_contents++- 4,, ,24$$\23DDD D++- t(( (.4$$X.s@T@R@ @ "" "(4$$R(:t:r: :|$$r c"||j|<yr)r )r typekeyrs r add_set_handlerzContentManager.add_set_handlers%,'"r c|jdk(r td|j||}|j|||g|i|y)N multipartz"set_content not valid on multipart)r TypeError_find_set_handler clear_content)r robjrrrs r set_contentzContentManager.set_contentsS  # # % 4@A A((c2 S&4&2&r cd}t|jD]}||jvr|j|cS|j}t |dd}|rdj ||fn|}||}||jvr|j|cS||jvr|j|cS|j }||jvs|j|cSd|jvr|jdSt|)N __module__r.)type__mro__r __qualname__getattrjoin__name__r) r rr%full_path_for_errortypqnamemodname full_pathnames r r#z ContentManager._find_set_handler's "9$$Cd'''((--$$Ec<4G6='5!125I"*&/#D---((33)))((//<>'&> 11r textc&|jdS)NTr8r=rs r get_non_text_contentrEGs ??$? ''r zaudio image video applicationc$|jdSNrrCrDs r get_message_contentrHNs ??1 r zrfc822 external-bodyzmessage/c6t|jdSrG)bytesr=rDs r %get_and_fixup_unknown_message_contentrKUs # $$r messagecdj||f|d<|rzt|dds8|j}|Dcgc]!}|j|j |g#}} |D],}|j r|j d|||j <.yycc}w#tjj$r:}tdjj|j|d}~wwxYw)N/z Content-Typerr5zInvalid header: {})policy) r.hasattrrOheader_factoryheader_source_parsedefectsr5emailr< HeaderDefect ValueErrorformatfold)rrsubtypeheadersmpheaderexcs r _prepare_setr^as((Hg#67Cwqz6*B%,.%,6)r(("*@*@&*JK%, . J!>> ..++#)FKK " .||(( J188 & 3:: >@AFI J Js&B!1BC065C++C0c||d}|||d<||jd|dd|||d<|+|jD]\}}|j||yy)N attachmentzContent-DispositionfilenameT)r\replacez Content-ID) set_paramitems)r dispositionracidparamsrvalues r _finalize_setrirsx3" %0 !" j2"  $ L  ,,.JC MM#u %)r cg}|dzdz}tdt||D]=}||||z}|jtj|j d?dj |S)Nrasciir)rangelenappendbinascii b2a_base64r9r.)datamax_line_length encoded_linesunencoded_bytes_per_lineithislines r _encode_base64rysvM.!3a7 1c$i!9 :!445X00:AA'JK; 77= !!r c |j|j}|jjd fd}d}|td|Dd|jkr d||j dfS||dd }tj|j d |j}tj|} t|t| kDrd }nd }t|d kr||fS|dk(r||j d} || fS|dk(r||j dd } || fS|d k(r9tj||j d |j} || fS|d k(r t|||j} || fStdj|#t $rYnwxYw|jdk(s[d||j dd fS)Nrmc,j|zSrr.)lineslineseps r embedded_bodyz#_encode_text..embedded_bodysW\\%%87%BBr c*dj|dzS)N r|)r}s r normal_bodyz!_encode_text..normal_bodys5::e#4u#<z_encode_text..s&1Asr)default7bit8bitsurrogateescape zlatin-1base64quoted-printablez$Unknown content transfer encoding {})encode splitlinesr~maxrtr9UnicodeDecodeErrorcte_typer body_encoderqrrroryrVrW) stringr:cterOr}rrsniffsniff_qp sniff_base64rsr~s @r _encode_textrs MM' " - - /Enn##G,GB< { && 2f6L6L L {5188AAA eCRj)))%,,y*A*0*@*@B**51 x=3|, ,C$C5zRH}$ f}5!((1 9 5!((2CD 9 " "%%k%&8&?&? &J&,&<&<> 9 mE2F4J4JK 9?FFsKLL3&  &({5188BSTTTs(F<< GGc t|d|| t||||j\}} |j| |j dt j jj||d||d<t|||||y)NrAr:TrbContent-Transfer-Encoding) r^rrO set_payloadrcrTr:ALIASESgetri) rrrYr:rrerarfrgrZpayloads r set_text_contentrsfgw/cjjALCOOGMM)--''++GW= (+C#$#{Hc6:r c 4|dk(r td|dk(r%|dvrtdj||dn|}n*|dk(r!|dvrtd j|d }n|d }t|d |||j|g||d <t |||||y) Npartialz4message/partial is not supported for Message objectsrfc822)Nrrbinaryz*message/rfc822 parts do not support cte={}rz external-body)Nrz1message/external-body parts do not support cte={}rrLr)rVrWr^rri) rrLrYrrerarfrgrZs r set_message_contentrs)OPP( 6 6<CCCHJ J f O # n $CJJ3OQ Q i'2OOWI'*C#$#{Hc6:r c rt|||| |dk(r"t||jj}n]|dk(r+t j |ddd}|j d}n-|dk(r|j d}n|d vr|j dd }|j|||d <t|||||y) Nr)rtrFT)istextr\ quotetabsrmr)rrrr) r^ryrOrtrqb2a_qpr9rri) rrsrrYrrerarfrgrZs r set_bytes_contentrsh1 hdCJJ4N4NO " "tE%4P{{7# {{7# " "{{7$56OOD'*C#$#{Hc6:r r)plainzutf-8NNNNNN)rNNNNNN)rNNNNN)rq email.charsetrT email.message email.errorsrrraw_data_managerr@rrEsplitrrHrYrKr^riryrrrstrrrLMessagerrJ bytearray memoryviewr1r6r r rs[3,3,l"#2 )9:(/557H$$X/CD8 %++-G$$Z%79LM. % !FHJ"&*"$NIM:>*. ; &67=A<@,0;< !6!68KL9A:>*.;& 9j )C$$S*;< *r __pycache__/headerregistry.cpython-312.opt-1.pyc000064400000074301152526700320015446 0ustar00 {|jSQ,dZddlmZddlmZddlmZddlmZGddZGdd Z Gd d e Z d Z Gd dZ Gdde ZGddZGddeZGddZGddeZGddeZGddeZGddZGdd ZGd!d"eZGd#d$eZGd%d&ZGd'd(Zid)ed*ed+ed,ed-ed.ed/ed0ed1ed2ed3ed4ed5ed6ed7ed8ed9eeeed:ZGd;d<Zy=)>zRepresenting and manipulating email headers via custom objects. This module provides an implementation of the HeaderRegistry API. The implementation is designed to flexibly follow RFC5322 rules. )MappingProxyType)utils)errors)_header_value_parsercfeZdZd dZedZedZedZedZdZ dZ d Z y) AddressNc djtd||||f}d|vsd|vr td|w|s|r tdt j |\}}|rtdj |||jr|jd|j}|j}||_ ||_ ||_ y) aCreate an object representing a full email address. An address can have a 'display_name', a 'username', and a 'domain'. In addition to specifying the username and domain separately, they may be specified together by using the addr_spec keyword *instead of* the username and domain keywords. If an addr_spec string is specified it must be properly quoted according to RFC 5322 rules; an error will be raised if it is not. An Address object has display_name, username, domain, and addr_spec attributes, all of which are read-only. The addr_spec and the string value of the object are both quoted according to RFC5322 rules, but without any Content Transfer Encoding. N  z8invalid arguments; address parts cannot contain CR or LFz=addrspec specified when username and/or domain also specifiedz6Invalid addr_spec; only '{}' could be parsed from '{}'r) joinfilter ValueError TypeErrorparser get_addr_specformat all_defects local_partdomain _display_name _username_domain)self display_nameusernamer addr_specinputsa_srests -/usr/lib64/python3.12/email/headerregistry.py__init__zAddress.__init__s"|Xvy&QRS 6>TV^WX X  6!899,,Y7IC "==CV$'>455ooa((~~HZZF)! c|jSNrrs r!rzAddress.display_name8!!!r#c|jSr%)rr's r!rzAddress.username< ~~r#c|jSr%)rr's r!rzAddress.domain@ ||r#c|j}tjj|stj|}|j r|dz|j zS|sy|S)zThe addr_spec (username@domain) portion of the address, quoted according to RFC 5322 rules, but with no Content Transfer Encoding. @<>)rr DOT_ATOM_ENDS isdisjoint quote_stringr)rlps r!rzAddress.addr_specDsV ]]##..r2$$R(B ;;8dkk) ) r#cdj|jj|j|j|j S)Nz1{}(display_name={!r}, username={!r}, domain={!r}))r __class____name__rrrr's r!__repr__zAddress.__repr__Rs9BII//))4==$++G Gr#c|j}tjj|stj|}|r/|j dk(rdn |j }dj ||S|j S)Nr/r z{} <{}>)rrSPECIALSr1r2rr)rdisprs r!__str__zAddress.__str__Wse  ))$/&&t,D "nnd2I##D)4 4~~r#ct|tstS|j|jk(xr4|j|jk(xr|j |j k(Sr%) isinstancerNotImplementedrrrrothers r!__eq__zAddress.__eq__`sU%)! !!!U%7%77, /, u||+ -r#)r r r N) r6 __module__ __qualname__r"propertyrrrrr7r;rAr#r!rr sh(T""  G -r#rcFeZdZddZedZedZdZdZdZ y) GroupNcV||_|rt||_yt|_y)aCreate an object representing an address group. An address group consists of a display_name followed by colon and a list of addresses (see Address) terminated by a semi-colon. The Group is created by specifying a display_name and a possibly empty list of Address objects. A Group can also be used to represent a single address that is not in a group, which is convenient when manipulating lists that are a combination of Groups and individual Addresses. In this case the display_name should be set to None. In particular, the string representation of a Group whose display_name is None is the same as the Address object, if there is one and only one Address object in the addresses list. N)rtuple _addresses)rr addressess r!r"zGroup.__init__js"*.7% *UWr#c|jSr%r&r's r!rzGroup.display_name|r(r#c|jSr%)rJr's r!rKzGroup.addressess r#cxdj|jj|j|jS)Nz${}(display_name={!r}, addresses={!r})rr5r6rrKr's r!r7zGroup.__repr__s15<<((""DNN4 4r#cx|j0t|jdk(rt|jdS|j}|4tj j |st j|}djd|jD}|rd|zn|}dj||S)Nr, c32K|]}t|ywr%)str).0xs r! z Group.__str__..s:>a3q6>s z{}:{};) rlenrKrSrr9r1r2r r)rr:adrstrs r!r;z Group.__str__s    $T^^)$>t$D&&t,D:4>>::!'vVtV,,r#ct|tstS|j|jk(xr|j|jk(Sr%)r=rGr>rrKr?s r!rAz Group.__eq__s@%'! !!!U%7%772%//1 3r#)NN) r6rBrCr"rDrrKr7r;rArEr#r!rGrGhs?E$""4 -3r#rGcXeZdZdZdZdZedZedZdZ e dZ dZ y ) BaseHeadera|Base class for message headers. Implements generic behavior and provides tools for subclasses. A subclass must define a classmethod named 'parse' that takes an unfolded value string and a dictionary as its arguments. The dictionary will contain one key, 'defects', initialized to an empty list. After the call the dictionary must contain two additional keys: parse_tree, set to the parse tree obtained from parsing the header, and 'decoded', set to the string value of the idealized representation of the data from the value. (That is, encoded words are decoded, and values that have canonical representations are so represented.) The defects key is intended to collect parsing defects, which the message parser will subsequently dispose of as appropriate. The parser should not, insofar as practical, raise any errors. Defects should be added to the list instead. The standard header parsers register defects for RFC compliance issues, for obsolete RFC syntax, and for unrecoverable parsing errors. The parse method may add additional keys to the dictionary. In this case the subclass must define an 'init' method, which will be passed the dictionary as its keyword arguments. The method should use (usually by setting them as the value of similarly named attributes) and remove all the extra keys added by its parse method, and then use super to call its parent class with the remaining arguments and keywords. The subclass should also make sure that a 'max_count' attribute is defined that is either None or 1. XXX: need to better define this API. cdgi}|j||tj|drtj|d|d<tj ||d}|d=|j |fi||S)Ndefectsdecoded)parser_has_surrogates _sanitizerS__new__init)clsnamevaluekwdsrs r!rczBaseHeader.__new__st2 %  i 1#ood9o>DO{{3Y0 O $$ r#c.||_||_||_yr%)_name _parse_tree_defects)rrf parse_treer^s r!rdzBaseHeader.inits % r#c|jSr%)rjr's r!rfzBaseHeader.names zzr#c,t|jSr%)rIrlr's r!r^zBaseHeader.defectssT]]##r#ct|jj|jjt |f|j fSr%)_reconstruct_headerr5r6 __bases__rS __getstate__r's r! __reduce__zBaseHeader.__reduce__sC ''((D      ! !r#c.tj||Sr%)rSrc)rergs r! _reconstructzBaseHeader._reconstructs{{3&&r#c tjtjtj|jdtjddgg}|j r9|j tjtjddg|j |j |j|S)atFold header according to policy. The parsed representation of the header is folded according to RFC5322 rules, as modified by the policy. If the parse tree contains surrogateescaped bytes, the bytes are CTE encoded using the charset 'unknown-8bit". Any non-ASCII characters in the parse tree are CTE encoded using charset utf-8. XXX: make this a policy setting. The returned value is an ASCII-only string possibly containing linesep characters, and ending with a linesep character. The string includes the header name and the ': ' separator. z header-name:z header-seprWfws)policy) rHeader HeaderLabel ValueTerminalrfrkappendCFWSListWhiteSpaceTerminalfold)rrzheaders r!rzBaseHeader.folds"   $$TYY >$$S,7 9 :     MM!:!:3!F GH J d&&'{{&{))r#N) r6rBrC__doc__rcrdrDrfr^rt classmethodrvrrEr#r!r\r\sX@ $$!''*r#r\c:t||ij|Sr%)typerv)cls_namebasesrgs r!rqrqs % $ 1 1% 88r#cDeZdZdZeej ZedZ y)UnstructuredHeaderNcN|j||d<t|d|d<y)Nrmr_) value_parserrSrergrhs r!r`zUnstructuredHeader.parse s* --e4\d<01Yr#) r6rBrC max_count staticmethodrget_unstructuredrrr`rEr#r!rrs)I 7 78L22r#rceZdZdZy)UniqueUnstructuredHeaderrPNr6rBrCrrEr#r!rrIr#rcjeZdZdZdZeejZe dZ fdZ e dZ xZS) DateHeaderaHeader whose value consists of a single timestamp. Provides an additional attribute, datetime, which is either an aware datetime using a timezone, or a naive datetime if the timezone in the input string is -0000. Also accepts a datetime as input. The 'value' attribute is the normalized form of the timestamp, which means it is the output of format_datetime on the datetime. Nc|sH|djtjd|d<d|d<tj|d<yt |t r||d< tj|}||d<tj|d|d<|j|d|d<y#t$rF|djtjdd|d<tj|d<YywxYw)Nr^datetimer r_rmzInvalid date value or format) r~rHeaderMissingRequiredValuer TokenListr=rSrparsedate_to_datetimerInvalidDateDefectformat_datetimerrs r!r`zDateHeader.parse$s O " "6#D#D#F G#D  DO!'!1!1!3D   eS !#DO 33E: !Z//Z0@AY --d9o>\ Y&&v'?'?@^'_`#'Z %+%5%5%7\"  s!B..A C=<C=cP|jd|_t| |i|y)Nr)pop _datetimesuperrdrargskwr5s r!rdzDateHeader.init9s$ +  d!b!r#c|jSr%)rr's r!rzDateHeader.datetime=r*r#)r6rBrCrrrrrrrr`rdrDr __classcell__r5s@r!rrsLI  7 78L??("r#rceZdZdZy)UniqueDateHeaderrPNrrEr#r!rrBrr#rcbeZdZdZedZedZfdZe dZ e dZ xZ S) AddressHeaderNc6tj|\}}|Sr%)rget_address_list)rg address_lists r!rzAddressHeader.value_parserKs$55e< er#ct|tr|j|x|d<}g}|jD]t}|j t |j |jDcgc]9}t|j xsd|jxsd|jxsd;c}vt|j}n9t|ds|g}|Dcgc]}t|ds t d|gn|}}g}||d<||d<dj|Dcgc] }t|c}|d<d|vr|j|d|d<yycc}wcc}wcc}w) Nrmr __iter__rKgroupsr^rQr_)r=rSrrKr~rGr all_mailboxesrrrlistrhasattrr ) rergrhrraddrmbr^items r!r`zAddressHeader.parseQs eS !140@0@0G GD F$.. eD$5$504/A/A%C0B&-R__-B-/]]-@b-/YY_"&>0B%CDE/ <334G5*-1670529{1KeD4&)/3405 7GX!Y))6$B64SY6$BCY t #!$!1!1$y/!BD  $!%C7 %Cs!>E "EEcpt|jd|_d|_t ||i|y)Nr)rIr_groupsrJrrdrs r!rdzAddressHeader.initms0RVVH-.   d!b!r#c|jSr%)rr's r!rzAddressHeader.groupsrr,r#ct|j!td|jD|_|jS)Nc3BK|]}|jD]}|ywr%)rK)rTgroupaddresss r!rVz*AddressHeader.addresses..ys($L;@??%,;J%,s)rJrIrr's r!rKzAddressHeader.addressesvs5 ?? "#$L$LLDOr#) r6rBrCrrrrr`rdrDrrKrrs@r!rrGs]I CC6" r#rceZdZdZy)UniqueAddressHeaderrPNrrEr#r!rr~rr#rceZdZedZy)SingleAddressHeaderct|jdk7r$tdj|j|jdS)NrPz9value of single address header {} is not a single addressr)rXrKrrrfr's r!rzSingleAddressHeader.addresssB t~~  !#$*F499$57 7~~a  r#N)r6rBrCrDrrEr#r!rrs !!r#rceZdZdZy)UniqueSingleAddressHeaderrPNrrEr#r!rrrr#rceZdZdZeej ZedZ fdZ e dZ e dZ e dZxZS)MIMEVersionHeaderrPc:|j|x|d<}t||d<|dj|j|jdn |j |d<|j|d<|jdj |d|d|d<yd|d<y)Nrmr_r^majorminorz{}.{}version)rrSextendrrrrrergrhrms r!r`zMIMEVersionHeader.parses*-*:*:5*AA\Zj/Y Yz556 * 0 0 8j>N>NW "((W    '%nnT']DMJDO"DOr#c|jd|_|jd|_|jd|_t ||i|y)Nrrr)r_version_major_minorrrdrs r!rdzMIMEVersionHeader.initsBy) ffWo ffWo   d!b!r#c|jSr%)rr's r!rzMIMEVersionHeader.major {{r#c|jSr%)rr's r!rzMIMEVersionHeader.minorrr#c|jSr%)rr's r!rzMIMEVersionHeader.version }}r#)r6rBrCrrrparse_mime_versionrrr`rdrDrrrrrs@r!rrskI 9 9:L # #" r#rcBeZdZdZedZfdZedZxZ S)ParameterizedMIMEHeaderrPcf|j|x|d<}t||d<|dj|j|ji|d<y|jDcic]<\}}t j |jt j |>c}}|d<ycc}}w)Nrmr_r^params)rrSrrrrrblower)rergrhrmrfs r!r`zParameterizedMIMEHeader.parses*-*:*:5*AA\Zj/Y Yz556    $DN 3=2C2CE2C;4$ood399;$)OOE$:;2CEDNEs$AB-cP|jd|_t| |i|y)Nr)r_paramsrrdrs r!rdzParameterizedMIMEHeader.inits$vvh'   d!b!r#c,t|jSr%)rrr's r!rzParameterizedMIMEHeader.paramss --r#) r6rBrCrrr`rdrDrrrs@r!rrs7 I E E"..r#rcreZdZeej ZfdZedZ edZ edZ xZ S)ContentTypeHeaderct||i|tj|jj |_tj|jj|_yr%) rrdrrbrkmaintype _maintypesubtype_subtypers r!rdzContentTypeHeader.initsL  d!b!)9)9)B)BC(8(8(@(@A r#c|jSr%)rr's r!rzContentTypeHeader.maintyper*r#c|jSr%)rr's r!rzContentTypeHeader.subtyperr#c:|jdz|jzS)N/)rrr's r! content_typezContentTypeHeader.content_types}}s"T\\11r#) r6rBrCrrparse_content_type_headerrrdrDrrrrrs@r!rrsU @ @ALB 22r#rcReZdZeej ZfdZedZ xZ S)ContentDispositionHeaderct||i||jj}|||_yt j ||_yr%)rrdrkcontent_dispositionrrb_content_disposition)rrrcdr5s r!rdzContentDispositionHeader.initsA  d!b!    1 1*,*B!%//":M!r#c|jSr%)rr's r!rz,ContentDispositionHeader.content_dispositions(((r#) r6rBrCrr parse_content_disposition_headerrrdrDrrrs@r!rrs- G GHLN ))r#rcfeZdZdZeej ZedZ fdZ e dZ xZ S)ContentTransferEncodingHeaderrPc|j|x|d<}t||d<|dj|jyNrmr_r^rrSrrrs r!r`z#ContentTransferEncodingHeader.parseA*-*:*:5*AA\Zj/Y Yz556r#ct||i|tj|jj |_yr%)rrdrrbrkcte_cters r!rdz"ContentTransferEncodingHeader.inits0  d!b!OOD$4$4$8$89 r#c|jSr%)rr's r!rz!ContentTransferEncodingHeader.ctes yyr#)r6rBrCrrr&parse_content_transfer_encoding_headerrrr`rdrDrrrs@r!rrsCI M MNL77 :r#rcDeZdZdZeej ZedZ y)MessageIDHeaderrPc|j|x|d<}t||d<|dj|jyrrrs r!r`zMessageIDHeader.parserr#N) r6rBrCrrrparse_message_idrrr`rEr#r!rr s)I 7 78L77r#rsubjectdatez resent-datez orig-datesenderz resent-sendertoz resent-toccz resent-ccbccz resent-bccfromz resent-fromzreply-toz mime-versionz content-type)zcontent-dispositionzcontent-transfer-encodingz message-idc0eZdZdZeedfdZdZdZdZ y)HeaderRegistryz%A header_factory and header registry.Tcri|_||_||_|r |jjtyy)aCreate a header_factory that works with the Policy API. base_class is the class that will be the last class in the created header class's __bases__ list. default_class is the class that will be used if "name" (see __call__) does not appear in the registry. use_default_map controls whether or not the default mapping of names to specialized classes is copied in to the registry when the factory is created. The default is True. N)registry base_class default_classupdate_default_header_map)rrruse_default_maps r!r"zHeaderRegistry.__init__6s5 $*  MM !4 5 r#c>||j|j<y)zLRegister cls as the specialized class for handling "name" headers. N)rrrrfres r! map_to_typezHeaderRegistry.map_to_typeHs'* djjl#r#c|jj|j|j}t d|j z||j fiS)N_)rgetrrrr6rrs r! __getitem__zHeaderRegistry.__getitem__NsEmm d.@.@AC $sDOO&rs #0Y-Y-x/3/3ha*a*H9221 ++\z 44n- !-! 3 ""J..:2/2, )6 )* 7 7 $< $4J$4   $=  $7  $7M $7M $7M $7M$7 $5!"$5#$%=$A$3).*'*'r#__pycache__/encoders.cpython-312.opt-2.pyc000064400000003346152526700320014231 0ustar00 {|jD gdZddlmZddlmZdZdZdZ dZ dZ y ) )encode_7or8bit encode_base64 encode_noop encode_quopri) encodebytes) encodestringc@t|d}|jddS)NT) quotetabs s=20) _encodestringreplace)sencs '/usr/lib64/python3.12/email/encoders.py_qencoders T *C ;;tV $$c |jd}tt|d}|j|d|d<y)NTdecodeasciibase64Content-Transfer-Encoding) get_payloadstr_bencode set_payloadmsgorigencdatas rrrs@ ??$? 'D(4.'*GOOG'/C#$rcl |jd}t|}|j|d|d<y)NTrzquoted-printabler)rrrrs rrr$s9 ??$? 'DtnGOOG'9C#$rc |jd}|d|d<y |jdd|d<y#t$rd|d<YywxYw)NTr7bitrr8bit)rr UnicodeError)rrs rrr/sbC ??$? 'D |+1 '(2 G,2 '( 2+1 '(2s4AAcy)N)rs rrr@srN) __all__rrrquoprirr rrrrrr'rrr*s2 ' +0% 0:2"r__pycache__/quoprimime.cpython-312.opt-1.pyc000064400000023340152526700320014611 0ustar00 {|j&dZgdZddlZddlmZmZmZdZdZdZ e dDcgc]}d |z c}Z e ddZ e ddZ d ejd zejd zD] Zeee e<d e ed <dD] Zeee e<dZdZdZdZddZdZdZddZe ddZdD] Zeeee<[defdZefdZeZeZdZdZ ycc}w)aFQuoted-printable content transfer encoding per RFCs 2045-2047. This module handles the content transfer encoding method defined in RFC 2045 to encode US ASCII-like 8-bit data called `quoted-printable'. It is used to safely encode text that is in a character set similar to the 7-bit US ASCII character set, but that includes some 8-bit characters that are normally not allowed in email bodies or headers. Quoted-printable is very space-inefficient for encoding binary files; use the email.base64mime module for that instead. This module provides an interface to encode and decode both headers and bodies with quoted-printable encoding. RFC 2045 defines a method for including character set information in an `encoded-word' in a header. This method is commonly used for 8-bit real names in To:/From:/Cc: etc. fields, as well as Subject: lines. This module does not do the line wrapping or end-of-line character conversion necessary for proper internationalized headers; it only does dumb encoding and decoding. To deal with the various line wrapping issues, use the email.header module. ) body_decode body_encode body_lengthdecode decodestring header_decode header_encode header_lengthquoteunquoteN) ascii_lettersdigits hexdigits  z=%02Xs-!*+/ascii_ s_ !"#$%&'()*+,-./0123456789:;<>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ c,t|t|k7S)z>Return True if the octet should be escaped with header quopri.)chr_QUOPRI_HEADER_MAPoctets )/usr/lib64/python3.12/email/quoprimime.py header_checkrJs u:+E2 22c,t|t|k7S)zz header_length..^sE9%s%e,-9sum bytearrays rr r Ts E9E EErc&td|DS)zReturn a body quoted-printable encoding length. :param bytearray: An array of bytes (a.k.a. octets). :return: The length in bytes of the byte array when it is encoded with quoted-printable for bodies. c3@K|]}tt|ywr$)r%r r&s rr(zbody_length..hsCs#E*+r)r*r,s rrras CC CCrct|ts t|}|s |j|j yt |dt |z|kr|dxx||zz cc<y|j|j y)N) isinstancestrrappendlstripr%)Lsmaxlenextras r _max_appendr:ksg a  F   QrUc!f  & " rc2tt|dddS)zDTurn a string in the form =AB to the ASCII character with value 0xab)rintr7s rr r vs s1Qq62 rc&tt|Sr$) _QUOPRI_MAPordcs rr r {s s1v rcb|sy|jdjt}d|d|dS)aEncode a single header line with quoted-printable (like) encoding. Defined in RFC 2045, this `Q' encoding is similar to quoted-printable, but used specifically for email header fields to allow charsets with mostly 7 bit characters (and some 8 bit) to remain more or less readable in non-RFC 2045 aware mail clients. charset names the character set to use in the RFC 2046 header. It defaults to iso-8859-1. rlatin1z=?z?q?z?=)r translater) header_bytescharsetencodeds rrrs3 !!(+556HIG$W --rs Lc|dkr td|s|S|jt}d|z}|dz }g}|j}|j D]}d}t |dz |z } || krV||z} || dz dk(r|||| dz | dz }n,|| dz dk(r|||| | dz }n|||| dz| }|| krV|rN|ddvrG|| z } | d k\rt |d} n| dk(r |d|z} n|t |dz} |||d| z|||d |dtvr|d |j|S) aEncode with quoted-printable, wrapping at maxlinelen characters. Each line of encoded text will end with eol, which defaults to "\n". Set this to "\r\n" if you will be using the result of this function directly in an email. Each line will be wrapped at, at most, maxlinelen characters before the eol string (maxlinelen defaults to 76 characters, the maximum value permitted by RFC 2045). Long lines will have the 'soft line break' quoted-printable character "=" appended to them, so the decoded text will be identical to the original text. The minimum maxlinelen is 4 to have room for a quoted character ("=XX") followed by a soft line break. Smaller values will generate a ValueError. zmaxlinelen must be at least 4=r<r r1z r=Nr) ValueErrorrH_QUOPRI_BODY_ENCODE_MAPr4 splitlinesr%r CRLFjoin) body maxlineleneol soft_break maxlinelen1 encoded_bodyr4linestart laststartstoproomqs rrrs&A~899   >>1 2DsJq.KL  F!IMJ. y ;&DD1H~$tE$(+,qdQh3&tE$'(qtE$'#-.y  DH%9$Dqy$r(OHz)tBx0 4b>A% & 4< C"H Bx4r 88L !!rc|s|Sd}|jD]}|j}|s||z }d}t|}||ks.||}|dk7r ||z }|dz }nV|dz|k(r|dz })|dz|kr6||dztvr(||dztvr|t |||dzz }|dz }n ||z }|dz }||k(r||z }||kr{|ddvr|j |r|d d}|S) z_Decode a quoted-printable string. Lines are separated with eol, which defaults to \n. rr rOr<rPr=r1rN)rSrstripr%rr endswith)rKrXdecodedr\inrEs rrrs3 G""${{} sNG   I!eQACx1 Q1Q1qT!A#Y)3QqS Y8N74!A#;//Q1 QAv3)!e%<r{& W%5%5c%:#2, Nrc:|jd}t|S)zCTurn a match in the form =AB to the ASCII character with value 0xabr )groupr )matchr7s r_unquote_matchrks AA 1:rc||jdd}tjdt|tjS)aDecode a string encoded with RFC 2045 MIME header `Q' encoding. This function does not parse a full MIME header value encoded with quoted-printable (like =?iso-8859-1?q?Hello_World?=) -- please use the high level email.header class for that functionality. rrz=[a-fA-F0-9]{2})flags)replaceresubrkASCIIr@s rrr$s. #sA 66$narxx HHr)r)z iso-8859-1)!__doc____all__rostringr rrrTNL EMPTYSTRINGrangerBrr encoderErrCrr!r rr:r r rrRrrrrrkrrDs0rrysQ 0  33   %*#J/Jqw{J/  ^q> (M((1 1MFMM'4J JAFq K #3s8 .Aa&Q .3 1 FD .*+1- A!$QA !#I"^,`  I[0s C__pycache__/errors.cpython-312.opt-1.pyc000064400000015557152526700320013751 0ustar00 {|j`dZGddeZGddeZGddeZGddeZGd d eeZGd d eZGd deZ Gdde Z Gdde Z Gdde Z Gdde ZGdde ZGdde ZGdde ZeZGdde ZGdd e ZGd!d"e ZGd#d$e ZGd%d&e ZGd'd(e ZGd)d*e ZGd+d,eZGd-d.eZGd/d0eZGd1d2eZGd3d4eZGd5d6eZy7)8z email package exception classes.ceZdZdZy) MessageErrorz+Base class for errors in the email package.N__name__ __module__ __qualname____doc__%/usr/lib64/python3.12/email/errors.pyrr5r rceZdZdZy)MessageParseErrorz&Base class for message parsing errors.Nrr r r rr s0r rceZdZdZy)HeaderParseErrorzError while parsing headers.Nrr r r rr&r rceZdZdZy) BoundaryErrorz#Couldn't find terminating boundary.Nrr r r rrs-r rceZdZdZy)MultipartConversionErrorz(Conversion to a multipart is prohibited.Nrr r r rr2r rceZdZdZy) CharsetErrorzAn illegal charset was given.Nrr r r rrs'r rceZdZdZy)HeaderWriteErrorzError while writing headers.Nrr r r rr rr rc$eZdZdZdfd ZxZS) MessageDefectz Base class for a message defect.c6|t||||_yN)super__init__line)selfr! __class__s r r zMessageDefect.__init__(s   G T " r rrrrrr __classcell__r#s@r rr%s*r rceZdZdZy)NoBoundaryInMultipartDefectzBA message claimed to be a multipart but had no boundary parameter.Nrr r r r(r(-sLr r(ceZdZdZy)StartBoundaryNotFoundDefectz+The claimed start boundary was never found.Nrr r r r*r*0r r r*ceZdZdZy)CloseBoundaryNotFoundDefectzEA start boundary was found, but not the corresponding close boundary.Nrr r r r,r,3Or r,ceZdZdZy)#FirstHeaderLineIsContinuationDefectz;A message had a continuation line as its first header line.Nrr r r r/r/6sEr r/ceZdZdZy)MisplacedEnvelopeHeaderDefectz?A 'Unix-from' header was found in the middle of a header block.Nrr r r r1r19Ir r1ceZdZdZy) MissingHeaderBodySeparatorDefectzEFound line with no leading whitespace and no colon before blank line.Nrr r r r4r4<r-r r4ceZdZdZy)!MultipartInvariantViolationDefectz?A message claimed to be a multipart but no subparts were found.Nrr r r r6r6Ar2r r6ceZdZdZy)-InvalidMultipartContentTransferEncodingDefectzEAn invalid content transfer encoding was set on the multipart itself.Nrr r r r8r8Dr-r r8ceZdZdZy)UndecodableBytesDefectz0Header contained bytes that could not be decodedNrr r r r:r:G:r r:ceZdZdZy)InvalidBase64PaddingDefectz/base64 encoded sequence had an incorrect lengthNrr r r r=r=Js9r r=ceZdZdZy)InvalidBase64CharactersDefectz=base64 encoded sequence had characters not in base64 alphabetNrr r r r?r?MsGr r?ceZdZdZy)InvalidBase64LengthDefectz4base64 encoded sequence had invalid length (1 mod 4)Nrr r r rArAPs>r rAc"eZdZdZfdZxZS) HeaderDefectzBase class for a header defect.c$t||i|yr)rr )r"argskwr#s r r zHeaderDefect.__init__Xs $%"%r r$r&s@r rCrCUs)&&r rCceZdZdZy)InvalidHeaderDefectz+Header is not valid, message gives details.Nrr r r rHrH[r r rHceZdZdZy)HeaderMissingRequiredValuez(A header that must have a value had noneNrr r r rJrJ^rr rJc(eZdZdZfdZdZxZS)NonPrintableDefectz8ASCII characters outside the ascii-printable range foundc2t||||_yr)rr non_printables)r"rNr#s r r zNonPrintableDefect.__init__ds (,r c8dj|jS)Nz6the following ASCII non-printables found in header: {})formatrN)r"s r __str__zNonPrintableDefect.__str__hs++, .r )rrrrr rQr%r&s@r rLrLasB-.r rLceZdZdZy)ObsoleteHeaderDefectz0Header uses syntax declared obsolete by RFC 5322Nrr r r rSrSlr;r rSceZdZdZy)NonASCIILocalPartDefectz(local_part contains non-ASCII charactersNrr r r rUrUorr rUceZdZdZy)InvalidDateDefectz%Header has unparsable or invalid dateNrr r r rWrWts/r rWN) r Exceptionrrrr TypeErrorrrr ValueErrorrr(r*r,r/r1r4MalformedHeaderDefectr6r8r:r=r?rArCrHrJrLrSrUrWr r r r\sj '6961 1'('.%.3|Y3(<('|' JM-M6-6P-PF-FJMJP}P9J JPMP;];::HMH? ? &=& 6,633 . .;<;3l3 0 0r __pycache__/_encoded_words.cpython-312.pyc000064400000020164152526700320014442 0ustar00 {|j]!2dZddlZddlZddlZddlZddlmZmZddlm Z gdZ ejejdjdZdZGd d eZeZd eed <d ZdZdZdZdZeedZdZeedZeedZddZy)z Routines for manipulating RFC2047 encoded words. This is currently a package-private API, but will be considered for promotion to a public API if there is demand. N) ascii_lettersdigits)errors)decode_qencode_qdecode_bencode_blen_qlen_bdecodeencodes=([a-fA-F0-9]{2})cftj|jdjS)N)bytesfromhexgroupr )ms -/usr/lib64/python3.12/email/_encoded_words.pyrAs%-- 1 1 34c@|jdd}t|gfS)N_ )replace_q_byte_subber)encodeds rrrCs"oodD)G ' "B &&rcbeZdZdejdzejdzZdZy) _QByteMaps-!*+/asciicv||jvrt|||<||Sdj|||<||S)Nz={:02X})safechrformat)selfkeys r __missing__z_QByteMap.__missing__MsG $)) CDICy"((-DICyrN)__name__ __module__ __qualname__rr rr!r&rrrrIs/ *m**73 3mfmmG6L LDrr_ c2djd|DS)Nc3.K|] }t|ywN) _q_byte_map.0xs r zencode_q..Zs37a;q>7s)joinbstrings rrrYs 77373 33rc&td|DS)Nc3@K|]}tt|ywr0)lenr1r2s rr5zlen_q..]s4Gqs;q>"Gs)sumr7s rr r \s 4G4 44rcPt|dz}|rddd|z nd} tj||zd|rtjgfSgfS#t j $r tj|dtjgfcYS#t j $r| tj|dzdtjtjgfcYcYS#t j $r|tjgfcYcYcYSwxYwwxYwwxYw)Ns===rT)validateFs==) r;base64 b64decoderInvalidBase64PaddingDefectbinasciiErrorInvalidBase64CharactersDefectInvalidBase64LengthDefect)rpad_errmissing_paddings rrrds7'lQG,3fZai(OE   W6 F5>E  E  595578 ~~ E E$$Wu_uE99;668: >> E !A!A!C DDD  E EEsZ0A AD%$+BD%D!&AC,'D!(D%,*DD!D%DD!!D%cJtj|jdS)Nr)r@ b64encoder r7s rr r s   G $ + +G 44rcNtt|d\}}|dz|rdzSdzS)Nr>r)divmodr;)r8 groups_of_3leftovers rr r s0"3w<3K ?8a 33 33r)qbc<|jd\}}}}}|jd\}}}|j}|jdd}t ||\}} |j |}||||fS#t $r=|jtjd|d|j |d}YKttf$rP|j dd}|jdk7r(|jtjd|d YwxYw) aDecode encoded word and return (string, charset, lang, defects) tuple. An RFC 2047/2243 encoded word has the form: =?charset*lang?cte?encoded_string?= where '*lang' may be omitted but the other parts may not be. This function expects exactly such a string (that is, it does not check the syntax and may raise errors if the string is not well formed), and returns the encoded_string decoded first from its Content Transfer Encoding and then from the resulting bytes into unicode using the specified charset. If the cte-decoded string does not successfully decode using the specified character set, a defect is added to the defects list and the unknown octets are replaced by the unicode 'unknown' character \uFDFF. The specified charset and language are returned. The default for language, which is rarely if ever encountered, is the empty string. ?*rsurrogateescapez0Encoded word contains bytes not decodable using z charset unknown-8bitzUnknown charset z* in encoded word; decoded as unknown bytes) split partitionlowerr _cte_decodersr UnicodeDecodeErrorappendrUndecodableBytesDefect LookupErrorUnicodeEncodeError CharsetError) ewr+charsetcte cte_stringlangr8defectsstrings rr r s1*&(XXc]"AwZ((-GQ ))+C):;G$S)'2GW ?( 7D' )) <v446229H6FG H):; + ,?):; ==?n , NN6..1A'M<0=> ??s!A88AD=ADDc|dk(r|jdd}n|j|}|(td|}td|}||z dkrdnd}t||}|rd|z}dj||||S) aEncode string using the CTE encoding that produces the shorter result. Produces an RFC 2047/2243 encoded word of the form: =?charset*lang?cte?encoded_string?= where '*lang' is omitted unless the 'lang' parameter is given a value. Optional argument charset (defaults to utf-8) specifies the charset to use to encode the string to binary before CTE encoding it. Optional argument 'encoding' is the cte specifier for the encoding that should be used ('q' or 'b'); if it is None (the default) the encoding which produces the shortest encoded sequence is used, except that 'q' is preferred if it is up to five characters longer. Optional argument 'lang' (default '') gives the RFC 2243 language string to specify in the encoded word. rVrrUrPrQrTz=?{}{}?{}?{}?=)r _cte_encode_length _cte_encodersr#)rgrbencodingrer8qlenblenrs rr r s". --):;--(!#&w/!#&w/+/3sH%g.G Tz  " "7D(G DDr)zutf-8Nr.)__doc__rer@rC functoolsrgrremailr__all__partialcompilesubrrdictrr1ordrr rr r rZr rkrjr r*rrrysR ( #"":2::.C#D#H#H46'  k  CH45$EL54   '*V     Er__pycache__/iterators.cpython-312.opt-2.pyc000064400000004243152526700320014440 0ustar00 {|jQ@ gdZddlZddlmZdZddZd dZd dZy) )body_line_iteratortyped_subpart_iteratorwalkN)StringIOc#K ||jr.|jD]}|jEd{yy7wN) is_multipart get_payloadr)selfsubparts (/usr/lib64/python3.12/email/iterators.pyrrsH J '')G||~ % %* %sr/s- 8   &)  >r*__pycache__/charset.cpython-312.opt-2.pyc000064400000021320152526700320014050 0ustar00 {|jB gdZddlmZddlZddlZddlmZddlmZdZ dZ dZ d Z d Z d Zd Zid e e dfde e dfde e dfde e dfde e dfde e dfde e dfde e dfde e dfde e dfde e dfde e dfd dde e dfde e dfde ddfde ddfe ddfe e dfe e dfd Zid!d d"d d#dd$dd%dd&dd'dd(dd)dd*dd+dd,dd-dd.dd/dd0dd1ddddd2dd3d d4Zd5d6dd7Zdd8Zd9Zd:Zd;ZGd<d=Zy)>)Charset add_alias add_charset add_codec)partialN)errors)encode_7or8bitus-asciiz unknown-8bitz iso-8859-1z iso-8859-2z iso-8859-3z iso-8859-4z iso-8859-9z iso-8859-10z iso-8859-13z iso-8859-14z iso-8859-15z iso-8859-16z windows-1252viscii)NNNbig5gb2312zeuc-jp iso-2022-jp shift_jisutf-8)rzkoi8-rrlatin_1zlatin-1latin_2zlatin-2latin_3zlatin-3latin_4zlatin-4latin_5zlatin-5latin_6zlatin-6latin_7zlatin-7latin_8zlatin-8latin_9zks_c_5601-1987zeuc-kr)zlatin-9latin_10zlatin-10cp949euc_jpeuc_krascii eucgb2312_cnbig5_tw)rrrcF |tk(r td|||ft|<y)Nz!SHORTEST not allowed for body_enc)SHORTEST ValueErrorCHARSETS)charset header_encbody_encoutput_charsets &/usr/lib64/python3.12/email/charset.pyrrjs.,8<==#X~>HWc |t|<yN)ALIASES)alias canonicals r.rrs GENr/c |t|<yr1) CODEC_MAP)r* codecnames r.rrs #Igr/cZ|tk(r|jddS|j|S)Nr#surrogateescape) UNKNOWN8BITencode)stringcodecs r._encoder>s+ }}W&788}}U##r/cHeZdZ efdZdZdZdZdZdZ dZ dZ d Z y ) rc t|tr|jdn t|d}|j }tj|||_ tj|jttdf\}}}|s |j}||_ ||_tj|||_t j|j|j|_t j|j|j|_y#t$rt j |wxYw)Nr#) isinstancestrr; UnicodeErrorr CharsetErrorlowerr2get input_charsetr)r'BASE64header_encoding body_encodingr-r6 input_codec output_codec)selfrGhencbencconvs r.__init__zCharset.__init__s  5--$$W- #M7 ; &++- $[[ F$<<(:(:)164(@BdD%%D#!%kk$5%==););)-););=%MM$*=*=*.*=*=?) 5%%m4 4 5s .D D?c6|jjSr1)rGrErMs r.__repr__zCharset.__repr__s!!''))r/cLt|t|jk(Sr1)rBrE)rMothers r.__eq__zCharset.__eq__s4yCJ,,...r/c` |jtk(ry|jtk(rytS)Nzquoted-printablebase64)rJQPrHr rSs r.get_body_encodingzCharset.get_body_encodings1     #%   6 )! !r/c8 |jxs |jSr1)r-rGrSs r.get_output_charsetzCharset.get_output_charset s  ""8d&8&88r/c |jxsd}t||}|j|}||S|j||S)Nr)rLr> _get_encoder header_encode)rMr<r= header_bytesencoder_modules r.r`zCharset.header_encodesS !!/Zvu- **<8  !M++L%@@r/c |jxsd}t||}|j|}t|j|}|j }t |tz}g} g} t||z } |D]} | j| tj| } |jt| |}|| kDsJ| j| s| s| jdn8tj| }t||}| j||| g} t||z } tj| }t||}| j||| S)Nr)r*)rLr>r_rr`r]lenRFC2047_CHROME_LENnextappend EMPTYSTRINGjoin header_lengthpop)rMr< maxlengthsr=rarbencoderr*extralines current_linemaxlen character this_linelength joined_lines r.header_encode_lineszCharset.header_encode_lines%s[ "!!/Zvu- **<8.66F))+G 11 j!E)I    *#((6I#11')W2MNF  "\LL&"-"2"2<"@K#*;#>LLL!67 ){ j)E1 "&&|4 {E2  W\*+ r/c||jtk(rtjS|jtk(rtj S|jt k(rctjj|}tj j|}||krtjStj Syr1)rIrHemail base64mimerZ quoprimimer'rj)rMralen64lenqps r.r_zCharset._get_encoderbs   6 )## #  ! !R '## #  ! !X -$$22<@E$$22<@Eu}''''''r/c |s|S|jturJt|tr|j |j }t jj|S|jtur[t|tr|j |j }|jd}t jj|St|tr*|j |j jd}|S)Nlatin1r#) rJrHrArBr;r-rxry body_encoderZdecoderz)rMr<s r.rzCharset.body_encodeqs M    '&#&t':':;##//7 7   2 %&#&t':':;]]8,F##//7 7&#&t':':;BB7KMr/N) __name__ __module__ __qualname__DEFAULT_CHARSETrQrTrWr[r]r`rvr_rr/r.rrs=*V&5?B*/"*9A&;z r/r)__all__ functoolsremail.base64mimerxemail.quoprimimeremail.encodersr rZrHr'rerr:rhr)r2r6rrrr>rrr/r.rs  )   Br- Br- Br-   Br-  Br- Br- Br- Br- Br-  Br-! "Br-# $ Br-% &-' ( Fv-) * Fv-+ , Ft 6- .Ft 6/ 0t-v-vw/5 >  |  | | |   |   |  | | | | } } } } }  }! "}# $1 <"   ?8#$llr/__pycache__/encoders.cpython-312.pyc000064400000004053152526700320013265 0ustar00 {|jFdZgdZddlmZddlmZdZdZ dZ dZ d Z y ) z Encodings and related functions.)encode_7or8bit encode_base64 encode_noop encode_quopri) encodebytes) encodestringc@t|d}|jddS)NT) quotetabs s=20) _encodestringreplace)sencs '/usr/lib64/python3.12/email/encoders.py_qencoders T *C ;;tV $$c~|jd}tt|d}|j|d|d<y)zlEncode the message's payload in Base64. Also, add an appropriate Content-Transfer-Encoding header. Tdecodeasciibase64Content-Transfer-EncodingN) get_payloadstr_bencode set_payloadmsgorigencdatas rrrs; ??$? 'D(4.'*GOOG'/C#$rcj|jd}t|}|j|d|d<y)zvEncode the message's payload in quoted-printable. Also, add an appropriate Content-Transfer-Encoding header. Trzquoted-printablerN)rrrrs rrr$s4 ??$? 'DtnGOOG'9C#$rc|jd}|d|d<y |jdd|d<y#t$rd|d<YywxYw)z9Set the Content-Transfer-Encoding header to 7bit or 8bit.TrN7bitrr8bit)rr UnicodeError)rrs rrr/s_ ??$? 'D |+1 '(2 G,2 '( 2+1 '(2s3AAcy)z Do nothing.N)rs rrr@srN) __doc____all__rrrquoprirr rrrrrr'rrr+s2 ' +0% 0:2"r__pycache__/parser.cpython-312.opt-2.pyc000064400000007303152526700320013720 0ustar00 {|jo gdZddlmZmZddlmZmZddlmZGddZ Gdde Z Gd d Z Gd d e Z y ))Parser HeaderParser BytesParserBytesHeaderParser FeedParserBytesFeedParser)StringIO TextIOWrapper)rr)compat32c*eZdZdeddZddZddZy)rNpolicyc" ||_||_yN)_classr)selfrrs %/usr/lib64/python3.12/email/parser.py__init__zParser.__init__s (  c t|j|j}|r|j|j dx}r%|j ||j dx}r%|j S)Nr i )rrr_set_headersonlyreadfeedclose)rfp headersonly feedparserdatas rparsez Parser.parse)so   DKK@   ' ' )ggdm#d# OOD !ggdm#d#!!rc< |jt||S)Nr)rr rtextrs rparsestrzParser.parsestr8s  zz(4.kzBBrrF)__name__ __module__ __qualname__r rrr$rrrrsh0 "CrrceZdZddZddZy)rc0tj||dSNT)rrrrrs rrzHeaderParser.parseDs||D"d++rc0tj||dSr,)rr$r"s rr$zHeaderParser.parsestrGstT400rNT)r&r'r(rr$r)rrrrCs ,1rrc"eZdZdZddZddZy)rc& t|i||_yr)rparser)rargskws rrzBytesParser.__init__Ms d)b) rc t|dd} |jj|||jS#|jwxYw)Nasciisurrogateescape)encodingerrors)r r2rdetachr-s rrzBytesParser.parse_sD 28I J ;;$$R5 IIKBIIKs =Acb |jdd}|jj||S)NASCIIr7)r9)decoder2r$r"s r parsebyteszBytesParser.parsebytesns3 {{7+<{={{##D+66rNr%)r&r'r(rrr>r)rrrrKs*$  7rrceZdZddZddZy)rc2tj||dSNTr!)rrr-s rrzBytesHeaderParser.parse{s  rt <r"s rr>zBytesHeaderParser.parsebytes~s%%dDd%CCrNr/)r&r'r(rr>r)rrrrzs =DrrN) __all__ior r email.feedparserrremail._policybaser rrrrr)rrrGsN 4 ,'8&0C0Cf161,7,7^D Dr__pycache__/_policybase.cpython-312.opt-2.pyc000064400000022452152526700320014717 0ustar00 {|j< ddlZddlmZddlmZddlmZgdZGddZdZ d Z Gd d eej Z e Gd de Z e Zy)N)header)charset)_has_surrogates)PolicyCompat32compat32c8eZdZ fdZdZdZdZdZxZS) _PolicyBasec  |jD]T\}}t||rtt|||'t dj ||jjyNz*{!r} is an invalid keyword argument for {}) itemshasattrsuperr __setattr__ TypeErrorformat __class____name__)selfkwnamevaluers */usr/lib64/python3.12/email/_policybase.py__init__z_PolicyBase.__init__)sc 88:KD%tT"k$3D%@@GGdnn55788 &c|jjDcgc]\}}dj||}}}dj|jjdj |Scc}}w)Nz{}={!r}z{}({})z, )__dict__r rrrjoin)rrrargss r__repr__z_PolicyBase.__repr__7sh$(MM$7$7$9<$9[T5!!$.$9 <t~~66 $HH>: ==..0KD%   y$ 6188:KD%4&@GGdnn55788   y$ 6 & rct||rd}nd}t|j|jj|)Nz'{!r} object attribute {!r} is read-onlyz!{!r} object has no attribute {!r})rAttributeErrorrrr)rrrmsgs rrz_PolicyBase.__setattr__Ns6 4 ;C5CSZZ(?(?FGGrc< |jdi|jS)N)r&r)rothers r__add__z_PolicyBase.__add__Us! tzz+ENN++r) r __module__ __qualname__rr r&rr- __classcell__)rs@rr r s#* 8I $H,rr cf|jddd}|jddd}|dz|zS)N r)rsplitsplit)doc added_docs r _append_docr8^s; **T1 a Ca(+I : !!rc|jrM|jjdr2t|jdj|j|_|jj D]{\}}|js|jjds/d|jDD]7}t t ||d}|st||j|_{}|S)N+rc3JK|]}|jD]}|ywN)mro).0basecs r z%_extend_docstrings..hsFMD488:aa:aMs!#__doc__)rB startswithr8 __bases__rr getattr)clsrr%r@r6s r_extend_docstringsrGcs {{s{{--c2!#--"2":":CKKH ll((* d <rss  %' I,I,X" d"[CKKd"NcvccL :r__pycache__/parser.cpython-312.opt-1.pyc000064400000015134152526700320013720 0ustar00 {|jodZgdZddlmZmZddlmZmZddlm Z GddZ Gdd e Z Gd d Z Gd d e Z y)z-A parser of RFC 2822 and MIME email messages.)Parser HeaderParser BytesParserBytesHeaderParser FeedParserBytesFeedParser)StringIO TextIOWrapper)rr)compat32c*eZdZdeddZddZddZy)rNpolicyc ||_||_y)aParser of RFC 2822 and MIME email messages. Creates an in-memory object tree representing the email message, which can then be manipulated and turned over to a Generator to return the textual representation of the message. The string must be formatted as a block of RFC 2822 headers and header continuation lines, optionally preceded by a `Unix-from' header. The header block is terminated either by the end of the string or by a blank line. _class is the class to instantiate for new message objects when they must be created. This class must have a constructor that can take zero arguments. Default is Message.Message. The policy keyword specifies a policy object that controls a number of aspects of the parser's operation. The default policy maintains backward compatibility. N)_classr)selfrrs %/usr/lib64/python3.12/email/parser.py__init__zParser.__init__s*  ct|j|j}|r|j|j dx}r%|j ||j dx}r%|j S)a\Create a message structure from the data in a file. Reads all the data from the file and returns the root of the message structure. Optional headersonly is a flag specifying whether to stop parsing after reading the headers or not. The default is False, meaning it parses the entire contents of the file. r i )rrr_set_headersonlyreadfeedclose)rfp headersonly feedparserdatas rparsez Parser.parse)sj  DKK@   ' ' )ggdm#d# OOD !ggdm#d#!!rc:|jt||S)a-Create a message structure from a string. Returns the root of the message structure. Optional headersonly is a flag specifying whether to stop parsing after reading the headers or not. The default is False, meaning it parses the entire contents of the file. r)rr rtextrs rparsestrzParser.parsestr8szz(4.kzBBr)NF)__name__ __module__ __qualname__r rrr#rrrrsh0 "CrrceZdZddZddZy)rc0tj||dSNT)rrrrrs rrzHeaderParser.parseDs||D"d++rc0tj||dSr+)rr#r!s rr#zHeaderParser.parsestrGstT400rNT)r%r&r'rr#r(rrrrCs ,1rrc"eZdZdZddZddZy)rc$t|i||_y)aParser of binary RFC 2822 and MIME email messages. Creates an in-memory object tree representing the email message, which can then be manipulated and turned over to a Generator to return the textual representation of the message. The input must be formatted as a block of RFC 2822 headers and header continuation lines, optionally preceded by a `Unix-from' header. The header block is terminated either by the end of the input or by a blank line. _class is the class to instantiate for new message objects when they must be created. This class must have a constructor that can take zero arguments. Default is Message.Message. N)rparser)rargskws rrzBytesParser.__init__Ms d)b) rct|dd} |jj|||jS#|jwxYw)acCreate a message structure from the data in a binary file. Reads all the data from the file and returns the root of the message structure. Optional headersonly is a flag specifying whether to stop parsing after reading the headers or not. The default is False, meaning it parses the entire contents of the file. asciisurrogateescape)encodingerrors)r r1rdetachr,s rrzBytesParser.parse_s?28I J ;;$$R5 IIKBIIKs <Ac`|jdd}|jj||S)a2Create a message structure from a byte string. Returns the root of the message structure. Optional headersonly is a flag specifying whether to stop parsing after reading the headers or not. The default is False, meaning it parses the entire contents of the file. ASCIIr6)r8)decoder1r#r!s r parsebyteszBytesParser.parsebytesns.{{7+<{={{##D+66rNr$)r%r&r'rrr=r(rrrrKs*$  7rrceZdZddZddZy)rc2tj||dSNTr )rrr,s rrzBytesHeaderParser.parse{s  rt <rGsN 4 ,'8&0C0Cf161,7,7^D Dr__pycache__/__init__.cpython-312.opt-1.pyc000064400000003601152526700320014157 0ustar00 {|j(dZgdZdZdZdZdZy)z?A package for parsing, handling, and generating email messages.) base64mimecharsetencoderserrors feedparser generatorheader iteratorsmessagemessage_from_filemessage_from_binary_filemessage_from_stringmessage_from_bytesmimeparser quoprimimeutilsc<ddlm}||i|j|S)zvParse a string into a Message object model. Optional _class and strict are passed to the Parser constructor. Parser) email.parserrparsestr)sargskwsrs '/usr/lib64/python3.12/email/__init__.pyr r s" $ 4 3  ( ( ++c<ddlm}||i|j|S)z|Parse a bytes string into a Message object model. Optional _class and strict are passed to the Parser constructor. r BytesParser)rr parsebytes)rrrr s rrr's" )  $ $ / / 22rc<ddlm}||i|j|S)zRead a file and parse its contents into a Message object model. Optional _class and strict are passed to the Parser constructor. rr)rrparse)fprrrs rr r /s" $ 4 3  % %b ))rc<ddlm}||i|j|S)zRead a binary file and parse its contents into a Message object model. Optional _class and strict are passed to the Parser constructor. rr)rr r#)r$rrr s rr r 7s" )  $ $ * *2 ..rN)__doc____all__r rr r rrr)s& F 0,3*/r__pycache__/message.cpython-312.pyc000064400000147567152526700320013131 0ustar00 {|j dZddgZddlZddlZddlZddlmZmZddlm Z ddlm Z ddl m Z dd lm Zdd lmZej"Zd Zej&d Zd ZddZdZdZdZGddZGddeZGddeZy)z8Basic message object for the email package object model.Message EmailMessageN)BytesIOStringIO)utils)errors)compat32charset)decode_bz; z[ \(\)<>@,;:\\"/\[\]\?=]ct|jd\}}}|s|jdfS|j|jfS)N;)str partitionstrip)paramasepbs &/usr/lib64/python3.12/email/message.py _splitparamrsH E $$S)IAsA wwy$ 779aggi c|t|dkDrt|tr,|dz }tj|d|d|d}|d|S |j d|stj|r|d tj|d S|d|S|S#t $r&|dz }tj|dd}|d|cYSwxYw) a~Convenience function to format and return a key=value pair. This will quote the value if needed or if quote is true. If value is a three tuple (charset, language, value), it will be encoded according to RFC2231 rules. If it contains non-ascii characters it will likewise be encoded according to RFC2231 rules, using the utf-8 charset and a null language. r*=asciizutf-8z="") len isinstancetuplerencode_rfc2231encodeUnicodeEncodeError tspecialssearchquote)rvaluer)s r _formatparamr+'s SZ!^ eU # SLE((q58U1XFE#U+ + 0 W% I$$U+ %u{{5'9: :#U+ + & 0 ,,UGR@"'// 0sB,C C cxdt|z}g}d}|jd||k(r|dz }|jd|}|d}}|dkDrP||jd|||jd||z z }|dzdk(rn||jd|dz}}|dkDrP|dkr t|}|jd||}|dk(r|||}n;|||j j dz||dz|j z}|j|j|}|jd||k(r|S) Nrrrr z\"rr) rfindcountr!rstriplowerlstripappendr)spliststartendinddiffifs r _parseparamr<IsP c!f A E E &&e  %  ffS% 1TAg AGGCc*QWWUC-EE EDax1}AFF3a0C Ag 7a&C FF3s # 7% A% !!#))+c1Aac#J4E4E4GGA QWWY# &&e  %$ Lrct|tr!|d|dtj|dfStj|S)Nrrr)r"r#runquote)r*s r _unquotevaluer?cs? %Qxq5==q#:::}}U##rcRg}t|j}|D]G}|jds|jdj d\}}} t |dn t d|D]L}|s t d|jddk(rn) tj|}|j|Ndj|S#t $rYwxYw#tj$r/|d d z d zd zd zdz}tj|d|}YtwxYw)zDecode uuencoded data.sbegin  )basez`begin` line not foundzTruncated inputs sendr ?Nr) iter splitlines startswith removeprefixrint ValueErrorrbinasciia2b_uuErrorr3join) encoded decoded_linesencoded_lines_iterlinemode_path decoded_linenbytess r _decode_uur\ns2Mg0023" ??9 % --i8BB4HMD!T Dq!#122"./ / ZZ % /  :#??40L \*# 88M ""'  ~~ :Q b(A-1a7F#??4=9L :s$ CC$ C! C!$?D&%D&cTeZdZdZefdZdZd2dZdZd3dZ d Z d Z d Z d Z d4d Zd5dZdZdZdZdZdZdZdZdZdZdZdZd5dZdZdZd5dZdZdZ d Z!d!Z"d"Z#d#Z$d$Z%d%Z&d6d&Z' d6d'Z( d7d(Z)d8d)Z*d9d*Z+d5d+Z,d5d,Z-d-Z.d5d.Z/d5d/Z0d0Z1dd1l2m3Z3y):raBasic message object. A message object is defined as something that has a bunch of RFC 2822 headers and a payload. It may optionally have an envelope header (a.k.a. Unix-From or From_ header). If the message is a container (i.e. a multipart or a message/rfc822), then the payload is a list of Message objects, otherwise it is a string. Message objects implement part of the `mapping' interface, which assumes there is exactly one occurrence of the header per message. Some headers do in fact appear multiple times (e.g. Received) and for those headers, you must use the explicit API to set or get all the headers. Not all of the mapping methods are implemented. c||_g|_d|_d|_d|_dx|_|_g|_d|_y)N text/plain) policy_headers _unixfrom_payload_charsetpreambleepiloguedefects _default_type)selfr`s r__init__zMessage.__init__sB    (,,   )rc"|jS)z9Return the entire formatted message as a string. ) as_stringris r__str__zMessage.__str__s~~rrNcddlm}| |jn|}t}||d||}|j |||j S)aReturn the entire formatted message as a string. Optional 'unixfrom', when true, means include the Unix From_ envelope header. For backward compatibility reasons, if maxheaderlen is not specified it defaults to 0, so you must override it explicitly if you want a different maxheaderlen. 'policy' is passed to the Generator instance used to serialize the message; if it is not specified the policy associated with the message instance is used. If the message object contains binary data that is not encoded according to RFC standards, the non-compliant data will be replaced by unicode "unknown character" code points. r) GeneratorF) mangle_from_ maxheaderlenr`unixfrom)email.generatorrpr`rflattengetvalue)rirtrrr`rpfpgs rrlzMessage.as_stringsP . &F Z b#(#/# % $ *{{}rc"|jS)z?Return the entire formatted message as a bytes object. )as_bytesrms r __bytes__zMessage.__bytes__s}}rcddlm}| |jn|}t}||d|}|j |||j S)aJReturn the entire formatted message as a bytes object. Optional 'unixfrom', when true, means include the Unix From_ envelope header. 'policy' is passed to the BytesGenerator instance used to serialize the message; if not specified the policy associated with the message instance is used. r)BytesGeneratorF)rqr`rs)rur~r`rrvrw)rirtr`r~rxrys rr{zMessage.as_bytessG 3 &F Y 2E& A $ *{{}rc6t|jtS)z6Return True if the message consists of multiple parts.)r"rclistrms r is_multipartzMessage.is_multiparts$--..rc||_yNrb)rirts r set_unixfromzMessage.set_unixfroms !rc|jSrrrms r get_unixfromzMessage.get_unixfroms ~~rc|j |g|_y |jj|y#t$r tdwxYw)zAdd the given payload to the current payload. The current payload will always be a list of objects after this method is called. If you want to set the payload to a scalar object, use set_payload() instead. Nz=Attach is not valid on a message with a non-multipart payload)rcr3AttributeError TypeError)ripayloads rattachzMessage.attachsO == $IDM : $$W-! :!9:: :s 3Ac|jr |ry| |jS|j|S|;t|jts!t dt |jz|j}|j dd}t|dr |j}n't|jj}|s^t|trLtj|r7 |jdd} |j|j!dd}|S|St|tr |jdd}|d k(rt'j(S|d k(rPt+d j-j/\}}|D]}|j0j3|| |S|d vr t5St|trS|S#t"$r|jdd}Y|SwxYw#t$$rY|SwxYw#t$$r|jd }YwxYw#t6$rcYSwxYw)aZReturn a reference to the payload. The payload will either be a list object or a string. If you mutate the list object, you modify the message's payload in place. Optional i returns that index into the payload. Optional decode is a flag indicating whether the payload should be decoded or not, according to the Content-Transfer-Encoding header (default is False). When True and the message is not a multipart, the payload will be decoded if this header's value is `quoted-printable' or `base64'. If some other encoding is used, or the header is missing, or if the payload has bogus data (i.e. bogus base64 or uuencoded data), the payload is returned as-is. If the message is a multipart and the decode flag is True, then None is returned. NzExpected list, got %szcontent-transfer-encodingrctersurrogateescapereplaceraw-unicode-escapezquoted-printablebase64r)z x-uuencodeuuencodeuuezx-uue)rrcr"rrtypegethasattrrrrr1r_has_surrogatesr%decodeget_content_charset LookupErrorr&quopri decodestringr rRrJr` handle_defectr\rN) rir:rrrbpayloadr*rgdefects r get_payloadzMessage.get_payloads8D    y}}$}}Q'' =DMM4!@3d4==6IIJ J--hh2B7 3 ''Cc(.."((*C'3'E,A,A',J&~~g7HIHF"*//$2J2J72SU^"_ N7N gs # @">>'3DE $ $&&x0 0 H_&chhx/B/B/D&EFNE7! ))$7"L > > !(++ gs #O?'F"*//'9"EN F)N & @ #>>*>?  @$  sT4H!G"=H H4"H=HHH HHH10H14 IIct|drA|||_yt|ts t|}|j |j d}t|dr|j dd|_n||_||j|yy)zSet the payload to the given value. Optional charset sets the message's default character set. See set_charset() for details. r%Nrrr)rrcr"Charsetr%output_charsetr set_charset)rirr s r set_payloadzMessage.set_payloadUs 7H % ' gw/!'*nnW%;%;=NOG 7H %#NN74EFDM#DM     W % rc||jdd|_yt|ts t|}||_d|vr|j ddd|vr#|j dd|j n |j d|j ||j k7r |j|j|_d|vr|j} ||yy#t$rw|j}|r> |jd d }n*#t$r|j|j}YnwxYw|j||_|j d|YywxYw) aSet the charset of the payload to a given character set. charset can be a Charset instance, a string naming a character set, or None. If it is a string it will be converted to a Charset instance. If charset is None, the charset parameter will be removed from the Content-Type field. Anything else will generate a TypeError. The message will be assumed to be of type text/* encoded with charset.input_charset. It will be converted to charset.output_charset and encoded properly, if needed, when generating the plain text representation of the message. MIME headers (MIME-Version, Content-Type, Content-Transfer-Encoding) will be added as needed. Nr MIME-Version1.0 Content-Typer_r zContent-Transfer-Encodingrr) del_paramrdr"r add_headerget_output_charset set_param body_encodercget_body_encodingrr% UnicodeErrorr)rir rrs rrzMessage.set_charsetis` ? NN9 % DM '7+g&G  % OONE 2  % OONL$+$>$>$@  B NN9g&@&@&B C g002 2#// >DM &d 2++-C BD  3 B--I")..:K"L'I")..1G1G"HI ' 3 3G <  ;SA Bs6#C--E-DE-$D?<E->D??+E-,E-c|jS)zKReturn the Charset instance associated with the message's payload. )rdrms r get_charsetzMessage.get_charsets}}rc,t|jS)z9Return the total number of headers, including duplicates.)r!rarms r__len__zMessage.__len__s4==!!rc$|j|S)a-Get a header value. Return None if the header is missing instead of raising an exception. Note that if the header appeared multiple times, exactly which occurrence gets returned is undefined. Use get_all() to get all the values matching a header field name. )r)rinames r __getitem__zMessage.__getitem__sxx~rcf|jj|}|r_|j}d}|jD]>\}}|j|k(s|dz }||k\s%t dj |||jj |jj||y)zSet the value of a header. Note: this does not overwrite an existing header with the same field name. Use __delitem__() first to delete any existing headers. rrz/There may be at most {} {} headers in a messageN)r`header_max_countr1rarNformatr3header_store_parse)rirval max_countlnamefoundkvs r __setitem__zMessage.__setitem__s KK006 JJLEE 1779%QJE )(*88>y$8OQQ & T[[;;D#FGrc|j}g}|jD],\}}|j|k7s|j||f.||_y)zwDelete all occurrences of a header, if present. Does not raise an exception if the header is missing. N)r1rar3)rir newheadersrrs r __delitem__zMessage.__delitem__sO zz| MMDAqwwyD !!1a&)"# rcv|j}|jD]\}}||jk(syy)NTF)r1ra)rir name_lowerrrs r __contains__zMessage.__contains__s5ZZ\ MMDAqQWWY&"rc#<K|jD] \}}| ywrra)rifieldr*s r__iter__zMessage.__iter__s MMLE5K*scL|jDcgc]\}}| c}}Scc}}w)a.Return a list of all the message's header field names. These will be sorted in the order they appeared in the original message, or were added to the message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. rrirrs rkeysz Message.keyss$#mm,mdam,,,s c|jDcgc]!\}}|jj||#c}}Scc}}w)a)Return a list of all the message's header values. These will be sorted in the order they appeared in the original message, or were added to the message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. rar`header_fetch_parsers rvalueszMessage.valuessB!MM+)DAq ..q!4)+ ++s&:c |jDcgc]#\}}||jj||f%c}}Scc}}w)a'Get all the message's header fields and values. These will be sorted in the order they appeared in the original message, or were added to the message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. rrs ritemsz Message.itemssG!MM+)DAqDKK221a89)+ ++s(<c|j}|jD]6\}}|j|k(s|jj||cS|S)z~Get a header value. Like __getitem__() but return failobj instead of None when the field is missing. )r1rar`r)rirfailobjrrs rrz Message.getsM zz|MMDAqwwyD {{55a;;"rc>|jj||fy)zStore name and value in the model without modification. This is an "internal" API, intended only for use by a parser. N)rar3)rirr*s rset_rawzMessage.set_raw s dE]+rcHt|jjS)zReturn the (name, value) header pairs without modification. This is an "internal" API, intended only for use by a generator. )rIracopyrms r raw_itemszMessage.raw_itemss DMM&&())rcg}|j}|jD]D\}}|j|k(s|j|jj ||F|s|S|S)aQReturn a list of all the values for the named field. These will be sorted in the order they appeared in the original message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. If no such fields exist, failobj is returned (defaults to None). )r1rar3r`r)rirrrrrs rget_allzMessage.get_alls`zz|MMDAqwwyD  dkk<rrs r get_paramzMessage.get_paramsZ0  N--gv>DAqwwyEKKM)(++H ? rcft|ts|r|||f}||vr|jdk(rd}n|j|}|j ||s3|st |||}nt j|t |||g}nwd}|j||D]_\} } d} | j|jk(rt |||} n t | | |} |s| }It j|| g}a||j|k7r|r|j||y||=|||<yy)aSet a parameter in the Content-Type header. If the parameter already exists in the header, its value will be replaced with the new value. If header is Content-Type and has not yet been defined for this message, it will be set to "text/plain" and the new parameter and value will be appended as per RFC 2045. An alternate header can be specified in the header argument, and all parameters will be quoted as necessary unless requote is False. If charset is specified, the parameter will be encoded according to RFC 2231. Optional language specifies the RFC 2231 language, defaulting to the empty string. Both charset and language should be strings. rr_)rrrr>N) r"r#r1rr r+rrRrr) rirr*rrequoter languagerr old_param old_value append_params rrzMessage.set_params<$%'Gh.E  &,,.N"B EHHV$E~~eF~3$UE7;!Lw?@BE(,v@G)8)I$ 9! ??$ 5#/ug#FL#/ 9g#NL(E%NNE<+@AE)I DHHV$ $##FE2L$V %rc *||vryd}|j||D]Y\}}|j|jk7s(|st|||}8tj |t|||g}[||j |k7r ||=|||<yy)a>Remove the given parameter completely from the Content-Type header. The header will be re-written in place without the parameter or its value. All values will be quoted as necessary unless requote is False. Optional header specifies an alternative to the Content-Type header. Nrr )rr1r+rrRr)rirrr  new_ctyperrs rrzMessage.del_params    OO67OCDAqwwyEKKM) ,Q7 ;I ) 0^ +^$#(D  DL @ LV 12JDAq NN1a 1rct}|jd|d}||ur|jd|d}||ur|Stj|j S)a@Return the filename associated with the payload if present. The filename is extracted from the Content-Disposition header's `filename' parameter, and it is unquoted. If that header is missing the `filename' parameter, this method falls back to looking for the `name' parameter. filenamecontent-dispositionrr)rr rcollapse_rfc2231_valuer)rirrrs r get_filenamezMessage.get_filenamePs_(>>*g7LM w ~~fg~FH w N++H5;;==rct}|jd|}||ur|Stj|j S)zReturn the boundary associated with the payload if present. The boundary is extracted from the Content-Type header's `boundary' parameter, and it is unquoted. boundary)rr rrr0)rirrrs r get_boundaryzMessage.get_boundary`sB (>>*g6 w N++H5<<>>rct}|j|d}||urtjdg}d}|D]D\}}|j dk(r|j dd|zfd}2|j ||fF|s|j dd|zfg}|j D]\} } | j dk(rzg} |D]2\} } | dk(r| j | | j | d| 4tj| } |j |jj| | |j | | f||_y ) aSet the boundary parameter in Content-Type to 'boundary'. This is subtly different than deleting the Content-Type header and adding a new one with a new boundary parameter via add_header(). The main difference is that using the set_boundary() method preserves the order of the Content-Type header in the original message. HeaderParseError is raised if the message has no Content-Type header. rzNo Content-Type header foundFrz"%s"TrrN) rrrHeaderParseErrorr1r3rarrRr`r)rirrr newparamsfoundppkpvrhrrrrs r set_boundaryzMessage.set_boundarymsT(**7NC W ))*HI I FBxxzZ'  *fx.?!@A  "b*     j&8*;< = MMDAqwwyN*%DAqBw Q 1%56 &  nnU+!!$++"@"@C"HI!!1a&)"# rcTt}|jd|}||ur|St|tr*|dxsd} |dj d}t ||} |j d|jS#t tf$r|d}Y8wxYw#t$r|cYSwxYw)zReturn the charset parameter of the Content-Type header. The returned string is always coerced to lower case. If there is no Content-Type header, or if that header has no charset parameter, failobj is returned. r rzus-asciirr) rr r"r#r%rrrr1)rirrr pcharsetr{s rrzMessage.get_content_charsets(..G4 g N gu %qz/ZH %#1:,,-ABh1  NN: &}} . %!!* %  N s# A?B?BB B'&B'cf|jDcgc]}|j|c}Scc}w)aReturn a list containing the charset(s) used in this message. The returned list of items describes the Content-Type headers' charset parameter for this message and all the subparts in its payload. Each item will either be a string (the value of the charset parameter in the Content-Type header of that part) or the value of the 'failobj' parameter (defaults to None), if the part does not have a main MIME type of "text", or the charset is not defined. The list will contain one string for each part of the message, plus one for the container message (i.e. self), so that a non-multipart message will still return a list of length 1. )walkr)rirparts r get_charsetszMessage.get_charsetss. ?CiikJkd((1kJJJs.cf|jd}|yt|dj}|S)zReturn the message's content-disposition if it exists, or None. The return values can be either 'inline', 'attachment' or None according to the rfc2183. rNr)rrr1)rir*c_ds rget_content_dispositionzMessage.get_content_dispositions8 ./ =% #))+ r)r))FrN)FN)NFr)NrT)rTNrF)rT)rT)4__name__ __module__ __qualname____doc__r rjrnrlr|r{rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr rrrrrr%rr+r.email.iteratorsr)rrrrs ' * 0 /" : Zx&(-B^" H$ #- + + ",*$,< "&0##"#*,5C DFJ5:1%f%,2@> ?,#\<K$ %rceZdZdfd Zdfd ZdZdZdZddZhdZ d Z d Z dd d Z dd d Z dZddZddZddZdddZdZdZdZdZdZxZS)MIMEPartNc8|ddlm}|}t| |y)Nr)default) email.policyr8superrj)rir`r8 __class__s rrjzMIMEPart.__init__s > ,F  rcb| |jn|}| |j}t| |||S)aReturn the entire formatted message as a string. Optional 'unixfrom', when true, means include the Unix From_ envelope header. maxheaderlen is retained for backward compatibility with the base Message class, but defaults to None, meaning that the policy value for max_line_length controls the header maximum length. 'policy' is passed to the Generator instance used to serialize the message; if it is not specified the policy associated with the message instance is used. )r`max_line_lengthr:rl)rirtrrr`r;s rrlzMIMEPart.as_strings9!'F  !11Lw <@@rcZ|j|jjdS)NT)utf8r`)rlr`clonerms rrnzMIMEPart.__str__s%~~T[[%6%6D%6%A~BBrcJ|jd}|dS|jdk(S)NrF attachment)rcontent_disposition)rir-s r is_attachmentzMIMEPart.is_attachments+hh,- uP)@)@L)PPrc#\K|jry|jjd\}}|dk(r||vr|j||fy|dk7s|j sy|dk7r0|j D]}|j ||Ed{yd|vr|jd|fd}|jd}|r!|j D]}|d|k(s |}n||j}|r|dnd}||j ||Ed{yy77w)Nrtext multipartrelatedr6 content-idr) rErrindexr iter_parts _find_bodyr r) rir*preferencelistmaintypesubtypesubpart candidater6subpartss rrMzMIMEPart._find_bodysK      11399#>' v .(%++G4d;;  { "$*;*;*=  i ??,??7NCCC-   &!'' 2D9 9 w' ??,<(E1 'I-  '')H'/ TI  y.A A A !D Bs+BD,D(AD,*7D,!D*"D,*D,cxt|}d}|j||D]\}}||ks |}|}|dk(s|S|S)aReturn best candidate mime part for display as 'body' of message. Do a depth first search, starting with self, looking for the first part matching each of the items in preferencelist, and return the part corresponding to the first item that has a match, or None if no items have a match. If 'related' is not included in preferencelist, consider the root part of any multipart/related encountered as a candidate match. Ignore parts with 'Content-Disposition: attachment'. Nr)r!rM)rirN best_priobodyprior*s rget_bodyzMIMEPart.get_bodysU' //$?JD$i 19 @  r>rGhtmlrGplainrHrIrH alternativec#K|jjd\}}|dk7s|dk(ry|j} |j}|dk(rt|dk(ro|j d}|r@d}g}|D]*}|j d|k(rd }|j|,|r |Ed{y|jd |Ed{yg} |D]^}|jjd\}}||f|jvr&|js|| vr| j|[|`y#t$rYywxYw77|w) aReturn an iterator over the non-main parts of a multipart. Skip the first of each occurrence of text/plain, text/html, multipart/related, or multipart/alternative in the multipart (unless they have a 'Content-Disposition: attachment' header) and include all remaining subparts in the returned iterator. When applied to a multipart/related, return all parts except the root part. Return an empty iterator when applied to a multipart/alternative or a non-multipart. rrHr_NrIr6FrJTr) rrrrrr rr3pop _body_typesrE) rirOrPrrr6r attachmentsr*seens riter_attachmentszMIMEPart.iter_attachments0sb!11399#>' { "g&> ""$ LLNE { "w)';NN7+E !Dxx -6 $#**40 " *** IIaL   D $ 5 5 7 = =c B Hg7#t'7'77**,1D G$J 7   $+ sI>ED0AE(D?)EEA+E0 D<9E;D<<EEc#bK|jr|jEd{yy7w)z~Return an iterator over all immediate subparts of a multipart. Return an empty iterator for a non-multipart. N)rrrms rrLzMIMEPart.iter_partsgs.    '') ) )  )s $/-/)content_managerc^||jj}|j|g|i|Sr)r`rg get_contentrirgargskws rrizMIMEPart.get_contentos4  ""kk99O***4=$="==rc`||jj}|j|g|i|yr)r`rg set_contentrjs rrnzMIMEPart.set_contentts1  ""kk99O###D64626rc$|jdk(r5|j}||fz}||vrtdj||g}g}|jD]K\}}|j j dr|j||f9|j||fM|r=t||j} || _|j| _ | g|_ ng|_ ||_d|z|d<||jd|yy)NrHzCannot convert {} to {}content-r@z multipart/rr) rrrNrrar1rKr3rr`rcr) rirPdisallowed_subtypesrexisting_subtype keep_headers part_headersrr*r*s r_make_multipartzMIMEPart._make_multipartys  $ $ &+ 5#779 "5 "B #66 !:!A!A$g"/00  ==KD%zz|&&z2##T5M2##T5M2 ) 4:T[[1D(DM MMDM!FDMDM$ +g5^   NN:x 0 rc*|jdd|y)NrI)r_mixedrurirs r make_relatedzMIMEPart.make_relateds Y(@(Krc*|jdd|y)Nr_)rwrxrys rmake_alternativezMIMEPart.make_alternatives ]JArc*|jdd|y)Nrwr4rxrys r make_mixedzMIMEPart.make_mixeds Wb(3r)_dispc |jdk7s|j|k7rt|d|zt||j}|j |i||r d|vr||d<|j |y)NrHmake_r@rzContent-Disposition)rrgetattrrr`rnr)ri_subtyperrkrlr*s r_add_multipartzMIMEPart._add_multiparts  % % '; 6((*h6 -GD'H, - /tDz-$%"% *$6*/D& ' Drc4|jdg|ddi|y)NrIrinlinerrirkrls r add_relatedzMIMEPart.add_relateds!ICCHCCrc0|jdg|i|y)Nr_rrs radd_alternativezMIMEPart.add_alternativesM7D7B7rc4|jdg|ddi|y)NrwrrCrrs radd_attachmentzMIMEPart.add_attachments!GEdE,E"Erc g|_d|_yr)rarcrms rclearzMIMEPart.clears  rc|jDcgc](\}}|jjds||f*c}}|_d|_ycc}}w)Nrp)rar1rKrc)rinrs r clear_contentzMIMEPart.clear_contentsN,0MMBMDAq ! 4 4Z @QMB  Bs-Ar)FNN))rIrZr\)r/r0r1rjrlrnrErMrXrbrerLrirnrurzr|r~rrrrrr __classcell__r;s@rr6r6s!A CQB:(1K5n*26> 267 16LB459D8Frr6ceZdZfdZxZS)rc8t||i|d|vrd|d<yy)Nrr)r:rn)rirkrlr;s rrnzEmailMessage.set_contents, T(R(  %#(D  &r)r/r0r1rnrrs@rrrs ))r)NT)r2__all__rOreriorremailrremail._policybaser r rdemail._encoded_wordsr rrcompiler'rr+r<r?r\rr6rr4rrrs ? n % &%)      BJJ2 3   D4$#>K %K %\\w\~)8)r__pycache__/__init__.cpython-312.opt-2.pyc000064400000002460152526700320014162 0ustar00 {|j& gdZdZdZdZdZy)) base64mimecharsetencoderserrors feedparser generatorheader iteratorsmessagemessage_from_filemessage_from_binary_filemessage_from_stringmessage_from_bytesmimeparser quoprimimeutilsc> ddlm}||i|j|SN)Parser) email.parserrparsestr)sargskwsrs '/usr/lib64/python3.12/email/__init__.pyr r s'$ 4 3  ( ( ++c> ddlm}||i|j|SNr) BytesParser)rr parsebytes)rrrr s rrr's')  $ $ / / 22rc> ddlm}||i|j|Sr)rrparse)fprrrs rr r /s'$ 4 3  % %b ))rc> ddlm}||i|j|Sr)rr r#)r$rrr s rr r 7s')  $ $ * *2 ..rN)__all__r rr r rrr(s& F 0,3*/r__pycache__/feedparser.cpython-312.opt-1.pyc000064400000046231152526700320014546 0ustar00 {|j YRdZddgZddlZddlmZddlmZddlmZddl m Z ejd Z ejd Z ejd Zejd Zejd Zd ZdZeZGddeZGddZGddeZy)aFeedParser - An email feed parser. The feed parser implements an interface for incrementally parsing an email message, line by line. This has advantages for certain applications, such as those reading email messages off a socket. FeedParser.feed() is the primary interface for pushing new data into the parser. It returns when there's nothing more it can do with the available data. When you have no more data to push into the parser, call .close(). This completes the parsing and returns the root message object. The other advantage of this parser is that it will never raise a parsing exception. Instead, when it finds something unexpected, it adds a 'defect' to the current message. Defects are just instances that live on the message object's .defects attribute. FeedParserBytesFeedParserN)errors)compat32)deque)StringIOz \r\n|\r|\nz (\r\n|\r|\n)z(\r\n|\r|\n)\Zz%^(From |[\041-\071\073-\176]*:|[\t ]) cLeZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z y ) BufferedSubFileakA file-ish object that can have new data loaded into it. You can also push and pop line-matching predicates onto a stack. When the current predicate matches the current line, a false EOF response (i.e. empty string) is returned instead. This lets the parser adhere to a simple abstraction -- it parses until EOF closes the current message. c`td|_t|_g|_d|_y)Nr )newlineF)r_partialr_lines _eofstack_closedselfs )/usr/lib64/python3.12/email/feedparser.py__init__zBufferedSubFile.__init__4s'!, g  c:|jj|yN)rappend)rpreds rpush_eof_matcherz BufferedSubFile.push_eof_matcher?s d#rc6|jjSr)rpoprs rpop_eof_matcherzBufferedSubFile.pop_eof_matcherBs~~!!##rc|jjd|j|jj|jjd|jj d|_y)NrT)rseek pushlines readlinestruncaterrs rclosezBufferedSubFile.closeEsV 1 t}}..01 1   rc|js|jrytS|jj}t |j D]'}||s |jj |y|SNr )rr NeedMoreDatapopleftreversedr appendleft)rlineateofs rreadlinezBufferedSubFile.readlineMse{{|| {{""$dnn-ET{ &&t, .  rc:|jj|yr)rr+rr,s r unreadlinezBufferedSubFile.unreadline_s t$rc|jj|d|vrd|vry|jjd|jj}|jjd|jj |dj ds)|jj|j |j|y)z$Push some new data into this object.r  Nr)rwriter!r#r$endswithrr")rdatapartss rpushzBufferedSubFile.pushds D! t D 0  1 '') 1  Ry!!$' MM   , urc:|jj|yr)rextend)rliness rr"zBufferedSubFile.pushlinesys 5!rc|Srrs r__iter__zBufferedSubFile.__iter__|s rc<|j}|dk(rt|Sr')r. StopIterationr0s r__next__zBufferedSubFile.__next__s}} 2:  rN)__name__ __module__ __qualname____doc__rrrr%r.r1r9r"r?rBr>rrr r ,s9 $$$% *"rr cNeZdZdZd eddZdZdZdZdZ d Z d Z d Z d Z y)rzA feed-style parser of email.Npolicycr||_d|_|,|jddlm}||_n-|j|_n||_ ||jt|_g|_ |jj|_ d|_ d|_d|_y#t $r d|_Y]wxYw)a_factory is called with no arguments to create a new message obj The policy keyword specifies a policy object that controls a number of aspects of the parser's operation. The default policy maintains backward compatibility. FNr)MessagerHT)rI_old_style_factorymessage_factory email.messagerK_factory TypeErrorr _input _msgstack _parsegenrB_parse_cur_last _headersonly)rrOrIrKs rrzFeedParser.__init__s "'  %%-1 ' & 6 6 $DM / ,&' nn&//   ! /*.' /sB##B65B6cd|_y)NT)rWrs r_set_headersonlyzFeedParser._set_headersonlys  rcZ|jj||jy)zPush more data into the parser.N)rQr9 _call_parse)rr7s rfeedzFeedParser.feeds   rcD |jy#t$rYywxYwr)rTrArs rr[zFeedParser._call_parses"  KKM   s  c8|jj|j|j}|j dk(rL|j s<|j s0tj}|jj|||S)z> NN2  % %c * c"  rc|jj}|jr|jd|_|Sd|_|S)Nr4)rRrrU)rretvals rr`zFeedParser._pop_messages@##% >>r*DI DI rc#BK|jg}|jD]}|tur ttj |slt j |sUt j}|jj|j||jj|n|j||j||jrug} |jj}|tur t,|dk(rn|j|C|jj!t"j%|y|jj'dk(r |jj)t j|j+D]}|tur tn|j-|jj/ |jj}|tur t, |jj}|tur t, |dk(r y|jj||jj1dk(r8|j+D]}|tur tn|j-y|jj1dk(r|jj3}|t j4}|jj|j|g}|jD]$}|tur t|j|&|jj!t"j%|yt7|jj9ddj;dvr:t j<}|jj|j|d |z}t?j@d t?jB|zd z}d} g} d } d } |jj}|tur t,|dk(rn|j |} | r| jEd rd} | jEd} ny| r| ra| d}tFjI|}|r!|dtK|jEd | d<t"j%| |j_&d } |jj| |jj}|tur t,|j |} | s|jj|n[|jj)|j|j+D]}|tur tn|jNj1dk(rv|jNjP}|dk(rd|jN_(n|tFjI|} | rtK| jEd}|d| |jN_(nl|jNjR}tU|t6rFtFjI|} | r/|dtK| jEd }||jN_)|jj/|j-|j|_'n| j|| rt jV}|jj|j||jj!t"j%| g}|jD]}|tus tt"j%||j_(y| s;t jX}|jj|j|y| rdg}ng}|jD]$}|tur t|j|&|r<|d}tZj |}|r |tK|jEdd|d<t"j%||j_(yg}|jD]$}|tur t|j|&|jj!t"j%|yw)NTr zmessage/delivery-statusmessager_zcontent-transfer-encoding8bit)7bitrqbinaryz--z(?Pz4)(?P--)?(?P[ \t]*)(?P\r\n|\r|\n)?$Fendlinesepr4r).rlrQr(headerREmatchNLCREr MissingHeaderBodySeparatorDefectrIrdrUr1r_parse_headersrWr. set_payload EMPTYSTRINGjoinrhrrSr`rra get_boundaryNoBoundaryInMultipartDefectstrgetlower-InvalidMultipartContentTransferEncodingDefectrecompileescapegroup NLCRE_eolsearchlenpreamblerVepilogue_payload isinstanceStartBoundaryNotFoundDefectCloseBoundaryNotFoundDefect NLCRE_bol)rheadersr,rfr<rnboundary separator boundaryrecapturing_preamblerruclose_boundary_seenmolastlineeolmorrtpayload firstlinebolmos rrSzFeedParser._parsegens KKD|#"">>$'{{4(#DDFFKK--dii@KK**40 NN4  G$   E{{++-<'&&2: T" II ! !+"2"25"9 :  99 % % '+D D  ,,U[[9"nn.F-**  / !!# ++- ;;//1D|+** ;;//1D|+** 2:  &&t,?B 99 ) ) +y 8..*\)&& +      99 ) ) +{ :yy--/H  ;;= ))$))V< KKD|+** LL& (  %%k&6&6u&=>DIIMM"=vFGMMO56MMO ))$))V< xIRYYy11GHIJ"& HG"' {{++-<'&&2:%%d+ xx.2+"$((9"5)#(0|H$-$4$4X$>E$/78M#ekk!n:M9M/N 1<1A1A(1KDII.-2* ..t4 #{{335</"..$'--d3! KK2248!KK001A1AB"&.."2!\1"..$ #3zz668KG#'::#6#6#r>26DJJ/%1!*!1!1(!;B!&)"((1+&66>uo 3"&**"5"5%gs3!*!1!1'!:B!*12DC 4D3D*E6= 3KK//1%%'"&DJOOD)_f";;= ))$))V< %%k&6&6x&@A KKD|+** (&1%5%5h%? "';;= ))$))V<4 <'&&% $$QK ! 2"+C A,?,@"AHQK!,!1!1(!;DII  KKD|#"" LL   k..u56s ^.d1E.dcd}g}t|D]\}}|ddvrP|s>yI J rr)rCrDrErFrrrYr\r[r%rlr`rSrzr>rrrrs<'"">!   {7z:Krc"eZdZdZfdZxZS)rz(Like FeedParser, but feed accepts bytes.cDt||jddy)Nasciisurrogateescape)superr\decode)rr7 __class__s rr\zBytesFeedParser.feeds  T[[*;<=r)rCrDrErFr\ __classcell__)rs@rrrs2>>r)rF__all__remailremail._policybaser collectionsriorrrxrr NLCRE_crackrvr|NLobjectr(r rrr>rrrs " * + & =! BJJ ' BJJ( ) bjj)  2::> ?  x WfWtIKIKX >j>r__pycache__/message.cpython-312.opt-2.pyc000064400000107762152526700320014062 0ustar00 {|j  ddgZddlZddlZddlZddlmZmZddlmZddlm Z ddl m Z ddlm Z dd lmZe j Zd Zej$d Zd Zdd ZdZdZdZGddZGddeZGddeZy)Message EmailMessageN)BytesIOStringIO)utils)errors)compat32charset)decode_bz; z[ \(\)<>@,;:\\"/\[\]\?=]ct|jd\}}}|s|jdfS|j|jfS)N;)str partitionstrip)paramasepbs &/usr/lib64/python3.12/email/message.py _splitparamrsH E $$S)IAsA wwy$ 779aggi c |t|dkDrt|tr,|dz }tj|d|d|d}|d|S |j d|stj|r|d tj|d S|d|S|S#t $r&|dz }tj|dd}|d|cYSwxYw) Nr*=asciizutf-8z="") len isinstancetuplerencode_rfc2231encodeUnicodeEncodeError tspecialssearchquote)rvaluer)s r _formatparamr+'s SZ!^ eU # SLE((q58U1XFE#U+ + 0 W% I$$U+ %u{{5'9: :#U+ + & 0 ,,UGR@"'// 0sB,C  C cxdt|z}g}d}|jd||k(r|dz }|jd|}|d}}|dkDrP||jd|||jd||z z }|dzdk(rn||jd|dz}}|dkDrP|dkr t|}|jd||}|dk(r|||}n;|||j j dz||dz|j z}|j|j|}|jd||k(r|S) Nrrrr z\"rr) rfindcountr!rstriplowerlstripappendr)spliststartendinddiffifs r _parseparamr<IsP c!f A E E &&e  %  ffS% 1TAg AGGCc*QWWUC-EE EDax1}AFF3a0C Ag 7a&C FF3s # 7% A% !!#))+c1Aac#J4E4E4GGA QWWY# &&e  %$ Lrct|tr!|d|dtj|dfStj|S)Nrrr)r"r#runquote)r*s r _unquotevaluer?cs? %Qxq5==q#:::}}U##rcT g}t|j}|D]G}|jds|jdj d\}}} t |dn t d|D]L}|s t d|jddk(rn) tj|}|j|Ndj|S#t $rYwxYw#tj$r/|d d z d zd zd zdz}tj|d|}YtwxYw)Nsbegin  )basez`begin` line not foundzTruncated inputs sendr ?r) iter splitlines startswith removeprefixrint ValueErrorrbinasciia2b_uuErrorr3join) encoded decoded_linesencoded_lines_iterlinemode_path decoded_linenbytess r _decode_uur\ns5 Mg0023" ??9 % --i8BB4HMD!T Dq!#122"./ / ZZ % /  :#??40L \*# 88M ""'  ~~ :Q b(A-1a7F#??4=9L :s$ CC% C"!C"%?D'&D'cReZdZ efdZdZd1dZdZd2dZdZ d Z d Z d Z d3d Z d4d ZdZdZdZdZdZdZdZdZdZdZdZd4dZdZdZd4dZdZdZdZ d Z!d!Z"d"Z#d#Z$d$Z%d5d%Z& d5d&Z' d6d'Z(d7d(Z)d8d)Z*d4d*Z+d4d+Z,d,Z-d4d-Z.d4d.Z/d/Z0dd0l1m2Z2y)9rc||_g|_d|_d|_d|_dx|_|_g|_d|_y)N text/plain) policy_headers _unixfrom_payload_charsetpreambleepiloguedefects _default_type)selfr`s r__init__zMessage.__init__sB    (,,   )rc$ |jSN) as_stringris r__str__zMessage.__str__s ~~rrNc ddlm}| |jn|}t}||d||}|j |||j S)Nr) GeneratorF) mangle_from_ maxheaderlenr`unixfrom)email.generatorrqr`rflattengetvalue)rirursr`rqfpgs rrmzMessage.as_stringsU  . &F Z b#(#/# % $ *{{}rc$ |jSrl)as_bytesrns r __bytes__zMessage.__bytes__s }}rc ddlm}| |jn|}t}||d|}|j |||j S)Nr)BytesGeneratorF)rrr`rt)rvrr`rrwrx)rirur`rryrzs rr|zMessage.as_bytessL  3 &F Y 2E& A $ *{{}rc8 t|jtSrl)r"rclistrns r is_multipartzMessage.is_multipartsD$--..rc||_yrlrb)rirus r set_unixfromzMessage.set_unixfroms !rc|jSrlrrns r get_unixfromzMessage.get_unixfroms ~~rc |j |g|_y |jj|y#t$r tdwxYw)Nz=Attach is not valid on a message with a non-multipart payload)rcr3AttributeError TypeError)ripayloads rattachzMessage.attachsT == $IDM : $$W-! :!9:: :s 4A c |jr |ry| |jS|j|S|;t|jts!t dt |jz|j}|j dd}t|dr |j}n't|jj}|s^t|trLtj|r7 |jdd} |j|j!dd}|S|St|tr |jdd}|d k(rt'j(S|d k(rPt+d j-j/\}}|D]}|j0j3|| |S|d vr t5St|trS|S#t"$r|jdd}Y|SwxYw#t$$rY|SwxYw#t$$r|jd}YwxYw#t6$rcYSwxYw) NzExpected list, got %szcontent-transfer-encodingrctersurrogateescapereplaceraw-unicode-escapezquoted-printablebase64r)z x-uuencodeuuencodeuuezx-uue)rrcr"rrtypegethasattrrrrr1r_has_surrogatesr%decodeget_content_charset LookupErrorr&quopri decodestringr rRrJr` handle_defectr\rN) rir:rrrbpayloadr*rgdefects r get_payloadzMessage.get_payloads= B    y}}$}}Q'' =DMM4!@3d4==6IIJ J--hh2B7 3 ''Cc(.."((*C'3'E,A,A',J&~~g7HIHF"*//$2J2J72SU^"_ N7N gs # @">>'3DE $ $&&x0 0 H_&chhx/B/B/D&EFNE7! ))$7"L > > !(++ gs #O?'F"*//'9"EN F)N & @ #>>*>?  @$  sT5H!G#>H H5#H>HHH HHH21H25 IIc t|drA|||_yt|ts t|}|j |j d}t|dr|j dd|_n||_||j|yy)Nr%rrr)rrcr"Charsetr%output_charsetr set_charset)rirr s r set_payloadzMessage.set_payloadUs 7H % ' gw/!'*nnW%;%;=NOG 7H %#NN74EFDM#DM     W % rc ||jdd|_yt|ts t|}||_d|vr|j ddd|vr#|j dd|j n |j d|j ||j k7r |j|j|_d|vr|j} ||yy#t$rw|j}|r> |jdd }n*#t$r|j|j}YnwxYw|j||_|j d|YywxYw) Nr MIME-Version1.0 Content-Typer_r zContent-Transfer-Encodingrr) del_paramrdr"r add_headerget_output_charset set_param body_encodercget_body_encodingrr% UnicodeErrorr)rir rrs rrzMessage.set_charsetise  ? NN9 % DM '7+g&G  % OONE 2  % OONL$+$>$>$@  B NN9g&@&@&B C g002 2#// >DM &d 2++-C BD  3 B--I")..:K"L'I")..1G1G"HI ' 3 3G <  ;SA Bs6$C..E.DE.$E=E.?E+E.-E.c |jSrl)rdrns r get_charsetzMessage.get_charsets }}rc. t|jSrl)r!rarns r__len__zMessage.__len__sG4==!!rc& |j|Srl)r)rinames r __getitem__zMessage.__getitem__s xx~rch |jj|}|r_|j}d}|jD]>\}}|j|k(s|dz }||k\s%t dj |||jj |jj||y)Nrrz/There may be at most {} {} headers in a message)r`header_max_countr1rarNformatr3header_store_parse)rirval max_countlnamefoundkvs r __setitem__zMessage.__setitem__s KK006 JJLEE 1779%QJE )(*88>y$8OQQ & T[[;;D#FGrc |j}g}|jD],\}}|j|k7s|j||f.||_yrl)r1rar3)rir newheadersrrs r __delitem__zMessage.__delitem__sT zz| MMDAqwwyD !!1a&)"# rcv|j}|jD]\}}||jk(syy)NTF)r1ra)rir name_lowerrrs r __contains__zMessage.__contains__s5ZZ\ MMDAqQWWY&"rc#<K|jD] \}}| ywrlra)rifieldr*s r__iter__zMessage.__iter__s MMLE5K*scN |jDcgc]\}}| c}}Scc}}wrlrrirrs rkeysz Message.keyss) #mm,mdam,,,s !c |jDcgc]!\}}|jj||#c}}Scc}}wrlrar`header_fetch_parsers rvalueszMessage.valuessG !MM+)DAq ..q!4)+ ++s&;c  |jDcgc]#\}}||jj||f%c}}Scc}}wrlrrs ritemsz Message.itemssL !MM+)DAqDKK221a89)+ ++s(=c |j}|jD]6\}}|j|k(s|jj||cS|Srl)r1rar`r)rirfailobjrrs rrz Message.getsR zz|MMDAqwwyD {{55a;;"rc@ |jj||fyrl)rar3)rirr*s rset_rawzMessage.set_raw s  dE]+rcJ t|jjSrl)rIracopyrns r raw_itemszMessage.raw_itemss! DMM&&())rc g}|j}|jD]D\}}|j|k(s|j|jj ||F|s|S|Srl)r1rar3r`r)rirrrrrs rget_allzMessage.get_allse zz|MMDAqwwyD  dkk<rrrrs r get_paramszMessage.get_paramss_ (**7F; W N 6<=fdaQ a()f= =M>sAc ||vr|S|j||D]9\}}|j|jk(s(|r t|cS|cS|Srl)rr1r?)rirrrr>rrs r get_paramzMessage.get_params_ ,  N--gv>DAqwwyEKKM)(++H ? rch t|ts|r|||f}||vr|jdk(rd}n|j|}|j ||s3|st |||}nt j|t |||g}nwd}|j||D]_\} } d} | j|jk(rt |||} n t | | |} |s| }It j|| g}a||j|k7r|r|j||y||=|||<yy)Nrr_)rrrr>) r"r#r1rr r+rrRrr) rirr*rrequoter languagerr old_param old_value append_params rrzMessage.set_paramsA %'Gh.E  &,,.N"B EHHV$E~~eF~3$UE7;!Lw?@BE(,v@G)8)I$ 9! ??$ 5#/ug#FL#/ 9g#NL(E%NNE<+@AE)I DHHV$ $##FE2L$V %rc , ||vryd}|j||D]Y\}}|j|jk7s(|st|||}8tj |t|||g}[||j |k7r ||=|||<yy)Nrr )rr1r+rrRr)rirrr  new_ctyperrs rrzMessage.del_params     OO67OCDAqwwyEKKM) ,Q7 ;I ) 0^ +^$#(D  DL @ LV 12JDAq NN1a 1rc t}|jd|d}||ur|jd|d}||ur|Stj|j S)Nfilenamecontent-dispositionrr)rr rcollapse_rfc2231_valuer)rirrrs r get_filenamezMessage.get_filenamePsd (>>*g7LM w ~~fg~FH w N++H5;;==rc t}|jd|}||ur|Stj|j S)Nboundary)rr rrr0)rirrrs r get_boundaryzMessage.get_boundary`sG (>>*g6 w N++H5<<>>rc t}|j|d}||urtjdg}d}|D]D\}}|j dk(r|j dd|zfd}2|j ||fF|s|j dd|zfg}|j D]\} } | j dk(rzg} |D]2\} } | dk(r| j | | j | d| 4tj| } |j |jj| | |j | | f||_y) NrzNo Content-Type header foundFrz"%s"Trr) rrrHeaderParseErrorr1r3rarrRr`r)rirrr newparamsfoundppkpvrhrrrrs r set_boundaryzMessage.set_boundarymsY (**7NC W ))*HI I FBxxzZ'  *fx.?!@A  "b*     j&8*;< = MMDAqwwyN*%DAqBw Q 1%56 &  nnU+!!$++"@"@C"HI!!1a&)"# rcV t}|jd|}||ur|St|tr*|dxsd} |dj d}t ||} |j d|jS#t tf$r|d}Y8wxYw#t$r|cYSwxYw)Nr rzus-asciirr) rr r"r#r%rrrr1)rirrr pcharsetr|s rrzMessage.get_content_charsets (..G4 g N gu %qz/ZH %#1:,,-ABh1  NN: &}} . %!!* %  N s# BBBB B('B(ch |jDcgc]}|j|c}Scc}wrl)walkr)rirparts r get_charsetszMessage.get_charsetss3 ?CiikJkd((1kJJJs/ch |jd}|yt|dj}|S)Nrr)rrr1)rir*c_ds rget_content_dispositionzMessage.get_content_dispositions= ./ =% #))+ r)r))FrN)FN)NFrl)NrT)rTNrF)rT)rT)3__name__ __module__ __qualname__r rjrormr}r|rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr rrrrrr%rr+r.email.iteratorsr)rrrrs ' * 0 /" : Zx&(-B^" H$ #- + + ",*$,< "&0##"#*,5C DFJ5:1%f%,2@> ?,#\<K$ %rceZdZdfd Zdfd ZdZdZdZddZhdZ d Z d Z dd d Z dd d Z dZddZddZddZdddZdZdZdZdZdZxZS)MIMEPartNc8|ddlm}|}t| |y)Nr)default) email.policyr7superrj)rir`r7 __class__s rrjzMIMEPart.__init__s > ,F  rcd | |jn|}| |j}t| |||Srl)r`max_line_lengthr9rm)rirursr`r:s rrmzMIMEPart.as_strings> !'F  !11Lw <@@rcZ|j|jjdS)NT)utf8r`)rmr`clonerns rrozMIMEPart.__str__s%~~T[[%6%6D%6%A~BBrcJ|jd}|dS|jdk(S)NrF attachment)rcontent_disposition)rir-s r is_attachmentzMIMEPart.is_attachments+hh,- uP)@)@L)PPrc#\K|jry|jjd\}}|dk(r||vr|j||fy|dk7s|j sy|dk7r0|j D]}|j ||Ed{yd|vr|jd|fd}|jd}|r!|j D]}|d|k(s |}n||j}|r|dnd}||j ||Ed{yy77w)Nrtext multipartrelatedr6 content-idr) rDrrindexr iter_parts _find_bodyr r) rir*preferencelistmaintypesubtypesubpart candidater6subpartss rrLzMIMEPart._find_bodysK      11399#>' v .(%++G4d;;  { "$*;*;*=  i ??,??7NCCC-   &!'' 2D9 9 w' ??,<(E1 'I-  '')H'/ TI  y.A A A !D Bs+BD,D(AD,*7D,!D*"D,*D,cz t|}d}|j||D]\}}||ks |}|}|dk(s|S|S)Nr)r!rL)rirM best_priobodyprior*s rget_bodyzMIMEPart.get_bodysZ ' //$?JD$i 19 @  r>rFhtmlrFplainrGrHrG alternativec#K |jjd\}}|dk7s|dk(ry|j} |j}|dk(rt|dk(ro|j d}|r@d}g}|D]*}|j d|k(rd}|j|,|r |Ed{y|jd |Ed{yg} |D]^}|jjd\}}||f|jvr&|js|| vr| j|[|`y#t$rYywxYw77|w) NrrGr^rHr6FrITr) rrrrrr rr3pop _body_typesrD) rirNrOrrr6r attachmentsr*seens riter_attachmentszMIMEPart.iter_attachments0sg !11399#>' { "g&> ""$ LLNE { "w)';NN7+E !Dxx -6 $#**40 " *** IIaL   D $ 5 5 7 = =c B Hg7#t'7'77**,1D G$J 7   $+ sI?ED1AE)E*EEA+E1 D=:E<D==EEc#dK |jr|jEd{yy7wrl)rrrns rrKzMIMEPart.iter_partsgs3     '') ) )  )s %0.0)content_managerc^||jj}|j|g|i|Srl)r`rf get_contentrirfargskws rrhzMIMEPart.get_contentos4  ""kk99O***4=$="==rc`||jj}|j|g|i|yrl)r`rf set_contentris rrmzMIMEPart.set_contentts1  ""kk99O###D64626rc$|jdk(r5|j}||fz}||vrtdj||g}g}|jD]K\}}|j j dr|j||f9|j||fM|r=t||j} || _|j| _ | g|_ ng|_ ||_d|z|d<||jd|yy)NrGzCannot convert {} to {}content-r?z multipart/rr) rrrNrrar1rKr3rr`rcr) rirOdisallowed_subtypesrexisting_subtype keep_headers part_headersrr*r*s r_make_multipartzMIMEPart._make_multipartys  $ $ &+ 5#779 "5 "B #66 !:!A!A$g"/00  ==KD%zz|&&z2##T5M2##T5M2 ) 4:T[[1D(DM MMDM!FDMDM$ +g5^   NN:x 0 rc*|jdd|y)NrH)r^mixedrtrirs r make_relatedzMIMEPart.make_relateds Y(@(Krc*|jdd|y)Nr^)rvrwrxs rmake_alternativezMIMEPart.make_alternatives ]JArc*|jdd|y)Nrvr3rwrxs r make_mixedzMIMEPart.make_mixeds Wb(3r)_dispc |jdk7s|j|k7rt|d|zt||j}|j |i||r d|vr||d<|j |y)NrGmake_r?rzContent-Disposition)rrgetattrrr`rmr)ri_subtyper~rjrkr*s r_add_multipartzMIMEPart._add_multiparts  % % '; 6((*h6 -GD'H, - /tDz-$%"% *$6*/D& ' Drc4|jdg|ddi|y)NrHr~inlinerrirjrks r add_relatedzMIMEPart.add_relateds!ICCHCCrc0|jdg|i|y)Nr^rrs radd_alternativezMIMEPart.add_alternativesM7D7B7rc4|jdg|ddi|y)Nrvr~rBrrs radd_attachmentzMIMEPart.add_attachments!GEdE,E"Erc g|_d|_yrl)rarcrns rclearzMIMEPart.clears  rc|jDcgc](\}}|jjds||f*c}}|_d|_ycc}}w)Nro)rar1rKrc)rinrs r clear_contentzMIMEPart.clear_contentsN,0MMBMDAq ! 4 4Z @QMB  Bs-Arl)FNN))rHrYr[)r/r0r1rjrmrorDrLrWrardrKrhrmrtryr{r}rrrrrr __classcell__r:s@rr5r5s!A CQB:(1K5n*26> 267 16LB459D8Frr5ceZdZfdZxZS)rc8t||i|d|vrd|d<yy)Nrr)r9rm)rirjrkr:s rrmzEmailMessage.set_contents, T(R(  %#(D  &r)r/r0r1rmrrs@rrrs ))r)NT)__all__rOreriorremailrremail._policybaser r rdemail._encoded_wordsr rrcompiler'rr+r<r?r\rr5rr3rrrs ? n % &%)      BJJ2 3   D4$#>K %K %\\w\~)8)r__pycache__/generator.cpython-312.opt-2.pyc000064400000042251152526700320014413 0ustar00 {|jS gdZddlZddlZddlZddlZddlmZddlmZm Z ddl m Z ddl m Z dZdZej d Zej d ej$Zej d Zej d ZGd dZGddeZdZGddeZeeej8dz ZdezZej>Zy)) GeneratorDecodedGeneratorBytesGeneratorN)deepcopy)StringIOBytesIO)_has_surrogates)HeaderWriteError_ z \r\n|\r|\nz^From z\r\n[^ \t]|\r[^ \n\t]|\n[^ \t]s\r\n[^ \t]|\r[^ \n\t]|\n[^ \t]ceZdZ ddddZdZddZdZdZdZd Z d Z d Z d Z d Z e ZdZdZdZdZeddZedZy)rNpolicycb ||dn |j}||_||_||_||_y)NT) mangle_from__fp _mangle_from_ maxheaderlenr)selfoutfprrrs (/usr/lib64/python3.12/email/generator.py__init__zGenerator.__init__&s> .  #)>4v7J7JL)( c:|jj|yN)rwriterss rrzGenerator.writeFs qrc |j |jn |j}||j|}|j|j|j}|j|_|j |j|_d|_|j |j|_|j}|j} ||_||_|rZ|j}|s*dtjtjz}|j||jz|j|||_||_y#||_||_wxYw)N)linesepmax_line_lengthz From nobody )rclonerr _NL_encode _encoded_NL_EMPTY_encoded_EMPTY get_unixfromtimectimer_write)rmsgunixfromr rold_gen_policyold_msg_policyufroms rflattenzGenerator.flattenJs* ( ${{2   \\'\2F    (\\$2C2C\DF>><<1 "ll4;;7  ( DKCJ((**TZZ -DDE 5488+, KK (DK'CJ)DK'CJs A;EE-cV |j||jd|jSNr) __class__rr)rfps rr$zGenerator.clone{s0?~~b"00"%)[[2 2rctSr)rrs r _new_bufferzGenerator._new_buffers zrc|Srrs rr&zGenerator._encodesrc|sytj|}|ddD].}|j||j|j0|dr|j|dyy)N)NLCREsplitrr%)rlineslines r _write_lineszGenerator._write_liness`  E"#2JD JJt  JJtxx  9 JJuRy ! rc |j} d|_|jx|_}|j|||_|j}|`|rOt |}|j d |d|d<n|j d|d|j d|dt|dd}||j|n|||jj|jy#||_|j}|`wxYw)Ncontent-transfer-encodingrContent-Transfer-Encoding content-type_write_headers) r _munge_cter: _dispatchrgetreplace_headergetattrrIrgetvalue)rr.oldfpsfp munge_ctemeths rr-zGenerator._writes "DO!--/ /DHs NN3 DHI 3-Cww23;3 ! M   ~y| <s,d3 <    $ J s||~&'DHIs /C66D c&|j}|j}tj||fj dd}t |d|zd}|0|j dd}t |d|zd}| |j }||y)N-r _handle_)get_content_maintypeget_content_subtype UNDERSCOREjoinreplacerN _writeBody)rr.mainsubspecificrSgenerics rrKzGenerator._dispatchs '')%%'??D#;/77SAtZ(2D9 <ll3,G4g!5tFrom ) get_payload isinstancestr TypeErrortyper _payload get_paramr set_payloadrJrfcrer^rC)rr.payloadros r _handle_textzGenerator._handle_texts//# ? '3'9DMIJ J 3<< (mmI.G"sm34 g6//+#&'B#C#&~#6#8   hhx1G '"rc0g}|j}|g}n5t|tr|j|yt|ts|g}|D]`}|j }|j |}|j|d|j|j|jb|j}|s=|jj|}|j|}|j||j e|j"r!t$j'd|j } n |j } |j)| |j|j|jd|z|jz|r*|j*j|j-d|D]K} |j|jdz|z|jz|j*j| M|j|jdz|zdz|jz|j.K|j"r!t$j'd|j.} n |j.} |j)| yy)NFr/r rpz--r)rqrrrsrlistr:r$r3r%appendrO get_boundaryr'rZ_make_boundary set_boundarypreamblerryr^rCrpopepilogue) rr.msgtextssubpartspartrgboundaryalltextr body_partrs r_handle_multipartzGenerator._handle_multipart s ??$  H # & JJx Hd+ zHD  "A 1 A IIdUDHHI = OOAJJL )  ##%&&++H5G**73H   X & << #!!88Hcll;<<   h ' JJtxx  4(?TXX-.  HHNN8<<? +"I JJtxx$1DHH< = HHNN9 % " 488d?X-4txx?@ << #!!88Hcll;<<   h ' $rc|j}|jd|_ |j|||_y#||_wxYw)Nrr!)rr$r)rr.ps r_handle_multipart_signedz"Generator._handle_multipart_signedGsA KKggag0    " "3 'DK!DKs > Acg}|jD]}|j}|j|}|j|d|j|j }|j |j}|r@|d|jk(r.|j|jj|dd|j||jj|jj|y)NFr}r>) rqr:r$r3r%rOr@r'r)rrZrr)rr.blocksrrrtextrAs r_handle_message_delivery_statusz)Generator._handle_message_delivery_statusRsOO%D  "A 1 A IIdUDHHI =::|j |j dd|j|j}n|j|}|jj|y)NrFr}) r:r$rvrrr~r3rqr%rOr&rr)rr.rrrzs r_handle_messagezGenerator._handle_messagegsz     JJqM,, gt $ IIcooa(5$((I KjjlGll7+G wrc@tjtj}dt|zzdz}||S|}d} |j dt j|zdzt j}|j|s |S|dzt|z}|dz }d)Nz===============z==rz^--z(--)?$.rH) random randrangesysmaxsize_fmt _compile_rereescape MULTILINErhrs)clsrtokenrbcountercres rrzGenerator._make_boundarys  -.5 <O //%"))A,"6"A2<<PC::d#3W-A qLG rc.tj||Sr)rcompilerrflagss rrzGenerator._compile_reszz!U##r)NN)FNr)__name__ __module__ __qualname__rrr3r$r:r&rCr-rKrIr{r\rrrr classmethodrrr<rrrrs@/(b2( " %'N( &#,J8(t 6* 2"$$rrcLeZdZ dZdZdZdZfdZeZe dZ xZ S)rcZ|jj|jddy)Nasciisurrogateescape)rrencoders rrzBytesGenerator.writes qxx):;#'#;#;#=#'#4#4_#E#'88,A,>$@#'88,G,;$= # ! "r)NNN)rrrrrKr<rrrrs <"rrrHz%%0%dd) __all__rrr+rcopyriorr email.utilsr email.errorsr rYNLrr?rryrgrrrrrlenreprr_widthrrr<rrrs A =  ')    =!rzz)R\\*!rzz"CD'RZZ(JKx$x$v 84Y84vN6"y6"t T#++a- !&))r__pycache__/generator.cpython-312.opt-1.pyc000064400000051362152526700320014415 0ustar00 {|jSdZgdZddlZddlZddlZddlZddlmZddlm Z m Z ddl m Z ddl mZdZd Zej"d Zej"d ej&Zej"d Zej"d ZGddZGddeZdZGddeZeeej:dz ZdezZej@Z y)z:Classes to generate plain text from a message object tree.) GeneratorDecodedGeneratorBytesGeneratorN)deepcopy)StringIOBytesIO)_has_surrogates)HeaderWriteError_ z \r\n|\r|\nz^From z\r\n[^ \t]|\r[^ \n\t]|\n[^ \t]s\r\n[^ \t]|\r[^ \n\t]|\n[^ \t]ceZdZdZddddZdZddZdZdZd Z d Z d Z d Z d Z dZeZdZdZdZdZeddZedZy)rzGenerates output from a Message object tree. This basic generator writes the message to the given file object as plain text. Npolicyc`||dn |j}||_||_||_||_y)aCreate the generator for message flattening. outfp is the output file-like object for writing the message to. It must have a write() method. Optional mangle_from_ is a flag that, when True (the default if policy is not set), escapes From_ lines in the body of the message by putting a `>' in front of them. Optional maxheaderlen specifies the longest length for a non-continued header. When a header line is longer (in characters, with tabs expanded to 8 spaces) than maxheaderlen, the header will split as defined in the Header class. Set maxheaderlen to zero to disable header wrapping. The default is 78, as recommended (but not required) by RFC 2822. The policy keyword specifies a policy object that controls a number of aspects of the generator's operation. If no policy is specified, the policy associated with the Message object passed to the flatten method is used. NT) mangle_from__fp _mangle_from_ maxheaderlenr)selfoutfprrrs (/usr/lib64/python3.12/email/generator.py__init__zGenerator.__init__&s92  #)>4v7J7JL)( c:|jj|yN)rwriterss rrzGenerator.writeFs qrc|j |jn |j}||j|}|j|j|j}|j|_|j |j|_d|_|j |j|_|j}|j} ||_||_|rZ|j}|s*dtjtjz}|j||jz|j|||_||_y#||_||_wxYw)aPrint the message object tree rooted at msg to the output file specified when the Generator instance was created. unixfrom is a flag that forces the printing of a Unix From_ delimiter before the first object in the message tree. If the original message has no From_ delimiter, a `standard' one is crafted. By default, this is False to inhibit the printing of any From_ delimiter. Note that for subobjects, no From_ line is printed. linesep specifies the characters used to indicate a new line in the output. The default value is determined by the policy specified when the Generator instance was created or, if none was specified, from the policy associated with the msg. N)linesepmax_line_lengthz From nobody )rclonerr _NL_encode _encoded_NL_EMPTY_encoded_EMPTY get_unixfromtimectimer_write)rmsgunixfromr rold_gen_policyold_msg_policyufroms rflattenzGenerator.flattenJs%* ${{2   \\'\2F    (\\$2C2C\DF>><<1 "ll4;;7  ( DKCJ((**TZZ -DDE 5488+, KK (DK'CJ)DK'CJs A;EE,cT|j||jd|jS)z1Clone this generator with the exact same options.Nr) __class__rr)rfps rr$zGenerator.clone{s-~~b"00"%)[[2 2rctSr)rrs r _new_bufferzGenerator._new_buffers zrc|Srrs rr&zGenerator._encodesrc|sytj|}|ddD].}|j||j|j0|dr|j|dyy)N)NLCREsplitrr%)rlineslines r _write_lineszGenerator._write_liness`  E"#2JD JJt  JJtxx  9 JJuRy ! rc |j} d|_|jx|_}|j|||_|j}|`|rOt |}|j d |d|d<n|j d|d|j d|dt|dd}||j|n|||jj|jy#||_|j}|`wxYw)Ncontent-transfer-encodingrContent-Transfer-Encoding content-type_write_headers) r _munge_cter9 _dispatchrgetreplace_headergetattrrHrgetvalue)rr.oldfpsfp munge_ctemeths rr-zGenerator._writes "DO!--/ /DHs NN3 DHI 3-Cww23;3 ! M   ~y| <s,d3 <    $ J s||~&'DHIs /C66D c&|j}|j}tj||fj dd}t |d|zd}|0|j dd}t |d|zd}| |j }||y)N-r _handle_)get_content_maintypeget_content_subtype UNDERSCOREjoinreplacerM _writeBody)rr.mainsubspecificrRgenerics rrJzGenerator._dispatchs '')%%'??D#;/77SAtZ(2D9 <ll3,G4g!5tFrom ) get_payload isinstancestr TypeErrortyper _payload get_paramr set_payloadrIrfcrer]rB)rr.payloadrns r _handle_textzGenerator._handle_texts//# ? '3'9DMIJ J 3<< (mmI.G"sm34 g6//+#&'B#C#&~#6#8   hhx1G '"rc0g}|j}|g}n5t|tr|j|yt|ts|g}|D]`}|j }|j |}|j|d|j|j|jb|j}|s=|jj|}|j|}|j||j e|j"r!t$j'd|j } n |j } |j)| |j|j|jd|z|jz|r*|j*j|j-d|D]K} |j|jdz|z|jz|j*j| M|j|jdz|zdz|jz|j.K|j"r!t$j'd|j.} n |j.} |j)| yy)NFr/r roz--r)rprqrrrlistr9r$r3r%appendrN get_boundaryr'rY_make_boundary set_boundarypreamblerrxr]rBrpopepilogue) rr.msgtextssubpartspartrgboundaryalltextr body_partrs r_handle_multipartzGenerator._handle_multipart s ??$  H # & JJx Hd+ zHD  "A 1 A IIdUDHHI = OOAJJL )  ##%&&++H5G**73H   X & << #!!88Hcll;<<   h ' JJtxx  4(?TXX-.  HHNN8<<? +"I JJtxx$1DHH< = HHNN9 % " 488d?X-4txx?@ << #!!88Hcll;<<   h ' $rc|j}|jd|_ |j|||_y#||_wxYw)Nrr!)rr$r)rr.ps r_handle_multipart_signedz"Generator._handle_multipart_signedGsA KKggag0    " "3 'DK!DKs > Acg}|jD]}|j}|j|}|j|d|j|j }|j |j}|r@|d|jk(r.|j|jj|dd|j||jj|jj|y)NFr|r=) rpr9r$r3r%rNr?r'r)r~rYrr)rr.blocksrrrtextr@s r_handle_message_delivery_statusz)Generator._handle_message_delivery_statusRsOO%D  "A 1 A IIdUDHHI =::|j |j dd|j|j}n|j|}|jj|y)NrFr|) r9r$rurqr}r3rpr%rNr&rr)rr.rrrys r_handle_messagezGenerator._handle_messagegsz     JJqM,, gt $ IIcooa(5$((I KjjlGll7+G wrc@tjtj}dt|zzdz}||S|}d} |j dt j|zdzt j}|j|s |S|dzt|z}|dz }d)Nz===============z==rz^--z(--)?$.rG) random randrangesysmaxsize_fmt _compile_rereescape MULTILINErgrr)clsrtokenrbcountercres rrzGenerator._make_boundarys  -.5 <O //%"))A,"6"A2<<PC::d#3W-A qLG rc.tj||Sr)rcompilerrflagss rrzGenerator._compile_reszz!U##r)NN)FNr)__name__ __module__ __qualname____doc__rrr3r$r9r&rBr-rJrHrzr[rrrr classmethodrrr;rrrrs@/(b2( " %'N( &#,J8(t 6* 2"$$rrcNeZdZdZdZdZdZdZfdZeZ e dZ xZ S)raGenerates a bytes version of a Message object tree. Functionally identical to the base Generator except that the output is bytes and not string. When surrogates were used in the input to encode bytes, these are decoded back to bytes for output. If the policy has cte_type set to 7bit, then the message is transformed such that the non-ASCII bytes are properly content transfer encoded, using the charset unknown-8bit. The outfp object must accept bytes in its write method. cZ|jj|jddy)Nasciisurrogateescape)rrencoders rrzBytesGenerator.writes qxx):;#'#;#;#=#'#4#4_#E#'88,A,>$@#'88,G,;$= # ! "r)NNN)rrrrrrJr;rrrrs <"rrrGz%%0%dd)!r__all__rrr+rcopyriorr email.utilsr email.errorsr rXNLrr>rrxrfrrrrrlenreprr_widthrrr;rrrs A =  ')    =!rzz)R\\*!rzz"CD'RZZ(JKx$x$v 84Y84vN6"y6"t T#++a- !&))r__pycache__/_header_value_parser.cpython-312.pyc000064400000405456152526700320015636 0ustar00 {|jE dZddlZddlZddlZddlmZddlmZddlm Z ddlm Z ddlm Z e dZee d zZe d ZeezZee d z Zee d z Zee d ze d z ZeezZee dzZeezZee dz ZddhZeezZdZdZdZej<dej>ej@zZ!Gdde"Z#Gdde#Z$Gdde#Z%Gdde#Z&Gdde#Z'Gd d!e$Z(Gd"d#e#Z)Gd$d%e#Z*Gd&d'e#Z+Gd(d)e#Z,Gd*d+e,Z-Gd,d-e$Z.Gd.d/e#Z/Gd0d1e#Z0Gd2d3e#Z1Gd4d5e#Z2Gd6d7e#Z3Gd8d9e#Z4Gd:d;e#Z5Gd<d=e#Z6Gd>d?e#Z7Gd@dAe#Z8GdBdCe#Z9GdDdEe#Z:GdFdGe#Z;GdHdIe#Z<GdJdKe#Z=GdLdMe#Z>GdNdOe&Z?GdPdQe#Z@GdRdSe#ZAGdTdUe#ZBGdVdWe#ZCGdXdYeCZDGdZd[e#ZEGd\d]e#ZFGd^d_e#ZGGd`dae#ZHGdbdce#ZIGdddeeIZJGdfdgeIZKGdhdie#ZLGdjdke#ZMGdldme#ZNGdndoeNZOGdpdqeOZPGdrdse#ZQGdtdueRZSGdvdweSZTGdxdyeSZUGdzd{eTZVGd|d}e jZXeUd d~ZYeUddZZdeZ_[deZ_\eUddZ]ej<djdjejZaej<djejdjejZdej<djZfej<djejdjejZgej<djejdjejZhej<djejdjejZidZjdZkdZlddZmdZndZodZpdZqdZrdZsdZtdZudZvdZwdZxdZydZzdZ{dZ|dZ}dZ~dZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZy)alHeader value parser implementing various email-related RFC parsing rules. The parsing methods defined in this module implement various email related parsing rules. Principal among them is RFC 5322, which is the followon to RFC 2822 and primarily a clarification of the former. It also implements RFC 2047 encoded word decoding. RFC 5322 goes to considerable trouble to maintain backward compatibility with RFC 822 in the parse phase, while cleaning up the structure on the generation phase. This parser supports correct RFC 5322 generation by tagging white space as folding white space only when folding is allowed in the non-obsolete rule sets. Actually, the parser is even more generous when accepting input than RFC 5322 mandates, following the spirit of Postel's Law, which RFC 5322 encourages. Where possible deviations from the standard are annotated on the 'defects' attribute of tokens that deviate. The general structure of the parser follows RFC 5322, and uses its terminology where there is a direct correspondence. Where the implementation requires a somewhat different structure than that used by the formal grammar, new terms that mimic the closest existing terms are used. Thus, it really helps to have a copy of RFC 5322 handy when studying this code. Input to the parser is a string that has already been unfolded according to RFC 5322 rules. According to the RFC this unfolding is the very first step, and this parser leaves the unfolding step to a higher level message parser, which will have already detected the line breaks that need unfolding while determining the beginning and end of each header. The output of the parser is a TokenList object, which is a list subclass. A TokenList is a recursive data structure. The terminal nodes of the structure are Terminal objects, which are subclasses of str. These do not correspond directly to terminal objects in the formal grammar, but are instead more practical higher level combinations of true terminals. All TokenList and Terminal objects have a 'value' attribute, which produces the semantically meaningful value of that part of the parse subtree. The value of all whitespace tokens (no matter how many sub-tokens they may contain) is a single space, as per the RFC rules. This includes 'CFWS', which is herein included in the general class of whitespace tokens. There is one exception to the rule that whitespace tokens are collapsed into single spaces in values: in the value of a 'bare-quoted-string' (a quoted-string with no leading or trailing whitespace), any whitespace that appeared between the quotation marks is preserved in the returned value. Note that in all Terminal strings quoted pairs are turned into their unquoted values. All TokenList and Terminal objects also have a string value, which attempts to be a "canonical" representation of the RFC-compliant form of the substring that produced the parsed subtree, including minimal use of quoted pair quoting. Whitespace runs are not collapsed. Comment tokens also have a 'content' attribute providing the string found between the parens (including any nested comments) with whitespace preserved. All TokenList and Terminal objects have a 'defects' attribute which is a possibly empty list all of the defects found while creating the token. Defects may appear on any token in the tree, and a composite list of all defects in the subtree is available through the 'all_defects' attribute of any node. (For Terminal notes x.defects == x.all_defects.) Each object in a parse tree is called a 'token', and each has a 'token_type' attribute that gives the name from the RFC 5322 grammar that it represents. Not all RFC 5322 nodes are produced, and there is one non-RFC 5322 node that may be produced: 'ptext'. A 'ptext' is a string of printable ascii characters. It is returned in place of lists of (ctext/quoted-pair) and (qtext/quoted-pair). XXX: provide complete list of token types. N) hexdigits) itemgetter)_encoded_words)errors)utilsz (z ()<>@,:;.\"[].z."(z/?=z*'%%  cXt|jddjddS)z;Escape dquote and backslash for use within a quoted-string.\\\"z\"strreplacevalues 3/usr/lib64/python3.12/email/_header_value_parser.pymake_quoted_pairsrcs& u:  dF + 3 3C ??cxt|jddjddjddS)z:Escape parenthesis and backslash for use within a comment.rrr\()\)rrs rmake_parenthesis_pairsrhs2 u:  dF + e WWS%01rc$t|}d|dS)Nr)r)rescapeds r quote_stringr ns&G wiq>rz =\? # literal =? [^?]* # charset \? # literal ? [qQbB] # literal 'q' or 'b', case insensitive \? # literal ? .*? # encoded word \?= # literal ?= ceZdZdZdZdZfdZdZfdZe dZ e dZ dZ e d Z e d Zd Zdd Zdd ZddZxZS) TokenListNTc2t||i|g|_yN)super__init__defects)selfargskw __class__s rr&zTokenList.__init__s $%"% rc2djd|DS)Nc32K|]}t|ywr$r.0xs r z$TokenList.__str__..,t!s1vtjoinr(s r__str__zTokenList.__str__sww,t,,,rchdj|jjt|SNz{}({})formatr+__name__r%__repr__r(r+s rr?zTokenList.__repr__s+t~~66"W-/1 1rc2djd|DS)Nr-c3NK|]}|js|jywr$rr0s rr3z"TokenList.value..s81qwws%%r6r8s rrzTokenList.valuesww8888rc<td|D|jS)Nc34K|]}|jywr$) all_defectsr0s rr3z(TokenList.all_defects..s04aAMM4)sumr'r8s rrEzTokenList.all_defectss040$,,??rc(|djSNr)startswith_fwsr8s rrJzTokenList.startswith_fwssAw%%''rc&td|DS)zATrue if all top level tokens of this part may be RFC2047 encoded.c34K|]}|jywr$) as_ew_allowed)r1parts rr3z*TokenList.as_ew_allowed..s7$$4%%$rF)allr8s rrMzTokenList.as_ew_alloweds7$777rcNg}|D]}|j|j|Sr$)extendcomments)r(rRtokens rrRzTokenList.commentss&E OOENN +rct||S)Npolicy)_refold_parse_treer(rVs rfoldzTokenList.folds!$v66rc:t|j|y)Nindent)printppstrr(r\s rpprintzTokenList.pprints djjj'(rcDdj|j|S)Nr r[)r7_ppr_s rr^zTokenList.ppstrsyy011rc#~Kdj||jj|j|D]A}t |ds|dj|z&|j |dzEd{C|j rdj|j }nd}dj||y7Ew)Nz{}{}/{}(rbz* !! invalid element in token list: {!r}z z Defects: {}r-z{}){})r=r+r> token_typehasattrrbr')r(r\rSextras rrbz TokenList._pps  NN # # OO E5%(!55;VE]CD!99VF]333  <<"))$,,7EEnnVU++ 4sA3B=5B;6AB=r-)r> __module__ __qualname__rdsyntactic_breakew_combine_allowedr&r9r?propertyrrErJrMrRrYr`r^rb __classcell__r+s@rr"r"sJO-199@@(88 7)2,rr"c,eZdZedZedZy)WhiteSpaceTokenListcyN r8s rrzWhiteSpaceTokenList.valuerc`|Dcgc]}|jdk(s|j c}Scc}w)Ncomment)rdcontentr(r2s rrRzWhiteSpaceTokenList.commentss)#'C4a1<<+B 4CCC++N)r>rhrirlrrRrtrrrprps* DDrrpceZdZdZy)UnstructuredTokenList unstructuredNr>rhrirdrtrrr|r|sJrr|ceZdZdZy)PhrasephraseNr~rtrrrrJrrceZdZdZy)WordwordNr~rtrrrrJrrceZdZdZy)CFWSListcfwsNr~rtrrrrrrrceZdZdZy)AtomatomNr~rtrrrrrrrceZdZdZdZy)TokenrSFN)r>rhrird encode_as_ewrtrrrrs JLrrceZdZdZdZdZdZy) EncodedWord encoded-wordN)r>rhrirdctecharsetlangrtrrrrsJ CG Drrc@eZdZdZedZedZedZy) QuotedString quoted-stringcL|D]}|jdk(s|jcSyNbare-quoted-stringrdrrys rrxzQuotedString.contents"A||33wwrcg}|D]G}|jdk(r|jt|-|j|jIdj |S)Nrr-)rdappendrrr7)r(resr2s r quoted_valuezQuotedString.quoted_valuesNA||33 3q6" 177#  wws|rcL|D]}|jdk(s|jcSyrrr(rSs rstripped_valuezQuotedString.stripped_values%E#77{{"rN)r>rhrirdrlrxrrrtrrrrsA J  ##rrc&eZdZdZdZedZy)BareQuotedStringrcDtdjd|DS)Nr-c32K|]}t|ywr$r/r0s rr3z+BareQuotedString.__str__..s#9DqCFDr5)r r7r8s rr9zBareQuotedString.__str__sBGG#9D#99::rc2djd|DS)Nr-c32K|]}t|ywr$r/r0s rr3z)BareQuotedString.value..r4r5r6r8s rrzBareQuotedString.valueww,t,,,rN)r>rhrirdr9rlrrtrrrr s %J;--rrc<eZdZdZdZdZedZedZy)Commentrwc djtdg|Dcgc]}|j|c}dgggScc}w)Nr-rr)r7rGquoterys rr9zComment.__str__sKwws E489DqTZZ]D9 E " #$ $9s>c|jdk(r t|St|jddjddjddS)Nrwrrrrrr)rdrr)r(rs rrz Comment.quote"sR   y (u: 5z!!$/77"%u..5g"%u/. .rc2djd|DS)Nr-c32K|]}t|ywr$r/r0s rr3z"Comment.content..+r4r5r6r8s rrxzComment.content)rrc|jgSr$)rxr8s rrRzComment.comments-s ~rN) r>rhrirdr9rrlrxrRrtrrrrs9J$.--rrc@eZdZdZedZedZedZy) AddressListz address-listcL|Dcgc]}|jdk(s|c}Scc}w)Naddressrdrys r addresseszAddressList.addresses5%;4a1<<#:4;;;!!c(td|DgS)Nc3RK|]}|jdk(r|j!ywrNrd mailboxesr0s rr3z(AddressList.mailboxes..;s'>!Q\\9%<KK!%'rGr8s rrzAddressList.mailboxes9!>!>?AC Crc(td|DgS)Nc3RK|]}|jdk(r|j!ywrrd all_mailboxesr0s rr3z,AddressList.all_mailboxes..@s'>!Q\\9%<OO!rrr8s rrzAddressList.all_mailboxes>rrN)r>rhrirdrlrrrrtrrrr1sEJ <<CCCCrrc@eZdZdZedZedZedZy)AddressrcF|djdk(r|djSy)Nrgrouprd display_namer8s rrzAddress.display_nameHs) 7   (7'' ' )rcx|djdk(r|dgS|djdk(rgS|djSNrmailboxinvalid-mailboxrr8s rrzAddress.mailboxesMsH 7   *G9  !W  #4 4IAw   rc|djdk(r|dgS|djdk(r|dgS|djSrrr8s rrzAddress.all_mailboxesUsO 7   *G9  !W  #4 4G9 Aw$$$rN)r>rhrirdrlrrrrtrrrrDsAJ ((!!%%rrc0eZdZdZedZedZy) MailboxList mailbox-listcL|Dcgc]}|jdk(s|c}Scc}w)Nrrrys rrzMailboxList.mailboxesarrcH|Dcgc]}|jdvr|c}Scc}w)N)rrrrys rrzMailboxList.all_mailboxeses2?4a||==4? ??sNr>rhrirdrlrrrtrrrr]s-J <<??rrc0eZdZdZedZedZy) GroupList group-listcL|r|djdk7rgS|djSNrrrr8s rrzGroupList.mailboxesos+tAw))^;IAw   rcL|r|djdk7rgS|djSrrr8s rrzGroupList.all_mailboxesus+tAw))^;IAw$$$rNrrtrrrrks-J !! %%rrc@eZdZdZedZedZedZy)GrouprcH|djdk7rgS|djSNrrr8s rrzGroup.mailboxess) 7   -IAw   rcH|djdk7rgS|djSrrr8s rrzGroup.all_mailboxess) 7   -IAw$$$rc |djSrI)rr8s rrzGroup.display_namesAw###rN)r>rhrirdrlrrrrtrrrr|sAJ !! %% $$rrc`eZdZdZedZedZedZedZedZ y)NameAddr name-addrc>t|dk(ry|djSNr)lenrr8s rrzNameAddr.display_names t9>Aw###rc |djSN local_partr8s rrzNameAddr.local_partsBx"""rc |djSrdomainr8s rrzNameAddr.domainsBxrc |djSr)router8s rrzNameAddr.routesBx~~rc |djSr addr_specr8s rrzNameAddr.addr_specsBx!!!rN r>rhrirdrlrrrrrrtrrrrsiJ $$ ##""rrcPeZdZdZedZedZedZedZy) AngleAddrz angle-addrcL|D]}|jdk(s|jcSyN addr-spec)rdrrys rrzAngleAddr.local_parts"A||{*||#rcL|D]}|jdk(s|jcSyrrdrrys rrzAngleAddr.domains!A||{*xxrcL|D]}|jdk(s|jcSy)N obs-route)rddomainsrys rrzAngleAddr.routes"A||{*yy rc|D]O}|jdk(s|jr|jcSt|j|jzcSy)Nrz<>)rdrrr rys rrzAngleAddr.addr_specsFA||{*<<;;&' 5 CC rN) r>rhrirdrlrrrrrtrrrrsUJ $$   !! rrc eZdZdZedZy)ObsRouterc`|Dcgc]}|jdk(s|j c}Scc}w)Nrrrys rrzObsRoute.domainss)"&C$Q!,,(*B$CCCrzN)r>rhrirdrlrrtrrrrsJ DDrrc`eZdZdZedZedZedZedZedZ y)MailboxrcF|djdk(r|djSyNrrrr8s rrzMailbox.display_names) 7   ,7'' ' -rc |djSrIrr8s rrzMailbox.local_partAw!!!rc |djSrIrr8s rrzMailbox.domainsAw~~rcF|djdk(r|djSyr )rdrr8s rrz Mailbox.routes' 7   ,7==  -rc |djSrIrr8s rrzMailbox.addr_specsAw   rNrrtrrr r siJ ((""!!!!rr c0eZdZdZedZexZxZxZZ y)InvalidMailboxrcyr$rtr8s rrzInvalidMailbox.display_namerNrrtrrrrs/"J /;:J::%)rrc0eZdZdZdZefdZxZS)DomainrFcRdjt|jSNr-r7r%rsplitr@s rrz Domain.domainwwuw}**,--r)r>rhrirdrMrlrrmrns@rrrsJM ..rrceZdZdZy)DotAtomdot-atomNr~rtrrrrsJrrceZdZdZdZy) DotAtomTextz dot-atom-textTNr>rhrirdrMrtrrr r  s  JMrr ceZdZdZdZy) NoFoldLiteralzno-fold-literalFNr!rtrrr#r#s "JMrr#cTeZdZdZdZedZedZedZedZ y)AddrSpecrFc |djSrIrr8s rrzAddrSpec.local_partr rc>t|dkry|djS)Nr)rrr8s rrzAddrSpec.domains t9q=Bxrct|dkr|djS|djj|djz|djjzS)Nr(rrr)rrrstriplstripr8s rrzAddrSpec.value$sU t9q=7== Aw}}##%d1gmm3DGMM4H4H4JJJrct|j}t|t|tz kDrt |j}n |j}|j |dz|j zS|S)N@)setrr DOT_ATOM_ENDSr r)r(namesetlps rrzAddrSpec.addr_spec*s_doo& w<#gm34 4doo.BB ;; "8dkk) ) rN) r>rhrirdrMrlrrrrrtrrr%r%s\JM "" KK rr%ceZdZdZdZy) ObsLocalPartzobs-local-partFNr!rtrrr3r36s !JMrr3c@eZdZdZdZedZefdZxZS) DisplayNamez display-nameFct|}t|dk(r |jS|djdk(r|j dneOC$Q""f,47I.Q %%/R##v-48Y/R ''61|D$5$566t; ;7= r) r>rhrirdrkrlrrrmrns@rr5r5<s4J $!!rr5c4eZdZdZdZedZedZy) LocalPartz local-partFcb|djdk(r|djS|djS)Nrr)rdrrr8s rrzLocalPart.valueqs2 7   07'' '7== rctg}t}d}|dtgzD]}|jdk(r|r2|jdk(r#|djdk(rt|dd|d<t|t}|r?|jdk(r0|djdk(r|j t|ddn|j ||d}|}t|dd}|j S)NFrrdotrr)DOTrdr"r8rr)r(rlast last_is_tltokis_tls rrzLocalPart.local_partxse 7cU?C~~'s~~6H''61#D"I.BsI.E$//U2F%%/ 9SW-. 3r7DJ#Ab "yyrN)r>rhrirdrMrlrrrtrrr=r=ls2JM !! rr=c@eZdZdZdZefdZedZxZS) DomainLiteralzdomain-literalFcRdjt|jSrrr@s rrzDomainLiteral.domainrrcL|D]}|jdk(s|jcSy)Nptextrrys ripzDomainLiteral.ips!A||w&wwr) r>rhrirdrMrlrrKrmrns@rrGrGs3!JM ..rrGceZdZdZdZdZy) MIMEVersionz mime-versionN)r>rhrirdmajorminorrtrrrMrMsJ E ErrMc<eZdZdZdZdZdZedZedZ y) Parameter parameterFus-asciic<|jr|djSdSr) sectionednumberr8s rsection_numberzParameter.section_numbers"&tAw~~6Q6rc|D]n}|jdk(r|jcS|jdk(s0|D]:}|jdk(s|D]#}|jdk(s|jcccS<py)Nrrrr-)rdrrs r param_valuezParameter.param_valuesxE7*+++?2"E''+??%*E$//7:',';'; ;&+# rN) r>rhrirdrUextendedrrlrWrYrtrrrQrQs<JIHG 77   rrQceZdZdZy)InvalidParameterinvalid-parameterNr~rtrrr\r\s$Jrr\c eZdZdZedZy) Attribute attributecd|D]+}|jjds|jcSy)Nattrtext)rdendswithrrs rrzAttribute.stripped_values*E((4{{"rNr>rhrirdrlrrtrrr_r_sJ ##rr_ceZdZdZdZy)SectionsectionN)r>rhrirdrVrtrrrfrfs J Frrfc eZdZdZedZy)Valuerc|d}|jdk(r|d}|jjdr |jS|jS)Nrrr)rr`zextended-attribute)rdrcrrrs rrzValue.stripped_valuesPQ   v %GE    $ $D F'' 'zzrNrdrtrrririsJ rric*eZdZdZdZedZdZy)MimeParametersmime-parametersFc#lKi}|D]w}|jjds|djdk7r2|djj}||vrg||<||j |j |fy|j D]\}}t|td}|dd}|j}|jsRt|dkDrD|dddk(r9|ddjj tjd|dd}g}d}|D]\} } | |k7ri| js/| jj tjdG| jj tjd|dz }| j} | jrv t j"j%| } | j'|d } t-j.| r.| jj tj0 |j | d j5|} || fy#t(t*f$r| j'd d } YwxYw#t*$r$t j"j3| d } YwxYww)NrRrr`)keyrz.duplicate parameter name; duplicate(s) ignoredz+duplicate parameter name; duplicate ignoredz(inconsistent RFC2231 parameter numberingsurrogateescaperSzlatin-1)encodingr-)rdrcrstriprrWitemssortedrrrZrr'rInvalidHeaderDefectrYurllibparseunquote_to_bytesdecode LookupErrorUnicodeEncodeErrorr_has_surrogatesUndecodableBytesDefectunquoter7) r(paramsrSnameparts first_paramr value_partsirWparamrs rrzMimeParameters.paramssE##,,[9Qx""k18>>'')D6!!t 4L  !5!5u = >"<<>KD%5jm4E(1+K!))G''CJN8A;!#!HQK''..v/I/IH0JK!"1IEKA).%!Q&!>> ,,V-G-GI.KL  ,,V-G-GF.HIQ))>>R & = =e DP$)LL:K$LE!007!MM001N1N1PQ""5)C*/DGGK(E+ g*R!,-?@P %*LL=N$OE P.P!' 4 4UY 4 O PsIF6J49JI+A2J4!J>J4JJ4*J1.J40J11J4c g}|jD]C\}}|r+|jdj|t|3|j|Edj |}|rd|zSdS)N{}={}z; rsr-)rrr=r r7)r(rrrs rr9zMimeParameters.__str__2se;;KD% gnnT<3FGH d# ' 6"%sV|-2-rN)r>rhrirdrjrlrr9rtrrrlrls&"JO CCJ.rrlc eZdZdZedZy)ParameterizedHeaderValueFc`t|D]}|jdk(s|jcSiS)Nrm)reversedrdrrs rrzParameterizedHeaderValue.paramsCs0d^E#44||#$ rN)r>rhrirjrlrrtrrrr=sO rrceZdZdZdZdZdZy) ContentTypez content-typeFtextplainN)r>rhrirdrMmaintypesubtypertrrrrKsJMHGrrceZdZdZdZdZy)ContentDispositionzcontent-dispositionFN)r>rhrirdrMcontent_dispositionrtrrrrRs&JMrrceZdZdZdZdZy)ContentTransferEncodingzcontent-transfer-encodingF7bitN)r>rhrirdrMrrtrrrrXs,JM CrrceZdZdZdZy) HeaderLabelz header-labelFNr!rtrrrr^s JMrrceZdZdZdZdZy)MsgIDzmsg-idFc2t||jzSr$)rlineseprXs rrYz MsgID.foldgs4y6>>))rN)r>rhrirdrMrYrtrrrrcsJM*rrceZdZdZy) MessageIDz message-idNr~rtrrrrlsJrrceZdZdZy)InvalidMessageIDzinvalid-message-idNr~rtrrrrps%JrrceZdZdZy)HeaderheaderNr~rtrrrrtrrrcreZdZdZdZdZfdZfdZdZe dZ d fd Z dZ e dZ d ZxZS) TerminalTcDt|||}||_g|_|Sr$)r%__new__rdr')clsrrdr(r+s rrzTerminal.__new__s&wsE*$  rchdj|jjt|Sr;r<r@s rr?zTerminal.__repr__s&t~~668H8JKKrcbt|jjdz|jzy)N/)r]r+r>rdr8s rr`zTerminal.pprints" dnn%%+doo=>rc,t|jSr$)listr'r8s rrEzTerminal.all_defectssDLL!!rc dj||jj|jt||j sdgSdj|j gS)Nz {}{}/{}({}){}r-z {})r=r+r>rdr%r?r')r(r\r+s rrbz Terminal._ppsg&&  NN # # OO G  llB   ). T\\(B  rcyr$rtr8s rpop_trailing_wszTerminal.pop_trailing_wsrrcgSr$rtr8s rrRzTerminal.commentss rc0t||jfSr$)rrdr8s r__getnewargs__zTerminal.__getnewargs__s4y$//**rrg)r>rhrirMrkrjrr?r`rlrErbrrRrrmrns@rrr|sZMO L?""+rrc"eZdZedZdZy)WhiteSpaceTerminalcyrrrtr8s rrzWhiteSpaceTerminal.valuerurc |xr |dtvSrIWSPr8s rrJz!WhiteSpaceTerminal.startswith_fwss&Q3&rNr>rhrirlrrJrtrrrrs 'rrc"eZdZedZdZy) ValueTerminalc|Sr$rtr8s rrzValueTerminal.values rcy)NFrtr8s rrJzValueTerminal.startswith_fwssrNrrtrrrrs rrc"eZdZedZdZy)EWWhiteSpaceTerminalcyrrtr8s rrzEWWhiteSpaceTerminal.valuesrcyrrtr8s rr9zEWWhiteSpaceTerminal.__str__srN)r>rhrirlrr9rtrrrrs rrceZdZdZy)_InvalidEwErrorz1Invalid encoded word found while parsing headers.N)r>rhri__doc__rtrrrrs;rrr@,zlist-separatorFr-zroute-component-markerz([{}]+)r-z[^{}]+z[\x00-\x20\x7F]ct|}|r.|jjtj|t j |r/|jjtjdyy)z@If input token contains ASCII non-printables, register a defect.z*Non-ASCII characters found in header tokenN)_non_printable_finderr'rrNonPrintableDefectrr|r})xtextnon_printabless r_validate_xtextrsc+51N V66~FG U# V:: 8: ;$rc"t|d^}}g}d}d}tt|D]6}||dk(r |rd}d}nd}|rd}n |||vrn|j||8dz}dj |dj ||dg|z|fS)akScan printables/quoted-pairs until endchars and return unquoted ptext. This function turns a run of qcontent, ccontent-without-comments, or dtext-with-quoted-printables into a single string by unquoting any quoted printables. It returns the string, the remaining value, and a flag that is True iff there were any quoted printables decoded. rFrTr-N) _wsp_splitterrangerrr7)rendcharsfragment remaindervcharsescapehad_qpposs r_get_ptext_to_endcharsrs)2Hy F F FS]# C=D  F c]h &  hsm$$Ag 776?BGGXcd^$4y$@A6 IIrcr|j}t|dt|t|z d}||fS)zFWS = 1*WSP This isn't the RFC definition. We're using fws to represent tokens where folding can be done, but when we are parsing the *un*folding has already been done so we don't need to watch out for CRLF. Nfws)r+rr)rnewvaluers rget_fwsrs:||~H U#@ @ABioodA.OC) eABi%% 0 7 7 >@ @ WWY F F aq Yq Y #!<<a0yDj4 399;! &44 ,. / BF GGI E@'*zz$*t2C'D$gtWBJBGJJg  7c>!$-KE4 IIe  )$2 e]3 %wwy!  q$ &44 <> ? u9)  !@ / 6 6rvv >@ @@s I 4I>c t}|r[|dtvr t|\}}|j|.d}|j dr t |d\}}d}t |dkDrB|djdk7r0|jjtjdd}|r2t |d kDr$|d jd k(rt|dd|d<|j|t|d ^}}|r(tj!|r|j#d^}}t%|d}t'||j|d j)|}|r[|S#t$rd}Ytj$rYwxYw) aOunstructured = (*([FWS] vchar) *WSP) / obs-unstruct obs-unstruct = *((*LF *CR *(obs-utext) *LF *CR)) / FWS) obs-utext = %d0 / obs-NO-WS-CTL / LF / CR obs-NO-WS-CTL is control characters except WSP/CR/LF. So, basically, we have printable runs, plus control characters or nulls in the obsolete syntax, separated by whitespace. Since RFC 2047 uses the obsolete syntax in its specification, but requires whitespace on either side of the encoded words, I can see no reason to need to separate the non-printable-non-whitespace from the printable runs if they occur, so we parse this into xtext tokens separated by WSP tokens. Because an 'unstructured' value must by definition constitute the entire value, this 'get' routine does not return a remaining value, only the parsed TokenList. rTrutextrrz&missing whitespace before encoded wordFrrr-)r|rrrrrrrdr'rrurrrrrfc2047_matchersearch partitionrrr7)rr}rSvalid_ewhave_wsrDrrs rget_unstructuredrWs.)*L  8s?"5>LE5    &    D ! /w? u|$q(#B'22e;$,,33F4N4ND5FG"'s<014#B'22nD+?(,e,5 R(##E*'q1i ..s3#ood3OC)c7+E" "Q R A# ! **  s E++ F 8F  F cXt|d\}}}t|d}t|||fS)actext = This is not the RFC ctext, since we are handling nested comments in comment and unquoting quoted-pairs here. We allow anything except the '()' characters, but if we find any ASCII other than the RFC defined printable ASCII, a NonPrintableDefect is added to the token's defects list. Since quoted pairs are converted to their unquoted values, what is returned is a 'ptext' token. In this case it is a WhiteSpaceTerminal, so it's value is ' '. z()rJ)rrrrrJ_s r get_qp_ctextrs4-UD9OE5! ug .EE %<rcXt|d\}}}t|d}t|||fS)aoqcontent = qtext / quoted-pair We allow anything except the DQUOTE character, but if we find any ASCII other than the RFC defined printable ASCII, a NonPrintableDefect is added to the token's defects list. Any quoted pairs are converted to their unquoted values, so what is returned is a 'ptext' token. In this case it is a ValueTerminal. rrJ)rrrrs r get_qcontentrs4-UC8OE5! % )EE %<rct|}|s$tjdj||j }|t |d}t |d}t|||fS)zatext = We allow any non-ATOM_ENDS in atext, but add an InvalidATextDefect to the token's defects list if we find non-atext characters. zexpected atext but found '{}'Natext)_non_atom_end_matcherrrr=rrrr)rmrs r get_atextrsk e$A %% + 2 25 9; ; GGIE #e*+ E % )EE %<rcN|r|ddk7r$tjdj|t}|dd}|r'|ddk(rt |\}}|j ||r|ddk7r|dt vrt|\}}n|dddk(rd} t|\}}|jj tjd d }|rSt|dkDrE|d jd k(r3|d jdk(r!t|d d |d <nt |\}}|j ||r |ddk7r|s2|jj tjd||fS||ddfS#tj$rt |\}}YwxYw)zbare-quoted-string = DQUOTE *([FWS] qcontent) [FWS] DQUOTE A quoted-string without the leading or trailing white space. Its value is the text between the quote marks, with whitespace preserved and quoted pairs decoded. rrzexpected '"' but found '{}'rNrrFz!encoded word inside quoted stringTrrrrz"end of header inside quoted string)rrr=rrrrrrr'rurrdr)rbare_quoted_stringrSrs rget_bare_quoted_stringrs E!HO%% * 1 1% 8: :)+ !"IE qS#E* u!!%( E!HO 8s?"5>LE5 2AY$ H 3/6 u"**11&2L2L739: C 23a7&r*55>*2.99^K-A*2..7&r*(.LE5!!%(+ E!HO, ""))&*D*D 0+2 3!5(( uQRy ((!** 3+E2 u 3s>F!F$#F$c|r,|ddk7r$tjdj|t}|dd}|rc|ddk7r[|dtvrt |\}}n%|ddk(rt |\}}nt|\}}|j||r |ddk7r[|s2|jjtjd||fS||ddfS)zcomment = "(" *([FWS] ccontent) [FWS] ")" ccontent = ctext / quoted-pair / comment We handle nested comments here, and quoted-pair in our qp-ctext routine. rrzexpected '(' but found '{}'rNrzend of header inside comment) rrr=rrr get_commentrrr'ru)rrwrSs rrrs  qS%% ) 0 0 79 9iG !"IE E!HO 8s?"5>LE5 1X_&u-LE5'.LE5u E!HO v99 * , -~ E!"I rct}|rR|dtvrG|dtvrt|\}}nt |\}}|j ||r |dtvrG||fS)z,CFWS = (1*([FWS] comment) [FWS]) / FWS r)r CFWS_LEADERrrrr)rrrSs rget_cfwsrsg :D E!H + 8s?"5>LE5&u-LE5 E E!H + ;rc t}|r*|dtvrt|\}}|j|t |\}}|j||r*|dtvrt|\}}|j|||fS)zquoted-string = [CFWS] [CFWS] 'bare-quoted-string' is an intermediate class defined by this parser and not by the RFC grammar. It is the quoted string without any attached CFWS. r)rrrrr)r quoted_stringrSs rget_quoted_stringr s!NM q[( uU#)%0LE5 q[( uU# % rct}|r*|dtvrt|\}}|j||r/|dtvr$t j dj||jdr t|\}}nt|\}}|j||r*|dtvrt|\}}|j|||fS#t j $rt|\}}YdwxYw)zPatom = [CFWS] 1*atext [CFWS] An atom could be an rfc2047 encoded word. rzexpected atom but found '{}'r) rrrr ATOM_ENDSrrr=rrr)rrrSs rget_atomr-s 6D q[( u E qY&%% * 1 1% 8: :  ,+E2LE5 !' uKK q[( u E ;&& ,%U+LE5 ,s:C!C<;C<ct}|r |dtvr$tjdj ||r\|dtvrQt |\}}|j ||r"|ddk(r|j t|dd}|r |dtvrQ|dtur'tjdj d|z||fS)z( dot-text = 1*atext *("." 1*atext) rz8expected atom at a start of dot-atom-text but found '{}'r rNrz4expected atom at end of dot-atom-text but found '{}')r r rrr=rrrA)r dot_atom_textrSs rget_dot_atom_textrHs MM E!H )%%'++16%=: : E!HI- ' uU# U1X_   %!"IE E!HI- RC%%'#VCI.0 0 % rct}|dtvrt|\}}|j||j dr t |\}}nt|\}}|j||r*|dtvrt|\}}|j|||fS#t j$rt|\}}YdwxYw)z dot-atom = [CFWS] dot-atom-text [CFWS] Any place we can have a dot atom, we could instead have an rfc2047 encoded word. rr) rrrrrrrrr)rdot_atomrSs r get_dot_atomr[s yH Qx; u  4+E2LE5 )/ u OOE q[( u U?&& 4-U3LE5 4sB%%!C C c(|dtvrt|\}}nd}|stjd|ddk(rt |\}}n=|dt vr$tjdj |t|\}}||g|dd||fS)aword = atom / quoted-string Either atom or quoted-string may start with CFWS. We have to peel off this CFWS first to determine which type of word to parse. Afterward we splice the leading CFWS, if any, into the parsed sub-token. If neither an atom or a quoted-string is found before the next special, a HeaderParseError is raised. The token returned is either an Atom or a QuotedString, as appropriate. This means the 'word' level of the formal grammar is not represented in the parse tree; this is because having that extra layer when manipulating the parse tree is more confusing than it is helpful. rNz5Expected 'atom' or 'quoted-string' but found nothing.rz1Expected 'atom' or 'quoted-string' but found '{}')rrrrr SPECIALSr=r)rleaderrSs rget_wordrts  Qx;   %% CE E Qx}(/ u qX %%'77=ve}F F  u Hbq %<rct} t|\}}|j||r|dtvr|ddk(rI|jt|j jtjd|dd}n t|\}}|j||r |dtvr||fS#tj$r1|j jtj dYwxYw#tj$rL|dtvr=t|\}}|j jtjdnYwxYw)a phrase = 1*word / obs-phrase obs-phrase = word *(word / "." / CFWS) This means a phrase can be a sequence of words, periods, and CFWS in any order as long as it starts with at least one word. If anything other than words is detected, an ObsoleteHeaderDefect is added to the token's defect list. We also accept a phrase that starts with CFWS followed by a dot; this is registered as an InvalidHeaderDefect, since it is not supported by even the obsolete grammar. zphrase does not start with wordrr zperiod in 'phrase'rNzcomment found without atom) rrrrrr'ru PHRASE_ENDSrAObsoleteHeaderDefectrr)rrrSs r get_phrasersMXF0 u e E!HK/ 8S= MM#  NN ! !&"="=$#& '!"IE ' u MM% ! E!HK/" 5=)  " "0f88 -/ 00** 8{*#+E?LE5NN))&*E*E4+677 s%B; D;AC?>C?AE! E!ct}d}|r|dtvrt|\}}|s$tjdj | t |\}}||g|dd|j||r|ddk(s |dtvrtt||z\}}|jdk(r/|jjtjdn.|jjtj d||d< |j"j%d||fS#tj$rK t|\}}n7#tj$r!|ddk7r |dtvrt}YnwxYwY6wxYw#t&$r4|jjtj(d Y||fSwxYw) z= local-part = dot-atom / quoted-string / obs-local-part Nrz"expected local-part but found '{}'rinvalid-obs-local-partz@ @ #E* uHbq e %(D.E!HK$? 23z?U3J K  $ $(@ @    % %f&@&@N'P Q    % %f&A&A>'@ A& 1 >( u 1  " "  #E?LE5&& Qx4E!H $;KE  * >!!&"@"@;#= > u >sHD6F6F EF1F  F F  FF7GGcNt}d}|rB|ddk(s |dtvr.|ddk(rM|r.|jjt j d|jt d}|dd}l|ddk(rT|jt|dd |dd}|jjt j d d}|r@|d jd k7r.|jjt j d  t|\}}d}|j||r|ddk(r!|dtvr.|s$t jdj||djd k(s2|djdk(rNt|dkDr@|djd k(r.|jjt j d|d jd k(s2|d jdk(rNt|dkDr@|djd k(r.|jjt j d|jrd|_||fS#tj$r|dtvrt|\}}Y{wxYw)z' obs-local-part = word *("." word) Frrr zinvalid repeated '.'TrNmisplaced-specialz/'\' character outside of quoted-string/ccontentrr@zmissing '.' between wordsz&expected obs-local-part but found '{}'rz!Invalid leading '.' in local partrz"Invalid trailing '.' in local partr)r3rr'rrrurArrdrrrrr=r)rr#last_non_ws_was_dotrSs rr r s"^N U1Xt^uQx{'B 8s?"&&--f.H.H*/,-  ! !# &"& !"IE  1Xt^  ! !-a0C#E F!"IE  " " ) )&*D*DB+D E"'   nR0;;uD  " " ) )&*D*D++- . +#E?LE5"'  e$7 U1Xt^uQx{'B8 %% 4 ; ;E BD Dq$$- 1  ( (& 0  ! # 1  ( (% /%%f&@&@ /'1 2r%%. 2  ) )6 1  ! # 2  ) )5 0%%f&@&@ 0'2 3$<! 5  -&& +Qx{*#E?LE5 +sI33-J$#J$ct|d\}}}t|d}|r.|jjt j dt |||fS)a dtext = / obs-dtext obs-dtext = obs-NO-WS-CTL / quoted-pair We allow anything except the excluded characters, but if we find any ASCII other than the RFC defined printable ASCII, a NonPrintableDefect is added to the token's defects list. Quoted pairs are converted to their unquoted values, so what is returned is a ptext token, in this case a ValueTerminal. If there were quoted-printables, an ObsoleteHeaderDefect is added to the returned token's defect list. z[]rJz(quoted printable found in domain-literal)rrr'rrrr)rrJrs r get_dtextr)sZ2%>E5& % )E  V88 68 9E %<rc|ry|jtjd|jtddy)NFz"end of input inside domain-literal]domain-literal-endT)rrrur)rdomain_literals r_check_for_early_dl_endr.+s? &44,./--ABC rcnt}|dtvrt|\}}|j||st j d|ddk7r$t j dj ||dd}t||r||fS|jtdd|dtvrt|\}}|j|t|\}}|j|t||r||fS|dtvrt|\}}|j|t||r||fS|ddk7r$t j d j ||jtdd |dd}|r*|dtvrt|\}}|j|||fS) zB domain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS] rzexpected domain-literal[z6expected '[' at start of domain-literal but found '{}'rNzdomain-literal-startr+z4expected ']' at end of domain-literal but found '{}'r,) rGrrrrrr=r.rrrr))rr-rSs rget_domain_literalr13s#_N Qx; ue$ %%&?@@ Qx3%%'!!'0 0 !"IEun5u$$--CDE Qx3u~ ue$U#LE5% un5u$$ Qx3u~ ue$un5u$$ Qx3%%'!!'0 0--ABC !"IE q[( ue$ 5  rc"t}d}|r|dtvrt|\}}|s$tjdj ||ddk(r+t |\}}||g|dd|j|||fS t|\}}|r|ddk(rtjd||g|dd|j||r|ddk(r|jjtjd|djd k(r|d|dd|rJ|ddk(rB|jtt|d d\}}|j||r |ddk(rB||fS#tj$rt|\}}YwxYw) z] domain = dot-atom / domain-literal / obs-domain obs-domain = atom *("." atom)) Nrzexpected domain but found '{}'r0r-zInvalid Domainr z(domain is not a dot-atom (contains CFWS)rr)rrrrrr=r1rrrr'rrdrA)rrrrSs r get_domainr3Zs XF F q[(   %% , 3 3E :< < Qx3)%0 u  E"1I eu}'#E* u qS%%&677 Hbq  MM% qSf99 68 9 !9  : -q F1IaC MM# #E!"I.LE5 MM% aC 5=!  " "' u'sE**!F FcNt}t|\}}|j||r|ddk7r2|jjt j d||fS|jt ddt|dd\}}|j|||fS)z( addr-spec = local-part "@" domain rr-z#addr-spec local part with no domainaddress-at-symbolrN)r%r$rr'rrurr3)rrrSs r get_addr_specr6s I!%(LE5 U E!HO  !;!; 1"3 4% ]3(;<=eABi(LE5 U e rct}|rw|ddk(s |dtvrd|dtvr t|\}}|j|n"|ddk(r|jt|dd}|r|ddk(rX|dtvrd|r|ddk7r$t j dj||jtt|dd\}}|j||r|ddk(r|jt|dd}|snw|dtvrt|\}}|j||snJ|ddk(r7|jtt|dd\}}|j||r |ddk(r|st j d|ddk7r$t j d j||jtdd ||ddfS) z obs-route = obs-domain-list ":" obs-domain-list = *(CFWS / ",") "@" domain *("," [CFWS] ["@" domain]) Returns an obs-route token with the appropriate sub-tokens (that is, there is no obs-domain-list in the parse tree). rrrNr-z(expected obs-route domain but found '{}'z%end of header while parsing obs-route:z4expected ':' marking end of obs-route but found '{}'zend-of-obs-route-marker) rrrr ListSeparatorrrr=RouteComponentMarkerr3r)r obs_routerSs r get_obs_router<s I U1Xs]eAh+&= 8{ "#E?LE5   U # 1X_   ] +!"IE U1Xs]eAh+&= E!HO%% 6 = =e DF F )*eABi(LE5 U E!HcM'ab   8{ "#E?LE5   U #  8s?   1 2%eABi0LE5   U # E!HcM %%&MNN Qx3%%(''-ve}6 6 ]3(ABC eABi rcxt}|r*|dtvrt|\}}|j||r|ddk7r$t j dj ||jtdd|dd}|rZ|ddk(rR|jtdd|jjt jd |dd}||fS t|\}}|j||r|ddk(r|dd}n.|jjt jd |jtdd|r*|dtvrt|\}}|j|||fS#tj $r t|\}}|jjt jd n;#tj $r%t j d j |wxYw|j|t|\}}YHwxYw) z angle-addr = [CFWS] "<" addr-spec ">" [CFWS] / obs-angle-addr obs-angle-addr = [CFWS] "<" obs-route addr-spec ">" [CFWS] rzangle-addr-endznull addr-spec in angle-addrz*obsolete route specification in angle-addrz.expected addr-spec or obs-route but found '{}'z"missing trailing '>' on angle-addr) rrrrrrr=rr'rur6r<r)r angle_addrrSs rget_angle_addrrAs4 J q[( u% E!HO%% 0 7 7 >@ @mC);<= !"IE qS--=>?!!&"<"< *#, -ab 5   ,$U+ ue qSab !!&"<"< 0#2 3mC)9:; q[( u% u )  " " , P(/LE5    % %f&A&A<'> ?&& P))@GGNP P P % $U+ u ,s*"F H9) rrrr=rrrrCr8r"rrA)r name_addrrrSs r get_name_addrrFs` I F %% / 6 6u =? ? Qx;  ))3::6BD D Qx3 8{ "))3::5AC C'. u))3::5AC C  %(I. &xa! #Hbq F!%(LE5 Hbq  U e rclt} t|\}}t d|jDrd|_|j|||fS#tj$rN t |\}}n;#tj$r%tjdj |wxYwYwxYw)z& mailbox = name-addr / addr-spec zexpected mailbox but found '{}'c3PK|]}t|tj ywr$)r8rrur0s rr3zget_mailbox..+s% 3 11 a33 4 1$&r) r rFrrr6r=anyrErdr)rrrSs r get_mailboxrKs iGA$U+ u  3 % 1 1 33. NN5 E>  " "A A(/LE5&& A))188?A A AAs)AB3&A54B358B--B32B3ct}|r_|d|vrX|dtvr$|jt|dd|dd}nt |\}}|j||r|d|vrX||fS)z Read everything up to one of the chars in endchars. This is outside the formal grammar. The InvalidMailbox TokenList that is returned acts like a Mailbox, but the data attributes are None. rr&rN)rrrrr)rrinvalid_mailboxrSs rget_invalid_mailboxrN1s%&O E!HH, 8{ "  " "=q1D$F G!"IE%e,LE5  " "5 ) E!HH, E !!rc\t}|r|ddk7r t|\}}|j||ra|ddvrZ|d}d |_ t|d\}}|j||jjtjd|r"|ddk(r|jt|d d}|r |ddk7r||fS#tj$rLd}|dt vrt |\}}|r|ddvr@|j||jjtjdnt|d\}}||g|dd|j||jjtjdn|ddk(r/|jjtjdnVt|d\}}||g|dd|j||jjtjdYwxYw) aJ mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list obs-mbox-list = *([CFWS] ",") mailbox *("," [mailbox / CFWS]) For this routine we go outside the formal grammar in order to improve error handling. We recognize the end of the mailbox list only at the end of the value or at a ';' (the group terminator). This is so that we can turn invalid mailboxes into InvalidMailbox tokens and continue parsing any remaining valid mailboxes. We also allow all mailbox entries to be null, and this condition is handled appropriately at a higher level. r;Nz,;zempty element in mailbox-listzinvalid mailbox in mailbox-listrrrr)rrKrrrrrr'rrNrurdrQr9)r mailbox_listrSrrs rget_mailbox_listrRCs5=L E!HO 8&u-LE5    &4 U1XT)#2&G!2G .ud;LE5 NN5 !  ' '(B(B1)3 4 U1X_    .!"IEQ E!HOR  K&& 8FQx;& ( aD 0 ''/ ((//0K0K719:$7ud#CLE5)%+Hbq  ''. ((//0J0J91;<qS$$++F,G,G3-56 35$? u%!'E"1I##E*$$++F,F,F5-78/ 8sC EH+*H+ct}|s2|jjtjd||fSd}|r{|dt vrpt |\}}|sC|jjtjd|j|||fS|ddk(r|j|||fSt|\}}t|jdk(rV||j||j||jjtjd||fS||g|dd|j|||fS)zg group-list = mailbox-list / CFWS / obs-group-list obs-group-list = 1*([CFWS] ",") [CFWS] zend of header before group-listNrzend of header in group-listrPzgroup-list with empty entries) rr'rrrurrrRrrrQr)r group_listrrSs rget_group_listrU|sa J !!&"<"< -#/ 05  F q[(      % %f&@&@-'/ 0   f %u$ $ 8s?   f %u$ $#E*LE5 5  "     f %% !!&"="= +#- .5   Hbq e u rct}t|\}}|r|ddk7r$tjdj ||j ||j t dd|dd}|r*|ddk(r"|j t dd||ddfSt|\}}|j ||s/|jj tjd n,|ddk7r$tjd j ||j t dd|dd}|r*|dtvrt|\}}|j |||fS) z7 group = display-name ":" [group-list] ";" [CFWS] rr8z8expected ':' at end of group display name but found '{}'zgroup-display-name-terminatorrNrPzgroup-terminatorzend of header in groupz)expected ';' at end of group but found {}) rrCrrr=rrrUr'rurr)rrrSs r get_grouprWsa GE#E*LE5 E!HO%%'**0&-9 9 LL LLs$CDE !"IE qS ]3(:;<eABi!%(LE5 LL  V77 $& ' qS%% 7 > >u EG G LLs$678 !"IE q[( u U %<rc&t} t|\}}|j |||fS#tj$rN t |\}}n;#tj$r%tjdj |wxYwYuwxYw)a address = mailbox / group Note that counter-intuitively, an address can be either a single address or a list of addresses (a group). This is why the returned Address object has a 'mailboxes' attribute which treats a single address as a list of length one. When you need to differentiate between to two cases, extract the single element, which is either a mailbox or a group token. zexpected address but found '{}')rrWrrrKr=r)rrrSs r get_addressrYs"iGA ' u NN5 E>  " "A A&u-LE5&& A))188?A A AAs'/BAB8B  BBc^t}|r t|\}}|j||re|ddk7r]|dd}d|_ t|d\}}|j||jjtjd|r|jt|d d}|r||fS#tj$rad}|dt vrt |\}}|r|ddk(r@|j||jjtjdnt|d\}}||g|dd|jt|g|jjtjdn|ddk(r/|jjtjdn`t|d\}}||g|dd|jt|g|jjtjdYwxYw) a address_list = (address *("," address)) / obs-addr-list obs-addr-list = *([CFWS] ",") address *("," [address / CFWS]) We depart from the formal grammar here by continuing to parse until the end of the input, assuming the input to be entirely composed of an address-list. This is always true in email parsing, and allows us to skip invalid addresses to parse additional valid ones. Nrrz"address-list entry with no contentzinvalid address in address-listzempty element in address-listrrr)rrYrrrrrr'rrNrrurdrQr9)r address_listrSrrs rget_address_listr\s(=L  8&u-LE5    &4 U1X_#2&q)G!2G .uc:LE5 NN5 !  ' '(B(B1)3 4     .!"IEQ R  K&& 8FQx;& ( aC ''/ ((//0K0K<1>?$7uc#BLE5)%+Hbq  ''(89 ((//0J0J91;<qS$$++F,G,G3-56 35#> u%!'E"1I##GUG$45$$++F,F,F5-78/ 8sB77E1H,+H,ct}|s$tjdj||ddk7r$tjdj||j t dd|dd}t |\}}|j ||r|ddk7r$tjd j||j t dd ||ddfS) z& no-fold-literal = "[" *dtext "]" z'expected no-fold-literal but found '{}'rr0z;expected '[' at the start of no-fold-literal but found '{}'zno-fold-literal-startrNr+z9expected ']' at the end of no-fold-literal but found '{}'zno-fold-literal-end)r#rrr=rrr))rno_fold_literalrSs rget_no_fold_literalr_s$oO %% 5 < " [CFWS] id-left = dot-atom-text / obs-id-left id-right = dot-atom-text / no-fold-literal / obs-id-right no-fold-literal = "[" *dtext "]" rr>zexpected msg-id but found '{}'z msg-id-startrNzobsolete id-left in msg-idz4expected dot-atom-text or obs-id-left but found '{}'r-zmsg-id with no id-rightr?z msg-id-endr5zobsolete id-right in msg-idzFexpected dot-atom-text, no-fold-literal or obs-id-right but found '{}'zmissing trailing '>' on msg-id)rrrrrrr=rrr r'rrur_r3)rmsg_idrSs r get_msg_idrb)s WF q[( u e E!HO%% , 3 3E :< < MM-^45 !"IE 1(/ u MM% E!HOf88 %' ( U1X_ MM-\: ;!"IEu} MM-%89: !"IE 5(/ u MM% qSab f88 ,. / MM-\23 q[( u e 5=a  " " 1 1-e4LE5 NN ! !&"="=,#. /&& 1))""(&-1 1 1 / 14  " " 5 5.u5LE5&& 5 5)%0 u%%f&A&A1'34** 5--&&,fUm55 54 5 5sxG,I'I$(> ##F$>$> ? F Fv N%P QM&':; [ M&(;< q[( uE" E!HO    )  ' '(B(BB)D E     eW = > c+>?@ !"IE q[( uE"     )  ' '(B(BB)D E F E!HK/%(ab  E!HK/ >> ##F$>$> ? F Fv N%P QM&':; [ M&(;< q[( uE" ##F$>$> 5%7 8M%9: rct}|ra|ddk7rY|dtvr$|jt|dd|dd}nt |\}}|j||r |ddk7rY||fS)z Read everything up to the next ';'. This is outside the formal grammar. The InvalidParameter TokenList that is returned acts like a Parameter, but the data attributes are None. rrPr&rN)r\rrrr)rinvalid_parameterrSs rget_invalid_parameterrps)* E!HO 8{ "  $ $]583F&H I!"IE%e,LE5  $ $U + E!HO e ##rct|}|s$tjdj||j }|t |d}t |d}t|||fS)a8ttext = We allow any non-TOKEN_ENDS in ttext, but add defects to the token's defects list if we find non-ttext characters. We also register defects for *any* non-printables even though the RFC doesn't exclude all of them, because we follow the spirit of RFC 5322. zexpected ttext but found '{}'Nttext)_non_token_end_matcherrrr=rrrr)rrrrs r get_ttextrtsk u%A %% + 2 25 9; ; GGIE #e*+ E % )EE %<rcnt}|r*|dtvrt|\}}|j||r/|dtvr$t j dj|t|\}}|j||r*|dtvrt|\}}|j|||fS)ztoken = [CFWS] 1*ttext [CFWS] The RFC equivalent of ttext is any US-ASCII chars except space, ctls, or tspecials. We also exclude tabs even though the RFC doesn't. The RFC implies the CFWS but is not explicit about it in the BNF. rexpected token but found '{}') rrrr TOKEN_ENDSrrr=rt)rmtokenrSs r get_tokenrysWF q[( u e qZ'%% + 2 25 9; ;U#LE5 MM% q[( u e 5=rct|}|s$tjdj||j }|t |d}t |d}t|||fS)aQattrtext = 1*(any non-ATTRIBUTE_ENDS character) We allow any non-ATTRIBUTE_ENDS in attrtext, but add defects to the token's defects list if we find non-attrtext characters. We also register defects for *any* non-printables even though the RFC doesn't exclude all of them, because we follow the spirit of RFC 5322. z expected attrtext but found {!r}Nrb)_non_attribute_end_matcherrrr=rrrrrrrbs r get_attrtextr} sk #5)A %% . 5 5e <> >wwyH #h-. !EXz2HH U?rcnt}|r*|dtvrt|\}}|j||r/|dtvr$t j dj|t|\}}|j||r*|dtvrt|\}}|j|||fS)aH [CFWS] 1*attrtext [CFWS] This version of the BNF makes the CFWS explicit, and as usual we use a value terminal for the actual run of characters. The RFC equivalent of attrtext is the token characters, with the subtraction of '*', "'", and '%'. We include tab in the excluded set just as we do for token. rrv) r_rrrATTRIBUTE_ENDSrrr=r}rr`rSs r get_attributer s I q[( u q^+%% + 2 25 9; ;&LE5 U q[( u e rct|}|s$tjdj||j }|t |d}t |d}t|||fS)zattrtext = 1*(any non-ATTRIBUTE_ENDS character plus '%') This is a special parsing routine so that we get a value that includes % escapes as a single string (which we decode as a single string later). z)expected extended attrtext but found {!r}Nextended-attrtext)#_non_extended_attribute_end_matcherrrr=rrrrr|s rget_extended_attrtextr4 sn ,E2A %% 7 > >u EG GwwyH #h-. !EX':;HH U?rcnt}|r*|dtvrt|\}}|j||r/|dtvr$t j dj|t|\}}|j||r*|dtvrt|\}}|j|||fS)z [CFWS] 1*extended_attrtext [CFWS] This is like the non-extended version except we allow % characters, so that we can pick up an encoded value as a single string. rrv) r_rrrEXTENDED_ATTRIBUTE_ENDSrrr=rrs rget_extended_attributerF s I q[( u q44%% + 2 25 9; ;(/LE5 U q[( u e rclt}|r|ddk7r$tjdj||j t dd|dd}|r|dj s$tjdj|d}|r6|dj r#||dz }|dd}|r|dj r#|dd k(r3|d k7r.|jj tjd t||_ |j t |d ||fS) a6 '*' digits The formal BNF is more complicated because leading 0s are not allowed. We check for that and add a defect. We also assume no CFWS is allowed between the '*' and the digits, though the RFC is not crystal clear on that. The caller should already have dealt with leading CFWS. r*zExpected section but found {}zsection-markerrNz$Expected section number but found {}r-0z'section number has an invalid leading 0rh) rfrrr=rrrjr'rurkrV)rrgrhs r get_sectionr\ s2iG E!HO%%&E&L&L(-'/0 0 NN=&678 !"IE a((*%%'117@ @ F E!H$$&%(ab  E!H$$&ayCFcMv999 ; <[GN NN=23 E>rcJt}|stjdd}|dtvrt |\}}|s$tjdj ||ddk(rt |\}}nt|\}}||g|dd|j|||fS)z quoted-string / attribute z&Expected value but found end of stringNrz Expected value but found only {}r) rirrrrr=r rr)rvrrSs r get_valuerz s A %%&NOO F Qx;   %%'006v@ @ Qx3(/ u-e4 u Hbq HHUO e8Orc2 t}t|\}}|j||r|ddk(rA|jjt j dj |||fS|ddk(rm t|\}}d|_|j||st jd|ddk(r'|jtdd|dd }d|_ |dd k7rt jd |jtd d |dd }|r*|dtvrt|\}}|j|d }|}|jr|r|dd k(rt|\}}|j}d}|j dk(r(|r |ddk(rd}n/t#|\}}|r|ddk(rd}n t%|\}}|sd} |ra|jjt j d|j||D]} | j&dk(sg| d d | }n|}n0d }|jjt j d|r |ddk(rd }nt)|\}}|jr|j dkDrZ|r|ddk7r"|j|| |rJ||}||fS|jjt j d|sF|jjt j d|j||#||fS|I|D]} | j&dk(sn j&dk(|j| | j*|_|ddk7r$t jdj ||jtdd|dd }|rf|ddk7r^t#|\}}|j||j*|_|r|ddk7r$t jdj ||jtdd|dd }|et1} |rV|dt2vrt5|\}}n(|dd k(rtd d}|dd }nt7|\}}| j||rV| }nt)|\}}|j|| |rJ||}||fS#tj$rYiwxYw#Y@xYw)aY attribute [section] ["*"] [CFWS] "=" value The CFWS is implied by the RFC but not made explicit in the BNF. This simplified form of the BNF from the RFC is made to conform with the RFC BNF through some extra checks. We do it this way because it makes both error recovery and working with the resulting parse tree easier. rrPz)Parameter contains name ({}) but no valuerTzIncomplete parameterzextended-parameter-markerrN=zParameter not followed by '='parameter-separatorrF'z5Quoted string value for extended parameter is invalidrzZParameter marked as extended but appears to have a quoted string value that is non-encodedzcApparent initial-extended-value but attribute was not marked as extended or was not initial sectionz(Missing required charset/lang delimitersrrbz=Expected RFC2231 char/lang encoding delimiter, but found {!r}zRFC2231-delimiterz;Expected RFC2231 char/lang encoding delimiter, but found {}DQUOTE)rQrrr'rrur=rrUrrrZrrr rrWr}rrdrrrrrirrr) rrrSrappendtoqstring inner_value semi_validrtrs r get_parameterr s+ KE 'LE5 LL E!HO V779%%+VE]4 5e| Qx3 &u-LE5"EO LL ))*@A A 8s? LLs,GH I!"IE!EN Qx3%%&EFF LLs$9:; !"IE q[( u UIH ~~%E!HO/u5,,    1 ${1~4! *;7 tDGsN!%J &3K@ t!%J  MM !;!;G"I J LL !<<#77AaD H   EI MM !;!;:"; < qS ' u >>U11A5aC OOE "$ '%'y!%<  V77 DE F  V77 68 9  %<   <<#66 LLJ & OOA GGEM 8s?))+FFLfUmU U c+>?@ab  U1X_'.LE5 OOE "EJE!HO--/<?@ab  GQx3&u~ uqS%c84ab +E2 u HHUO ' u OOE%y %<i&&   D s>&S7T7T TTct}|r t|\}}|j||rp|ddk7rh|d}d|_ t|\}}|j||jjtjdj||r |jtdd |d d}|r|S#tj$rd}|dt vrt |\}}|s|j||cYS|ddk(rB||j||jjtjdndt|\}}|r|g|dd|j||jjtjdj|YwxYw) a! parameter *( ";" parameter ) That BNF is meant to indicate this routine should only be called after finding and handling the leading ';'. There is no corresponding rule in the formal RFC grammar, but it is more convenient for us for the set of parameters to be treated as its own TokenList. This is 'parse' routine because it consumes the remaining value, but it would never be called to parse a full header. Instead it is called to parse everything after the non-parameter value of a specific MIME header. NrrPzparameter entry with no contentzinvalid parameter {!r}rr]z)parameter with invalid trailing text {!r}rr)rlrrrrrrr'rurpr=rdrQr)rmime_parametersrSrrs rparse_mime_parametersr s%&O  =(/LE5  " "5 )( U1X_$B'E2E 07LE5 LL   # # * *6+E+E;BB5I,K L   " "=6K#L M!"IEG H A&& =FQx;& ( &&v.&&Qx3%#**62''..v/I/I5078 5U; u!'E"1I&&u-''..v/I/I,33E:0<=# =sCAF= B.F=<F=c@|ra|ddk7rY|dtvr$|jt|dd|dd}nt|\}}|j||r |ddk7rY|sy|jtdd|jt |ddy)zBDo our best to find the parameters in an invalid MIME header rrPr&rNr)rrrrr) tokenlistrrSs r_find_mime_parametersrQ s E!HO 8{ "   ]585HI J!"IE%e,LE5   U # E!HO  ]3(=>? *5956rc8t}|s0|jjtjd|S t |\}}|j||r|ddk7r>|jjtjd|r t|||S|jjj|_ |jtdd|dd} t |\}}|j||jjj|_|s|S|dd k7rO|jjtjd j||` |`t|||S|jtd d |jt!|dd|S#tj $rN|jjtjdj|t|||cYSwxYw#tj $rN|jjtjd j|t|||cYSwxYw) z maintype "/" subtype *( ";" parameter ) The maintype and substype are tokens. Theoretically they could be checked against the official IANA list + x-token, but we don't do that. z"Missing content type specificationz(Expected content maintype but found {!r}rrzInvalid content typezcontent-type-separatorrNz'Expected content subtype but found {!r}rPz> 02 3  ' u  LL E!HO V77 "$ %  !% / [[&&(..0EN LLs$<=> !"IE ' u  LLKK%%'--/EM   Qx3 V77 ( ) NEMeU+  LLs$9:; LL&uQRy12 LQ  " " V77 6 = =e DF GeU+ &  " " V77 5 < . s%.,qa!>!>?,rI unknown-8bitTrmrUrr!rrrJrwrr)"max_line_lengthsysmaxsizeutf8rrr7rrd SPECIALSNL isdisjointNLSETr!r{rJrE_fold_mime_parametersrMrjrYrrrrre _fold_as_ewrkrJrr7rrrinsert) parse_treerVmaxlenrqrleading_whitespacelast_ew last_charsetr want_encodingend_ew_not_allowedrrNtstrr encoded_partnewlinewhitespace_accumulatorcharnewpartsps rrWrW s  # # 2s{{F ++w:H DEGLM!"&:;  E yy| % % ! #  4y"44$.$9$9$$? ? %*$4$4T$: :  ! KK !G ??/ / !$vx @  !3%% % ''#'99F9#;Q=Q#RL~~\9|,vE"I/FF&CE&JG!LL1b \1  4*T U* % ##'|+!^3!W,J1F"G%dE67&*&=&=wHZ\&("& %  %  t9U2Y/ / "I I     D A '3E:G$--/  Wt^,)+&!"ID3*11$7&&(WW-C%D"tX&DzH"66 #301&(&##4Q#7A&((#3012 )+"301'(& /##9!#>  u % 66}" !. ,,..(" M !B( (s:P)#Q1-Q!),QQc|+|r)tt|d|d|z}|dd||d<nM|dtvrB|d}|dd}t|d|k(r|j t ||dxx|z cc<d}|dtvr |d}|dd}|t|dn|} |dk(rdn|} t| dz} | dz|k\rt jd |r!|t|dz } | | z t|z } | dkr|j d  b [ L} } crN $+O#eBi.K"j0gIY!#JQ6!%% AC C  3uRy>1$z1C8J4KK ? LL   u:>c%)n16H::&8)LL "I %I!# ";J/zz.)D \"_4qj,CR0N::niHL&8F qj b \! c.123   LL eBi.K? @ "II,;6$6rc |jD]\}}|djjds |dxxdz cc<|}d} |j|d}|r6tjj|d | } d j||| } nd j|t|} t|dt| zd z|kr|ddz| z|d<t| dz|kr|jd| zd} |dz} |st|tt| zdzt| z} || dzkrd}|| z dz x}} |d|}tjj|d | } t| |krn|d z}<|jdj|| | | d } | d z } ||d}|r |dxxdz cc<|ry#t$r"d}t j |rd}d}nd}YwxYw)a>Fold TokenList 'part' into the 'lines' list as mime parameters. Using the decoded list of parameters and values, format them according to the RFC rules, including using RFC2231 encoding if the value cannot be expressed in 'encoding' and/or the parameter+value is too long to fit within 'maxlen'. rrPstrictFTrrprr-)saferz {}*={}''{}rrrsrrz''r(NNz {}*{}*={}{})rr*rcr!r{rr|rvrwrr=r rrr)rNrrrqrrr error_handlerencoding_required encoded_valuerrg extra_chromer splitpointmaxcharspartials rrr sA{{ e Ry!**3/ "I I  " LL " %  "LL..B}/6M&&tWmDD>>$ U(;CI % )F 2b C$.E"I  Y]f $ LLt $ ~ TSW%66:S=NNJa' $*Z$7!$; ;J , & 2 2"]!3!< }%1a  LL..g|]< =L qLG*+&Eb S -I#" " $ $$U+( 1 !  "sG'G>=G>)r)rrerrvstringroperatorremailrrrrr.rrrr r/r TSPECIALSrw ASPECIALSrrrrrrr compileVERBOSE MULTILINErrr"rpr|rrrrrrrrrrrrrrrrrr rrrr r#r%r3r5r=rGrMrQr\r_rfrirlrrrrrrrrrrrrrrrrrAr9rMrjr:r=r7rrrmatchrfindallrrsr{rrrrrrrrrrrrr rrrrrr$r r)r.r1r3r6r<rArCrFrKrNrRrUrWrYr\r_rbrfrmrprtryr}rrrrrrrrrrrrrWrrrtrrrs:CJ '  %jCHn   sN CH$ U# E "c#h . _ E " S(3s83 t    @ 1  "**ZZ",, @,@,FD)D I Y9"9I )#9#6 -| -!4C)C&%i%2 ?) ?% %"$I$*"y"6 DDyD!i!6;Y;.Y.i) I yB9 -!&-!`! !H I  ) 8%y% # #i I S.YS.l y *1 i ) *I*&y&Y(+s(+V''H->#I$4$4 BIIbggj!"%$%%*U'RZZ (8(8 BIIbggn%&)()).&0bjj1A1A BIIbgg-./21'227%$;J< /bAF"  ))V2  $6 &2 D$L%N2!h(%!N$L ) V,\ "H*"$6r#J<:4n&,BJ8BH$$&.&.$,<,KZ2h7 6p<^`7DJ7XI!r__pycache__/_header_value_parser.cpython-312.opt-1.pyc000064400000405360152526700320016567 0ustar00 {|jE dZddlZddlZddlZddlmZddlmZddlm Z ddlm Z ddlm Z e dZee d zZe d ZeezZee d z Zee d z Zee d ze d z ZeezZee dzZeezZee dz ZddhZeezZdZdZdZej<dej>ej@zZ!Gdde"Z#Gdde#Z$Gdde#Z%Gdde#Z&Gdde#Z'Gd d!e$Z(Gd"d#e#Z)Gd$d%e#Z*Gd&d'e#Z+Gd(d)e#Z,Gd*d+e,Z-Gd,d-e$Z.Gd.d/e#Z/Gd0d1e#Z0Gd2d3e#Z1Gd4d5e#Z2Gd6d7e#Z3Gd8d9e#Z4Gd:d;e#Z5Gd<d=e#Z6Gd>d?e#Z7Gd@dAe#Z8GdBdCe#Z9GdDdEe#Z:GdFdGe#Z;GdHdIe#Z<GdJdKe#Z=GdLdMe#Z>GdNdOe&Z?GdPdQe#Z@GdRdSe#ZAGdTdUe#ZBGdVdWe#ZCGdXdYeCZDGdZd[e#ZEGd\d]e#ZFGd^d_e#ZGGd`dae#ZHGdbdce#ZIGdddeeIZJGdfdgeIZKGdhdie#ZLGdjdke#ZMGdldme#ZNGdndoeNZOGdpdqeOZPGdrdse#ZQGdtdueRZSGdvdweSZTGdxdyeSZUGdzd{eTZVGd|d}e jZXeUd d~ZYeUddZZdeZ_[deZ_\eUddZ]ej<djdjejZaej<djejdjejZdej<djZfej<djejdjejZgej<djejdjejZhej<djejdjejZidZjdZkdZlddZmdZndZodZpdZqdZrdZsdZtdZudZvdZwdZxdZydZzdZ{dZ|dZ}dZ~dZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZy)alHeader value parser implementing various email-related RFC parsing rules. The parsing methods defined in this module implement various email related parsing rules. Principal among them is RFC 5322, which is the followon to RFC 2822 and primarily a clarification of the former. It also implements RFC 2047 encoded word decoding. RFC 5322 goes to considerable trouble to maintain backward compatibility with RFC 822 in the parse phase, while cleaning up the structure on the generation phase. This parser supports correct RFC 5322 generation by tagging white space as folding white space only when folding is allowed in the non-obsolete rule sets. Actually, the parser is even more generous when accepting input than RFC 5322 mandates, following the spirit of Postel's Law, which RFC 5322 encourages. Where possible deviations from the standard are annotated on the 'defects' attribute of tokens that deviate. The general structure of the parser follows RFC 5322, and uses its terminology where there is a direct correspondence. Where the implementation requires a somewhat different structure than that used by the formal grammar, new terms that mimic the closest existing terms are used. Thus, it really helps to have a copy of RFC 5322 handy when studying this code. Input to the parser is a string that has already been unfolded according to RFC 5322 rules. According to the RFC this unfolding is the very first step, and this parser leaves the unfolding step to a higher level message parser, which will have already detected the line breaks that need unfolding while determining the beginning and end of each header. The output of the parser is a TokenList object, which is a list subclass. A TokenList is a recursive data structure. The terminal nodes of the structure are Terminal objects, which are subclasses of str. These do not correspond directly to terminal objects in the formal grammar, but are instead more practical higher level combinations of true terminals. All TokenList and Terminal objects have a 'value' attribute, which produces the semantically meaningful value of that part of the parse subtree. The value of all whitespace tokens (no matter how many sub-tokens they may contain) is a single space, as per the RFC rules. This includes 'CFWS', which is herein included in the general class of whitespace tokens. There is one exception to the rule that whitespace tokens are collapsed into single spaces in values: in the value of a 'bare-quoted-string' (a quoted-string with no leading or trailing whitespace), any whitespace that appeared between the quotation marks is preserved in the returned value. Note that in all Terminal strings quoted pairs are turned into their unquoted values. All TokenList and Terminal objects also have a string value, which attempts to be a "canonical" representation of the RFC-compliant form of the substring that produced the parsed subtree, including minimal use of quoted pair quoting. Whitespace runs are not collapsed. Comment tokens also have a 'content' attribute providing the string found between the parens (including any nested comments) with whitespace preserved. All TokenList and Terminal objects have a 'defects' attribute which is a possibly empty list all of the defects found while creating the token. Defects may appear on any token in the tree, and a composite list of all defects in the subtree is available through the 'all_defects' attribute of any node. (For Terminal notes x.defects == x.all_defects.) Each object in a parse tree is called a 'token', and each has a 'token_type' attribute that gives the name from the RFC 5322 grammar that it represents. Not all RFC 5322 nodes are produced, and there is one non-RFC 5322 node that may be produced: 'ptext'. A 'ptext' is a string of printable ascii characters. It is returned in place of lists of (ctext/quoted-pair) and (qtext/quoted-pair). XXX: provide complete list of token types. N) hexdigits) itemgetter)_encoded_words)errors)utilsz (z ()<>@,:;.\"[].z."(z/?=z*'%%  cXt|jddjddS)z;Escape dquote and backslash for use within a quoted-string.\\\"z\"strreplacevalues 3/usr/lib64/python3.12/email/_header_value_parser.pymake_quoted_pairsrcs& u:  dF + 3 3C ??cxt|jddjddjddS)z:Escape parenthesis and backslash for use within a comment.rrr\()\)rrs rmake_parenthesis_pairsrhs2 u:  dF + e WWS%01rc$t|}d|dS)Nr)r)rescapeds r quote_stringr ns&G wiq>rz =\? # literal =? [^?]* # charset \? # literal ? [qQbB] # literal 'q' or 'b', case insensitive \? # literal ? .*? # encoded word \?= # literal ?= ceZdZdZdZdZfdZdZfdZe dZ e dZ dZ e d Z e d Zd Zdd Zdd ZddZxZS) TokenListNTc2t||i|g|_yN)super__init__defects)selfargskw __class__s rr&zTokenList.__init__s $%"% rc2djd|DS)Nc32K|]}t|ywr$r.0xs r z$TokenList.__str__..,t!s1vtjoinr(s r__str__zTokenList.__str__sww,t,,,rchdj|jjt|SNz{}({})formatr+__name__r%__repr__r(r+s rr?zTokenList.__repr__s+t~~66"W-/1 1rc2djd|DS)Nr-c3NK|]}|js|jywr$rr0s rr3z"TokenList.value..s81qwws%%r6r8s rrzTokenList.valuesww8888rc<td|D|jS)Nc34K|]}|jywr$) all_defectsr0s rr3z(TokenList.all_defects..s04aAMM4)sumr'r8s rrEzTokenList.all_defectss040$,,??rc(|djSNr)startswith_fwsr8s rrJzTokenList.startswith_fwssAw%%''rc&td|DS)zATrue if all top level tokens of this part may be RFC2047 encoded.c34K|]}|jywr$) as_ew_allowed)r1parts rr3z*TokenList.as_ew_allowed..s7$$4%%$rF)allr8s rrMzTokenList.as_ew_alloweds7$777rcNg}|D]}|j|j|Sr$)extendcomments)r(rRtokens rrRzTokenList.commentss&E OOENN +rct||S)Npolicy)_refold_parse_treer(rVs rfoldzTokenList.folds!$v66rc:t|j|y)Nindent)printppstrr(r\s rpprintzTokenList.pprints djjj'(rcDdj|j|S)Nr r[)r7_ppr_s rr^zTokenList.ppstrsyy011rc#~Kdj||jj|j|D]A}t |ds|dj|z&|j |dzEd{C|j rdj|j }nd}dj||y7Ew)Nz{}{}/{}(rbz* !! invalid element in token list: {!r}z z Defects: {}r-z{}){})r=r+r> token_typehasattrrbr')r(r\rSextras rrbz TokenList._pps  NN # # OO E5%(!55;VE]CD!99VF]333  <<"))$,,7EEnnVU++ 4sA3B=5B;6AB=r-)r> __module__ __qualname__rdsyntactic_breakew_combine_allowedr&r9r?propertyrrErJrMrRrYr`r^rb __classcell__r+s@rr"r"sJO-199@@(88 7)2,rr"c,eZdZedZedZy)WhiteSpaceTokenListcyN r8s rrzWhiteSpaceTokenList.valuerc`|Dcgc]}|jdk(s|j c}Scc}w)Ncomment)rdcontentr(r2s rrRzWhiteSpaceTokenList.commentss)#'C4a1<<+B 4CCC++N)r>rhrirlrrRrtrrrprps* DDrrpceZdZdZy)UnstructuredTokenList unstructuredNr>rhrirdrtrrr|r|sJrr|ceZdZdZy)PhrasephraseNr~rtrrrrJrrceZdZdZy)WordwordNr~rtrrrrJrrceZdZdZy)CFWSListcfwsNr~rtrrrrrrrceZdZdZy)AtomatomNr~rtrrrrrrrceZdZdZdZy)TokenrSFN)r>rhrird encode_as_ewrtrrrrs JLrrceZdZdZdZdZdZy) EncodedWord encoded-wordN)r>rhrirdctecharsetlangrtrrrrsJ CG Drrc@eZdZdZedZedZedZy) QuotedString quoted-stringcL|D]}|jdk(s|jcSyNbare-quoted-stringrdrrys rrxzQuotedString.contents"A||33wwrcg}|D]G}|jdk(r|jt|-|j|jIdj |S)Nrr-)rdappendrrr7)r(resr2s r quoted_valuezQuotedString.quoted_valuesNA||33 3q6" 177#  wws|rcL|D]}|jdk(s|jcSyrrr(rSs rstripped_valuezQuotedString.stripped_values%E#77{{"rN)r>rhrirdrlrxrrrtrrrrsA J  ##rrc&eZdZdZdZedZy)BareQuotedStringrcDtdjd|DS)Nr-c32K|]}t|ywr$r/r0s rr3z+BareQuotedString.__str__..s#9DqCFDr5)r r7r8s rr9zBareQuotedString.__str__sBGG#9D#99::rc2djd|DS)Nr-c32K|]}t|ywr$r/r0s rr3z)BareQuotedString.value..r4r5r6r8s rrzBareQuotedString.valueww,t,,,rN)r>rhrirdr9rlrrtrrrr s %J;--rrc<eZdZdZdZdZedZedZy)Commentrwc djtdg|Dcgc]}|j|c}dgggScc}w)Nr-rr)r7rGquoterys rr9zComment.__str__sKwws E489DqTZZ]D9 E " #$ $9s>c|jdk(r t|St|jddjddjddS)Nrwrrrrrr)rdrr)r(rs rrz Comment.quote"sR   y (u: 5z!!$/77"%u..5g"%u/. .rc2djd|DS)Nr-c32K|]}t|ywr$r/r0s rr3z"Comment.content..+r4r5r6r8s rrxzComment.content)rrc|jgSr$)rxr8s rrRzComment.comments-s ~rN) r>rhrirdr9rrlrxrRrtrrrrs9J$.--rrc@eZdZdZedZedZedZy) AddressListz address-listcL|Dcgc]}|jdk(s|c}Scc}w)Naddressrdrys r addresseszAddressList.addresses5%;4a1<<#:4;;;!!c(td|DgS)Nc3RK|]}|jdk(r|j!ywrNrd mailboxesr0s rr3z(AddressList.mailboxes..;s'>!Q\\9%<KK!%'rGr8s rrzAddressList.mailboxes9!>!>?AC Crc(td|DgS)Nc3RK|]}|jdk(r|j!ywrrd all_mailboxesr0s rr3z,AddressList.all_mailboxes..@s'>!Q\\9%<OO!rrr8s rrzAddressList.all_mailboxes>rrN)r>rhrirdrlrrrrtrrrr1sEJ <<CCCCrrc@eZdZdZedZedZedZy)AddressrcF|djdk(r|djSy)Nrgrouprd display_namer8s rrzAddress.display_nameHs) 7   (7'' ' )rcx|djdk(r|dgS|djdk(rgS|djSNrmailboxinvalid-mailboxrr8s rrzAddress.mailboxesMsH 7   *G9  !W  #4 4IAw   rc|djdk(r|dgS|djdk(r|dgS|djSrrr8s rrzAddress.all_mailboxesUsO 7   *G9  !W  #4 4G9 Aw$$$rN)r>rhrirdrlrrrrtrrrrDsAJ ((!!%%rrc0eZdZdZedZedZy) MailboxList mailbox-listcL|Dcgc]}|jdk(s|c}Scc}w)Nrrrys rrzMailboxList.mailboxesarrcH|Dcgc]}|jdvr|c}Scc}w)N)rrrrys rrzMailboxList.all_mailboxeses2?4a||==4? ??sNr>rhrirdrlrrrtrrrr]s-J <<??rrc0eZdZdZedZedZy) GroupList group-listcL|r|djdk7rgS|djSNrrrr8s rrzGroupList.mailboxesos+tAw))^;IAw   rcL|r|djdk7rgS|djSrrr8s rrzGroupList.all_mailboxesus+tAw))^;IAw$$$rNrrtrrrrks-J !! %%rrc@eZdZdZedZedZedZy)GrouprcH|djdk7rgS|djSNrrr8s rrzGroup.mailboxess) 7   -IAw   rcH|djdk7rgS|djSrrr8s rrzGroup.all_mailboxess) 7   -IAw$$$rc |djSrI)rr8s rrzGroup.display_namesAw###rN)r>rhrirdrlrrrrtrrrr|sAJ !! %% $$rrc`eZdZdZedZedZedZedZedZ y)NameAddr name-addrc>t|dk(ry|djSNr)lenrr8s rrzNameAddr.display_names t9>Aw###rc |djSN local_partr8s rrzNameAddr.local_partsBx"""rc |djSrdomainr8s rrzNameAddr.domainsBxrc |djSr)router8s rrzNameAddr.routesBx~~rc |djSr addr_specr8s rrzNameAddr.addr_specsBx!!!rN r>rhrirdrlrrrrrrtrrrrsiJ $$ ##""rrcPeZdZdZedZedZedZedZy) AngleAddrz angle-addrcL|D]}|jdk(s|jcSyN addr-spec)rdrrys rrzAngleAddr.local_parts"A||{*||#rcL|D]}|jdk(s|jcSyrrdrrys rrzAngleAddr.domains!A||{*xxrcL|D]}|jdk(s|jcSy)N obs-route)rddomainsrys rrzAngleAddr.routes"A||{*yy rc|D]O}|jdk(s|jr|jcSt|j|jzcSy)Nrz<>)rdrrr rys rrzAngleAddr.addr_specsFA||{*<<;;&' 5 CC rN) r>rhrirdrlrrrrrtrrrrsUJ $$   !! rrc eZdZdZedZy)ObsRouterc`|Dcgc]}|jdk(s|j c}Scc}w)Nrrrys rrzObsRoute.domainss)"&C$Q!,,(*B$CCCrzN)r>rhrirdrlrrtrrrrsJ DDrrc`eZdZdZedZedZedZedZedZ y)MailboxrcF|djdk(r|djSyNrrrr8s rrzMailbox.display_names) 7   ,7'' ' -rc |djSrIrr8s rrzMailbox.local_partAw!!!rc |djSrIrr8s rrzMailbox.domainsAw~~rcF|djdk(r|djSyr )rdrr8s rrz Mailbox.routes' 7   ,7==  -rc |djSrIrr8s rrzMailbox.addr_specsAw   rNrrtrrr r siJ ((""!!!!rr c0eZdZdZedZexZxZxZZ y)InvalidMailboxrcyr$rtr8s rrzInvalidMailbox.display_namerNrrtrrrrs/"J /;:J::%)rrc0eZdZdZdZefdZxZS)DomainrFcRdjt|jSNr-r7r%rsplitr@s rrz Domain.domainwwuw}**,--r)r>rhrirdrMrlrrmrns@rrrsJM ..rrceZdZdZy)DotAtomdot-atomNr~rtrrrrsJrrceZdZdZdZy) DotAtomTextz dot-atom-textTNr>rhrirdrMrtrrr r  s  JMrr ceZdZdZdZy) NoFoldLiteralzno-fold-literalFNr!rtrrr#r#s "JMrr#cTeZdZdZdZedZedZedZedZ y)AddrSpecrFc |djSrIrr8s rrzAddrSpec.local_partr rc>t|dkry|djS)Nr)rrr8s rrzAddrSpec.domains t9q=Bxrct|dkr|djS|djj|djz|djjzS)Nr(rrr)rrrstriplstripr8s rrzAddrSpec.value$sU t9q=7== Aw}}##%d1gmm3DGMM4H4H4JJJrct|j}t|t|tz kDrt |j}n |j}|j |dz|j zS|S)N@)setrr DOT_ATOM_ENDSr r)r(namesetlps rrzAddrSpec.addr_spec*s_doo& w<#gm34 4doo.BB ;; "8dkk) ) rN) r>rhrirdrMrlrrrrrtrrr%r%s\JM "" KK rr%ceZdZdZdZy) ObsLocalPartzobs-local-partFNr!rtrrr3r36s !JMrr3c@eZdZdZdZedZefdZxZS) DisplayNamez display-nameFct|}t|dk(r |jS|djdk(r|j dneOC$Q""f,47I.Q %%/R##v-48Y/R ''61|D$5$566t; ;7= r) r>rhrirdrkrlrrrmrns@rr5r5<s4J $!!rr5c4eZdZdZdZedZedZy) LocalPartz local-partFcb|djdk(r|djS|djS)Nrr)rdrrr8s rrzLocalPart.valueqs2 7   07'' '7== rctg}t}d}|dtgzD]}|jdk(r|r2|jdk(r#|djdk(rt|dd|d<t|t}|r?|jdk(r0|djdk(r|j t|ddn|j ||d}|}t|dd}|j S)NFrrdotrr)DOTrdr"r8rr)r(rlast last_is_tltokis_tls rrzLocalPart.local_partxse 7cU?C~~'s~~6H''61#D"I.BsI.E$//U2F%%/ 9SW-. 3r7DJ#Ab "yyrN)r>rhrirdrMrlrrrtrrr=r=ls2JM !! rr=c@eZdZdZdZefdZedZxZS) DomainLiteralzdomain-literalFcRdjt|jSrrr@s rrzDomainLiteral.domainrrcL|D]}|jdk(s|jcSy)Nptextrrys ripzDomainLiteral.ips!A||w&wwr) r>rhrirdrMrlrrKrmrns@rrGrGs3!JM ..rrGceZdZdZdZdZy) MIMEVersionz mime-versionN)r>rhrirdmajorminorrtrrrMrMsJ E ErrMc<eZdZdZdZdZdZedZedZ y) Parameter parameterFus-asciic<|jr|djSdSr) sectionednumberr8s rsection_numberzParameter.section_numbers"&tAw~~6Q6rc|D]n}|jdk(r|jcS|jdk(s0|D]:}|jdk(s|D]#}|jdk(s|jcccS<py)Nrrrr-)rdrrs r param_valuezParameter.param_valuesxE7*+++?2"E''+??%*E$//7:',';'; ;&+# rN) r>rhrirdrUextendedrrlrWrYrtrrrQrQs<JIHG 77   rrQceZdZdZy)InvalidParameterinvalid-parameterNr~rtrrr\r\s$Jrr\c eZdZdZedZy) Attribute attributecd|D]+}|jjds|jcSy)Nattrtext)rdendswithrrs rrzAttribute.stripped_values*E((4{{"rNr>rhrirdrlrrtrrr_r_sJ ##rr_ceZdZdZdZy)SectionsectionN)r>rhrirdrVrtrrrfrfs J Frrfc eZdZdZedZy)Valuerc|d}|jdk(r|d}|jjdr |jS|jS)Nrrr)rr`zextended-attribute)rdrcrrrs rrzValue.stripped_valuesPQ   v %GE    $ $D F'' 'zzrNrdrtrrririsJ rric*eZdZdZdZedZdZy)MimeParametersmime-parametersFc#lKi}|D]w}|jjds|djdk7r2|djj}||vrg||<||j |j |fy|j D]\}}t|td}|dd}|j}|jsRt|dkDrD|dddk(r9|ddjj tjd|dd}g}d}|D]\} } | |k7ri| js/| jj tjdG| jj tjd|dz }| j} | jrv t j"j%| } | j'|d } t-j.| r.| jj tj0 |j | d j5|} || fy#t(t*f$r| j'd d } YwxYw#t*$r$t j"j3| d } YwxYww)NrRrr`)keyrz.duplicate parameter name; duplicate(s) ignoredz+duplicate parameter name; duplicate ignoredz(inconsistent RFC2231 parameter numberingsurrogateescaperSzlatin-1)encodingr-)rdrcrstriprrWitemssortedrrrZrr'rInvalidHeaderDefectrYurllibparseunquote_to_bytesdecode LookupErrorUnicodeEncodeErrorr_has_surrogatesUndecodableBytesDefectunquoter7) r(paramsrSnameparts first_paramr value_partsirWparamrs rrzMimeParameters.paramssE##,,[9Qx""k18>>'')D6!!t 4L  !5!5u = >"<<>KD%5jm4E(1+K!))G''CJN8A;!#!HQK''..v/I/IH0JK!"1IEKA).%!Q&!>> ,,V-G-GI.KL  ,,V-G-GF.HIQ))>>R & = =e DP$)LL:K$LE!007!MM001N1N1PQ""5)C*/DGGK(E+ g*R!,-?@P %*LL=N$OE P.P!' 4 4UY 4 O PsIF6J49JI+A2J4!J>J4JJ4*J1.J40J11J4c g}|jD]C\}}|r+|jdj|t|3|j|Edj |}|rd|zSdS)N{}={}z; rsr-)rrr=r r7)r(rrrs rr9zMimeParameters.__str__2se;;KD% gnnT<3FGH d# ' 6"%sV|-2-rN)r>rhrirdrjrlrr9rtrrrlrls&"JO CCJ.rrlc eZdZdZedZy)ParameterizedHeaderValueFc`t|D]}|jdk(s|jcSiS)Nrm)reversedrdrrs rrzParameterizedHeaderValue.paramsCs0d^E#44||#$ rN)r>rhrirjrlrrtrrrr=sO rrceZdZdZdZdZdZy) ContentTypez content-typeFtextplainN)r>rhrirdrMmaintypesubtypertrrrrKsJMHGrrceZdZdZdZdZy)ContentDispositionzcontent-dispositionFN)r>rhrirdrMcontent_dispositionrtrrrrRs&JMrrceZdZdZdZdZy)ContentTransferEncodingzcontent-transfer-encodingF7bitN)r>rhrirdrMrrtrrrrXs,JM CrrceZdZdZdZy) HeaderLabelz header-labelFNr!rtrrrr^s JMrrceZdZdZdZdZy)MsgIDzmsg-idFc2t||jzSr$)rlineseprXs rrYz MsgID.foldgs4y6>>))rN)r>rhrirdrMrYrtrrrrcsJM*rrceZdZdZy) MessageIDz message-idNr~rtrrrrlsJrrceZdZdZy)InvalidMessageIDzinvalid-message-idNr~rtrrrrps%JrrceZdZdZy)HeaderheaderNr~rtrrrrtrrrcreZdZdZdZdZfdZfdZdZe dZ d fd Z dZ e dZ d ZxZS) TerminalTcDt|||}||_g|_|Sr$)r%__new__rdr')clsrrdr(r+s rrzTerminal.__new__s&wsE*$  rchdj|jjt|Sr;r<r@s rr?zTerminal.__repr__s&t~~668H8JKKrcbt|jjdz|jzy)N/)r]r+r>rdr8s rr`zTerminal.pprints" dnn%%+doo=>rc,t|jSr$)listr'r8s rrEzTerminal.all_defectssDLL!!rc dj||jj|jt||j sdgSdj|j gS)Nz {}{}/{}({}){}r-z {})r=r+r>rdr%r?r')r(r\r+s rrbz Terminal._ppsg&&  NN # # OO G  llB   ). T\\(B  rcyr$rtr8s rpop_trailing_wszTerminal.pop_trailing_wsrrcgSr$rtr8s rrRzTerminal.commentss rc0t||jfSr$)rrdr8s r__getnewargs__zTerminal.__getnewargs__s4y$//**rrg)r>rhrirMrkrjrr?r`rlrErbrrRrrmrns@rrr|sZMO L?""+rrc"eZdZedZdZy)WhiteSpaceTerminalcyrrrtr8s rrzWhiteSpaceTerminal.valuerurc |xr |dtvSrIWSPr8s rrJz!WhiteSpaceTerminal.startswith_fwss&Q3&rNr>rhrirlrrJrtrrrrs 'rrc"eZdZedZdZy) ValueTerminalc|Sr$rtr8s rrzValueTerminal.values rcy)NFrtr8s rrJzValueTerminal.startswith_fwssrNrrtrrrrs rrc"eZdZedZdZy)EWWhiteSpaceTerminalcyrrtr8s rrzEWWhiteSpaceTerminal.valuesrcyrrtr8s rr9zEWWhiteSpaceTerminal.__str__srN)r>rhrirlrr9rtrrrrs rrceZdZdZy)_InvalidEwErrorz1Invalid encoded word found while parsing headers.N)r>rhri__doc__rtrrrrs;rrr@,zlist-separatorFr-zroute-component-markerz([{}]+)r-z[^{}]+z[\x00-\x20\x7F]ct|}|r.|jjtj|t j |r/|jjtjdyy)z@If input token contains ASCII non-printables, register a defect.z*Non-ASCII characters found in header tokenN)_non_printable_finderr'rrNonPrintableDefectrr|r})xtextnon_printabless r_validate_xtextrsc+51N V66~FG U# V:: 8: ;$rc"t|d^}}g}d}d}tt|D]6}||dk(r |rd}d}nd}|rd}n |||vrn|j||8dz}dj |dj ||dg|z|fS)akScan printables/quoted-pairs until endchars and return unquoted ptext. This function turns a run of qcontent, ccontent-without-comments, or dtext-with-quoted-printables into a single string by unquoting any quoted printables. It returns the string, the remaining value, and a flag that is True iff there were any quoted printables decoded. rFrTr-N) _wsp_splitterrangerrr7)rendcharsfragment remaindervcharsescapehad_qpposs r_get_ptext_to_endcharsrs)2Hy F F FS]# C=D  F c]h &  hsm$$Ag 776?BGGXcd^$4y$@A6 IIrcr|j}t|dt|t|z d}||fS)zFWS = 1*WSP This isn't the RFC definition. We're using fws to represent tokens where folding can be done, but when we are parsing the *un*folding has already been done so we don't need to watch out for CRLF. Nfws)r+rr)rnewvaluers rget_fwsrs:||~H U#@ @ABioodA.OC) eABi%% 0 7 7 >@ @ WWY F F aq Yq Y #!<<a0yDj4 399;! &44 ,. / BF GGI E@'*zz$*t2C'D$gtWBJBGJJg  7c>!$-KE4 IIe  )$2 e]3 %wwy!  q$ &44 <> ? u9)  !@ / 6 6rvv >@ @@s I 4I>c t}|r[|dtvr t|\}}|j|.d}|j dr t |d\}}d}t |dkDrB|djdk7r0|jjtjdd}|r2t |d kDr$|d jd k(rt|dd|d<|j|t|d ^}}|r(tj!|r|j#d^}}t%|d}t'||j|d j)|}|r[|S#t$rd}Ytj$rYwxYw) aOunstructured = (*([FWS] vchar) *WSP) / obs-unstruct obs-unstruct = *((*LF *CR *(obs-utext) *LF *CR)) / FWS) obs-utext = %d0 / obs-NO-WS-CTL / LF / CR obs-NO-WS-CTL is control characters except WSP/CR/LF. So, basically, we have printable runs, plus control characters or nulls in the obsolete syntax, separated by whitespace. Since RFC 2047 uses the obsolete syntax in its specification, but requires whitespace on either side of the encoded words, I can see no reason to need to separate the non-printable-non-whitespace from the printable runs if they occur, so we parse this into xtext tokens separated by WSP tokens. Because an 'unstructured' value must by definition constitute the entire value, this 'get' routine does not return a remaining value, only the parsed TokenList. rTrutextrrz&missing whitespace before encoded wordFrrr-)r|rrrrrrrdr'rrurrrrrfc2047_matchersearch partitionrrr7)rr}rSvalid_ewhave_wsrDrrs rget_unstructuredrWs.)*L  8s?"5>LE5    &    D ! /w? u|$q(#B'22e;$,,33F4N4ND5FG"'s<014#B'22nD+?(,e,5 R(##E*'q1i ..s3#ood3OC)c7+E" "Q R A# ! **  s E++ F 8F  F cXt|d\}}}t|d}t|||fS)actext = This is not the RFC ctext, since we are handling nested comments in comment and unquoting quoted-pairs here. We allow anything except the '()' characters, but if we find any ASCII other than the RFC defined printable ASCII, a NonPrintableDefect is added to the token's defects list. Since quoted pairs are converted to their unquoted values, what is returned is a 'ptext' token. In this case it is a WhiteSpaceTerminal, so it's value is ' '. z()rJ)rrrrrJ_s r get_qp_ctextrs4-UD9OE5! ug .EE %<rcXt|d\}}}t|d}t|||fS)aoqcontent = qtext / quoted-pair We allow anything except the DQUOTE character, but if we find any ASCII other than the RFC defined printable ASCII, a NonPrintableDefect is added to the token's defects list. Any quoted pairs are converted to their unquoted values, so what is returned is a 'ptext' token. In this case it is a ValueTerminal. rrJ)rrrrs r get_qcontentrs4-UC8OE5! % )EE %<rct|}|s$tjdj||j }|t |d}t |d}t|||fS)zatext = We allow any non-ATOM_ENDS in atext, but add an InvalidATextDefect to the token's defects list if we find non-atext characters. zexpected atext but found '{}'Natext)_non_atom_end_matcherrrr=rrrr)rmrs r get_atextrsk e$A %% + 2 25 9; ; GGIE #e*+ E % )EE %<rcN|r|ddk7r$tjdj|t}|dd}|r'|ddk(rt |\}}|j ||r|ddk7r|dt vrt|\}}n|dddk(rd} t|\}}|jj tjd d }|rSt|dkDrE|d jd k(r3|d jdk(r!t|d d |d <nt |\}}|j ||r |ddk7r|s2|jj tjd||fS||ddfS#tj$rt |\}}YwxYw)zbare-quoted-string = DQUOTE *([FWS] qcontent) [FWS] DQUOTE A quoted-string without the leading or trailing white space. Its value is the text between the quote marks, with whitespace preserved and quoted pairs decoded. rrzexpected '"' but found '{}'rNrrFz!encoded word inside quoted stringTrrrrz"end of header inside quoted string)rrr=rrrrrrr'rurrdr)rbare_quoted_stringrSrs rget_bare_quoted_stringrs E!HO%% * 1 1% 8: :)+ !"IE qS#E* u!!%( E!HO 8s?"5>LE5 2AY$ H 3/6 u"**11&2L2L739: C 23a7&r*55>*2.99^K-A*2..7&r*(.LE5!!%(+ E!HO, ""))&*D*D 0+2 3!5(( uQRy ((!** 3+E2 u 3s>F!F$#F$c|r,|ddk7r$tjdj|t}|dd}|rc|ddk7r[|dtvrt |\}}n%|ddk(rt |\}}nt|\}}|j||r |ddk7r[|s2|jjtjd||fS||ddfS)zcomment = "(" *([FWS] ccontent) [FWS] ")" ccontent = ctext / quoted-pair / comment We handle nested comments here, and quoted-pair in our qp-ctext routine. rrzexpected '(' but found '{}'rNrzend of header inside comment) rrr=rrr get_commentrrr'ru)rrwrSs rrrs  qS%% ) 0 0 79 9iG !"IE E!HO 8s?"5>LE5 1X_&u-LE5'.LE5u E!HO v99 * , -~ E!"I rct}|rR|dtvrG|dtvrt|\}}nt |\}}|j ||r |dtvrG||fS)z,CFWS = (1*([FWS] comment) [FWS]) / FWS r)r CFWS_LEADERrrrr)rrrSs rget_cfwsrsg :D E!H + 8s?"5>LE5&u-LE5 E E!H + ;rc t}|r*|dtvrt|\}}|j|t |\}}|j||r*|dtvrt|\}}|j|||fS)zquoted-string = [CFWS] [CFWS] 'bare-quoted-string' is an intermediate class defined by this parser and not by the RFC grammar. It is the quoted string without any attached CFWS. r)rrrrr)r quoted_stringrSs rget_quoted_stringr s!NM q[( uU#)%0LE5 q[( uU# % rct}|r*|dtvrt|\}}|j||r/|dtvr$t j dj||jdr t|\}}nt|\}}|j||r*|dtvrt|\}}|j|||fS#t j $rt|\}}YdwxYw)zPatom = [CFWS] 1*atext [CFWS] An atom could be an rfc2047 encoded word. rzexpected atom but found '{}'r) rrrr ATOM_ENDSrrr=rrr)rrrSs rget_atomr-s 6D q[( u E qY&%% * 1 1% 8: :  ,+E2LE5 !' uKK q[( u E ;&& ,%U+LE5 ,s:C!C<;C<ct}|r |dtvr$tjdj ||r\|dtvrQt |\}}|j ||r"|ddk(r|j t|dd}|r |dtvrQ|dtur'tjdj d|z||fS)z( dot-text = 1*atext *("." 1*atext) rz8expected atom at a start of dot-atom-text but found '{}'r rNrz4expected atom at end of dot-atom-text but found '{}')r r rrr=rrrA)r dot_atom_textrSs rget_dot_atom_textrHs MM E!H )%%'++16%=: : E!HI- ' uU# U1X_   %!"IE E!HI- RC%%'#VCI.0 0 % rct}|dtvrt|\}}|j||j dr t |\}}nt|\}}|j||r*|dtvrt|\}}|j|||fS#t j$rt|\}}YdwxYw)z dot-atom = [CFWS] dot-atom-text [CFWS] Any place we can have a dot atom, we could instead have an rfc2047 encoded word. rr) rrrrrrrrr)rdot_atomrSs r get_dot_atomr[s yH Qx; u  4+E2LE5 )/ u OOE q[( u U?&& 4-U3LE5 4sB%%!C C c(|dtvrt|\}}nd}|stjd|ddk(rt |\}}n=|dt vr$tjdj |t|\}}||g|dd||fS)aword = atom / quoted-string Either atom or quoted-string may start with CFWS. We have to peel off this CFWS first to determine which type of word to parse. Afterward we splice the leading CFWS, if any, into the parsed sub-token. If neither an atom or a quoted-string is found before the next special, a HeaderParseError is raised. The token returned is either an Atom or a QuotedString, as appropriate. This means the 'word' level of the formal grammar is not represented in the parse tree; this is because having that extra layer when manipulating the parse tree is more confusing than it is helpful. rNz5Expected 'atom' or 'quoted-string' but found nothing.rz1Expected 'atom' or 'quoted-string' but found '{}')rrrrr SPECIALSr=r)rleaderrSs rget_wordrts  Qx;   %% CE E Qx}(/ u qX %%'77=ve}F F  u Hbq %<rct} t|\}}|j||r|dtvr|ddk(rI|jt|j jtjd|dd}n t|\}}|j||r |dtvr||fS#tj$r1|j jtj dYwxYw#tj$rL|dtvr=t|\}}|j jtjdnYwxYw)a phrase = 1*word / obs-phrase obs-phrase = word *(word / "." / CFWS) This means a phrase can be a sequence of words, periods, and CFWS in any order as long as it starts with at least one word. If anything other than words is detected, an ObsoleteHeaderDefect is added to the token's defect list. We also accept a phrase that starts with CFWS followed by a dot; this is registered as an InvalidHeaderDefect, since it is not supported by even the obsolete grammar. zphrase does not start with wordrr zperiod in 'phrase'rNzcomment found without atom) rrrrrr'ru PHRASE_ENDSrAObsoleteHeaderDefectrr)rrrSs r get_phrasersMXF0 u e E!HK/ 8S= MM#  NN ! !&"="=$#& '!"IE ' u MM% ! E!HK/" 5=)  " "0f88 -/ 00** 8{*#+E?LE5NN))&*E*E4+677 s%B; D;AC?>C?AE! E!ct}d}|r|dtvrt|\}}|s$tjdj | t |\}}||g|dd|j||r|ddk(s |dtvrtt||z\}}|jdk(r/|jjtjdn.|jjtj d||d< |j"j%d||fS#tj$rK t|\}}n7#tj$r!|ddk7r |dtvrt}YnwxYwY6wxYw#t&$r4|jjtj(d Y||fSwxYw) z= local-part = dot-atom / quoted-string / obs-local-part Nrz"expected local-part but found '{}'rinvalid-obs-local-partz@ @ #E* uHbq e %(D.E!HK$? 23z?U3J K  $ $(@ @    % %f&@&@N'P Q    % %f&A&A>'@ A& 1 >( u 1  " "  #E?LE5&& Qx4E!H $;KE  * >!!&"@"@;#= > u >sHD6F6F EF1F  F F  FF7GGcNt}d}|rB|ddk(s |dtvr.|ddk(rM|r.|jjt j d|jt d}|dd}l|ddk(rT|jt|dd |dd}|jjt j d d}|r@|d jd k7r.|jjt j d  t|\}}d}|j||r|ddk(r!|dtvr.|s$t jdj||djd k(s2|djdk(rNt|dkDr@|djd k(r.|jjt j d|d jd k(s2|d jdk(rNt|dkDr@|djd k(r.|jjt j d|jrd|_||fS#tj$r|dtvrt|\}}Y{wxYw)z' obs-local-part = word *("." word) Frrr zinvalid repeated '.'TrNmisplaced-specialz/'\' character outside of quoted-string/ccontentrr@zmissing '.' between wordsz&expected obs-local-part but found '{}'rz!Invalid leading '.' in local partrz"Invalid trailing '.' in local partr)r3rr'rrrurArrdrrrrr=r)rr#last_non_ws_was_dotrSs rr r s"^N U1Xt^uQx{'B 8s?"&&--f.H.H*/,-  ! !# &"& !"IE  1Xt^  ! !-a0C#E F!"IE  " " ) )&*D*DB+D E"'   nR0;;uD  " " ) )&*D*D++- . +#E?LE5"'  e$7 U1Xt^uQx{'B8 %% 4 ; ;E BD Dq$$- 1  ( (& 0  ! # 1  ( (% /%%f&@&@ /'1 2r%%. 2  ) )6 1  ! # 2  ) )5 0%%f&@&@ 0'2 3$<! 5  -&& +Qx{*#E?LE5 +sI33-J$#J$ct|d\}}}t|d}|r.|jjt j dt |||fS)a dtext = / obs-dtext obs-dtext = obs-NO-WS-CTL / quoted-pair We allow anything except the excluded characters, but if we find any ASCII other than the RFC defined printable ASCII, a NonPrintableDefect is added to the token's defects list. Quoted pairs are converted to their unquoted values, so what is returned is a ptext token, in this case a ValueTerminal. If there were quoted-printables, an ObsoleteHeaderDefect is added to the returned token's defect list. z[]rJz(quoted printable found in domain-literal)rrr'rrrr)rrJrs r get_dtextr)sZ2%>E5& % )E  V88 68 9E %<rc|ry|jtjd|jtddy)NFz"end of input inside domain-literal]domain-literal-endT)rrrur)rdomain_literals r_check_for_early_dl_endr.+s? &44,./--ABC rcnt}|dtvrt|\}}|j||st j d|ddk7r$t j dj ||dd}t||r||fS|jtdd|dtvrt|\}}|j|t|\}}|j|t||r||fS|dtvrt|\}}|j|t||r||fS|ddk7r$t j d j ||jtdd |dd}|r*|dtvrt|\}}|j|||fS) zB domain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS] rzexpected domain-literal[z6expected '[' at start of domain-literal but found '{}'rNzdomain-literal-startr+z4expected ']' at end of domain-literal but found '{}'r,) rGrrrrrr=r.rrrr))rr-rSs rget_domain_literalr13s#_N Qx; ue$ %%&?@@ Qx3%%'!!'0 0 !"IEun5u$$--CDE Qx3u~ ue$U#LE5% un5u$$ Qx3u~ ue$un5u$$ Qx3%%'!!'0 0--ABC !"IE q[( ue$ 5  rc"t}d}|r|dtvrt|\}}|s$tjdj ||ddk(r+t |\}}||g|dd|j|||fS t|\}}|r|ddk(rtjd||g|dd|j||r|ddk(r|jjtjd|djd k(r|d|dd|rJ|ddk(rB|jtt|d d\}}|j||r |ddk(rB||fS#tj$rt|\}}YwxYw) z] domain = dot-atom / domain-literal / obs-domain obs-domain = atom *("." atom)) Nrzexpected domain but found '{}'r0r-zInvalid Domainr z(domain is not a dot-atom (contains CFWS)rr)rrrrrr=r1rrrr'rrdrA)rrrrSs r get_domainr3Zs XF F q[(   %% , 3 3E :< < Qx3)%0 u  E"1I eu}'#E* u qS%%&677 Hbq  MM% qSf99 68 9 !9  : -q F1IaC MM# #E!"I.LE5 MM% aC 5=!  " "' u'sE**!F FcNt}t|\}}|j||r|ddk7r2|jjt j d||fS|jt ddt|dd\}}|j|||fS)z( addr-spec = local-part "@" domain rr-z#addr-spec local part with no domainaddress-at-symbolrN)r%r$rr'rrurr3)rrrSs r get_addr_specr6s I!%(LE5 U E!HO  !;!; 1"3 4% ]3(;<=eABi(LE5 U e rct}|rw|ddk(s |dtvrd|dtvr t|\}}|j|n"|ddk(r|jt|dd}|r|ddk(rX|dtvrd|r|ddk7r$t j dj||jtt|dd\}}|j||r|ddk(r|jt|dd}|snw|dtvrt|\}}|j||snJ|ddk(r7|jtt|dd\}}|j||r |ddk(r|st j d|ddk7r$t j d j||jtdd ||ddfS) z obs-route = obs-domain-list ":" obs-domain-list = *(CFWS / ",") "@" domain *("," [CFWS] ["@" domain]) Returns an obs-route token with the appropriate sub-tokens (that is, there is no obs-domain-list in the parse tree). rrrNr-z(expected obs-route domain but found '{}'z%end of header while parsing obs-route:z4expected ':' marking end of obs-route but found '{}'zend-of-obs-route-marker) rrrr ListSeparatorrrr=RouteComponentMarkerr3r)r obs_routerSs r get_obs_router<s I U1Xs]eAh+&= 8{ "#E?LE5   U # 1X_   ] +!"IE U1Xs]eAh+&= E!HO%% 6 = =e DF F )*eABi(LE5 U E!HcM'ab   8{ "#E?LE5   U #  8s?   1 2%eABi0LE5   U # E!HcM %%&MNN Qx3%%(''-ve}6 6 ]3(ABC eABi rcxt}|r*|dtvrt|\}}|j||r|ddk7r$t j dj ||jtdd|dd}|rZ|ddk(rR|jtdd|jjt jd |dd}||fS t|\}}|j||r|ddk(r|dd}n.|jjt jd |jtdd|r*|dtvrt|\}}|j|||fS#tj $r t|\}}|jjt jd n;#tj $r%t j d j |wxYw|j|t|\}}YHwxYw) z angle-addr = [CFWS] "<" addr-spec ">" [CFWS] / obs-angle-addr obs-angle-addr = [CFWS] "<" obs-route addr-spec ">" [CFWS] rzangle-addr-endznull addr-spec in angle-addrz*obsolete route specification in angle-addrz.expected addr-spec or obs-route but found '{}'z"missing trailing '>' on angle-addr) rrrrrrr=rr'rur6r<r)r angle_addrrSs rget_angle_addrrAs4 J q[( u% E!HO%% 0 7 7 >@ @mC);<= !"IE qS--=>?!!&"<"< *#, -ab 5   ,$U+ ue qSab !!&"<"< 0#2 3mC)9:; q[( u% u )  " " , P(/LE5    % %f&A&A<'> ?&& P))@GGNP P P % $U+ u ,s*"F H9) rrrr=rrrrCr8r"rrA)r name_addrrrSs r get_name_addrrFs` I F %% / 6 6u =? ? Qx;  ))3::6BD D Qx3 8{ "))3::5AC C'. u))3::5AC C  %(I. &xa! #Hbq F!%(LE5 Hbq  U e rclt} t|\}}t d|jDrd|_|j|||fS#tj$rN t |\}}n;#tj$r%tjdj |wxYwYwxYw)z& mailbox = name-addr / addr-spec zexpected mailbox but found '{}'c3PK|]}t|tj ywr$)r8rrur0s rr3zget_mailbox..+s% 3 11 a33 4 1$&r) r rFrrr6r=anyrErdr)rrrSs r get_mailboxrKs iGA$U+ u  3 % 1 1 33. NN5 E>  " "A A(/LE5&& A))188?A A AAs)AB3&A54B358B--B32B3ct}|r_|d|vrX|dtvr$|jt|dd|dd}nt |\}}|j||r|d|vrX||fS)z Read everything up to one of the chars in endchars. This is outside the formal grammar. The InvalidMailbox TokenList that is returned acts like a Mailbox, but the data attributes are None. rr&rN)rrrrr)rrinvalid_mailboxrSs rget_invalid_mailboxrN1s%&O E!HH, 8{ "  " "=q1D$F G!"IE%e,LE5  " "5 ) E!HH, E !!rc\t}|r|ddk7r t|\}}|j||ra|ddvrZ|d}d |_ t|d\}}|j||jjtjd|r"|ddk(r|jt|d d}|r |ddk7r||fS#tj$rLd}|dt vrt |\}}|r|ddvr@|j||jjtjdnt|d\}}||g|dd|j||jjtjdn|ddk(r/|jjtjdnVt|d\}}||g|dd|j||jjtjdYwxYw) aJ mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list obs-mbox-list = *([CFWS] ",") mailbox *("," [mailbox / CFWS]) For this routine we go outside the formal grammar in order to improve error handling. We recognize the end of the mailbox list only at the end of the value or at a ';' (the group terminator). This is so that we can turn invalid mailboxes into InvalidMailbox tokens and continue parsing any remaining valid mailboxes. We also allow all mailbox entries to be null, and this condition is handled appropriately at a higher level. r;Nz,;zempty element in mailbox-listzinvalid mailbox in mailbox-listrrrr)rrKrrrrrr'rrNrurdrQr9)r mailbox_listrSrrs rget_mailbox_listrRCs5=L E!HO 8&u-LE5    &4 U1XT)#2&G!2G .ud;LE5 NN5 !  ' '(B(B1)3 4 U1X_    .!"IEQ E!HOR  K&& 8FQx;& ( aD 0 ''/ ((//0K0K719:$7ud#CLE5)%+Hbq  ''. ((//0J0J91;<qS$$++F,G,G3-56 35$? u%!'E"1I##E*$$++F,F,F5-78/ 8sC EH+*H+ct}|s2|jjtjd||fSd}|r{|dt vrpt |\}}|sC|jjtjd|j|||fS|ddk(r|j|||fSt|\}}t|jdk(rV||j||j||jjtjd||fS||g|dd|j|||fS)zg group-list = mailbox-list / CFWS / obs-group-list obs-group-list = 1*([CFWS] ",") [CFWS] zend of header before group-listNrzend of header in group-listrPzgroup-list with empty entries) rr'rrrurrrRrrrQr)r group_listrrSs rget_group_listrU|sa J !!&"<"< -#/ 05  F q[(      % %f&@&@-'/ 0   f %u$ $ 8s?   f %u$ $#E*LE5 5  "     f %% !!&"="= +#- .5   Hbq e u rct}t|\}}|r|ddk7r$tjdj ||j ||j t dd|dd}|r*|ddk(r"|j t dd||ddfSt|\}}|j ||s/|jj tjd n,|ddk7r$tjd j ||j t dd|dd}|r*|dtvrt|\}}|j |||fS) z7 group = display-name ":" [group-list] ";" [CFWS] rr8z8expected ':' at end of group display name but found '{}'zgroup-display-name-terminatorrNrPzgroup-terminatorzend of header in groupz)expected ';' at end of group but found {}) rrCrrr=rrrUr'rurr)rrrSs r get_grouprWsa GE#E*LE5 E!HO%%'**0&-9 9 LL LLs$CDE !"IE qS ]3(:;<eABi!%(LE5 LL  V77 $& ' qS%% 7 > >u EG G LLs$678 !"IE q[( u U %<rc&t} t|\}}|j |||fS#tj$rN t |\}}n;#tj$r%tjdj |wxYwYuwxYw)a address = mailbox / group Note that counter-intuitively, an address can be either a single address or a list of addresses (a group). This is why the returned Address object has a 'mailboxes' attribute which treats a single address as a list of length one. When you need to differentiate between to two cases, extract the single element, which is either a mailbox or a group token. zexpected address but found '{}')rrWrrrKr=r)rrrSs r get_addressrYs"iGA ' u NN5 E>  " "A A&u-LE5&& A))188?A A AAs'/BAB8B  BBc^t}|r t|\}}|j||re|ddk7r]|dd}d|_ t|d\}}|j||jjtjd|r|jt|d d}|r||fS#tj$rad}|dt vrt |\}}|r|ddk(r@|j||jjtjdnt|d\}}||g|dd|jt|g|jjtjdn|ddk(r/|jjtjdn`t|d\}}||g|dd|jt|g|jjtjdYwxYw) a address_list = (address *("," address)) / obs-addr-list obs-addr-list = *([CFWS] ",") address *("," [address / CFWS]) We depart from the formal grammar here by continuing to parse until the end of the input, assuming the input to be entirely composed of an address-list. This is always true in email parsing, and allows us to skip invalid addresses to parse additional valid ones. Nrrz"address-list entry with no contentzinvalid address in address-listzempty element in address-listrrr)rrYrrrrrr'rrNrrurdrQr9)r address_listrSrrs rget_address_listr\s(=L  8&u-LE5    &4 U1X_#2&q)G!2G .uc:LE5 NN5 !  ' '(B(B1)3 4     .!"IEQ R  K&& 8FQx;& ( aC ''/ ((//0K0K<1>?$7uc#BLE5)%+Hbq  ''(89 ((//0J0J91;<qS$$++F,G,G3-56 35#> u%!'E"1I##GUG$45$$++F,F,F5-78/ 8sB77E1H,+H,ct}|s$tjdj||ddk7r$tjdj||j t dd|dd}t |\}}|j ||r|ddk7r$tjd j||j t dd ||ddfS) z& no-fold-literal = "[" *dtext "]" z'expected no-fold-literal but found '{}'rr0z;expected '[' at the start of no-fold-literal but found '{}'zno-fold-literal-startrNr+z9expected ']' at the end of no-fold-literal but found '{}'zno-fold-literal-end)r#rrr=rrr))rno_fold_literalrSs rget_no_fold_literalr_s$oO %% 5 < " [CFWS] id-left = dot-atom-text / obs-id-left id-right = dot-atom-text / no-fold-literal / obs-id-right no-fold-literal = "[" *dtext "]" rr>zexpected msg-id but found '{}'z msg-id-startrNzobsolete id-left in msg-idz4expected dot-atom-text or obs-id-left but found '{}'r-zmsg-id with no id-rightr?z msg-id-endr5zobsolete id-right in msg-idzFexpected dot-atom-text, no-fold-literal or obs-id-right but found '{}'zmissing trailing '>' on msg-id)rrrrrrr=rrr r'rrur_r3)rmsg_idrSs r get_msg_idrb)s WF q[( u e E!HO%% , 3 3E :< < MM-^45 !"IE 1(/ u MM% E!HOf88 %' ( U1X_ MM-\: ;!"IEu} MM-%89: !"IE 5(/ u MM% qSab f88 ,. / MM-\23 q[( u e 5=a  " " 1 1-e4LE5 NN ! !&"="=,#. /&& 1))""(&-1 1 1 / 14  " " 5 5.u5LE5&& 5 5)%0 u%%f&A&A1'34** 5--&&,fUm55 54 5 5sxG,I'I$(> ##F$>$> ? F Fv N%P QM&':; [ M&(;< q[( uE" E!HO    )  ' '(B(BB)D E     eW = > c+>?@ !"IE q[( uE"     )  ' '(B(BB)D E F E!HK/%(ab  E!HK/ >> ##F$>$> ? F Fv N%P QM&':; [ M&(;< q[( uE" ##F$>$> 5%7 8M%9: rct}|ra|ddk7rY|dtvr$|jt|dd|dd}nt |\}}|j||r |ddk7rY||fS)z Read everything up to the next ';'. This is outside the formal grammar. The InvalidParameter TokenList that is returned acts like a Parameter, but the data attributes are None. rrPr&rN)r\rrrr)rinvalid_parameterrSs rget_invalid_parameterrps)* E!HO 8{ "  $ $]583F&H I!"IE%e,LE5  $ $U + E!HO e ##rct|}|s$tjdj||j }|t |d}t |d}t|||fS)a8ttext = We allow any non-TOKEN_ENDS in ttext, but add defects to the token's defects list if we find non-ttext characters. We also register defects for *any* non-printables even though the RFC doesn't exclude all of them, because we follow the spirit of RFC 5322. zexpected ttext but found '{}'Nttext)_non_token_end_matcherrrr=rrrr)rrrrs r get_ttextrtsk u%A %% + 2 25 9; ; GGIE #e*+ E % )EE %<rcnt}|r*|dtvrt|\}}|j||r/|dtvr$t j dj|t|\}}|j||r*|dtvrt|\}}|j|||fS)ztoken = [CFWS] 1*ttext [CFWS] The RFC equivalent of ttext is any US-ASCII chars except space, ctls, or tspecials. We also exclude tabs even though the RFC doesn't. The RFC implies the CFWS but is not explicit about it in the BNF. rexpected token but found '{}') rrrr TOKEN_ENDSrrr=rt)rmtokenrSs r get_tokenrysWF q[( u e qZ'%% + 2 25 9; ;U#LE5 MM% q[( u e 5=rct|}|s$tjdj||j }|t |d}t |d}t|||fS)aQattrtext = 1*(any non-ATTRIBUTE_ENDS character) We allow any non-ATTRIBUTE_ENDS in attrtext, but add defects to the token's defects list if we find non-attrtext characters. We also register defects for *any* non-printables even though the RFC doesn't exclude all of them, because we follow the spirit of RFC 5322. z expected attrtext but found {!r}Nrb)_non_attribute_end_matcherrrr=rrrrrrrbs r get_attrtextr} sk #5)A %% . 5 5e <> >wwyH #h-. !EXz2HH U?rcnt}|r*|dtvrt|\}}|j||r/|dtvr$t j dj|t|\}}|j||r*|dtvrt|\}}|j|||fS)aH [CFWS] 1*attrtext [CFWS] This version of the BNF makes the CFWS explicit, and as usual we use a value terminal for the actual run of characters. The RFC equivalent of attrtext is the token characters, with the subtraction of '*', "'", and '%'. We include tab in the excluded set just as we do for token. rrv) r_rrrATTRIBUTE_ENDSrrr=r}rr`rSs r get_attributer s I q[( u q^+%% + 2 25 9; ;&LE5 U q[( u e rct|}|s$tjdj||j }|t |d}t |d}t|||fS)zattrtext = 1*(any non-ATTRIBUTE_ENDS character plus '%') This is a special parsing routine so that we get a value that includes % escapes as a single string (which we decode as a single string later). z)expected extended attrtext but found {!r}Nextended-attrtext)#_non_extended_attribute_end_matcherrrr=rrrrr|s rget_extended_attrtextr4 sn ,E2A %% 7 > >u EG GwwyH #h-. !EX':;HH U?rcnt}|r*|dtvrt|\}}|j||r/|dtvr$t j dj|t|\}}|j||r*|dtvrt|\}}|j|||fS)z [CFWS] 1*extended_attrtext [CFWS] This is like the non-extended version except we allow % characters, so that we can pick up an encoded value as a single string. rrv) r_rrrEXTENDED_ATTRIBUTE_ENDSrrr=rrs rget_extended_attributerF s I q[( u q44%% + 2 25 9; ;(/LE5 U q[( u e rclt}|r|ddk7r$tjdj||j t dd|dd}|r|dj s$tjdj|d}|r6|dj r#||dz }|dd}|r|dj r#|dd k(r3|d k7r.|jj tjd t||_ |j t |d ||fS) a6 '*' digits The formal BNF is more complicated because leading 0s are not allowed. We check for that and add a defect. We also assume no CFWS is allowed between the '*' and the digits, though the RFC is not crystal clear on that. The caller should already have dealt with leading CFWS. r*zExpected section but found {}zsection-markerrNz$Expected section number but found {}r-0z'section number has an invalid leading 0rh) rfrrr=rrrjr'rurkrV)rrgrhs r get_sectionr\ s2iG E!HO%%&E&L&L(-'/0 0 NN=&678 !"IE a((*%%'117@ @ F E!H$$&%(ab  E!H$$&ayCFcMv999 ; <[GN NN=23 E>rcJt}|stjdd}|dtvrt |\}}|s$tjdj ||ddk(rt |\}}nt|\}}||g|dd|j|||fS)z quoted-string / attribute z&Expected value but found end of stringNrz Expected value but found only {}r) rirrrrr=r rr)rvrrSs r get_valuerz s A %%&NOO F Qx;   %%'006v@ @ Qx3(/ u-e4 u Hbq HHUO e8Orc t}t|\}}|j||r|ddk(rA|jjt j dj |||fS|ddk(rm t|\}}d|_|j||st jd|ddk(r'|jtdd|dd }d|_ |dd k7rt jd |jtd d |dd }|r*|dtvrt|\}}|j|d }|}|jr|r|dd k(rt|\}}|j}d}|j dk(r(|r |ddk(rd}n/t#|\}}|r|ddk(rd}n t%|\}}|sd} |ra|jjt j d|j||D]} | j&dk(sg| d d | }n|}n0d }|jjt j d|r |ddk(rd }nt)|\}}|jr|j dkDrQ|r|ddk7r|j|||}||fS|jjt j d|sF|jjt j d|j||#||fS|I|D]} | j&dk(sn j&dk(|j| | j*|_|ddk7r$t jdj ||jtdd|dd }|rf|ddk7r^t#|\}}|j||j*|_|r|ddk7r$t jdj ||jtdd|dd }|et1} |rV|dt2vrt5|\}}n(|dd k(rtd d}|dd }nt7|\}}| j||rV| }nt)|\}}|j|||}||fS#tj$rYWwxYw#Y.xYw)aY attribute [section] ["*"] [CFWS] "=" value The CFWS is implied by the RFC but not made explicit in the BNF. This simplified form of the BNF from the RFC is made to conform with the RFC BNF through some extra checks. We do it this way because it makes both error recovery and working with the resulting parse tree easier. rrPz)Parameter contains name ({}) but no valuerTzIncomplete parameterzextended-parameter-markerrN=zParameter not followed by '='parameter-separatorrF'z5Quoted string value for extended parameter is invalidrzZParameter marked as extended but appears to have a quoted string value that is non-encodedzcApparent initial-extended-value but attribute was not marked as extended or was not initial sectionz(Missing required charset/lang delimitersrrbz=Expected RFC2231 char/lang encoding delimiter, but found {!r}zRFC2231-delimiterz;Expected RFC2231 char/lang encoding delimiter, but found {}DQUOTE)rQrrr'rrur=rrUrrrZrrr rrWr}rrdrrrrrirrr) rrrSrappendtoqstring inner_value semi_validrtrs r get_parameterr s KE 'LE5 LL E!HO V779%%+VE]4 5e| Qx3 &u-LE5"EO LL ))*@A A 8s? LLs,GH I!"IE!EN Qx3%%&EFF LLs$9:; !"IE q[( u UIH ~~%E!HO/u5,,    1 ${1~4! *;7 tDGsN!%J &3K@ t!%J  MM !;!;G"I J LL !<<#77AaD H   EI MM !;!;:"; < qS ' u >>U11A5aC OOE "$!%<  V77 DE F  V77 68 9  %<   <<#66 LLJ & OOA GGEM 8s?))+FFLfUmU U c+>?@ab  U1X_'.LE5 OOE "EJE!HO--/<?@ab  GQx3&u~ uqS%c84ab +E2 u HHUO ' u OOE %<i&&   D s>&S%S?%S<;S<?Tct}|r t|\}}|j||rp|ddk7rh|d}d|_ t|\}}|j||jjtjdj||r |jtdd |d d}|r|S#tj$rd}|dt vrt |\}}|s|j||cYS|ddk(rB||j||jjtjdndt|\}}|r|g|dd|j||jjtjdj|YwxYw) a! parameter *( ";" parameter ) That BNF is meant to indicate this routine should only be called after finding and handling the leading ';'. There is no corresponding rule in the formal RFC grammar, but it is more convenient for us for the set of parameters to be treated as its own TokenList. This is 'parse' routine because it consumes the remaining value, but it would never be called to parse a full header. Instead it is called to parse everything after the non-parameter value of a specific MIME header. NrrPzparameter entry with no contentzinvalid parameter {!r}rr]z)parameter with invalid trailing text {!r}rr)rlrrrrrrr'rurpr=rdrQr)rmime_parametersrSrrs rparse_mime_parametersr s%&O  =(/LE5  " "5 )( U1X_$B'E2E 07LE5 LL   # # * *6+E+E;BB5I,K L   " "=6K#L M!"IEG H A&& =FQx;& ( &&v.&&Qx3%#**62''..v/I/I5078 5U; u!'E"1I&&u-''..v/I/I,33E:0<=# =sCAF= B.F=<F=c@|ra|ddk7rY|dtvr$|jt|dd|dd}nt|\}}|j||r |ddk7rY|sy|jtdd|jt |ddy)zBDo our best to find the parameters in an invalid MIME header rrPr&rNr)rrrrr) tokenlistrrSs r_find_mime_parametersrQ s E!HO 8{ "   ]585HI J!"IE%e,LE5   U # E!HO  ]3(=>? *5956rc8t}|s0|jjtjd|S t |\}}|j||r|ddk7r>|jjtjd|r t|||S|jjj|_ |jtdd|dd} t |\}}|j||jjj|_|s|S|dd k7rO|jjtjd j||` |`t|||S|jtd d |jt!|dd|S#tj $rN|jjtjdj|t|||cYSwxYw#tj $rN|jjtjd j|t|||cYSwxYw) z maintype "/" subtype *( ";" parameter ) The maintype and substype are tokens. Theoretically they could be checked against the official IANA list + x-token, but we don't do that. z"Missing content type specificationz(Expected content maintype but found {!r}rrzInvalid content typezcontent-type-separatorrNz'Expected content subtype but found {!r}rPz> 02 3  ' u  LL E!HO V77 "$ %  !% / [[&&(..0EN LLs$<=> !"IE ' u  LLKK%%'--/EM   Qx3 V77 ( ) NEMeU+  LLs$9:; LL&uQRy12 LQ  " " V77 6 = =e DF GeU+ &  " " V77 5 < . s%.,qa!>!>?,rI unknown-8bitTrmrUrr!rrrJrwrr)"max_line_lengthsysmaxsizeutf8rrr7rrd SPECIALSNL isdisjointNLSETr!r{rJrE_fold_mime_parametersrMrjrYrrrrre _fold_as_ewrkrJrr7rrrinsert) parse_treerVmaxlenrqrleading_whitespacelast_ew last_charsetr want_encodingend_ew_not_allowedrrNtstrr encoded_partnewlinewhitespace_accumulatorcharnewpartsps rrWrW s  # # 2s{{F ++w:H DEGLM!"&:;  E yy| % % ! #  4y"44$.$9$9$$? ? %*$4$4T$: :  ! KK !G ??/ / !$vx @  !3%% % ''#'99F9#;Q=Q#RL~~\9|,vE"I/FF&CE&JG!LL1b \1  4*T U* % ##'|+!^3!W,J1F"G%dE67&*&=&=wHZ\&("& %  %  t9U2Y/ / "I I     D A '3E:G$--/  Wt^,)+&!"ID3*11$7&&(WW-C%D"tX&DzH"66 #301&(&##4Q#7A&((#3012 )+"301'(& /##9!#>  u % 66}" !. ,,..(" M !B( (s:P)#Q1-Q!),QQc|+|r)tt|d|d|z}|dd||d<nM|dtvrB|d}|dd}t|d|k(r|j t ||dxx|z cc<d}|dtvr |d}|dd}|t|dn|} |dk(rdn|} t| dz} | dz|k\rt jd |r!|t|dz } | | z t|z } | dkr|j d  b [ L} } crN $+O#eBi.K"j0gIY!#JQ6!%% AC C  3uRy>1$z1C8J4KK ? LL   u:>c%)n16H::&8)LL "I %I!# ";J/zz.)D \"_4qj,CR0N::niHL&8F qj b \! c.123   LL eBi.K? @ "II,;6$6rc |jD]\}}|djjds |dxxdz cc<|}d} |j|d}|r6tjj|d | } d j||| } nd j|t|} t|dt| zd z|kr|ddz| z|d<t| dz|kr|jd| zd} |dz} |st|tt| zdzt| z} || dzkrd}|| z dz x}} |d|}tjj|d | } t| |krn|d z}<|jdj|| | | d } | d z } ||d}|r |dxxdz cc<|ry#t$r"d}t j |rd}d}nd}YwxYw)a>Fold TokenList 'part' into the 'lines' list as mime parameters. Using the decoded list of parameters and values, format them according to the RFC rules, including using RFC2231 encoding if the value cannot be expressed in 'encoding' and/or the parameter+value is too long to fit within 'maxlen'. rrPstrictFTrrprr-)saferz {}*={}''{}rrrsrrz''r(NNz {}*{}*={}{})rr*rcr!r{rr|rvrwrr=r rrr)rNrrrqrrr error_handlerencoding_required encoded_valuerrg extra_chromer splitpointmaxcharspartials rrr sA{{ e Ry!**3/ "I I  " LL " %  "LL..B}/6M&&tWmDD>>$ U(;CI % )F 2b C$.E"I  Y]f $ LLt $ ~ TSW%66:S=NNJa' $*Z$7!$; ;J , & 2 2"]!3!< }%1a  LL..g|]< =L qLG*+&Eb S -I#" " $ $$U+( 1 !  "sG'G>=G>)r)rrerrvstringroperatorremailrrrrr.rrrr r/r TSPECIALSrw ASPECIALSrrrrrrr compileVERBOSE MULTILINErrr"rpr|rrrrrrrrrrrrrrrrrr rrrr r#r%r3r5r=rGrMrQr\r_rfrirlrrrrrrrrrrrrrrrrrAr9rMrjr:r=r7rrrmatchrfindallrrsr{rrrrrrrrrrrrr rrrrrr$r r)r.r1r3r6r<rArCrFrKrNrRrUrWrYr\r_rbrfrmrprtryr}rrrrrrrrrrrrrWrrrtrrrs:CJ '  %jCHn   sN CH$ U# E "c#h . _ E " S(3s83 t    @ 1  "**ZZ",, @,@,FD)D I Y9"9I )#9#6 -| -!4C)C&%i%2 ?) ?% %"$I$*"y"6 DDyD!i!6;Y;.Y.i) I yB9 -!&-!`! !H I  ) 8%y% # #i I S.YS.l y *1 i ) *I*&y&Y(+s(+V''H->#I$4$4 BIIbggj!"%$%%*U'RZZ (8(8 BIIbggn%&)()).&0bjj1A1A BIIbgg-./21'227%$;J< /bAF"  ))V2  $6 &2 D$L%N2!h(%!N$L ) V,\ "H*"$6r#J<:4n&,BJ8BH$$&.&.$,<,KZ2h7 6p<^`7DJ7XI!r__pycache__/_policybase.cpython-312.opt-1.pyc000064400000044314152526700320014717 0ustar00 {|j<dZddlZddlmZddlmZddlmZgdZGddZ d Z d Z Gd d e ej Z e Gdde ZeZy)zwPolicy framework for the email package. Allows fine grained feature control of how the package parses and emits data. N)header)charset)_has_surrogates)PolicyCompat32compat32c:eZdZdZfdZdZdZdZdZxZ S) _PolicyBaseaPolicy Object basic framework. This class is useless unless subclassed. A subclass should define class attributes with defaults for any values that are to be managed by the Policy object. The constructor will then allow non-default values to be set for these attributes at instance creation time. The instance will be callable, taking these same attributes keyword arguments, and returning a new instance identical to the called instance except for those values changed by the keyword arguments. Instances may be added, yielding new instances with any non-default values from the right hand operand overriding those in the left hand operand. That is, A + B == A() The repr of an instance can be used to reconstruct the object if and only if the repr of the values can be used to reconstruct those values. c |jD]T\}}t||rtt|||'t dj ||jjy)zCreate new Policy, possibly overriding some defaults. See class docstring for a list of overridable attributes. *{!r} is an invalid keyword argument for {}N) itemshasattrsuperr __setattr__ TypeErrorformat __class____name__)selfkwnamevaluers */usr/lib64/python3.12/email/_policybase.py__init__z_PolicyBase.__init__)s^ 88:KD%tT"k$3D%@@GGdnn55788 &c|jjDcgc]\}}dj||}}}dj|jjdj |Scc}}w)Nz{}={!r}z{}({})z, )__dict__r rrrjoin)rrrargss r__repr__z_PolicyBase.__repr__7sh$(MM$7$7$9<$9[T5!!$.$9 <t~~66 $HH>: ==..0KD%   y$ 6188:KD%4&@GGdnn55788   y$ 6 & rct||rd}nd}t|j|jj|)Nz'{!r} object attribute {!r} is read-onlyz!{!r} object has no attribute {!r})rAttributeErrorrrr)rrrmsgs rrz_PolicyBase.__setattr__Ns6 4 ;C5CSZZ(?(?FGGrc:|jdi|jS)zNon-default values from right operand override those from left. The object returned is a new instance of the subclass. )r&r)rothers r__add__z_PolicyBase.__add__Us tzz+ENN++r) r __module__ __qualname____doc__rr r&rr- __classcell__)rs@rr r s#* 8I $H,rr cf|jddd}|jddd}|dz|zS)N r)rsplitsplit)doc added_docs r _append_docr9^s; **T1 a Ca(+I : !!rc|jrM|jjdr2t|jdj|j|_|jj D]{\}}|js|jjds/d|jDD]7}t t ||d}|st||j|_{}|S)N+rc3JK|]}|jD]}|yw)N)mro).0basecs r z%_extend_docstrings..hsFMD488:aa:aMs!#r0)r0 startswithr9 __bases__rr getattr)clsrr%r@r7s r_extend_docstringsrFcs {{s{{--c2!#--"2":":CKKH ll((* d <' in front of them. This is used when the message is being serialized by a generator. Default: False. message_factory -- the class to use to create new message objects. If the value is None, the default is Message. verify_generated_headers -- if true, the generator verifies that each header they are properly folded, so that a parser won't treat it as multiple headers, start-of-body, or part of another header. This is a check against custom Header & fold() implementations. Fr38bitNNTcD|jr||j||y)aZBased on policy, either raise defect or call register_defect. handle_defect(obj, defect) defect should be a Defect subclass, but in any case must be an Exception subclass. obj is the object on which the defect should be registered if it is not raised. If the raise_on_defect is True, the defect is raised as an error, otherwise the object and the defect are passed to register_defect. This method is intended to be called by parsers that discover defects. The email package parsers always call it with Defect instances. N)raise_on_defectregister_defectrobjdefects r handle_defectzPolicy.handle_defects"   L S&)rc:|jj|y)aRecord 'defect' on 'obj'. Called by handle_defect if raise_on_defect is False. This method is part of the Policy API so that Policy subclasses can implement custom defect handling. The default implementation calls the append method of the defects attribute of obj. The objects used by the email package by default that get passed to this method will always have a defects attribute with an append method. N)defectsappendrMs rrLzPolicy.register_defects 6"rcy)a[Return the maximum allowed number of headers named 'name'. Called when a header is added to a Message object. If the returned value is not 0 or None, and there are already a number of headers with the name 'name' equal to the value returned, a ValueError is raised. Because the default behavior of Message's __setitem__ is to append the value to the list of headers, it is easy to create duplicate headers without realizing it. This method allows certain headers to be limited in the number of instances of that header that may be added to a Message programmatically. (The limit is not observed by the parser, which will faithfully produce as many headers as exist in the message being parsed.) The default implementation returns None for all header names. Nr+)rrs rheader_max_countzPolicy.header_max_counts"rct)aZGiven a list of linesep terminated strings constituting the lines of a single header, return the (name, value) tuple that should be stored in the model. The input lines should retain their terminating linesep characters. The lines passed in by the email package may contain surrogateescaped binary data. NotImplementedError)r sourceliness rheader_source_parsezPolicy.header_source_parse "!rct)zGiven the header name and the value provided by the application program, return the (name, value) that should be stored in the model. rWrrrs rheader_store_parsezPolicy.header_store_parses "!rct)awGiven the header name and the value from the model, return the value to be returned to the application program that is requesting that header. The value passed in by the email package may contain surrogateescaped binary data if the lines were parsed by a BytesParser. The returned value should not contain any surrogateescaped data. rWr]s rheader_fetch_parsezPolicy.header_fetch_parses "!rct)aGiven the header name and the value from the model, return a string containing linesep characters that implement the folding of the header according to the policy controls. The value passed in by the email package may contain surrogateescaped binary data if the lines were parsed by a BytesParser. The returned value should not contain any surrogateescaped data. rWr]s rfoldz Policy.folds "!rct)a%Given the header name and the value from the model, return binary data containing linesep characters that implement the folding of the header according to the policy controls. The value passed in by the email package may contain surrogateescaped binary data. rWr]s r fold_binaryzPolicy.fold_binary r[r)rr.r/r0rKlinesepcte_typemax_line_length mangle_from_message_factoryverify_generated_headersrPrLrUabcabstractmethodrZr^r`rbrdr+rrrrps5nOGHOLO#*& #& "" ""  ""  " " ""rr) metaclassc>eZdZdZdZdZdZdZdZdZ dZ d Z y ) rz+ This particular policy is the backward compatibility Policy. It replicates the behavior of the email package version 5.1. Tct|ts|St|r&tj|t j |S|S)Nr header_name) isinstancestrrrHeader_charset UNKNOWN8BITr]s r_sanitize_headerzCompat32._sanitize_header!s@%%L 5 !==0D0D-13 3Lrc|djdd\}}dj|g|ddjd}||jdfS)a4+ The name is parsed as everything up to the ':' and returned unmodified. The value is determined by stripping leading whitespace off the remainder of the first line joined with all subsequent lines, and stripping any trailing carriage return or linefeed characters. r:r4Nz z )r6rlstriprstrip)rrYrrs rrZzCompat32.header_source_parse-sY"!n**32 e1QR1299)Dell6*++rc ||fS)z>+ The name and value are returned unmodified. r+r]s rr^zCompat32.header_store_parse9se}rc&|j||S)z+ If the value contains binary data, it is converted into a Header object using the unknown-8bit charset. Otherwise it is returned unmodified. )rwr]s rr`zCompat32.header_fetch_parse?s $$T511rc*|j||dS)a+ Headers are folded using the Header folding algorithm, which preserves existing line breaks in the value, and wraps each resulting line to the max_line_length. Non-ASCII binary data are CTE encoded using the unknown-8bit charset. Tsanitize)_foldr]s rrbz Compat32.foldFszz$z55rch|j|||jdk(}|jddS)a+ Headers are folded using the Header folding algorithm, which preserves existing line breaks in the value, and wraps each resulting line to the max_line_length. If cte_type is 7bit, non-ascii binary data is CTE encoded using the unknown-8bit charset. Otherwise the original source header is used, with its existing line breaks and/or binary data. 7bitrasciisurrogateescape)rrfencode)rrrfoldeds rrdzCompat32.fold_binaryPs3D%$--2GH}}W&788rcg}|jd|zt|tr`t|r=|r't j |t j|}n.|j|d}nt j ||}n|}|Fd}|j |j}|j|j|j||j|jdj|S)Nz%s: rp)rqr)re maxlinelenrz) rSrrrsrrrtrurvrgrrer)rrrrpartshrs rrzCompat32._fold\s Vd]# eS !u% e.6.B.B268ALL'AMM%T:A =J##/!11 LL$,,:N O T\\"wwu~rN) rr.r/r0rhrwrZr^r`rbrdrr+rrrrs1 L  , 26 9rr)r0rkemailrrru email.utilsr__all__r r9rFABCMetarrrr+rrrss  %' I,I,X" d"[CKKd"NcvccL :r__pycache__/errors.cpython-312.pyc000064400000015557152526700320013012 0ustar00 {|j`dZGddeZGddeZGddeZGddeZGd d eeZGd d eZGd deZ Gdde Z Gdde Z Gdde Z Gdde ZGdde ZGdde ZGdde ZeZGdde ZGdd e ZGd!d"e ZGd#d$e ZGd%d&e ZGd'd(e ZGd)d*e ZGd+d,eZGd-d.eZGd/d0eZGd1d2eZGd3d4eZGd5d6eZy7)8z email package exception classes.ceZdZdZy) MessageErrorz+Base class for errors in the email package.N__name__ __module__ __qualname____doc__%/usr/lib64/python3.12/email/errors.pyrr5r rceZdZdZy)MessageParseErrorz&Base class for message parsing errors.Nrr r r rr s0r rceZdZdZy)HeaderParseErrorzError while parsing headers.Nrr r r rr&r rceZdZdZy) BoundaryErrorz#Couldn't find terminating boundary.Nrr r r rrs-r rceZdZdZy)MultipartConversionErrorz(Conversion to a multipart is prohibited.Nrr r r rr2r rceZdZdZy) CharsetErrorzAn illegal charset was given.Nrr r r rrs'r rceZdZdZy)HeaderWriteErrorzError while writing headers.Nrr r r rr rr rc$eZdZdZdfd ZxZS) MessageDefectz Base class for a message defect.c6|t||||_yN)super__init__line)selfr! __class__s r r zMessageDefect.__init__(s   G T " r rrrrrr __classcell__r#s@r rr%s*r rceZdZdZy)NoBoundaryInMultipartDefectzBA message claimed to be a multipart but had no boundary parameter.Nrr r r r(r(-sLr r(ceZdZdZy)StartBoundaryNotFoundDefectz+The claimed start boundary was never found.Nrr r r r*r*0r r r*ceZdZdZy)CloseBoundaryNotFoundDefectzEA start boundary was found, but not the corresponding close boundary.Nrr r r r,r,3Or r,ceZdZdZy)#FirstHeaderLineIsContinuationDefectz;A message had a continuation line as its first header line.Nrr r r r/r/6sEr r/ceZdZdZy)MisplacedEnvelopeHeaderDefectz?A 'Unix-from' header was found in the middle of a header block.Nrr r r r1r19Ir r1ceZdZdZy) MissingHeaderBodySeparatorDefectzEFound line with no leading whitespace and no colon before blank line.Nrr r r r4r4<r-r r4ceZdZdZy)!MultipartInvariantViolationDefectz?A message claimed to be a multipart but no subparts were found.Nrr r r r6r6Ar2r r6ceZdZdZy)-InvalidMultipartContentTransferEncodingDefectzEAn invalid content transfer encoding was set on the multipart itself.Nrr r r r8r8Dr-r r8ceZdZdZy)UndecodableBytesDefectz0Header contained bytes that could not be decodedNrr r r r:r:G:r r:ceZdZdZy)InvalidBase64PaddingDefectz/base64 encoded sequence had an incorrect lengthNrr r r r=r=Js9r r=ceZdZdZy)InvalidBase64CharactersDefectz=base64 encoded sequence had characters not in base64 alphabetNrr r r r?r?MsGr r?ceZdZdZy)InvalidBase64LengthDefectz4base64 encoded sequence had invalid length (1 mod 4)Nrr r r rArAPs>r rAc"eZdZdZfdZxZS) HeaderDefectzBase class for a header defect.c$t||i|yr)rr )r"argskwr#s r r zHeaderDefect.__init__Xs $%"%r r$r&s@r rCrCUs)&&r rCceZdZdZy)InvalidHeaderDefectz+Header is not valid, message gives details.Nrr r r rHrH[r r rHceZdZdZy)HeaderMissingRequiredValuez(A header that must have a value had noneNrr r r rJrJ^rr rJc(eZdZdZfdZdZxZS)NonPrintableDefectz8ASCII characters outside the ascii-printable range foundc2t||||_yr)rr non_printables)r"rNr#s r r zNonPrintableDefect.__init__ds (,r c8dj|jS)Nz6the following ASCII non-printables found in header: {})formatrN)r"s r __str__zNonPrintableDefect.__str__hs++, .r )rrrrr rQr%r&s@r rLrLasB-.r rLceZdZdZy)ObsoleteHeaderDefectz0Header uses syntax declared obsolete by RFC 5322Nrr r r rSrSlr;r rSceZdZdZy)NonASCIILocalPartDefectz(local_part contains non-ASCII charactersNrr r r rUrUorr rUceZdZdZy)InvalidDateDefectz%Header has unparsable or invalid dateNrr r r rWrWts/r rWN) r Exceptionrrrr TypeErrorrrr ValueErrorrr(r*r,r/r1r4MalformedHeaderDefectr6r8r:r=r?rArCrHrJrLrSrUrWr r r r\sj '6961 1'('.%.3|Y3(<('|' JM-M6-6P-PF-FJMJP}P9J JPMP;];::HMH? ? &=& 6,633 . .;<;3l3 0 0r __pycache__/encoders.cpython-312.opt-1.pyc000064400000004053152526700320014224 0ustar00 {|jFdZgdZddlmZddlmZdZdZ dZ dZ d Z y ) z Encodings and related functions.)encode_7or8bit encode_base64 encode_noop encode_quopri) encodebytes) encodestringc@t|d}|jddS)NT) quotetabs s=20) _encodestringreplace)sencs '/usr/lib64/python3.12/email/encoders.py_qencoders T *C ;;tV $$c~|jd}tt|d}|j|d|d<y)zlEncode the message's payload in Base64. Also, add an appropriate Content-Transfer-Encoding header. Tdecodeasciibase64Content-Transfer-EncodingN) get_payloadstr_bencode set_payloadmsgorigencdatas rrrs; ??$? 'D(4.'*GOOG'/C#$rcj|jd}t|}|j|d|d<y)zvEncode the message's payload in quoted-printable. Also, add an appropriate Content-Transfer-Encoding header. Trzquoted-printablerN)rrrrs rrr$s4 ??$? 'DtnGOOG'9C#$rc|jd}|d|d<y |jdd|d<y#t$rd|d<YywxYw)z9Set the Content-Transfer-Encoding header to 7bit or 8bit.TrN7bitrr8bit)rr UnicodeError)rrs rrr/s_ ??$? 'D |+1 '(2 G,2 '( 2+1 '(2s3AAcy)z Do nothing.N)rs rrr@srN) __doc____all__rrrquoprirr rrrrrr'rrr+s2 ' +0% 0:2"r__pycache__/header.cpython-312.pyc000064400000057677152526700320012737 0ustar00 {|j^dZgdZddlZddlZddlZddlZddlmZddlm Z e jZ dZ dZ dZd Zd Zd Zd Ze d Ze dZej*dej,ej.zZej*dZej*dZej6j8ZdZ ddZGddZGddZ Gdde!Z"y)z+Header encoding and decoding functionality.)Header decode_header make_headerN)HeaderParseError)charset   z Nz us-asciizutf-8ai =\? # literal =? (?P[^?]*?) # non-greedy up to the next ? is the charset \? # literal ? (?P[qQbB]) # either a "q" or a "b", case insensitive \? # literal ? (?P.*?) # non-greedy up to the next ?= is the encoded string \?= # literal ?= z[\041-\176]+:$z \n[^ \t]+:c t|drG|jDcgc]/\}}tj|t |t |f1c}}St j |s|dfgSg}|jD]}t j|}d}|s|jd}|r|j}d}|r|j|ddf|rc|jdj}|jdj}|jd} |j| ||f|rg} t|D]K\} } | dkDs | ds|| dz ds|| dz djs8| j| dz Mt| D]} || =g}|D]\}}}||j||f|dk(r3t j"j%|}|j||fU|d k(rOt'|d z}|r |d dd |z z } t j(j+|}|j||ft3d |zg}dx}}|D]Y\}}t5|tr t7|d}||}|})||k7r|j||f|}|}F| |t8|zz }U||z }[|j||f|Scc}}w#t,j.$r t1d wxYw)a;Decode a message header value without converting charset. Returns a list of (string, charset) pairs containing each of the decoded parts of the header. Charset is None for non-encoded parts of the header, otherwise a lower-case string containing the name of the character set specified in the encoded string. header may be a string that may or may not contain RFC2047 encoded words, or it may be a Header object. An email.errors.HeaderParseError may be raised when certain decoding error occurs (e.g. a base64 decoding exception). _chunksNTrFqbz===zBase64 decoding errorzUnexpected encoding: zraw-unicode-escape)hasattrr_charset_encodestrecresearch splitlinessplitpoplstripappendlower enumerateisspacereversedemail quoprimime header_decodelen base64mimedecodebinasciiErrorrAssertionError isinstancebytesBSPACE)headerstringrwordslinepartsfirst unencodedencodingencodeddroplistnwd decoded_wordsencoded_stringwordpaderr collapsed last_word last_charsets %/usr/lib64/python3.12/email/header.pyrr;s8vy!+1>>;+9!!&#g,7WF+9; ; ;;v  E!!# 4  ! I%,,.  it45))A,,,. 99Q<--/))A, gx9:$"H% 1 Q31Q4E!A#JqMeAaCjm.C.C.E OOAaC !h  !H M-2)'    .'!: ; _##11.AD  $ 1 _(1,F% V"44 6''..~>$$dG_5 !88!CD D%.3*I##I & g dC 34D  I"L  $   i6 7I"L  ! $ &I  I'i./ W;d>> @&'>?? @s4K%*K++L ct|||}|D]4\}}|t|ts t|}|j||6|S)aCreate a Header from a sequence of pairs as returned by decode_header() decode_header() takes a header value string and returns a sequence of pairs of the format (decoded_string, charset) where charset is the string name of the character set. This function takes one of those sequence of pairs and returns a Header instance. Optional maxlinelen, header_name, and continuation_ws are as in the Header constructor. ) maxlinelen header_namecontinuation_ws)rr-Charsetr) decoded_seqrFrGrHhsrs rDrrsQ *+. 0A! 7  z'7'Cg&G G " HcBeZdZ d dZdZdZd dZdZd dZdZ y) rNc|t}nt|ts t|}||_||_g|_||j ||||t}||_|d|_ yt|dz|_ y)aDCreate a MIME-compliant header that can contain many character sets. Optional s is the initial header value. If None, the initial header value is not set. You can later append to the header with .append() method calls. s may be a byte string or a Unicode string, but see the .append() documentation for semantics. Optional charset serves two purposes: it has the same meaning as the charset argument to the .append() method. It also sets the default character set for all subsequent .append() calls that omit the charset argument. If charset is not provided in the constructor, the us-ascii charset is used both as s's initial charset and as the default for subsequent .append() calls. The maximum line length can be specified explicitly via maxlinelen. For splitting the first line to a shorter value (to account for the field header which isn't included in s, e.g. `Subject') pass in the name of the field in header_name. The default maxlinelen is 78 as recommended by RFC 2822. continuation_ws must be RFC 2822 compliant folding whitespace (usually either a space or a hard tab) which will be prepended to continuation lines. errors is passed through to the .append() call. Nrr) USASCIIr-rIr_continuation_wsrr MAXLINELEN _maxlinelen _headerlenr')selfrLrrFrGrHerrorss rD__init__zHeader.__init__s: ?GGW-g&G / = KK7F +  #J%  DO"+.2DOrMc|jg}d}d}|jD]\}}|}|tjk(r$|j dd}|j dd}|rU|xr|j |d}|dvr|dvr5|s3|jtd}n|dvr|s|jt|xr|j |d}|}|j|tj|S)z&Return the string value of the header.NasciisurrogateescapereplacerNr ) _normalizerr UNKNOWN8BITencoder) _nonctextrSPACE EMPTYSTRINGjoin) rUuchunkslastcs lastspacer1rnextcsoriginal_byteshasspaces rD__str__zHeader.__str__s  #||OFGF---!'w8I!J'..w B!?dnnVAY&?!33!33Hu-!%#55iNN5)=4>>&*#=IF NN6 "+ ,,((rMc|t|k(SN)r)rUothers rD__eq__z Header.__eq__sD !!rMc| |j}nt|ts t|}t|tsH|jxsd}|tj k(r|j dd}n|j ||}|jxsd}|tj k7r |j|||jj||fy#t$r|dk7rt}Y5wxYw)a.Append a string to the MIME header. Optional charset, if given, should be a Charset instance or the name of a character set (which will be converted to a Charset instance). A value of None (the default) means that the charset given in the constructor is used. s may be a byte string or a Unicode string. If it is a byte string (i.e. isinstance(s, str) is false), then charset is the encoding of that byte string, and a UnicodeError will be raised if the string cannot be decoded with that charset. If s is a Unicode string, then charset is a hint specifying the character set of the characters in the string. In either case, when producing an RFC 2822 compliant header using RFC 2047 rules, the string will be encoded using the output codec of the charset. If the string cannot be encoded to the output codec, a UnicodeError will be raised. Optional `errors' is passed as the errors argument to the decode call if s is a byte string. Nr rZ) rr-rIr input_codecr_r) output_codecr`UnicodeEncodeErrorUTF8rr)rUrLrrV input_charsetoutput_charsets rDrz Header.appends* ?mmGGW-g&G!S!#//=:M 4 44HHZ):;HH]F3!--; X11 1 0 QL) & !:- s'CC/.C/c.|jxs|dvS)z=True if string s is not a ctext character of RFC822. )()\)r")rUrLs rDrazHeader._nonctext0syy{3a#333rMc.|j| |j}|dk(rd}t|j||j|}d}dx}}|j D][\}} |I|xr|j |d}|dvr|r| dvr'|jn| dvr|s|j|xr|j |d}| }d}|j} | r|jd| d| n|jdd| | ddD]} |j| j/|j|jd | jz| N| j} | dt| t| z } |j| | | t| dkDsL|j^|j r|j|j|}tj!|rt#d j%||S) aEncode a message header into an RFC-compliant format. There are many issues involved in converting a given string for use in an email header. Only certain character sets are readable in most email clients, and as header strings can only contain a subset of 7-bit ASCII, care must be taken to properly convert and encode (with Base64 or quoted-printable) header strings. In addition, there is a 75-character length limit on any given encoded header field, so line-wrapping must be performed, even with double-byte character sets. Optional maxlinelen specifies the maximum length of each generated line, exclusive of the linesep string. Individual lines may be longer than maxlinelen if a folding point cannot be found. The first line will be shorter by the length of the header name plus ": " if a header name was specified at Header construction time. The default value for maxlinelen is determined at header construction time. Optional splitchars is a string containing characters which should be given extra weight by the splitting algorithm during normal header wrapping. This is in very rough support of RFC 2822's `higher level syntactic breaks': split points preceded by a splitchar are preferred during line splitting, with the characters preferred in the order in which they appear in the string. Space and tab may be included in the string to indicate whether preference should be given to one over the other as a split point when other split chars do not appear in the line being split. Splitchars does not affect RFC 2047 encoded lines. Optional linesep is a string to be used to separate the lines of the value. The default value is the most useful for typical Python applications, but it can be set to \r\n to produce RFC-compliant line separators when needed. Nri@Br\r]Fr rr z8header value appears to contain an embedded header: {!r})r^rS_ValueFormatterrTrQrraadd_transitionrfeednewlineheader_encodingrr'_str_embedded_headerrrformat)rU splitcharsrFlinesep formatterrfrjrgr1rlinesr3slinefwsvalues rDr`z Header.encode5sB   ))J ? J#DOOZ$($9$9:G ##9#||OFG#!?dnnVAY&?!33#w6H'H!002$66y,,.=4>>&*#=IFH%%'Er58W5r2w/ab !!#**6NN4#8#8# :M#*,!KKME4D #e* 45CNN3w7"5zA~!!#5 ,6 <<  $ $ &w'  " "5 )"$++16%=: : rMcg}d}g}|jD]I\}}||k(r|j||&|jtj||f|g}|}K|r&|jtj||f||_yrm)rrrbrd)rUchunksrC last_chunkr1rs rDr^zHeader._normalizes  #||OFG,&!!&)+MM5::j#9<"HI$X &  ,  MM5::j1<@ A rM)NNNNr strict)Nr)z;, Nr) __name__ __module__ __qualname__rWrkrorrar`r^rMrDrrs3'+.2-5-3^)@" )*V4 N`rMrcBeZdZdZdZdZdZdZdZdZ dZ d Z y ) r|c|||_||_t||_||_g|_t ||_yrm)_maxlenrQr'_continuation_ws_len _splitchars_lines _Accumulator _current_line)rU headerlenmaxlenrHrs rDrWz_ValueFormatter.__init__s: /$'$8!% ))4rMcX|j|j|jSrm)rrdr)rUrs rDrz_ValueFormatter._strs ||DKK((rMc,|jtSrm)rNLrUs rDrkz_ValueFormatter.__str__syy}rMc|jj}|dk7r|jj|t|jdkDr|jj r7|j r+|j dxxt |jz cc<n.|j jt |j|jjy)N)r r rr]) rrpushr' is_onlywsrrrreset)rU end_of_lines rDrz_ValueFormatter.newlines((,,. ) # #D   # #[ 1 t!! "Q &!!++-$++ B3t'9'9#:: ""3t'9'9#:;   "rMc<|jjddy)Nr r )rrrs rDr}z_ValueFormatter.add_transitions R(rMc |j|j|||jy|j||j } |j d}||j|| |j }|j|jj|j||D]*}|jj|j|z,y#t $rYywxYw#t $rYywxYwNr)r _ascii_splitrheader_encode_lines _maxlengthsr IndexError _append_chunkrrrrQrr)rUrr1r encoded_lines first_line last_liner3s rDr~z_ValueFormatter.feeds  " " *   c64+;+; <  33FDq@!RHAzz|"003A63q62:!#11!A#6q9HHRL"$4I'!..224 T%%33a7LLN"""''T2**33A6I KK  s4#5#56 7    $ $Y /9 2rMN) rrrrWrrkrr}r~rrrrrMrDr|r|s05) #)#=J; *,0rMr|c\eZdZd fd ZdZd dZfdZdZdZd dZ dZ fd Z xZ S) rc0||_t| yrm)rsuperrW)rU initial_size __class__s rDrWz_Accumulator.__init__s) rMc*|j||fyrm)r)rUrr1s rDrz_Accumulator.pushs S&M"rMc||d}g||d|Srmr)rUrpoppeds rDrz_Accumulator.pop_from!sabQR rMcH|jdk(ryt| S)Nr)r r )rrrrUrs rDrz_Accumulator.pop&s! ?? a w{}rMc<td|D|jS)Nc3PK|]\}}t|t|z ywrm)r'.0rrs rD z'_Accumulator.__len__..,s"=93CHSY&$&)sumrrs rD__len__z_Accumulator.__len__+s ==%%' 'rMc:tjd|DS)Nc3PK|]\}}tj||f ywrmrcrdrs rDrz'_Accumulator.__str__..0s+!715IC"-!1!13+!>15rrrs rDrkz_Accumulator.__str__/s"!715!78 8rMc$|g}||ddd|_yr)r)rUstartvals rDrz_Accumulator.reset3s  HQrMc`|jdk(xr| xst|jSr)rrr"rs rDrz_Accumulator.is_onlyws9s,!!1$Jd(*Ic$i6G6G6IJrMc t|Srm)rrrs rDrz_Accumulator.part_count<sw  rM)rrm) rrrrWrrrrrkrrr __classcell__)rs@rDrrs6#  '8 K!!rMr)NNr )#__doc____all__rr*email.quoprimimer$email.base64mime email.errorsrrrrIrrbr/SPACE8rcrRrrPrtcompileVERBOSE MULTILINErfcrerr% _max_appendrrrr|listrrrMrDrs 2   )%           * wrzz zzBLL "rzz#$2::m,** [|;? # ,ffR}0}0@%!4%!rM__pycache__/iterators.cpython-312.opt-1.pyc000064400000005361152526700320014441 0ustar00 {|jQBdZgdZddlZddlmZdZd dZd dZd dZy) z1Various types of useful iterators and generators.)body_line_iteratortyped_subpart_iteratorwalkN)StringIOc#K||jr.|jD]}|jEd{yy7w)zWalk over the message tree, yielding each subpart. The walk is performed in depth-first order. This method is a generator. N) is_multipart get_payloadr)selfsubparts (/usr/lib64/python3.12/email/iterators.pyrrsC J '')G||~ % %* %s;AA Ac#K|jD]8}|j|}t|ts&t |Ed{:y7w)zIterate over the parts, returning string payloads line-by-line. Optional decode (default False) is passed through to .get_payload(). )decodeN)rr isinstancestrr)msgrr payloads r rr sH 88:%%V%4 gs #( ( ( )s6AAAAc#K|jD]0}|j|k(s||j|k(s-|2yw)zIterate over the subparts with a given MIME type. Use `maintype' as the main MIME type to match against; this defaults to "text". Optional `subtype' is the MIME subtype to match against; if omitted, only the main type is matched. N)rget_content_maintypeget_content_subtype)rmaintypesubtyper s r rr+sC88:  ' ' )X 5'"="="?7"J s'AAAc>|tj}d|dzz}t||jzd||rtd|j z|n t||j r'|j D]}t|||dz|yy) zA handy debugging aidN )endfilez [%s])r)sysstdoutprintget_content_typeget_default_typerr _structure)rfplevelinclude_defaulttabr s r r$r$8s z ZZ  C #$$& &BR8 g,,..R8 2 (G wE!G_ =))F)textN)NrF) __doc____all__riorrrrr$r)r r/s- 8   &)  >r)__pycache__/parser.cpython-312.pyc000064400000015134152526700320012761 0ustar00 {|jodZgdZddlmZmZddlmZmZddlm Z GddZ Gdd e Z Gd d Z Gd d e Z y)z-A parser of RFC 2822 and MIME email messages.)Parser HeaderParser BytesParserBytesHeaderParser FeedParserBytesFeedParser)StringIO TextIOWrapper)rr)compat32c*eZdZdeddZddZddZy)rNpolicyc ||_||_y)aParser of RFC 2822 and MIME email messages. Creates an in-memory object tree representing the email message, which can then be manipulated and turned over to a Generator to return the textual representation of the message. The string must be formatted as a block of RFC 2822 headers and header continuation lines, optionally preceded by a `Unix-from' header. The header block is terminated either by the end of the string or by a blank line. _class is the class to instantiate for new message objects when they must be created. This class must have a constructor that can take zero arguments. Default is Message.Message. The policy keyword specifies a policy object that controls a number of aspects of the parser's operation. The default policy maintains backward compatibility. N)_classr)selfrrs %/usr/lib64/python3.12/email/parser.py__init__zParser.__init__s*  ct|j|j}|r|j|j dx}r%|j ||j dx}r%|j S)a\Create a message structure from the data in a file. Reads all the data from the file and returns the root of the message structure. Optional headersonly is a flag specifying whether to stop parsing after reading the headers or not. The default is False, meaning it parses the entire contents of the file. r i )rrr_set_headersonlyreadfeedclose)rfp headersonly feedparserdatas rparsez Parser.parse)sj  DKK@   ' ' )ggdm#d# OOD !ggdm#d#!!rc:|jt||S)a-Create a message structure from a string. Returns the root of the message structure. Optional headersonly is a flag specifying whether to stop parsing after reading the headers or not. The default is False, meaning it parses the entire contents of the file. r)rr rtextrs rparsestrzParser.parsestr8szz(4.kzBBr)NF)__name__ __module__ __qualname__r rrr#rrrrsh0 "CrrceZdZddZddZy)rc0tj||dSNT)rrrrrs rrzHeaderParser.parseDs||D"d++rc0tj||dSr+)rr#r!s rr#zHeaderParser.parsestrGstT400rNT)r%r&r'rr#r(rrrrCs ,1rrc"eZdZdZddZddZy)rc$t|i||_y)aParser of binary RFC 2822 and MIME email messages. Creates an in-memory object tree representing the email message, which can then be manipulated and turned over to a Generator to return the textual representation of the message. The input must be formatted as a block of RFC 2822 headers and header continuation lines, optionally preceded by a `Unix-from' header. The header block is terminated either by the end of the input or by a blank line. _class is the class to instantiate for new message objects when they must be created. This class must have a constructor that can take zero arguments. Default is Message.Message. N)rparser)rargskws rrzBytesParser.__init__Ms d)b) rct|dd} |jj|||jS#|jwxYw)acCreate a message structure from the data in a binary file. Reads all the data from the file and returns the root of the message structure. Optional headersonly is a flag specifying whether to stop parsing after reading the headers or not. The default is False, meaning it parses the entire contents of the file. asciisurrogateescape)encodingerrors)r r1rdetachr,s rrzBytesParser.parse_s?28I J ;;$$R5 IIKBIIKs <Ac`|jdd}|jj||S)a2Create a message structure from a byte string. Returns the root of the message structure. Optional headersonly is a flag specifying whether to stop parsing after reading the headers or not. The default is False, meaning it parses the entire contents of the file. ASCIIr6)r8)decoder1r#r!s r parsebyteszBytesParser.parsebytesns.{{7+<{={{##D+66rNr$)r%r&r'rrr=r(rrrrKs*$  7rrceZdZddZddZy)rc2tj||dSNTr )rrr,s rrzBytesHeaderParser.parse{s  rt <rGsN 4 ,'8&0C0Cf161,7,7^D Dr__pycache__/charset.cpython-312.pyc000064400000035615152526700320013124 0ustar00 {|jB gdZddlmZddlZddlZddlmZddlmZdZ dZ dZ d Z d Z d Zd Zid e e dfde e dfde e dfde e dfde e dfde e dfde e dfde e dfde e dfde e dfde e dfde e dfd dde e dfde e dfde ddfde ddfe ddfe e dfe e dfd Zid!d d"d d#dd$dd%dd&dd'dd(dd)dd*dd+dd,dd-dd.dd/dd0dd1ddddd2dd3d d4Zd5d6dd7Zdd8Zd9Zd:Zd;ZGd<d=Zy)>)Charset add_alias add_charset add_codec)partialN)errors)encode_7or8bitus-asciiz unknown-8bitz iso-8859-1z iso-8859-2z iso-8859-3z iso-8859-4z iso-8859-9z iso-8859-10z iso-8859-13z iso-8859-14z iso-8859-15z iso-8859-16z windows-1252viscii)NNNbig5gb2312zeuc-jp iso-2022-jp shift_jisutf-8)rzkoi8-rrlatin_1zlatin-1latin_2zlatin-2latin_3zlatin-3latin_4zlatin-4latin_5zlatin-5latin_6zlatin-6latin_7zlatin-7latin_8zlatin-8latin_9zks_c_5601-1987zeuc-kr)zlatin-9latin_10zlatin-10cp949euc_jpeuc_krascii eucgb2312_cnbig5_tw)rrrcD|tk(r td|||ft|<y)a>Add character set properties to the global registry. charset is the input character set, and must be the canonical name of a character set. Optional header_enc and body_enc is either charset.QP for quoted-printable, charset.BASE64 for base64 encoding, charset.SHORTEST for the shortest of qp or base64 encoding, or None for no encoding. SHORTEST is only valid for header_enc. It describes how message headers and message bodies in the input charset are to be encoded. Default is no encoding. Optional output_charset is the character set that the output should be in. Conversions will proceed from input charset, to Unicode, to the output charset when the method Charset.convert() is called. The default is to output in the same character set as the input. Both input_charset and output_charset must have Unicode codec entries in the module's charset-to-codec mapping; use add_codec(charset, codecname) to add codecs the module does not know about. See the codecs module's documentation for more information. z!SHORTEST not allowed for body_encN)SHORTEST ValueErrorCHARSETS)charset header_encbody_encoutput_charsets &/usr/lib64/python3.12/email/charset.pyrrjs).8<==#X~>HWc|t|<y)zAdd a character set alias. alias is the alias name, e.g. latin-1 canonical is the character set's canonical name, e.g. iso-8859-1 N)ALIASES)alias canonicals r.rrs GENr/c|t|<y)a$Add a codec that map characters in the given charset to/from Unicode. charset is the canonical name of a character set. codecname is the name of a Python codec, as appropriate for the second argument to the unicode() built-in, or to the encode() method of a Unicode string. N) CODEC_MAP)r* codecnames r.rrs#Igr/cZ|tk(r|jddS|j|S)Nr#surrogateescape) UNKNOWN8BITencode)stringcodecs r._encoder=s+ }}W&788}}U##r/cJeZdZdZefdZdZdZdZdZ dZ dZ d Z d Z y ) ra@ Map character sets to their email properties. This class provides information about the requirements imposed on email for a specific character set. It also provides convenience routines for converting between character sets, given the availability of the applicable codecs. Given a character set, it will do its best to provide information on how to use that character set in an email in an RFC-compliant way. Certain character sets must be encoded with quoted-printable or base64 when used in email headers or bodies. Certain character sets must be converted outright, and are not allowed in email. Instances of this module expose the following information about a character set: input_charset: The initial character set specified. Common aliases are converted to their `official' email names (e.g. latin_1 is converted to iso-8859-1). Defaults to 7-bit us-ascii. header_encoding: If the character set must be encoded before it can be used in an email header, this attribute will be set to charset.QP (for quoted-printable), charset.BASE64 (for base64 encoding), or charset.SHORTEST for the shortest of QP or BASE64 encoding. Otherwise, it will be None. body_encoding: Same as header_encoding, but describes the encoding for the mail message's body, which indeed may be different than the header encoding. charset.SHORTEST is not allowed for body_encoding. output_charset: Some character sets must be converted before they can be used in email headers or bodies. If the input_charset is one of them, this attribute will contain the name of the charset output will be converted to. Otherwise, it will be None. input_codec: The name of the Python codec used to convert the input_charset to Unicode. If no conversion codec is necessary, this attribute will be None. output_codec: The name of the Python codec used to convert Unicode to the output_charset. If no conversion codec is necessary, this attribute will have the same value as the input_codec. c t|tr|jdn t|d}|j }tj|||_ tj|jttdf\}}}|s |j}||_ ||_tj|||_t j|j|j|_t j|j|j|_y#t$rt j |wxYw)Nr#) isinstancestrr: UnicodeErrorr CharsetErrorlowerr1get input_charsetr)r'BASE64header_encoding body_encodingr-r5 input_codec output_codec)selfrFhencbencconvs r.__init__zCharset.__init__s  5--$$W- #M7 ; &++- $[[ F$<<(:(:)164(@BdD%%D#!%kk$5%==););)-););=%MM$*=*=*.*=*=?) 5%%m4 4 5s .D D?c6|jjSN)rFrDrLs r.__repr__zCharset.__repr__s!!''))r/cLt|t|jk(SrR)rArD)rLothers r.__eq__zCharset.__eq__s4yCJ,,...r/c|jtk7sJ|jtk(ry|jtk(rytS)aPReturn the content-transfer-encoding used for body encoding. This is either the string `quoted-printable' or `base64' depending on the encoding used, or it is a function in which case you should call the function with a single argument, the Message object being encoded. The function should then set the Content-Transfer-Encoding header itself to whatever is appropriate. Returns "quoted-printable" if self.body_encoding is QP. Returns "base64" if self.body_encoding is BASE64. Returns conversion function otherwise. zquoted-printablebase64)rIr'QPrGr rSs r.get_body_encodingzCharset.get_body_encodings@!!X---    #%   6 )! !r/c6|jxs |jS)zReturn the output character set. This is self.output_charset if that is not None, otherwise it is self.input_charset. )r-rFrSs r.get_output_charsetzCharset.get_output_charset s ""8d&8&88r/c|jxsd}t||}|j|}||S|j||S)aHeader-encode a string by converting it first to bytes. The type of encoding (base64 or quoted-printable) will be based on this charset's `header_encoding`. :param string: A unicode string for the header. It must be possible to encode this string to bytes using the character set's output codec. :return: The encoded string, with RFC 2047 chrome. r)rKr= _get_encoder header_encode)rLr;r< header_bytesencoder_modules r.r`zCharset.header_encodesN!!/Zvu- **<8  !M++L%@@r/c|jxsd}t||}|j|}t|j|}|j }t |tz}g} g} t||z } |D]} | j| tj| } |jt| |}|| kDsJ| j| s| s| jdn8tj| }t||}| j||| g} t||z } tj| }t||}| j||| S)afHeader-encode a string by converting it first to bytes. This is similar to `header_encode()` except that the string is fit into maximum line lengths as given by the argument. :param string: A unicode string for the header. It must be possible to encode this string to bytes using the character set's output codec. :param maxlengths: Maximum line length iterator. Each element returned from this iterator will provide the next maximum line length. This parameter is used as an argument to built-in next() and should never be exhausted. The maximum line lengths should not count the RFC 2047 chrome. These line lengths are only a hint; the splitter does the best it can. :return: Lines of encoded strings, each with RFC 2047 chrome. r)r*N)rKr=r_rr`r]lenRFC2047_CHROME_LENnextappend EMPTYSTRINGjoin header_lengthpop)rLr; maxlengthsr<rarbencoderr*extralines current_linemaxlen character this_linelength joined_lines r.header_encode_lineszCharset.header_encode_lines%sV$!!/Zvu- **<8.66F))+G 11 j!E)I    *#((6I#11')W2MNF  "\LL&"-"2"2<"@K#*;#>LLL!67 ){ j)E1 "&&|4 {E2  W\*+ r/c||jtk(rtjS|jtk(rtj S|jt k(rctjj|}tj j|}||krtjStj SyrR)rHrGemail base64mimerZ quoprimimer'rj)rLralen64lenqps r.r_zCharset._get_encoderbs   6 )## #  ! !R '## #  ! !X -$$22<@E$$22<@Eu}''''''r/c|s|S|jturJt|tr|j |j }t jj|S|jtur[t|tr|j |j }|jd}t jj|St|tr*|j |j jd}|S)avBody-encode a string by converting it first to bytes. The type of encoding (base64 or quoted-printable) will be based on self.body_encoding. If body_encoding is None, we assume the output charset is a 7bit encoding, so re-encoding the decoded string using the ascii codec produces the correct string version of the content. latin1r#) rIrGr@rAr:r-rxry body_encoderZdecoderz)rLr;s r.rzCharset.body_encodeqsM    '&#&t':':;##//7 7   2 %&#&t':':;]]8,F##//7 7&#&t':':;BB7KMr/N)__name__ __module__ __qualname____doc__DEFAULT_CHARSETrPrTrWr[r]r`rvr_rr/r.rrs=*V&5?B*/"*9A&;z r/r)__all__ functoolsremail.base64mimerxemail.quoprimimeremail.encodersr rZrGr'rerr9rhr)r1r5rrrr=rrr/r.rs  )   Br- Br- Br-   Br-  Br- Br- Br- Br- Br-  Br-! "Br-# $ Br-% &-' ( Fv-) * Fv-+ , Ft 6- .Ft 6/ 0t-v-vw/5 >  |  | | |   |   |  | | | | } } } } }  }! "}# $1 <"   ?8#$llr/__pycache__/errors.cpython-312.opt-2.pyc000064400000012632152526700320013741 0ustar00 {|j^ GddeZGddeZGddeZGddeZGdd eeZGd d eZGd d eZGdde Z Gdde Z Gdde Z Gdde Z Gdde ZGdde ZGdde ZeZGdde ZGdde ZGd d!e ZGd"d#e ZGd$d%e ZGd&d'e ZGd(d)e ZGd*d+eZGd,d-eZGd.d/eZGd0d1eZGd2d3eZGd4d5eZy6)7c eZdZy) MessageErrorN__name__ __module__ __qualname__%/usr/lib64/python3.12/email/errors.pyrr5r rc eZdZy)MessageParseErrorNrrr r r r s0r r c eZdZy)HeaderParseErrorNrrr r rr&r rc eZdZy) BoundaryErrorNrrr r rrs-r rc eZdZy)MultipartConversionErrorNrrr r rr2r rc eZdZy) CharsetErrorNrrr r rrs'r rc eZdZy)HeaderWriteErrorNrrr r rr rr rc"eZdZ dfd ZxZS) MessageDefectc6|t||||_yN)super__init__line)selfr __class__s r rzMessageDefect.__init__(s   G T " r rrrrr __classcell__r"s@r rr%s*r rc eZdZy)NoBoundaryInMultipartDefectNrrr r r'r'-sLr r'c eZdZy)StartBoundaryNotFoundDefectNrrr r r)r)0r r r)c eZdZy)CloseBoundaryNotFoundDefectNrrr r r+r+3Or r+c eZdZy)#FirstHeaderLineIsContinuationDefectNrrr r r.r.6sEr r.c eZdZy)MisplacedEnvelopeHeaderDefectNrrr r r0r09Ir r0c eZdZy) MissingHeaderBodySeparatorDefectNrrr r r3r3<r,r r3c eZdZy)!MultipartInvariantViolationDefectNrrr r r5r5Ar1r r5c eZdZy)-InvalidMultipartContentTransferEncodingDefectNrrr r r7r7Dr,r r7c eZdZy)UndecodableBytesDefectNrrr r r9r9G:r r9c eZdZy)InvalidBase64PaddingDefectNrrr r r<r<Js9r r<c eZdZy)InvalidBase64CharactersDefectNrrr r r>r>MsGr r>c eZdZy)InvalidBase64LengthDefectNrrr r r@r@Ps>r r@c eZdZ fdZxZS) HeaderDefectc$t||i|yr)rr)r!argskwr"s r rzHeaderDefect.__init__Xs $%"%r r#r%s@r rBrBUs)&&r rBc eZdZy)InvalidHeaderDefectNrrr r rGrG[r r rGc eZdZy)HeaderMissingRequiredValueNrrr r rIrI^rr rIc&eZdZ fdZdZxZS)NonPrintableDefectc2t||||_yr)rrnon_printables)r!rMr"s r rzNonPrintableDefect.__init__ds (,r c8dj|jS)Nz6the following ASCII non-printables found in header: {})formatrM)r!s r __str__zNonPrintableDefect.__str__hs++, .r )rrrrrPr$r%s@r rKrKasB-.r rKc eZdZy)ObsoleteHeaderDefectNrrr r rRrRlr:r rRc eZdZy)NonASCIILocalPartDefectNrrr r rTrTorr rTc eZdZy)InvalidDateDefectNrrr r rVrVts/r rVN) Exceptionrr rr TypeErrorrrr ValueErrorrr'r)r+r.r0r3MalformedHeaderDefectr5r7r9r<r>r@rBrGrIrKrRrTrVrr r r[sj '6961 1'('.%.3|Y3(<('|' JM-M6-6P-PF-FJMJP}P9J JPMP;];::HMH? ? &=& 6,633 . .;<;3l3 0 0r _encoded_words.py000064400000020535152526700320010103 0ustar00""" Routines for manipulating RFC2047 encoded words. This is currently a package-private API, but will be considered for promotion to a public API if there is demand. """ # An ecoded word looks like this: # # =?charset[*lang]?cte?encoded_string?= # # for more information about charset see the charset module. Here it is one # of the preferred MIME charset names (hopefully; you never know when parsing). # cte (Content Transfer Encoding) is either 'q' or 'b' (ignoring case). In # theory other letters could be used for other encodings, but in practice this # (almost?) never happens. There could be a public API for adding entries # to the CTE tables, but YAGNI for now. 'q' is Quoted Printable, 'b' is # Base64. The meaning of encoded_string should be obvious. 'lang' is optional # as indicated by the brackets (they are not part of the syntax) but is almost # never encountered in practice. # # The general interface for a CTE decoder is that it takes the encoded_string # as its argument, and returns a tuple (cte_decoded_string, defects). The # cte_decoded_string is the original binary that was encoded using the # specified cte. 'defects' is a list of MessageDefect instances indicating any # problems encountered during conversion. 'charset' and 'lang' are the # corresponding strings extracted from the EW, case preserved. # # The general interface for a CTE encoder is that it takes a binary sequence # as input and returns the cte_encoded_string, which is an ascii-only string. # # Each decoder must also supply a length function that takes the binary # sequence as its argument and returns the length of the resulting encoded # string. # # The main API functions for the module are decode, which calls the decoder # referenced by the cte specifier, and encode, which adds the appropriate # RFC 2047 "chrome" to the encoded string, and can optionally automatically # select the shortest possible encoding. See their docstrings below for # details. import re import base64 import binascii import functools from string import ascii_letters, digits from email import errors __all__ = ['decode_q', 'encode_q', 'decode_b', 'encode_b', 'len_q', 'len_b', 'decode', 'encode', ] # # Quoted Printable # # regex based decoder. _q_byte_subber = functools.partial(re.compile(br'=([a-fA-F0-9]{2})').sub, lambda m: bytes.fromhex(m.group(1).decode())) def decode_q(encoded): encoded = encoded.replace(b'_', b' ') return _q_byte_subber(encoded), [] # dict mapping bytes to their encoded form class _QByteMap(dict): safe = b'-!*+/' + ascii_letters.encode('ascii') + digits.encode('ascii') def __missing__(self, key): if key in self.safe: self[key] = chr(key) else: self[key] = "={:02X}".format(key) return self[key] _q_byte_map = _QByteMap() # In headers spaces are mapped to '_'. _q_byte_map[ord(' ')] = '_' def encode_q(bstring): return ''.join(_q_byte_map[x] for x in bstring) def len_q(bstring): return sum(len(_q_byte_map[x]) for x in bstring) # # Base64 # def decode_b(encoded): # First try encoding with validate=True, fixing the padding if needed. # This will succeed only if encoded includes no invalid characters. pad_err = len(encoded) % 4 missing_padding = b'==='[:4-pad_err] if pad_err else b'' try: return ( base64.b64decode(encoded + missing_padding, validate=True), [errors.InvalidBase64PaddingDefect()] if pad_err else [], ) except binascii.Error: # Since we had correct padding, this is likely an invalid char error. # # The non-alphabet characters are ignored as far as padding # goes, but we don't know how many there are. So try without adding # padding to see if it works. try: return ( base64.b64decode(encoded, validate=False), [errors.InvalidBase64CharactersDefect()], ) except binascii.Error: # Add as much padding as could possibly be necessary (extra padding # is ignored). try: return ( base64.b64decode(encoded + b'==', validate=False), [errors.InvalidBase64CharactersDefect(), errors.InvalidBase64PaddingDefect()], ) except binascii.Error: # This only happens when the encoded string's length is 1 more # than a multiple of 4, which is invalid. # # bpo-27397: Just return the encoded string since there's no # way to decode. return encoded, [errors.InvalidBase64LengthDefect()] def encode_b(bstring): return base64.b64encode(bstring).decode('ascii') def len_b(bstring): groups_of_3, leftover = divmod(len(bstring), 3) # 4 bytes out for each 3 bytes (or nonzero fraction thereof) in. return groups_of_3 * 4 + (4 if leftover else 0) _cte_decoders = { 'q': decode_q, 'b': decode_b, } def decode(ew): """Decode encoded word and return (string, charset, lang, defects) tuple. An RFC 2047/2243 encoded word has the form: =?charset*lang?cte?encoded_string?= where '*lang' may be omitted but the other parts may not be. This function expects exactly such a string (that is, it does not check the syntax and may raise errors if the string is not well formed), and returns the encoded_string decoded first from its Content Transfer Encoding and then from the resulting bytes into unicode using the specified charset. If the cte-decoded string does not successfully decode using the specified character set, a defect is added to the defects list and the unknown octets are replaced by the unicode 'unknown' character \\uFDFF. The specified charset and language are returned. The default for language, which is rarely if ever encountered, is the empty string. """ _, charset, cte, cte_string, _ = ew.split('?') charset, _, lang = charset.partition('*') cte = cte.lower() # Recover the original bytes and do CTE decoding. bstring = cte_string.encode('ascii', 'surrogateescape') bstring, defects = _cte_decoders[cte](bstring) # Turn the CTE decoded bytes into unicode. try: string = bstring.decode(charset) except UnicodeDecodeError: defects.append(errors.UndecodableBytesDefect("Encoded word " f"contains bytes not decodable using {charset!r} charset")) string = bstring.decode(charset, 'surrogateescape') except (LookupError, UnicodeEncodeError): string = bstring.decode('ascii', 'surrogateescape') if charset.lower() != 'unknown-8bit': defects.append(errors.CharsetError(f"Unknown charset {charset!r} " f"in encoded word; decoded as unknown bytes")) return string, charset, lang, defects _cte_encoders = { 'q': encode_q, 'b': encode_b, } _cte_encode_length = { 'q': len_q, 'b': len_b, } def encode(string, charset='utf-8', encoding=None, lang=''): """Encode string using the CTE encoding that produces the shorter result. Produces an RFC 2047/2243 encoded word of the form: =?charset*lang?cte?encoded_string?= where '*lang' is omitted unless the 'lang' parameter is given a value. Optional argument charset (defaults to utf-8) specifies the charset to use to encode the string to binary before CTE encoding it. Optional argument 'encoding' is the cte specifier for the encoding that should be used ('q' or 'b'); if it is None (the default) the encoding which produces the shortest encoded sequence is used, except that 'q' is preferred if it is up to five characters longer. Optional argument 'lang' (default '') gives the RFC 2243 language string to specify in the encoded word. """ if charset == 'unknown-8bit': bstring = string.encode('ascii', 'surrogateescape') else: bstring = string.encode(charset) if encoding is None: qlen = _cte_encode_length['q'](bstring) blen = _cte_encode_length['b'](bstring) # Bias toward q. 5 is arbitrary. encoding = 'q' if qlen - blen < 5 else 'b' encoded = _cte_encoders[encoding](bstring) if lang: lang = '*' + lang return "=?{}{}?{}?{}?=".format(charset, lang, encoding, encoded) policy.py000064400000024566152526700320006434 0ustar00"""This will be the home for the policy that hooks in the new code that adds all the email6 features. """ import re import sys from email._policybase import Policy, Compat32, compat32, _extend_docstrings from email.utils import _has_surrogates from email.headerregistry import HeaderRegistry as HeaderRegistry from email.contentmanager import raw_data_manager from email.message import EmailMessage __all__ = [ 'Compat32', 'compat32', 'Policy', 'EmailPolicy', 'default', 'strict', 'SMTP', 'HTTP', ] linesep_splitter = re.compile(r'\n|\r\n?') @_extend_docstrings class EmailPolicy(Policy): """+ PROVISIONAL The API extensions enabled by this policy are currently provisional. Refer to the documentation for details. This policy adds new header parsing and folding algorithms. Instead of simple strings, headers are custom objects with custom attributes depending on the type of the field. The folding algorithm fully implements RFCs 2047 and 5322. In addition to the settable attributes listed above that apply to all Policies, this policy adds the following additional attributes: utf8 -- if False (the default) message headers will be serialized as ASCII, using encoded words to encode any non-ASCII characters in the source strings. If True, the message headers will be serialized using utf8 and will not contain encoded words (see RFC 6532 for more on this serialization format). refold_source -- if the value for a header in the Message object came from the parsing of some source, this attribute indicates whether or not a generator should refold that value when transforming the message back into stream form. The possible values are: none -- all source values use original folding long -- source values that have any line that is longer than max_line_length will be refolded all -- all values are refolded. The default is 'long'. header_factory -- a callable that takes two arguments, 'name' and 'value', where 'name' is a header field name and 'value' is an unfolded header field value, and returns a string-like object that represents that header. A default header_factory is provided that understands some of the RFC5322 header field types. (Currently address fields and date fields have special treatment, while all other fields are treated as unstructured. This list will be completed before the extension is marked stable.) content_manager -- an object with at least two methods: get_content and set_content. When the get_content or set_content method of a Message object is called, it calls the corresponding method of this object, passing it the message object as its first argument, and any arguments or keywords that were passed to it as additional arguments. The default content_manager is :data:`~email.contentmanager.raw_data_manager`. """ message_factory = EmailMessage utf8 = False refold_source = 'long' header_factory = HeaderRegistry() content_manager = raw_data_manager def __init__(self, **kw): # Ensure that each new instance gets a unique header factory # (as opposed to clones, which share the factory). if 'header_factory' not in kw: object.__setattr__(self, 'header_factory', HeaderRegistry()) super().__init__(**kw) def header_max_count(self, name): """+ The implementation for this class returns the max_count attribute from the specialized header class that would be used to construct a header of type 'name'. """ return self.header_factory[name].max_count # The logic of the next three methods is chosen such that it is possible to # switch a Message object between a Compat32 policy and a policy derived # from this class and have the results stay consistent. This allows a # Message object constructed with this policy to be passed to a library # that only handles Compat32 objects, or to receive such an object and # convert it to use the newer style by just changing its policy. It is # also chosen because it postpones the relatively expensive full rfc5322 # parse until as late as possible when parsing from source, since in many # applications only a few headers will actually be inspected. def header_source_parse(self, sourcelines): """+ The name is parsed as everything up to the ':' and returned unmodified. The value is determined by stripping leading whitespace off the remainder of the first line joined with all subsequent lines, and stripping any trailing carriage return or linefeed characters. (This is the same as Compat32). """ name, value = sourcelines[0].split(':', 1) value = ''.join((value, *sourcelines[1:])).lstrip(' \t\r\n') return (name, value.rstrip('\r\n')) def header_store_parse(self, name, value): """+ The name is returned unchanged. If the input value has a 'name' attribute and it matches the name ignoring case, the value is returned unchanged. Otherwise the name and value are passed to header_factory method, and the resulting custom header object is returned as the value. In this case a ValueError is raised if the input value contains CR or LF characters. """ if hasattr(value, 'name') and value.name.lower() == name.lower(): return (name, value) if isinstance(value, str) and len(value.splitlines())>1: # XXX this error message isn't quite right when we use splitlines # (see issue 22233), but I'm not sure what should happen here. raise ValueError("Header values may not contain linefeed " "or carriage return characters") return (name, self.header_factory(name, value)) def header_fetch_parse(self, name, value): """+ If the value has a 'name' attribute, it is returned to unmodified. Otherwise the name and the value with any linesep characters removed are passed to the header_factory method, and the resulting custom header object is returned. Any surrogateescaped bytes get turned into the unicode unknown-character glyph. """ if hasattr(value, 'name'): return value # We can't use splitlines here because it splits on more than \r and \n. value = ''.join(linesep_splitter.split(value)) return self.header_factory(name, value) def fold(self, name, value): """+ Header folding is controlled by the refold_source policy setting. A value is considered to be a 'source value' if and only if it does not have a 'name' attribute (having a 'name' attribute means it is a header object of some sort). If a source value needs to be refolded according to the policy, it is converted into a custom header object by passing the name and the value with any linesep characters removed to the header_factory method. Folding of a custom header object is done by calling its fold method with the current policy. Source values are split into lines using splitlines. If the value is not to be refolded, the lines are rejoined using the linesep from the policy and returned. The exception is lines containing non-ascii binary data. In that case the value is refolded regardless of the refold_source setting, which causes the binary data to be CTE encoded using the unknown-8bit charset. """ return self._fold(name, value, refold_binary=True) def fold_binary(self, name, value): """+ The same as fold if cte_type is 7bit, except that the returned value is bytes. If cte_type is 8bit, non-ASCII binary data is converted back into bytes. Headers with binary data are not refolded, regardless of the refold_header setting, since there is no way to know whether the binary data consists of single byte characters or multibyte characters. If utf8 is true, headers are encoded to utf8, otherwise to ascii with non-ASCII unicode rendered as encoded words. """ folded = self._fold(name, value, refold_binary=self.cte_type=='7bit') charset = 'utf8' if self.utf8 else 'ascii' return folded.encode(charset, 'surrogateescape') def _fold(self, name, value, refold_binary=False): if hasattr(value, 'name'): return value.fold(policy=self) maxlen = self.max_line_length if self.max_line_length else sys.maxsize # We can't use splitlines here because it splits on more than \r and \n. lines = linesep_splitter.split(value) refold = (self.refold_source == 'all' or self.refold_source == 'long' and (lines and len(lines[0])+len(name)+2 > maxlen or any(len(x) > maxlen for x in lines[1:]))) if not refold: if not self.utf8: refold = not value.isascii() elif refold_binary: refold = _has_surrogates(value) if refold: return self.header_factory(name, ''.join(lines)).fold(policy=self) return name + ': ' + self.linesep.join(lines) + self.linesep default = EmailPolicy() # Make the default policy use the class default header_factory del default.header_factory strict = default.clone(raise_on_defect=True) SMTP = default.clone(linesep='\r\n') HTTP = default.clone(linesep='\r\n', max_line_length=None) SMTPUTF8 = SMTP.clone(utf8=True) errors.py000064400000003134152526700320006435 0ustar00# Copyright (C) 2001-2006 Python Software Foundation # Author: Barry Warsaw # Contact: email-sig@python.org """email package exception classes.""" class MessageError(Exception): """Base class for errors in the email package.""" class MessageParseError(MessageError): """Base class for message parsing errors.""" class HeaderParseError(MessageParseError): """Error while parsing headers.""" class BoundaryError(MessageParseError): """Couldn't find terminating boundary.""" class MultipartConversionError(MessageError, TypeError): """Conversion to a multipart is prohibited.""" class CharsetError(MessageError): """An illegal charset was given.""" # These are parsing defects which the parser was able to work around. class MessageDefect: """Base class for a message defect.""" def __init__(self, line=None): self.line = line class NoBoundaryInMultipartDefect(MessageDefect): """A message claimed to be a multipart but had no boundary parameter.""" class StartBoundaryNotFoundDefect(MessageDefect): """The claimed start boundary was never found.""" class FirstHeaderLineIsContinuationDefect(MessageDefect): """A message had a continuation line as its first header line.""" class MisplacedEnvelopeHeaderDefect(MessageDefect): """A 'Unix-from' header was found in the middle of a header block.""" class MalformedHeaderDefect(MessageDefect): """Found a header that was missing a colon, or was otherwise malformed.""" class MultipartInvariantViolationDefect(MessageDefect): """A message claimed to be a multipart but no subparts were found.""" _policybase.py000064400000036257152526700320007426 0ustar00"""Policy framework for the email package. Allows fine grained feature control of how the package parses and emits data. """ import abc from email import header from email import charset as _charset from email.utils import _has_surrogates __all__ = [ 'Policy', 'Compat32', 'compat32', ] class _PolicyBase: """Policy Object basic framework. This class is useless unless subclassed. A subclass should define class attributes with defaults for any values that are to be managed by the Policy object. The constructor will then allow non-default values to be set for these attributes at instance creation time. The instance will be callable, taking these same attributes keyword arguments, and returning a new instance identical to the called instance except for those values changed by the keyword arguments. Instances may be added, yielding new instances with any non-default values from the right hand operand overriding those in the left hand operand. That is, A + B == A() The repr of an instance can be used to reconstruct the object if and only if the repr of the values can be used to reconstruct those values. """ def __init__(self, **kw): """Create new Policy, possibly overriding some defaults. See class docstring for a list of overridable attributes. """ for name, value in kw.items(): if hasattr(self, name): super(_PolicyBase,self).__setattr__(name, value) else: raise TypeError( "{!r} is an invalid keyword argument for {}".format( name, self.__class__.__name__)) def __repr__(self): args = [ "{}={!r}".format(name, value) for name, value in self.__dict__.items() ] return "{}({})".format(self.__class__.__name__, ', '.join(args)) def clone(self, **kw): """Return a new instance with specified attributes changed. The new instance has the same attribute values as the current object, except for the changes passed in as keyword arguments. """ newpolicy = self.__class__.__new__(self.__class__) for attr, value in self.__dict__.items(): object.__setattr__(newpolicy, attr, value) for attr, value in kw.items(): if not hasattr(self, attr): raise TypeError( "{!r} is an invalid keyword argument for {}".format( attr, self.__class__.__name__)) object.__setattr__(newpolicy, attr, value) return newpolicy def __setattr__(self, name, value): if hasattr(self, name): msg = "{!r} object attribute {!r} is read-only" else: msg = "{!r} object has no attribute {!r}" raise AttributeError(msg.format(self.__class__.__name__, name)) def __add__(self, other): """Non-default values from right operand override those from left. The object returned is a new instance of the subclass. """ return self.clone(**other.__dict__) def _append_doc(doc, added_doc): doc = doc.rsplit('\n', 1)[0] added_doc = added_doc.split('\n', 1)[1] return doc + '\n' + added_doc def _extend_docstrings(cls): if cls.__doc__ and cls.__doc__.startswith('+'): cls.__doc__ = _append_doc(cls.__bases__[0].__doc__, cls.__doc__) for name, attr in cls.__dict__.items(): if attr.__doc__ and attr.__doc__.startswith('+'): for c in (c for base in cls.__bases__ for c in base.mro()): doc = getattr(getattr(c, name), '__doc__') if doc: attr.__doc__ = _append_doc(doc, attr.__doc__) break return cls class Policy(_PolicyBase, metaclass=abc.ABCMeta): r"""Controls for how messages are interpreted and formatted. Most of the classes and many of the methods in the email package accept Policy objects as parameters. A Policy object contains a set of values and functions that control how input is interpreted and how output is rendered. For example, the parameter 'raise_on_defect' controls whether or not an RFC violation results in an error being raised or not, while 'max_line_length' controls the maximum length of output lines when a Message is serialized. Any valid attribute may be overridden when a Policy is created by passing it as a keyword argument to the constructor. Policy objects are immutable, but a new Policy object can be created with only certain values changed by calling the Policy instance with keyword arguments. Policy objects can also be added, producing a new Policy object in which the non-default attributes set in the right hand operand overwrite those specified in the left operand. Settable attributes: raise_on_defect -- If true, then defects should be raised as errors. Default: False. linesep -- string containing the value to use as separation between output lines. Default '\n'. cte_type -- Type of allowed content transfer encodings 7bit -- ASCII only 8bit -- Content-Transfer-Encoding: 8bit is allowed Default: 8bit. Also controls the disposition of (RFC invalid) binary data in headers; see the documentation of the binary_fold method. max_line_length -- maximum length of lines, excluding 'linesep', during serialization. None or 0 means no line wrapping is done. Default is 78. mangle_from_ -- a flag that, when True escapes From_ lines in the body of the message by putting a `>' in front of them. This is used when the message is being serialized by a generator. Default: False. message_factory -- the class to use to create new message objects. If the value is None, the default is Message. verify_generated_headers -- if true, the generator verifies that each header they are properly folded, so that a parser won't treat it as multiple headers, start-of-body, or part of another header. This is a check against custom Header & fold() implementations. """ raise_on_defect = False linesep = '\n' cte_type = '8bit' max_line_length = 78 mangle_from_ = False message_factory = None verify_generated_headers = True def handle_defect(self, obj, defect): """Based on policy, either raise defect or call register_defect. handle_defect(obj, defect) defect should be a Defect subclass, but in any case must be an Exception subclass. obj is the object on which the defect should be registered if it is not raised. If the raise_on_defect is True, the defect is raised as an error, otherwise the object and the defect are passed to register_defect. This method is intended to be called by parsers that discover defects. The email package parsers always call it with Defect instances. """ if self.raise_on_defect: raise defect self.register_defect(obj, defect) def register_defect(self, obj, defect): """Record 'defect' on 'obj'. Called by handle_defect if raise_on_defect is False. This method is part of the Policy API so that Policy subclasses can implement custom defect handling. The default implementation calls the append method of the defects attribute of obj. The objects used by the email package by default that get passed to this method will always have a defects attribute with an append method. """ obj.defects.append(defect) def header_max_count(self, name): """Return the maximum allowed number of headers named 'name'. Called when a header is added to a Message object. If the returned value is not 0 or None, and there are already a number of headers with the name 'name' equal to the value returned, a ValueError is raised. Because the default behavior of Message's __setitem__ is to append the value to the list of headers, it is easy to create duplicate headers without realizing it. This method allows certain headers to be limited in the number of instances of that header that may be added to a Message programmatically. (The limit is not observed by the parser, which will faithfully produce as many headers as exist in the message being parsed.) The default implementation returns None for all header names. """ return None @abc.abstractmethod def header_source_parse(self, sourcelines): """Given a list of linesep terminated strings constituting the lines of a single header, return the (name, value) tuple that should be stored in the model. The input lines should retain their terminating linesep characters. The lines passed in by the email package may contain surrogateescaped binary data. """ raise NotImplementedError @abc.abstractmethod def header_store_parse(self, name, value): """Given the header name and the value provided by the application program, return the (name, value) that should be stored in the model. """ raise NotImplementedError @abc.abstractmethod def header_fetch_parse(self, name, value): """Given the header name and the value from the model, return the value to be returned to the application program that is requesting that header. The value passed in by the email package may contain surrogateescaped binary data if the lines were parsed by a BytesParser. The returned value should not contain any surrogateescaped data. """ raise NotImplementedError @abc.abstractmethod def fold(self, name, value): """Given the header name and the value from the model, return a string containing linesep characters that implement the folding of the header according to the policy controls. The value passed in by the email package may contain surrogateescaped binary data if the lines were parsed by a BytesParser. The returned value should not contain any surrogateescaped data. """ raise NotImplementedError @abc.abstractmethod def fold_binary(self, name, value): """Given the header name and the value from the model, return binary data containing linesep characters that implement the folding of the header according to the policy controls. The value passed in by the email package may contain surrogateescaped binary data. """ raise NotImplementedError @_extend_docstrings class Compat32(Policy): """+ This particular policy is the backward compatibility Policy. It replicates the behavior of the email package version 5.1. """ mangle_from_ = True def _sanitize_header(self, name, value): # If the header value contains surrogates, return a Header using # the unknown-8bit charset to encode the bytes as encoded words. if not isinstance(value, str): # Assume it is already a header object return value if _has_surrogates(value): return header.Header(value, charset=_charset.UNKNOWN8BIT, header_name=name) else: return value def header_source_parse(self, sourcelines): """+ The name is parsed as everything up to the ':' and returned unmodified. The value is determined by stripping leading whitespace off the remainder of the first line joined with all subsequent lines, and stripping any trailing carriage return or linefeed characters. """ name, value = sourcelines[0].split(':', 1) value = ''.join((value, *sourcelines[1:])).lstrip(' \t\r\n') return (name, value.rstrip('\r\n')) def header_store_parse(self, name, value): """+ The name and value are returned unmodified. """ return (name, value) def header_fetch_parse(self, name, value): """+ If the value contains binary data, it is converted into a Header object using the unknown-8bit charset. Otherwise it is returned unmodified. """ return self._sanitize_header(name, value) def fold(self, name, value): """+ Headers are folded using the Header folding algorithm, which preserves existing line breaks in the value, and wraps each resulting line to the max_line_length. Non-ASCII binary data are CTE encoded using the unknown-8bit charset. """ return self._fold(name, value, sanitize=True) def fold_binary(self, name, value): """+ Headers are folded using the Header folding algorithm, which preserves existing line breaks in the value, and wraps each resulting line to the max_line_length. If cte_type is 7bit, non-ascii binary data is CTE encoded using the unknown-8bit charset. Otherwise the original source header is used, with its existing line breaks and/or binary data. """ folded = self._fold(name, value, sanitize=self.cte_type=='7bit') return folded.encode('ascii', 'surrogateescape') def _fold(self, name, value, sanitize): parts = [] parts.append('%s: ' % name) if isinstance(value, str): if _has_surrogates(value): if sanitize: h = header.Header(value, charset=_charset.UNKNOWN8BIT, header_name=name) else: # If we have raw 8bit data in a byte string, we have no idea # what the encoding is. There is no safe way to split this # string. If it's ascii-subset, then we could do a normal # ascii split, but if it's multibyte then we could break the # string. There's no way to know so the least harm seems to # be to not split the string and risk it being too long. parts.append(value) h = None else: h = header.Header(value, header_name=name) else: # Assume it is a Header-like object. h = value if h is not None: # The Header class interprets a value of None for maxlinelen as the # default value of 78, as recommended by RFC 2822. maxlinelen = 0 if self.max_line_length is not None: maxlinelen = self.max_line_length parts.append(h.encode(linesep=self.linesep, maxlinelen=maxlinelen)) parts.append(self.linesep) return ''.join(parts) compat32 = Compat32() architecture.rst000064400000022531152526700320007765 0ustar00:mod:`email` Package Architecture ================================= Overview -------- The email package consists of three major components: Model An object structure that represents an email message, and provides an API for creating, querying, and modifying a message. Parser Takes a sequence of characters or bytes and produces a model of the email message represented by those characters or bytes. Generator Takes a model and turns it into a sequence of characters or bytes. The sequence can either be intended for human consumption (a printable unicode string) or bytes suitable for transmission over the wire. In the latter case all data is properly encoded using the content transfer encodings specified by the relevant RFCs. Conceptually the package is organized around the model. The model provides both "external" APIs intended for use by application programs using the library, and "internal" APIs intended for use by the Parser and Generator components. This division is intentionally a bit fuzzy; the API described by this documentation is all a public, stable API. This allows for an application with special needs to implement its own parser and/or generator. In addition to the three major functional components, there is a third key component to the architecture: Policy An object that specifies various behavioral settings and carries implementations of various behavior-controlling methods. The Policy framework provides a simple and convenient way to control the behavior of the library, making it possible for the library to be used in a very flexible fashion while leveraging the common code required to parse, represent, and generate message-like objects. For example, in addition to the default :rfc:`5322` email message policy, we also have a policy that manages HTTP headers in a fashion compliant with :rfc:`2616`. Individual policy controls, such as the maximum line length produced by the generator, can also be controlled individually to meet specialized application requirements. The Model --------- The message model is implemented by the :class:`~email.message.Message` class. The model divides a message into the two fundamental parts discussed by the RFC: the header section and the body. The `Message` object acts as a pseudo-dictionary of named headers. Its dictionary interface provides convenient access to individual headers by name. However, all headers are kept internally in an ordered list, so that the information about the order of the headers in the original message is preserved. The `Message` object also has a `payload` that holds the body. A `payload` can be one of two things: data, or a list of `Message` objects. The latter is used to represent a multipart MIME message. Lists can be nested arbitrarily deeply in order to represent the message, with all terminal leaves having non-list data payloads. Message Lifecycle ----------------- The general lifecycle of a message is: Creation A `Message` object can be created by a Parser, or it can be instantiated as an empty message by an application. Manipulation The application may examine one or more headers, and/or the payload, and it may modify one or more headers and/or the payload. This may be done on the top level `Message` object, or on any sub-object. Finalization The Model is converted into a unicode or binary stream, or the model is discarded. Header Policy Control During Lifecycle -------------------------------------- One of the major controls exerted by the Policy is the management of headers during the `Message` lifecycle. Most applications don't need to be aware of this. A header enters the model in one of two ways: via a Parser, or by being set to a specific value by an application program after the Model already exists. Similarly, a header exits the model in one of two ways: by being serialized by a Generator, or by being retrieved from a Model by an application program. The Policy object provides hooks for all four of these pathways. The model storage for headers is a list of (name, value) tuples. The Parser identifies headers during parsing, and passes them to the :meth:`~email.policy.Policy.header_source_parse` method of the Policy. The result of that method is the (name, value) tuple to be stored in the model. When an application program supplies a header value (for example, through the `Message` object `__setitem__` interface), the name and the value are passed to the :meth:`~email.policy.Policy.header_store_parse` method of the Policy, which returns the (name, value) tuple to be stored in the model. When an application program retrieves a header (through any of the dict or list interfaces of `Message`), the name and value are passed to the :meth:`~email.policy.Policy.header_fetch_parse` method of the Policy to obtain the value returned to the application. When a Generator requests a header during serialization, the name and value are passed to the :meth:`~email.policy.Policy.fold` method of the Policy, which returns a string containing line breaks in the appropriate places. The :meth:`~email.policy.Policy.cte_type` Policy control determines whether or not Content Transfer Encoding is performed on the data in the header. There is also a :meth:`~email.policy.Policy.binary_fold` method for use by generators that produce binary output, which returns the folded header as binary data, possibly folded at different places than the corresponding string would be. Handling Binary Data -------------------- In an ideal world all message data would conform to the RFCs, meaning that the parser could decode the message into the idealized unicode message that the sender originally wrote. In the real world, the email package must also be able to deal with badly formatted messages, including messages containing non-ASCII characters that either have no indicated character set or are not valid characters in the indicated character set. Since email messages are *primarily* text data, and operations on message data are primarily text operations (except for binary payloads of course), the model stores all text data as unicode strings. Un-decodable binary inside text data is handled by using the `surrogateescape` error handler of the ASCII codec. As with the binary filenames the error handler was introduced to handle, this allows the email package to "carry" the binary data received during parsing along until the output stage, at which time it is regenerated in its original form. This carried binary data is almost entirely an implementation detail. The one place where it is visible in the API is in the "internal" API. A Parser must do the `surrogateescape` encoding of binary input data, and pass that data to the appropriate Policy method. The "internal" interface used by the Generator to access header values preserves the `surrogateescaped` bytes. All other interfaces convert the binary data either back into bytes or into a safe form (losing information in some cases). Backward Compatibility ---------------------- The :class:`~email.policy.Policy.Compat32` Policy provides backward compatibility with version 5.1 of the email package. It does this via the following implementation of the four+1 Policy methods described above: header_source_parse Splits the first line on the colon to obtain the name, discards any spaces after the colon, and joins the remainder of the line with all of the remaining lines, preserving the linesep characters to obtain the value. Trailing carriage return and/or linefeed characters are stripped from the resulting value string. header_store_parse Returns the name and value exactly as received from the application. header_fetch_parse If the value contains any `surrogateescaped` binary data, return the value as a :class:`~email.header.Header` object, using the character set `unknown-8bit`. Otherwise just returns the value. fold Uses :class:`~email.header.Header`'s folding to fold headers in the same way the email5.1 generator did. binary_fold Same as fold, but encodes to 'ascii'. New Algorithm ------------- header_source_parse Same as legacy behavior. header_store_parse Same as legacy behavior. header_fetch_parse If the value is already a header object, returns it. Otherwise, parses the value using the new parser, and returns the resulting object as the value. `surrogateescaped` bytes get turned into unicode unknown character code points. fold Uses the new header folding algorithm, respecting the policy settings. surrogateescaped bytes are encoded using the ``unknown-8bit`` charset for ``cte_type=7bit`` or ``8bit``. Returns a string. At some point there will also be a ``cte_type=unicode``, and for that policy fold will serialize the idealized unicode message with RFC-like folding, converting any surrogateescaped bytes into the unicode unknown character glyph. binary_fold Uses the new header folding algorithm, respecting the policy settings. surrogateescaped bytes are encoded using the `unknown-8bit` charset for ``cte_type=7bit``, and get turned back into bytes for ``cte_type=8bit``. Returns bytes. At some point there will also be a ``cte_type=unicode``, and for that policy binary_fold will serialize the message according to :rfc:``5335``. quoprimime.py000064400000025140152526700320007311 0ustar00# Copyright (C) 2001-2006 Python Software Foundation # Author: Ben Gertzfield # Contact: email-sig@python.org """Quoted-printable content transfer encoding per RFCs 2045-2047. This module handles the content transfer encoding method defined in RFC 2045 to encode US ASCII-like 8-bit data called `quoted-printable'. It is used to safely encode text that is in a character set similar to the 7-bit US ASCII character set, but that includes some 8-bit characters that are normally not allowed in email bodies or headers. Quoted-printable is very space-inefficient for encoding binary files; use the email.base64mime module for that instead. This module provides an interface to encode and decode both headers and bodies with quoted-printable encoding. RFC 2045 defines a method for including character set information in an `encoded-word' in a header. This method is commonly used for 8-bit real names in To:/From:/Cc: etc. fields, as well as Subject: lines. This module does not do the line wrapping or end-of-line character conversion necessary for proper internationalized headers; it only does dumb encoding and decoding. To deal with the various line wrapping issues, use the email.header module. """ __all__ = [ 'body_decode', 'body_encode', 'body_quopri_check', 'body_quopri_len', 'decode', 'decodestring', 'encode', 'encodestring', 'header_decode', 'header_encode', 'header_quopri_check', 'header_quopri_len', 'quote', 'unquote', ] import re from string import hexdigits from email.utils import fix_eols CRLF = '\r\n' NL = '\n' # See also Charset.py MISC_LEN = 7 hqre = re.compile(r'[^-a-zA-Z0-9!*+/ ]') bqre = re.compile(r'[^ !-<>-~\t]') # Helpers def header_quopri_check(c): """Return True if the character should be escaped with header quopri.""" return bool(hqre.match(c)) def body_quopri_check(c): """Return True if the character should be escaped with body quopri.""" return bool(bqre.match(c)) def header_quopri_len(s): """Return the length of str when it is encoded with header quopri.""" count = 0 for c in s: if hqre.match(c): count += 3 else: count += 1 return count def body_quopri_len(str): """Return the length of str when it is encoded with body quopri.""" count = 0 for c in str: if bqre.match(c): count += 3 else: count += 1 return count def _max_append(L, s, maxlen, extra=''): if not L: L.append(s.lstrip()) elif len(L[-1]) + len(s) <= maxlen: L[-1] += extra + s else: L.append(s.lstrip()) def unquote(s): """Turn a string in the form =AB to the ASCII character with value 0xab""" return chr(int(s[1:3], 16)) def quote(c): return "=%02X" % ord(c) def header_encode(header, charset="iso-8859-1", keep_eols=False, maxlinelen=76, eol=NL): """Encode a single header line with quoted-printable (like) encoding. Defined in RFC 2045, this `Q' encoding is similar to quoted-printable, but used specifically for email header fields to allow charsets with mostly 7 bit characters (and some 8 bit) to remain more or less readable in non-RFC 2045 aware mail clients. charset names the character set to use to encode the header. It defaults to iso-8859-1. The resulting string will be in the form: "=?charset?q?I_f=E2rt_in_your_g=E8n=E8ral_dire=E7tion?\\n =?charset?q?Silly_=C8nglish_Kn=EEghts?=" with each line wrapped safely at, at most, maxlinelen characters (defaults to 76 characters). If maxlinelen is None, the entire string is encoded in one chunk with no splitting. End-of-line characters (\\r, \\n, \\r\\n) will be automatically converted to the canonical email line separator \\r\\n unless the keep_eols parameter is True (the default is False). Each line of the header will be terminated in the value of eol, which defaults to "\\n". Set this to "\\r\\n" if you are using the result of this function directly in email. """ # Return empty headers unchanged if not header: return header if not keep_eols: header = fix_eols(header) # Quopri encode each line, in encoded chunks no greater than maxlinelen in # length, after the RFC chrome is added in. quoted = [] if maxlinelen is None: # An obnoxiously large number that's good enough max_encoded = 100000 else: max_encoded = maxlinelen - len(charset) - MISC_LEN - 1 for c in header: # Space may be represented as _ instead of =20 for readability if c == ' ': _max_append(quoted, '_', max_encoded) # These characters can be included verbatim elif not hqre.match(c): _max_append(quoted, c, max_encoded) # Otherwise, replace with hex value like =E2 else: _max_append(quoted, "=%02X" % ord(c), max_encoded) # Now add the RFC chrome to each encoded chunk and glue the chunks # together. BAW: should we be able to specify the leading whitespace in # the joiner? joiner = eol + ' ' return joiner.join(['=?%s?q?%s?=' % (charset, line) for line in quoted]) def encode(body, binary=False, maxlinelen=76, eol=NL): """Encode with quoted-printable, wrapping at maxlinelen characters. If binary is False (the default), end-of-line characters will be converted to the canonical email end-of-line sequence \\r\\n. Otherwise they will be left verbatim. Each line of encoded text will end with eol, which defaults to "\\n". Set this to "\\r\\n" if you will be using the result of this function directly in an email. Each line will be wrapped at, at most, maxlinelen characters (defaults to 76 characters). Long lines will have the `soft linefeed' quoted-printable character "=" appended to them, so the decoded text will be identical to the original text. """ if not body: return body if not binary: body = fix_eols(body) # BAW: We're accumulating the body text by string concatenation. That # can't be very efficient, but I don't have time now to rewrite it. It # just feels like this algorithm could be more efficient. encoded_body = '' lineno = -1 # Preserve line endings here so we can check later to see an eol needs to # be added to the output later. lines = body.splitlines(1) for line in lines: # But strip off line-endings for processing this line. if line.endswith(CRLF): line = line[:-2] elif line[-1] in CRLF: line = line[:-1] lineno += 1 encoded_line = '' prev = None linelen = len(line) # Now we need to examine every character to see if it needs to be # quopri encoded. BAW: again, string concatenation is inefficient. for j in range(linelen): c = line[j] prev = c if bqre.match(c): c = quote(c) elif j+1 == linelen: # Check for whitespace at end of line; special case if c not in ' \t': encoded_line += c prev = c continue # Check to see to see if the line has reached its maximum length if len(encoded_line) + len(c) >= maxlinelen: encoded_body += encoded_line + '=' + eol encoded_line = '' encoded_line += c # Now at end of line.. if prev and prev in ' \t': # Special case for whitespace at end of file if lineno + 1 == len(lines): prev = quote(prev) if len(encoded_line) + len(prev) > maxlinelen: encoded_body += encoded_line + '=' + eol + prev else: encoded_body += encoded_line + prev # Just normal whitespace at end of line else: encoded_body += encoded_line + prev + '=' + eol encoded_line = '' # Now look at the line we just finished and it has a line ending, we # need to add eol to the end of the line. if lines[lineno].endswith(CRLF) or lines[lineno][-1] in CRLF: encoded_body += encoded_line + eol else: encoded_body += encoded_line encoded_line = '' return encoded_body # For convenience and backwards compatibility w/ standard base64 module body_encode = encode encodestring = encode # BAW: I'm not sure if the intent was for the signature of this function to be # the same as base64MIME.decode() or not... def decode(encoded, eol=NL): """Decode a quoted-printable string. Lines are separated with eol, which defaults to \\n. """ if not encoded: return encoded # BAW: see comment in encode() above. Again, we're building up the # decoded string with string concatenation, which could be done much more # efficiently. decoded = '' for line in encoded.splitlines(): line = line.rstrip() if not line: decoded += eol continue i = 0 n = len(line) while i < n: c = line[i] if c != '=': decoded += c i += 1 # Otherwise, c == "=". Are we at the end of the line? If so, add # a soft line break. elif i+1 == n: i += 1 continue # Decode if in form =AB elif i+2 < n and line[i+1] in hexdigits and line[i+2] in hexdigits: decoded += unquote(line[i:i+3]) i += 3 # Otherwise, not in form =AB, pass literally else: decoded += c i += 1 if i == n: decoded += eol # Special case if original string did not end with eol if not encoded.endswith(eol) and decoded.endswith(eol): decoded = decoded[:-1] return decoded # For convenience and backwards compatibility w/ standard base64 module body_decode = decode decodestring = decode def _unquote_match(match): """Turn a match in the form =AB to the ASCII character with value 0xab""" s = match.group(0) return unquote(s) # Header decoding is done a bit differently def header_decode(s): """Decode a string encoded with RFC 2045 MIME header `Q' encoding. This function does not parse a full MIME header value encoded with quoted-printable (like =?iso-8859-1?q?Hello_World?=) -- please use the high level email.header class for that functionality. """ s = s.replace('_', ' ') return re.sub(r'=[a-fA-F0-9]{2}', _unquote_match, s) _parseaddr.py000064400000037412152526700320007233 0ustar00# Copyright (C) 2002-2007 Python Software Foundation # Contact: email-sig@python.org """Email address parsing code. Lifted directly from rfc822.py. This should eventually be rewritten. """ __all__ = [ 'mktime_tz', 'parsedate', 'parsedate_tz', 'quote', ] import time, calendar SPACE = ' ' EMPTYSTRING = '' COMMASPACE = ', ' # Parse a date field _monthnames = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec', 'january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'] _daynames = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] # The timezone table does not include the military time zones defined # in RFC822, other than Z. According to RFC1123, the description in # RFC822 gets the signs wrong, so we can't rely on any such time # zones. RFC1123 recommends that numeric timezone indicators be used # instead of timezone names. _timezones = {'UT':0, 'UTC':0, 'GMT':0, 'Z':0, 'AST': -400, 'ADT': -300, # Atlantic (used in Canada) 'EST': -500, 'EDT': -400, # Eastern 'CST': -600, 'CDT': -500, # Central 'MST': -700, 'MDT': -600, # Mountain 'PST': -800, 'PDT': -700 # Pacific } def parsedate_tz(data): """Convert a date string to a time tuple. Accounts for military timezones. """ data = data.split() # The FWS after the comma after the day-of-week is optional, so search and # adjust for this. if data[0].endswith(',') or data[0].lower() in _daynames: # There's a dayname here. Skip it del data[0] else: i = data[0].rfind(',') if i >= 0: data[0] = data[0][i+1:] if len(data) == 3: # RFC 850 date, deprecated stuff = data[0].split('-') if len(stuff) == 3: data = stuff + data[1:] if len(data) == 4: s = data[3] i = s.find('+') if i > 0: data[3:] = [s[:i], s[i+1:]] else: data.append('') # Dummy tz if len(data) < 5: return None data = data[:5] [dd, mm, yy, tm, tz] = data mm = mm.lower() if mm not in _monthnames: dd, mm = mm, dd.lower() if mm not in _monthnames: return None mm = _monthnames.index(mm) + 1 if mm > 12: mm -= 12 if dd[-1] == ',': dd = dd[:-1] i = yy.find(':') if i > 0: yy, tm = tm, yy if yy[-1] == ',': yy = yy[:-1] if not yy[0].isdigit(): yy, tz = tz, yy if tm[-1] == ',': tm = tm[:-1] tm = tm.split(':') if len(tm) == 2: [thh, tmm] = tm tss = '0' elif len(tm) == 3: [thh, tmm, tss] = tm else: return None try: yy = int(yy) dd = int(dd) thh = int(thh) tmm = int(tmm) tss = int(tss) except ValueError: return None # Check for a yy specified in two-digit format, then convert it to the # appropriate four-digit format, according to the POSIX standard. RFC 822 # calls for a two-digit yy, but RFC 2822 (which obsoletes RFC 822) # mandates a 4-digit yy. For more information, see the documentation for # the time module. if yy < 100: # The year is between 1969 and 1999 (inclusive). if yy > 68: yy += 1900 # The year is between 2000 and 2068 (inclusive). else: yy += 2000 tzoffset = None tz = tz.upper() if tz in _timezones: tzoffset = _timezones[tz] else: try: tzoffset = int(tz) except ValueError: pass # Convert a timezone offset into seconds ; -0500 -> -18000 if tzoffset: if tzoffset < 0: tzsign = -1 tzoffset = -tzoffset else: tzsign = 1 tzoffset = tzsign * ( (tzoffset//100)*3600 + (tzoffset % 100)*60) # Daylight Saving Time flag is set to -1, since DST is unknown. return yy, mm, dd, thh, tmm, tss, 0, 1, -1, tzoffset def parsedate(data): """Convert a time string to a time tuple.""" t = parsedate_tz(data) if isinstance(t, tuple): return t[:9] else: return t def mktime_tz(data): """Turn a 10-tuple as returned by parsedate_tz() into a POSIX timestamp.""" if data[9] is None: # No zone info, so localtime is better assumption than GMT return time.mktime(data[:8] + (-1,)) else: t = calendar.timegm(data) return t - data[9] def quote(str): """Prepare string to be used in a quoted string. Turns backslash and double quote characters into quoted pairs. These are the only characters that need to be quoted inside a quoted string. Does not add the surrounding double quotes. """ return str.replace('\\', '\\\\').replace('"', '\\"') class AddrlistClass: """Address parser class by Ben Escoto. To understand what this class does, it helps to have a copy of RFC 2822 in front of you. Note: this class interface is deprecated and may be removed in the future. Use rfc822.AddressList instead. """ def __init__(self, field): """Initialize a new instance. `field' is an unparsed address header field, containing one or more addresses. """ self.specials = '()<>@,:;.\"[]' self.pos = 0 self.LWS = ' \t' self.CR = '\r\n' self.FWS = self.LWS + self.CR self.atomends = self.specials + self.LWS + self.CR # Note that RFC 2822 now specifies `.' as obs-phrase, meaning that it # is obsolete syntax. RFC 2822 requires that we recognize obsolete # syntax, so allow dots in phrases. self.phraseends = self.atomends.replace('.', '') self.field = field self.commentlist = [] def gotonext(self): """Parse up to the start of the next address.""" while self.pos < len(self.field): if self.field[self.pos] in self.LWS + '\n\r': self.pos += 1 elif self.field[self.pos] == '(': self.commentlist.append(self.getcomment()) else: break def getaddrlist(self): """Parse all addresses. Returns a list containing all of the addresses. """ result = [] while self.pos < len(self.field): ad = self.getaddress() if ad: result += ad else: result.append(('', '')) return result def getaddress(self): """Parse the next address.""" self.commentlist = [] self.gotonext() oldpos = self.pos oldcl = self.commentlist plist = self.getphraselist() self.gotonext() returnlist = [] if self.pos >= len(self.field): # Bad email address technically, no domain. if plist: returnlist = [(SPACE.join(self.commentlist), plist[0])] elif self.field[self.pos] in '.@': # email address is just an addrspec # this isn't very efficient since we start over self.pos = oldpos self.commentlist = oldcl addrspec = self.getaddrspec() returnlist = [(SPACE.join(self.commentlist), addrspec)] elif self.field[self.pos] == ':': # address is a group returnlist = [] fieldlen = len(self.field) self.pos += 1 while self.pos < len(self.field): self.gotonext() if self.pos < fieldlen and self.field[self.pos] == ';': self.pos += 1 break returnlist = returnlist + self.getaddress() elif self.field[self.pos] == '<': # Address is a phrase then a route addr routeaddr = self.getrouteaddr() if self.commentlist: returnlist = [(SPACE.join(plist) + ' (' + ' '.join(self.commentlist) + ')', routeaddr)] else: returnlist = [(SPACE.join(plist), routeaddr)] else: if plist: returnlist = [(SPACE.join(self.commentlist), plist[0])] elif self.field[self.pos] in self.specials: self.pos += 1 self.gotonext() if self.pos < len(self.field) and self.field[self.pos] == ',': self.pos += 1 return returnlist def getrouteaddr(self): """Parse a route address (Return-path value). This method just skips all the route stuff and returns the addrspec. """ if self.field[self.pos] != '<': return expectroute = False self.pos += 1 self.gotonext() adlist = '' while self.pos < len(self.field): if expectroute: self.getdomain() expectroute = False elif self.field[self.pos] == '>': self.pos += 1 break elif self.field[self.pos] == '@': self.pos += 1 expectroute = True elif self.field[self.pos] == ':': self.pos += 1 else: adlist = self.getaddrspec() self.pos += 1 break self.gotonext() return adlist def getaddrspec(self): """Parse an RFC 2822 addr-spec.""" aslist = [] self.gotonext() while self.pos < len(self.field): if self.field[self.pos] == '.': aslist.append('.') self.pos += 1 elif self.field[self.pos] == '"': aslist.append('"%s"' % quote(self.getquote())) elif self.field[self.pos] in self.atomends: break else: aslist.append(self.getatom()) self.gotonext() if self.pos >= len(self.field) or self.field[self.pos] != '@': return EMPTYSTRING.join(aslist) aslist.append('@') self.pos += 1 self.gotonext() domain = self.getdomain() if not domain: # Invalid domain, return an empty address instead of returning a # local part to denote failed parsing. return EMPTYSTRING return EMPTYSTRING.join(aslist) + domain def getdomain(self): """Get the complete domain name from an address.""" sdlist = [] while self.pos < len(self.field): if self.field[self.pos] in self.LWS: self.pos += 1 elif self.field[self.pos] == '(': self.commentlist.append(self.getcomment()) elif self.field[self.pos] == '[': sdlist.append(self.getdomainliteral()) elif self.field[self.pos] == '.': self.pos += 1 sdlist.append('.') elif self.field[self.pos] == '@': # bpo-34155: Don't parse domains with two `@` like # `a@malicious.org@important.com`. return EMPTYSTRING elif self.field[self.pos] in self.atomends: break else: sdlist.append(self.getatom()) return EMPTYSTRING.join(sdlist) def getdelimited(self, beginchar, endchars, allowcomments=True): """Parse a header fragment delimited by special characters. `beginchar' is the start character for the fragment. If self is not looking at an instance of `beginchar' then getdelimited returns the empty string. `endchars' is a sequence of allowable end-delimiting characters. Parsing stops when one of these is encountered. If `allowcomments' is non-zero, embedded RFC 2822 comments are allowed within the parsed fragment. """ if self.field[self.pos] != beginchar: return '' slist = [''] quote = False self.pos += 1 while self.pos < len(self.field): if quote: slist.append(self.field[self.pos]) quote = False elif self.field[self.pos] in endchars: self.pos += 1 break elif allowcomments and self.field[self.pos] == '(': slist.append(self.getcomment()) continue # have already advanced pos from getcomment elif self.field[self.pos] == '\\': quote = True else: slist.append(self.field[self.pos]) self.pos += 1 return EMPTYSTRING.join(slist) def getquote(self): """Get a quote-delimited fragment from self's field.""" return self.getdelimited('"', '"\r', False) def getcomment(self): """Get a parenthesis-delimited fragment from self's field.""" return self.getdelimited('(', ')\r', True) def getdomainliteral(self): """Parse an RFC 2822 domain-literal.""" return '[%s]' % self.getdelimited('[', ']\r', False) def getatom(self, atomends=None): """Parse an RFC 2822 atom. Optional atomends specifies a different set of end token delimiters (the default is to use self.atomends). This is used e.g. in getphraselist() since phrase endings must not include the `.' (which is legal in phrases).""" atomlist = [''] if atomends is None: atomends = self.atomends while self.pos < len(self.field): if self.field[self.pos] in atomends: break else: atomlist.append(self.field[self.pos]) self.pos += 1 return EMPTYSTRING.join(atomlist) def getphraselist(self): """Parse a sequence of RFC 2822 phrases. A phrase is a sequence of words, which are in turn either RFC 2822 atoms or quoted-strings. Phrases are canonicalized by squeezing all runs of continuous whitespace into one space. """ plist = [] while self.pos < len(self.field): if self.field[self.pos] in self.FWS: self.pos += 1 elif self.field[self.pos] == '"': plist.append(self.getquote()) elif self.field[self.pos] == '(': self.commentlist.append(self.getcomment()) elif self.field[self.pos] in self.phraseends: break else: plist.append(self.getatom(self.phraseends)) return plist class AddressList(AddrlistClass): """An AddressList encapsulates a list of parsed RFC 2822 addresses.""" def __init__(self, field): AddrlistClass.__init__(self, field) if field: self.addresslist = self.getaddrlist() else: self.addresslist = [] def __len__(self): return len(self.addresslist) def __add__(self, other): # Set union newaddr = AddressList(None) newaddr.addresslist = self.addresslist[:] for x in other.addresslist: if not x in self.addresslist: newaddr.addresslist.append(x) return newaddr def __iadd__(self, other): # Set union, in-place for x in other.addresslist: if not x in self.addresslist: self.addresslist.append(x) return self def __sub__(self, other): # Set difference newaddr = AddressList(None) for x in self.addresslist: if not x in other.addresslist: newaddr.addresslist.append(x) return newaddr def __isub__(self, other): # Set difference, in-place for x in other.addresslist: if x in self.addresslist: self.addresslist.remove(x) return self def __getitem__(self, index): # Make indexing, slices, and 'in' work return self.addresslist[index] utils.py000064400000023452152526700320006266 0ustar00# Copyright (C) 2001-2010 Python Software Foundation # Author: Barry Warsaw # Contact: email-sig@python.org """Miscellaneous utilities.""" __all__ = [ 'collapse_rfc2231_value', 'decode_params', 'decode_rfc2231', 'encode_rfc2231', 'formataddr', 'formatdate', 'getaddresses', 'make_msgid', 'mktime_tz', 'parseaddr', 'parsedate', 'parsedate_tz', 'unquote', ] import os import re import time import base64 import random import socket import urllib import warnings from email._parseaddr import quote from email._parseaddr import AddressList as _AddressList from email._parseaddr import mktime_tz # We need wormarounds for bugs in these methods in older Pythons (see below) from email._parseaddr import parsedate as _parsedate from email._parseaddr import parsedate_tz as _parsedate_tz from quopri import decodestring as _qdecode # Intrapackage imports from email.encoders import _bencode, _qencode COMMASPACE = ', ' EMPTYSTRING = '' UEMPTYSTRING = u'' CRLF = '\r\n' TICK = "'" specialsre = re.compile(r'[][\\()<>@,:;".]') escapesre = re.compile(r'[][\\()"]') # Helpers def _identity(s): return s def _bdecode(s): """Decodes a base64 string. This function is equivalent to base64.decodestring and it's retained only for backward compatibility. It used to remove the last \\n of the decoded string, if it had any (see issue 7143). """ if not s: return s return base64.decodestring(s) def fix_eols(s): """Replace all line-ending characters with \\r\\n.""" # Fix newlines with no preceding carriage return s = re.sub(r'(?', name) return '%s%s%s <%s>' % (quotes, name, quotes, address) return address def getaddresses(fieldvalues): """Return a list of (REALNAME, EMAIL) for each fieldvalue.""" all = COMMASPACE.join(fieldvalues) a = _AddressList(all) return a.addresslist ecre = re.compile(r''' =\? # literal =? (?P[^?]*?) # non-greedy up to the next ? is the charset \? # literal ? (?P[qb]) # either a "q" or a "b", case insensitive \? # literal ? (?P.*?) # non-greedy up to the next ?= is the atom \?= # literal ?= ''', re.VERBOSE | re.IGNORECASE) def formatdate(timeval=None, localtime=False, usegmt=False): """Returns a date string as specified by RFC 2822, e.g.: Fri, 09 Nov 2001 01:08:47 -0000 Optional timeval if given is a floating point time value as accepted by gmtime() and localtime(), otherwise the current time is used. Optional localtime is a flag that when True, interprets timeval, and returns a date relative to the local timezone instead of UTC, properly taking daylight savings time into account. Optional argument usegmt means that the timezone is written out as an ascii string, not numeric one (so "GMT" instead of "+0000"). This is needed for HTTP, and is only used when localtime==False. """ # Note: we cannot use strftime() because that honors the locale and RFC # 2822 requires that day and month names be the English abbreviations. if timeval is None: timeval = time.time() if localtime: now = time.localtime(timeval) # Calculate timezone offset, based on whether the local zone has # daylight savings time, and whether DST is in effect. if time.daylight and now[-1]: offset = time.altzone else: offset = time.timezone hours, minutes = divmod(abs(offset), 3600) # Remember offset is in seconds west of UTC, but the timezone is in # minutes east of UTC, so the signs differ. if offset > 0: sign = '-' else: sign = '+' zone = '%s%02d%02d' % (sign, hours, minutes // 60) else: now = time.gmtime(timeval) # Timezone offset is always -0000 if usegmt: zone = 'GMT' else: zone = '-0000' return '%s, %02d %s %04d %02d:%02d:%02d %s' % ( ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][now[6]], now[2], ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][now[1] - 1], now[0], now[3], now[4], now[5], zone) def make_msgid(idstring=None): """Returns a string suitable for RFC 2822 compliant Message-ID, e.g: <142480216486.20800.16526388040877946887@nightshade.la.mastaler.com> Optional idstring if given is a string used to strengthen the uniqueness of the message id. """ timeval = int(time.time()*100) pid = os.getpid() randint = random.getrandbits(64) if idstring is None: idstring = '' else: idstring = '.' + idstring idhost = socket.getfqdn() msgid = '<%d.%d.%d%s@%s>' % (timeval, pid, randint, idstring, idhost) return msgid # These functions are in the standalone mimelib version only because they've # subsequently been fixed in the latest Python versions. We use this to worm # around broken older Pythons. def parsedate(data): if not data: return None return _parsedate(data) def parsedate_tz(data): if not data: return None return _parsedate_tz(data) def parseaddr(addr): """ Parse addr into its constituent realname and email address parts. Return a tuple of realname and email address, unless the parse fails, in which case return a 2-tuple of ('', ''). """ addrs = _AddressList(addr).addresslist if not addrs: return '', '' return addrs[0] # rfc822.unquote() doesn't properly de-backslash-ify in Python pre-2.3. def unquote(str): """Remove quotes from a string.""" if len(str) > 1: if str.startswith('"') and str.endswith('"'): return str[1:-1].replace('\\\\', '\\').replace('\\"', '"') if str.startswith('<') and str.endswith('>'): return str[1:-1] return str # RFC2231-related functions - parameter encoding and decoding def decode_rfc2231(s): """Decode string according to RFC 2231""" parts = s.split(TICK, 2) if len(parts) <= 2: return None, None, s return parts def encode_rfc2231(s, charset=None, language=None): """Encode string according to RFC 2231. If neither charset nor language is given, then s is returned as-is. If charset is given but not language, the string is encoded using the empty string for language. """ import urllib s = urllib.quote(s, safe='') if charset is None and language is None: return s if language is None: language = '' return "%s'%s'%s" % (charset, language, s) rfc2231_continuation = re.compile(r'^(?P\w+)\*((?P[0-9]+)\*?)?$') def decode_params(params): """Decode parameters list according to RFC 2231. params is a sequence of 2-tuples containing (param name, string value). """ # Copy params so we don't mess with the original params = params[:] new_params = [] # Map parameter's name to a list of continuations. The values are a # 3-tuple of the continuation number, the string value, and a flag # specifying whether a particular segment is %-encoded. rfc2231_params = {} name, value = params.pop(0) new_params.append((name, value)) while params: name, value = params.pop(0) if name.endswith('*'): encoded = True else: encoded = False value = unquote(value) mo = rfc2231_continuation.match(name) if mo: name, num = mo.group('name', 'num') if num is not None: num = int(num) rfc2231_params.setdefault(name, []).append((num, value, encoded)) else: new_params.append((name, '"%s"' % quote(value))) if rfc2231_params: for name, continuations in rfc2231_params.items(): value = [] extended = False # Sort by number continuations.sort() # And now append all values in numerical order, converting # %-encodings for the encoded segments. If any of the # continuation names ends in a *, then the entire string, after # decoding segments and concatenating, must have the charset and # language specifiers at the beginning of the string. for num, s, encoded in continuations: if encoded: s = urllib.unquote(s) extended = True value.append(s) value = quote(EMPTYSTRING.join(value)) if extended: charset, language, value = decode_rfc2231(value) new_params.append((name, (charset, language, '"%s"' % value))) else: new_params.append((name, '"%s"' % value)) return new_params def collapse_rfc2231_value(value, errors='replace', fallback_charset='us-ascii'): if isinstance(value, tuple): rawval = unquote(value[2]) charset = value[0] or 'us-ascii' try: return unicode(rawval, charset, errors) except LookupError: # XXX charset is unknown to Python. return unicode(rawval, fallback_charset, errors) else: return unquote(value) encoders.py000064400000003737152526700320006734 0ustar00# Copyright (C) 2001-2006 Python Software Foundation # Author: Barry Warsaw # Contact: email-sig@python.org """Encodings and related functions.""" __all__ = [ 'encode_7or8bit', 'encode_base64', 'encode_noop', 'encode_quopri', ] import base64 from quopri import encodestring as _encodestring def _qencode(s): enc = _encodestring(s, quotetabs=True) # Must encode spaces, which quopri.encodestring() doesn't do return enc.replace(' ', '=20') def _bencode(s): # We can't quite use base64.encodestring() since it tacks on a "courtesy # newline". Blech! if not s: return s hasnewline = (s[-1] == '\n') value = base64.encodestring(s) if not hasnewline and value[-1] == '\n': return value[:-1] return value def encode_base64(msg): """Encode the message's payload in Base64. Also, add an appropriate Content-Transfer-Encoding header. """ orig = msg.get_payload() encdata = _bencode(orig) msg.set_payload(encdata) msg['Content-Transfer-Encoding'] = 'base64' def encode_quopri(msg): """Encode the message's payload in quoted-printable. Also, add an appropriate Content-Transfer-Encoding header. """ orig = msg.get_payload() encdata = _qencode(orig) msg.set_payload(encdata) msg['Content-Transfer-Encoding'] = 'quoted-printable' def encode_7or8bit(msg): """Set the Content-Transfer-Encoding header to 7bit or 8bit.""" orig = msg.get_payload() if orig is None: # There's no payload. For backwards compatibility we use 7bit msg['Content-Transfer-Encoding'] = '7bit' return # We play a trick to make this go fast. If encoding to ASCII succeeds, we # know the data must be 7bit, otherwise treat it as 8bit. try: orig.encode('ascii') except UnicodeError: msg['Content-Transfer-Encoding'] = '8bit' else: msg['Content-Transfer-Encoding'] = '7bit' def encode_noop(msg): """Do nothing.""" iterators.py000064400000004232152526700320007135 0ustar00# Copyright (C) 2001-2006 Python Software Foundation # Author: Barry Warsaw # Contact: email-sig@python.org """Various types of useful iterators and generators.""" __all__ = [ 'body_line_iterator', 'typed_subpart_iterator', 'walk', # Do not include _structure() since it's part of the debugging API. ] import sys from cStringIO import StringIO # This function will become a method of the Message class def walk(self): """Walk over the message tree, yielding each subpart. The walk is performed in depth-first order. This method is a generator. """ yield self if self.is_multipart(): for subpart in self.get_payload(): for subsubpart in subpart.walk(): yield subsubpart # These two functions are imported into the Iterators.py interface module. def body_line_iterator(msg, decode=False): """Iterate over the parts, returning string payloads line-by-line. Optional decode (default False) is passed through to .get_payload(). """ for subpart in msg.walk(): payload = subpart.get_payload(decode=decode) if isinstance(payload, basestring): for line in StringIO(payload): yield line def typed_subpart_iterator(msg, maintype='text', subtype=None): """Iterate over the subparts with a given MIME type. Use `maintype' as the main MIME type to match against; this defaults to "text". Optional `subtype' is the MIME subtype to match against; if omitted, only the main type is matched. """ for subpart in msg.walk(): if subpart.get_content_maintype() == maintype: if subtype is None or subpart.get_content_subtype() == subtype: yield subpart def _structure(msg, fp=None, level=0, include_default=False): """A handy debugging aid""" if fp is None: fp = sys.stdout tab = ' ' * (level * 4) print >> fp, tab + msg.get_content_type(), if include_default: print >> fp, '[%s]' % msg.get_default_type() else: print >> fp if msg.is_multipart(): for subpart in msg.get_payload(): _structure(subpart, fp, level+1, include_default) header.py000064400000053343152526700320006360 0ustar00# Copyright (C) 2002-2006 Python Software Foundation # Author: Ben Gertzfield, Barry Warsaw # Contact: email-sig@python.org """Header encoding and decoding functionality.""" __all__ = [ 'Header', 'decode_header', 'make_header', ] import re import binascii import email.quoprimime import email.base64mime from email.errors import HeaderParseError from email.charset import Charset NL = '\n' SPACE = ' ' USPACE = u' ' SPACE8 = ' ' * 8 UEMPTYSTRING = u'' MAXLINELEN = 76 USASCII = Charset('us-ascii') UTF8 = Charset('utf-8') # Match encoded-word strings in the form =?charset?q?Hello_World?= ecre = re.compile(r''' =\? # literal =? (?P[^?]*?) # non-greedy up to the next ? is the charset \? # literal ? (?P[qb]) # either a "q" or a "b", case insensitive \? # literal ? (?P.*?) # non-greedy up to the next ?= is the encoded string \?= # literal ?= (?=[ \t]|$) # whitespace or the end of the string ''', re.VERBOSE | re.IGNORECASE | re.MULTILINE) # Field name regexp, including trailing colon, but not separating whitespace, # according to RFC 2822. Character range is from tilde to exclamation mark. # For use with .match() fcre = re.compile(r'[\041-\176]+:$') # Find a header embedded in a putative header value. Used to check for # header injection attack. _embeded_header = re.compile(r'\n[^ \t]+:') # Helpers _max_append = email.quoprimime._max_append def decode_header(header): """Decode a message header value without converting charset. Returns a list of (decoded_string, charset) pairs containing each of the decoded parts of the header. Charset is None for non-encoded parts of the header, otherwise a lower-case string containing the name of the character set specified in the encoded string. An email.errors.HeaderParseError may be raised when certain decoding error occurs (e.g. a base64 decoding exception). """ # If no encoding, just return the header header = str(header) if not ecre.search(header): return [(header, None)] decoded = [] dec = '' for line in header.splitlines(): # This line might not have an encoding in it if not ecre.search(line): decoded.append((line, None)) continue parts = ecre.split(line) while parts: unenc = parts.pop(0).strip() if unenc: # Should we continue a long line? if decoded and decoded[-1][1] is None: decoded[-1] = (decoded[-1][0] + SPACE + unenc, None) else: decoded.append((unenc, None)) if parts: charset, encoding = [s.lower() for s in parts[0:2]] encoded = parts[2] dec = None if encoding == 'q': dec = email.quoprimime.header_decode(encoded) elif encoding == 'b': paderr = len(encoded) % 4 # Postel's law: add missing padding if paderr: encoded += '==='[:4 - paderr] try: dec = email.base64mime.decode(encoded) except binascii.Error: # Turn this into a higher level exception. BAW: Right # now we throw the lower level exception away but # when/if we get exception chaining, we'll preserve it. raise HeaderParseError if dec is None: dec = encoded if decoded and decoded[-1][1] == charset: decoded[-1] = (decoded[-1][0] + dec, decoded[-1][1]) else: decoded.append((dec, charset)) del parts[0:3] return decoded def make_header(decoded_seq, maxlinelen=None, header_name=None, continuation_ws=' '): """Create a Header from a sequence of pairs as returned by decode_header() decode_header() takes a header value string and returns a sequence of pairs of the format (decoded_string, charset) where charset is the string name of the character set. This function takes one of those sequence of pairs and returns a Header instance. Optional maxlinelen, header_name, and continuation_ws are as in the Header constructor. """ h = Header(maxlinelen=maxlinelen, header_name=header_name, continuation_ws=continuation_ws) for s, charset in decoded_seq: # None means us-ascii but we can simply pass it on to h.append() if charset is not None and not isinstance(charset, Charset): charset = Charset(charset) h.append(s, charset) return h class Header: def __init__(self, s=None, charset=None, maxlinelen=None, header_name=None, continuation_ws=' ', errors='strict'): """Create a MIME-compliant header that can contain many character sets. Optional s is the initial header value. If None, the initial header value is not set. You can later append to the header with .append() method calls. s may be a byte string or a Unicode string, but see the .append() documentation for semantics. Optional charset serves two purposes: it has the same meaning as the charset argument to the .append() method. It also sets the default character set for all subsequent .append() calls that omit the charset argument. If charset is not provided in the constructor, the us-ascii charset is used both as s's initial charset and as the default for subsequent .append() calls. The maximum line length can be specified explicit via maxlinelen. For splitting the first line to a shorter value (to account for the field header which isn't included in s, e.g. `Subject') pass in the name of the field in header_name. The default maxlinelen is 76. continuation_ws must be RFC 2822 compliant folding whitespace (usually either a space or a hard tab) which will be prepended to continuation lines. errors is passed through to the .append() call. """ if charset is None: charset = USASCII if not isinstance(charset, Charset): charset = Charset(charset) self._charset = charset self._continuation_ws = continuation_ws cws_expanded_len = len(continuation_ws.replace('\t', SPACE8)) # BAW: I believe `chunks' and `maxlinelen' should be non-public. self._chunks = [] if s is not None: self.append(s, charset, errors) if maxlinelen is None: maxlinelen = MAXLINELEN if header_name is None: # We don't know anything about the field header so the first line # is the same length as subsequent lines. self._firstlinelen = maxlinelen else: # The first line should be shorter to take into account the field # header. Also subtract off 2 extra for the colon and space. self._firstlinelen = maxlinelen - len(header_name) - 2 # Second and subsequent lines should subtract off the length in # columns of the continuation whitespace prefix. self._maxlinelen = maxlinelen - cws_expanded_len def __str__(self): """A synonym for self.encode().""" return self.encode() def __unicode__(self): """Helper for the built-in unicode function.""" uchunks = [] lastcs = None for s, charset in self._chunks: # We must preserve spaces between encoded and non-encoded word # boundaries, which means for us we need to add a space when we go # from a charset to None/us-ascii, or from None/us-ascii to a # charset. Only do this for the second and subsequent chunks. nextcs = charset if uchunks: if lastcs not in (None, 'us-ascii'): if nextcs in (None, 'us-ascii'): uchunks.append(USPACE) nextcs = None elif nextcs not in (None, 'us-ascii'): uchunks.append(USPACE) lastcs = nextcs uchunks.append(unicode(s, str(charset))) return UEMPTYSTRING.join(uchunks) # Rich comparison operators for equality only. BAW: does it make sense to # have or explicitly disable <, <=, >, >= operators? def __eq__(self, other): # other may be a Header or a string. Both are fine so coerce # ourselves to a string, swap the args and do another comparison. return other == self.encode() def __ne__(self, other): return not self == other def append(self, s, charset=None, errors='strict'): """Append a string to the MIME header. Optional charset, if given, should be a Charset instance or the name of a character set (which will be converted to a Charset instance). A value of None (the default) means that the charset given in the constructor is used. s may be a byte string or a Unicode string. If it is a byte string (i.e. isinstance(s, str) is true), then charset is the encoding of that byte string, and a UnicodeError will be raised if the string cannot be decoded with that charset. If s is a Unicode string, then charset is a hint specifying the character set of the characters in the string. In this case, when producing an RFC 2822 compliant header using RFC 2047 rules, the Unicode string will be encoded using the following charsets in order: us-ascii, the charset hint, utf-8. The first character set not to provoke a UnicodeError is used. Optional `errors' is passed as the third argument to any unicode() or ustr.encode() call. """ if charset is None: charset = self._charset elif not isinstance(charset, Charset): charset = Charset(charset) # If the charset is our faux 8bit charset, leave the string unchanged if charset != '8bit': # We need to test that the string can be converted to unicode and # back to a byte string, given the input and output codecs of the # charset. if isinstance(s, str): # Possibly raise UnicodeError if the byte string can't be # converted to a unicode with the input codec of the charset. incodec = charset.input_codec or 'us-ascii' ustr = unicode(s, incodec, errors) # Now make sure that the unicode could be converted back to a # byte string with the output codec, which may be different # than the iput coded. Still, use the original byte string. outcodec = charset.output_codec or 'us-ascii' ustr.encode(outcodec, errors) elif isinstance(s, unicode): # Now we have to be sure the unicode string can be converted # to a byte string with a reasonable output codec. We want to # use the byte string in the chunk. for charset in USASCII, charset, UTF8: try: outcodec = charset.output_codec or 'us-ascii' s = s.encode(outcodec, errors) break except UnicodeError: pass else: assert False, 'utf-8 conversion failed' self._chunks.append((s, charset)) def _split(self, s, charset, maxlinelen, splitchars): # Split up a header safely for use with encode_chunks. splittable = charset.to_splittable(s) encoded = charset.from_splittable(splittable, True) elen = charset.encoded_header_len(encoded) # If the line's encoded length first, just return it if elen <= maxlinelen: return [(encoded, charset)] # If we have undetermined raw 8bit characters sitting in a byte # string, we really don't know what the right thing to do is. We # can't really split it because it might be multibyte data which we # could break if we split it between pairs. The least harm seems to # be to not split the header at all, but that means they could go out # longer than maxlinelen. if charset == '8bit': return [(s, charset)] # BAW: I'm not sure what the right test here is. What we're trying to # do is be faithful to RFC 2822's recommendation that ($2.2.3): # # "Note: Though structured field bodies are defined in such a way that # folding can take place between many of the lexical tokens (and even # within some of the lexical tokens), folding SHOULD be limited to # placing the CRLF at higher-level syntactic breaks." # # For now, I can only imagine doing this when the charset is us-ascii, # although it's possible that other charsets may also benefit from the # higher-level syntactic breaks. elif charset == 'us-ascii': return self._split_ascii(s, charset, maxlinelen, splitchars) # BAW: should we use encoded? elif elen == len(s): # We can split on _maxlinelen boundaries because we know that the # encoding won't change the size of the string splitpnt = maxlinelen first = charset.from_splittable(splittable[:splitpnt], False) last = charset.from_splittable(splittable[splitpnt:], False) else: # Binary search for split point first, last = _binsplit(splittable, charset, maxlinelen) # first is of the proper length so just wrap it in the appropriate # chrome. last must be recursively split. fsplittable = charset.to_splittable(first) fencoded = charset.from_splittable(fsplittable, True) chunk = [(fencoded, charset)] return chunk + self._split(last, charset, self._maxlinelen, splitchars) def _split_ascii(self, s, charset, firstlen, splitchars): chunks = _split_ascii(s, firstlen, self._maxlinelen, self._continuation_ws, splitchars) return zip(chunks, [charset]*len(chunks)) def _encode_chunks(self, newchunks, maxlinelen): # MIME-encode a header with many different charsets and/or encodings. # # Given a list of pairs (string, charset), return a MIME-encoded # string suitable for use in a header field. Each pair may have # different charsets and/or encodings, and the resulting header will # accurately reflect each setting. # # Each encoding can be email.utils.QP (quoted-printable, for # ASCII-like character sets like iso-8859-1), email.utils.BASE64 # (Base64, for non-ASCII like character sets like KOI8-R and # iso-2022-jp), or None (no encoding). # # Each pair will be represented on a separate line; the resulting # string will be in the format: # # =?charset1?q?Mar=EDa_Gonz=E1lez_Alonso?=\n # =?charset2?b?SvxyZ2VuIEL2aW5n?=" chunks = [] for header, charset in newchunks: if not header: continue if charset is None or charset.header_encoding is None: s = header else: s = charset.header_encode(header) # Don't add more folding whitespace than necessary if chunks and chunks[-1].endswith(' '): extra = '' else: extra = ' ' _max_append(chunks, s, maxlinelen, extra) joiner = NL + self._continuation_ws return joiner.join(chunks) def encode(self, splitchars=';, '): """Encode a message header into an RFC-compliant format. There are many issues involved in converting a given string for use in an email header. Only certain character sets are readable in most email clients, and as header strings can only contain a subset of 7-bit ASCII, care must be taken to properly convert and encode (with Base64 or quoted-printable) header strings. In addition, there is a 75-character length limit on any given encoded header field, so line-wrapping must be performed, even with double-byte character sets. This method will do its best to convert the string to the correct character set used in email, and encode and line wrap it safely with the appropriate scheme for that character set. If the given charset is not known or an error occurs during conversion, this function will return the header untouched. Optional splitchars is a string containing characters to split long ASCII lines on, in rough support of RFC 2822's `highest level syntactic breaks'. This doesn't affect RFC 2047 encoded lines. """ newchunks = [] maxlinelen = self._firstlinelen lastlen = 0 for s, charset in self._chunks: # The first bit of the next chunk should be just long enough to # fill the next line. Don't forget the space separating the # encoded words. targetlen = maxlinelen - lastlen - 1 if targetlen < charset.encoded_header_len(''): # Stick it on the next line targetlen = maxlinelen newchunks += self._split(s, charset, targetlen, splitchars) lastchunk, lastcharset = newchunks[-1] lastlen = lastcharset.encoded_header_len(lastchunk) value = self._encode_chunks(newchunks, maxlinelen) if _embeded_header.search(value): raise HeaderParseError("header value appears to contain " "an embedded header: {!r}".format(value)) return value def _split_ascii(s, firstlen, restlen, continuation_ws, splitchars): lines = [] maxlen = firstlen for line in s.splitlines(): # Ignore any leading whitespace (i.e. continuation whitespace) already # on the line, since we'll be adding our own. line = line.lstrip() if len(line) < maxlen: lines.append(line) maxlen = restlen continue # Attempt to split the line at the highest-level syntactic break # possible. Note that we don't have a lot of smarts about field # syntax; we just try to break on semi-colons, then commas, then # whitespace. for ch in splitchars: if ch in line: break else: # There's nothing useful to split the line on, not even spaces, so # just append this line unchanged lines.append(line) maxlen = restlen continue # Now split the line on the character plus trailing whitespace cre = re.compile(r'%s\s*' % ch) if ch in ';,': eol = ch else: eol = '' joiner = eol + ' ' joinlen = len(joiner) wslen = len(continuation_ws.replace('\t', SPACE8)) this = [] linelen = 0 for part in cre.split(line): curlen = linelen + max(0, len(this)-1) * joinlen partlen = len(part) onfirstline = not lines # We don't want to split after the field name, if we're on the # first line and the field name is present in the header string. if ch == ' ' and onfirstline and \ len(this) == 1 and fcre.match(this[0]): this.append(part) linelen += partlen elif curlen + partlen > maxlen: if this: lines.append(joiner.join(this) + eol) # If this part is longer than maxlen and we aren't already # splitting on whitespace, try to recursively split this line # on whitespace. if partlen > maxlen and ch != ' ': subl = _split_ascii(part, maxlen, restlen, continuation_ws, ' ') lines.extend(subl[:-1]) this = [subl[-1]] else: this = [part] linelen = wslen + len(this[-1]) maxlen = restlen else: this.append(part) linelen += partlen # Put any left over parts on a line by themselves if this: lines.append(joiner.join(this)) return lines def _binsplit(splittable, charset, maxlinelen): i = 0 j = len(splittable) while i < j: # Invariants: # 1. splittable[:k] fits for all k <= i (note that we *assume*, # at the start, that splittable[:0] fits). # 2. splittable[:k] does not fit for any k > j (at the start, # this means we shouldn't look at any k > len(splittable)). # 3. We don't know about splittable[:k] for k in i+1..j. # 4. We want to set i to the largest k that fits, with i <= k <= j. # m = (i+j+1) >> 1 # ceiling((i+j)/2); i < m <= j chunk = charset.from_splittable(splittable[:m], True) chunklen = charset.encoded_header_len(chunk) if chunklen <= maxlinelen: # m is acceptable, so is a new lower bound. i = m else: # m is not acceptable, so final i must be < m. j = m - 1 # i == j. Invariant #1 implies that splittable[:i] fits, and # invariant #2 implies that splittable[:i+1] does not fit, so i # is what we're looking for. first = charset.from_splittable(splittable[:i], False) last = charset.from_splittable(splittable[i:], False) return first, last generator.py000064400000033573152526700320007121 0ustar00# Copyright (C) 2001-2010 Python Software Foundation # Contact: email-sig@python.org """Classes to generate plain text from a message object tree.""" __all__ = ['Generator', 'DecodedGenerator'] import re import sys import time import random import warnings from cStringIO import StringIO from email.header import Header UNDERSCORE = '_' NL = '\n' fcre = re.compile(r'^From ', re.MULTILINE) def _is8bitstring(s): if isinstance(s, str): try: unicode(s, 'us-ascii') except UnicodeError: return True return False class Generator: """Generates output from a Message object tree. This basic generator writes the message to the given file object as plain text. """ # # Public interface # def __init__(self, outfp, mangle_from_=True, maxheaderlen=78): """Create the generator for message flattening. outfp is the output file-like object for writing the message to. It must have a write() method. Optional mangle_from_ is a flag that, when True (the default), escapes From_ lines in the body of the message by putting a `>' in front of them. Optional maxheaderlen specifies the longest length for a non-continued header. When a header line is longer (in characters, with tabs expanded to 8 spaces) than maxheaderlen, the header will split as defined in the Header class. Set maxheaderlen to zero to disable header wrapping. The default is 78, as recommended (but not required) by RFC 2822. """ self._fp = outfp self._mangle_from_ = mangle_from_ self._maxheaderlen = maxheaderlen def write(self, s): # Just delegate to the file object self._fp.write(s) def flatten(self, msg, unixfrom=False): """Print the message object tree rooted at msg to the output file specified when the Generator instance was created. unixfrom is a flag that forces the printing of a Unix From_ delimiter before the first object in the message tree. If the original message has no From_ delimiter, a `standard' one is crafted. By default, this is False to inhibit the printing of any From_ delimiter. Note that for subobjects, no From_ line is printed. """ if unixfrom: ufrom = msg.get_unixfrom() if not ufrom: ufrom = 'From nobody ' + time.ctime(time.time()) print >> self._fp, ufrom self._write(msg) def clone(self, fp): """Clone this generator with the exact same options.""" return self.__class__(fp, self._mangle_from_, self._maxheaderlen) # # Protected interface - undocumented ;/ # def _write(self, msg): # We can't write the headers yet because of the following scenario: # say a multipart message includes the boundary string somewhere in # its body. We'd have to calculate the new boundary /before/ we write # the headers so that we can write the correct Content-Type: # parameter. # # The way we do this, so as to make the _handle_*() methods simpler, # is to cache any subpart writes into a StringIO. The we write the # headers and the StringIO contents. That way, subpart handlers can # Do The Right Thing, and can still modify the Content-Type: header if # necessary. oldfp = self._fp try: self._fp = sfp = StringIO() self._dispatch(msg) finally: self._fp = oldfp # Write the headers. First we see if the message object wants to # handle that itself. If not, we'll do it generically. meth = getattr(msg, '_write_headers', None) if meth is None: self._write_headers(msg) else: meth(self) self._fp.write(sfp.getvalue()) def _dispatch(self, msg): # Get the Content-Type: for the message, then try to dispatch to # self._handle__(). If there's no handler for the # full MIME type, then dispatch to self._handle_(). If # that's missing too, then dispatch to self._writeBody(). main = msg.get_content_maintype() sub = msg.get_content_subtype() specific = UNDERSCORE.join((main, sub)).replace('-', '_') meth = getattr(self, '_handle_' + specific, None) if meth is None: generic = main.replace('-', '_') meth = getattr(self, '_handle_' + generic, None) if meth is None: meth = self._writeBody meth(msg) # # Default handlers # def _write_headers(self, msg): for h, v in msg.items(): print >> self._fp, '%s:' % h, if self._maxheaderlen == 0: # Explicit no-wrapping print >> self._fp, v elif isinstance(v, Header): # Header instances know what to do print >> self._fp, v.encode() elif _is8bitstring(v): # If we have raw 8bit data in a byte string, we have no idea # what the encoding is. There is no safe way to split this # string. If it's ascii-subset, then we could do a normal # ascii split, but if it's multibyte then we could break the # string. There's no way to know so the least harm seems to # be to not split the string and risk it being too long. print >> self._fp, v else: # Header's got lots of smarts, so use it. Note that this is # fundamentally broken though because we lose idempotency when # the header string is continued with tabs. It will now be # continued with spaces. This was reversedly broken before we # fixed bug 1974. Either way, we lose. print >> self._fp, Header( v, maxlinelen=self._maxheaderlen, header_name=h).encode() # A blank line always separates headers from body print >> self._fp # # Handlers for writing types and subtypes # def _handle_text(self, msg): payload = msg.get_payload() if payload is None: return if not isinstance(payload, basestring): raise TypeError('string payload expected: %s' % type(payload)) if self._mangle_from_: payload = fcre.sub('>From ', payload) self._fp.write(payload) # Default body handler _writeBody = _handle_text def _handle_multipart(self, msg): # The trick here is to write out each part separately, merge them all # together, and then make sure that the boundary we've chosen isn't # present in the payload. msgtexts = [] subparts = msg.get_payload() if subparts is None: subparts = [] elif isinstance(subparts, basestring): # e.g. a non-strict parse of a message with no starting boundary. self._fp.write(subparts) return elif not isinstance(subparts, list): # Scalar payload subparts = [subparts] for part in subparts: s = StringIO() g = self.clone(s) g.flatten(part, unixfrom=False) msgtexts.append(s.getvalue()) # BAW: What about boundaries that are wrapped in double-quotes? boundary = msg.get_boundary() if not boundary: # Create a boundary that doesn't appear in any of the # message texts. alltext = NL.join(msgtexts) boundary = _make_boundary(alltext) msg.set_boundary(boundary) # If there's a preamble, write it out, with a trailing CRLF if msg.preamble is not None: if self._mangle_from_: preamble = fcre.sub('>From ', msg.preamble) else: preamble = msg.preamble print >> self._fp, preamble # dash-boundary transport-padding CRLF print >> self._fp, '--' + boundary # body-part if msgtexts: self._fp.write(msgtexts.pop(0)) # *encapsulation # --> delimiter transport-padding # --> CRLF body-part for body_part in msgtexts: # delimiter transport-padding CRLF print >> self._fp, '\n--' + boundary # body-part self._fp.write(body_part) # close-delimiter transport-padding self._fp.write('\n--' + boundary + '--' + NL) if msg.epilogue is not None: if self._mangle_from_: epilogue = fcre.sub('>From ', msg.epilogue) else: epilogue = msg.epilogue self._fp.write(epilogue) def _handle_multipart_signed(self, msg): # The contents of signed parts has to stay unmodified in order to keep # the signature intact per RFC1847 2.1, so we disable header wrapping. # RDM: This isn't enough to completely preserve the part, but it helps. old_maxheaderlen = self._maxheaderlen try: self._maxheaderlen = 0 self._handle_multipart(msg) finally: self._maxheaderlen = old_maxheaderlen def _handle_message_delivery_status(self, msg): # We can't just write the headers directly to self's file object # because this will leave an extra newline between the last header # block and the boundary. Sigh. blocks = [] for part in msg.get_payload(): s = StringIO() g = self.clone(s) g.flatten(part, unixfrom=False) text = s.getvalue() lines = text.split('\n') # Strip off the unnecessary trailing empty line if lines and lines[-1] == '': blocks.append(NL.join(lines[:-1])) else: blocks.append(text) # Now join all the blocks with an empty line. This has the lovely # effect of separating each block with an empty line, but not adding # an extra one after the last one. self._fp.write(NL.join(blocks)) def _handle_message(self, msg): s = StringIO() g = self.clone(s) # The payload of a message/rfc822 part should be a multipart sequence # of length 1. The zeroth element of the list should be the Message # object for the subpart. Extract that object, stringify it, and # write it out. # Except, it turns out, when it's a string instead, which happens when # and only when HeaderParser is used on a message of mime type # message/rfc822. Such messages are generated by, for example, # Groupwise when forwarding unadorned messages. (Issue 7970.) So # in that case we just emit the string body. payload = msg.get_payload() if isinstance(payload, list): g.flatten(msg.get_payload(0), unixfrom=False) payload = s.getvalue() self._fp.write(payload) _FMT = '[Non-text (%(type)s) part of message omitted, filename %(filename)s]' class DecodedGenerator(Generator): """Generates a text representation of a message. Like the Generator base class, except that non-text parts are substituted with a format string representing the part. """ def __init__(self, outfp, mangle_from_=True, maxheaderlen=78, fmt=None): """Like Generator.__init__() except that an additional optional argument is allowed. Walks through all subparts of a message. If the subpart is of main type `text', then it prints the decoded payload of the subpart. Otherwise, fmt is a format string that is used instead of the message payload. fmt is expanded with the following keywords (in %(keyword)s format): type : Full MIME type of the non-text part maintype : Main MIME type of the non-text part subtype : Sub-MIME type of the non-text part filename : Filename of the non-text part description: Description associated with the non-text part encoding : Content transfer encoding of the non-text part The default value for fmt is None, meaning [Non-text (%(type)s) part of message omitted, filename %(filename)s] """ Generator.__init__(self, outfp, mangle_from_, maxheaderlen) if fmt is None: self._fmt = _FMT else: self._fmt = fmt def _dispatch(self, msg): for part in msg.walk(): maintype = part.get_content_maintype() if maintype == 'text': print >> self, part.get_payload(decode=True) elif maintype == 'multipart': # Just skip this pass else: print >> self, self._fmt % { 'type' : part.get_content_type(), 'maintype' : part.get_content_maintype(), 'subtype' : part.get_content_subtype(), 'filename' : part.get_filename('[no filename]'), 'description': part.get('Content-Description', '[no description]'), 'encoding' : part.get('Content-Transfer-Encoding', '[no encoding]'), } # Helper _width = len(repr(sys.maxint-1)) _fmt = '%%0%dd' % _width def _make_boundary(text=None): # Craft a random boundary. If text is given, ensure that the chosen # boundary doesn't appear in the text. token = random.randrange(sys.maxint) boundary = ('=' * 15) + (_fmt % token) + '==' if text is None: return boundary b = boundary counter = 0 while True: cre = re.compile('^--' + re.escape(b) + '(--)?$', re.MULTILINE) if not cre.search(text): break b = boundary + '.' + str(counter) counter += 1 return b _header_value_parser.py000064400000332105152526700320011263 0ustar00"""Header value parser implementing various email-related RFC parsing rules. The parsing methods defined in this module implement various email related parsing rules. Principal among them is RFC 5322, which is the followon to RFC 2822 and primarily a clarification of the former. It also implements RFC 2047 encoded word decoding. RFC 5322 goes to considerable trouble to maintain backward compatibility with RFC 822 in the parse phase, while cleaning up the structure on the generation phase. This parser supports correct RFC 5322 generation by tagging white space as folding white space only when folding is allowed in the non-obsolete rule sets. Actually, the parser is even more generous when accepting input than RFC 5322 mandates, following the spirit of Postel's Law, which RFC 5322 encourages. Where possible deviations from the standard are annotated on the 'defects' attribute of tokens that deviate. The general structure of the parser follows RFC 5322, and uses its terminology where there is a direct correspondence. Where the implementation requires a somewhat different structure than that used by the formal grammar, new terms that mimic the closest existing terms are used. Thus, it really helps to have a copy of RFC 5322 handy when studying this code. Input to the parser is a string that has already been unfolded according to RFC 5322 rules. According to the RFC this unfolding is the very first step, and this parser leaves the unfolding step to a higher level message parser, which will have already detected the line breaks that need unfolding while determining the beginning and end of each header. The output of the parser is a TokenList object, which is a list subclass. A TokenList is a recursive data structure. The terminal nodes of the structure are Terminal objects, which are subclasses of str. These do not correspond directly to terminal objects in the formal grammar, but are instead more practical higher level combinations of true terminals. All TokenList and Terminal objects have a 'value' attribute, which produces the semantically meaningful value of that part of the parse subtree. The value of all whitespace tokens (no matter how many sub-tokens they may contain) is a single space, as per the RFC rules. This includes 'CFWS', which is herein included in the general class of whitespace tokens. There is one exception to the rule that whitespace tokens are collapsed into single spaces in values: in the value of a 'bare-quoted-string' (a quoted-string with no leading or trailing whitespace), any whitespace that appeared between the quotation marks is preserved in the returned value. Note that in all Terminal strings quoted pairs are turned into their unquoted values. All TokenList and Terminal objects also have a string value, which attempts to be a "canonical" representation of the RFC-compliant form of the substring that produced the parsed subtree, including minimal use of quoted pair quoting. Whitespace runs are not collapsed. Comment tokens also have a 'content' attribute providing the string found between the parens (including any nested comments) with whitespace preserved. All TokenList and Terminal objects have a 'defects' attribute which is a possibly empty list all of the defects found while creating the token. Defects may appear on any token in the tree, and a composite list of all defects in the subtree is available through the 'all_defects' attribute of any node. (For Terminal notes x.defects == x.all_defects.) Each object in a parse tree is called a 'token', and each has a 'token_type' attribute that gives the name from the RFC 5322 grammar that it represents. Not all RFC 5322 nodes are produced, and there is one non-RFC 5322 node that may be produced: 'ptext'. A 'ptext' is a string of printable ascii characters. It is returned in place of lists of (ctext/quoted-pair) and (qtext/quoted-pair). XXX: provide complete list of token types. """ import re import sys import urllib # For urllib.parse.unquote from string import hexdigits from operator import itemgetter from email import _encoded_words as _ew from email import errors from email import utils # # Useful constants and functions # WSP = set(' \t') CFWS_LEADER = WSP | set('(') SPECIALS = set(r'()<>@,:;.\"[]') ATOM_ENDS = SPECIALS | WSP DOT_ATOM_ENDS = ATOM_ENDS - set('.') # '.', '"', and '(' do not end phrases in order to support obs-phrase PHRASE_ENDS = SPECIALS - set('."(') TSPECIALS = (SPECIALS | set('/?=')) - set('.') TOKEN_ENDS = TSPECIALS | WSP ASPECIALS = TSPECIALS | set("*'%") ATTRIBUTE_ENDS = ASPECIALS | WSP EXTENDED_ATTRIBUTE_ENDS = ATTRIBUTE_ENDS - set('%') NLSET = {'\n', '\r'} SPECIALSNL = SPECIALS | NLSET def make_quoted_pairs(value): """Escape dquote and backslash for use within a quoted-string.""" return str(value).replace('\\', '\\\\').replace('"', '\\"') def make_parenthesis_pairs(value): """Escape parenthesis and backslash for use within a comment.""" return str(value).replace('\\', '\\\\') \ .replace('(', '\\(').replace(')', '\\)') def quote_string(value): escaped = make_quoted_pairs(value) return f'"{escaped}"' # Match a RFC 2047 word, looks like =?utf-8?q?someword?= rfc2047_matcher = re.compile(r''' =\? # literal =? [^?]* # charset \? # literal ? [qQbB] # literal 'q' or 'b', case insensitive \? # literal ? .*? # encoded word \?= # literal ?= ''', re.VERBOSE | re.MULTILINE) # # TokenList and its subclasses # class TokenList(list): token_type = None syntactic_break = True ew_combine_allowed = True def __init__(self, *args, **kw): super().__init__(*args, **kw) self.defects = [] def __str__(self): return ''.join(str(x) for x in self) def __repr__(self): return '{}({})'.format(self.__class__.__name__, super().__repr__()) @property def value(self): return ''.join(x.value for x in self if x.value) @property def all_defects(self): return sum((x.all_defects for x in self), self.defects) def startswith_fws(self): return self[0].startswith_fws() @property def as_ew_allowed(self): """True if all top level tokens of this part may be RFC2047 encoded.""" return all(part.as_ew_allowed for part in self) @property def comments(self): comments = [] for token in self: comments.extend(token.comments) return comments def fold(self, *, policy): return _refold_parse_tree(self, policy=policy) def pprint(self, indent=''): print(self.ppstr(indent=indent)) def ppstr(self, indent=''): return '\n'.join(self._pp(indent=indent)) def _pp(self, indent=''): yield '{}{}/{}('.format( indent, self.__class__.__name__, self.token_type) for token in self: if not hasattr(token, '_pp'): yield (indent + ' !! invalid element in token ' 'list: {!r}'.format(token)) else: yield from token._pp(indent+' ') if self.defects: extra = ' Defects: {}'.format(self.defects) else: extra = '' yield '{}){}'.format(indent, extra) class WhiteSpaceTokenList(TokenList): @property def value(self): return ' ' @property def comments(self): return [x.content for x in self if x.token_type=='comment'] class UnstructuredTokenList(TokenList): token_type = 'unstructured' class Phrase(TokenList): token_type = 'phrase' class Word(TokenList): token_type = 'word' class CFWSList(WhiteSpaceTokenList): token_type = 'cfws' class Atom(TokenList): token_type = 'atom' class Token(TokenList): token_type = 'token' encode_as_ew = False class EncodedWord(TokenList): token_type = 'encoded-word' cte = None charset = None lang = None class QuotedString(TokenList): token_type = 'quoted-string' @property def content(self): for x in self: if x.token_type == 'bare-quoted-string': return x.value @property def quoted_value(self): res = [] for x in self: if x.token_type == 'bare-quoted-string': res.append(str(x)) else: res.append(x.value) return ''.join(res) @property def stripped_value(self): for token in self: if token.token_type == 'bare-quoted-string': return token.value class BareQuotedString(QuotedString): token_type = 'bare-quoted-string' def __str__(self): return quote_string(''.join(str(x) for x in self)) @property def value(self): return ''.join(str(x) for x in self) class Comment(WhiteSpaceTokenList): token_type = 'comment' def __str__(self): return ''.join(sum([ ["("], [self.quote(x) for x in self], [")"], ], [])) def quote(self, value): if value.token_type == 'comment': return str(value) return str(value).replace('\\', '\\\\').replace( '(', r'\(').replace( ')', r'\)') @property def content(self): return ''.join(str(x) for x in self) @property def comments(self): return [self.content] class AddressList(TokenList): token_type = 'address-list' @property def addresses(self): return [x for x in self if x.token_type=='address'] @property def mailboxes(self): return sum((x.mailboxes for x in self if x.token_type=='address'), []) @property def all_mailboxes(self): return sum((x.all_mailboxes for x in self if x.token_type=='address'), []) class Address(TokenList): token_type = 'address' @property def display_name(self): if self[0].token_type == 'group': return self[0].display_name @property def mailboxes(self): if self[0].token_type == 'mailbox': return [self[0]] elif self[0].token_type == 'invalid-mailbox': return [] return self[0].mailboxes @property def all_mailboxes(self): if self[0].token_type == 'mailbox': return [self[0]] elif self[0].token_type == 'invalid-mailbox': return [self[0]] return self[0].all_mailboxes class MailboxList(TokenList): token_type = 'mailbox-list' @property def mailboxes(self): return [x for x in self if x.token_type=='mailbox'] @property def all_mailboxes(self): return [x for x in self if x.token_type in ('mailbox', 'invalid-mailbox')] class GroupList(TokenList): token_type = 'group-list' @property def mailboxes(self): if not self or self[0].token_type != 'mailbox-list': return [] return self[0].mailboxes @property def all_mailboxes(self): if not self or self[0].token_type != 'mailbox-list': return [] return self[0].all_mailboxes class Group(TokenList): token_type = "group" @property def mailboxes(self): if self[2].token_type != 'group-list': return [] return self[2].mailboxes @property def all_mailboxes(self): if self[2].token_type != 'group-list': return [] return self[2].all_mailboxes @property def display_name(self): return self[0].display_name class NameAddr(TokenList): token_type = 'name-addr' @property def display_name(self): if len(self) == 1: return None return self[0].display_name @property def local_part(self): return self[-1].local_part @property def domain(self): return self[-1].domain @property def route(self): return self[-1].route @property def addr_spec(self): return self[-1].addr_spec class AngleAddr(TokenList): token_type = 'angle-addr' @property def local_part(self): for x in self: if x.token_type == 'addr-spec': return x.local_part @property def domain(self): for x in self: if x.token_type == 'addr-spec': return x.domain @property def route(self): for x in self: if x.token_type == 'obs-route': return x.domains @property def addr_spec(self): for x in self: if x.token_type == 'addr-spec': if x.local_part: return x.addr_spec else: return quote_string(x.local_part) + x.addr_spec else: return '<>' class ObsRoute(TokenList): token_type = 'obs-route' @property def domains(self): return [x.domain for x in self if x.token_type == 'domain'] class Mailbox(TokenList): token_type = 'mailbox' @property def display_name(self): if self[0].token_type == 'name-addr': return self[0].display_name @property def local_part(self): return self[0].local_part @property def domain(self): return self[0].domain @property def route(self): if self[0].token_type == 'name-addr': return self[0].route @property def addr_spec(self): return self[0].addr_spec class InvalidMailbox(TokenList): token_type = 'invalid-mailbox' @property def display_name(self): return None local_part = domain = route = addr_spec = display_name class Domain(TokenList): token_type = 'domain' as_ew_allowed = False @property def domain(self): return ''.join(super().value.split()) class DotAtom(TokenList): token_type = 'dot-atom' class DotAtomText(TokenList): token_type = 'dot-atom-text' as_ew_allowed = True class NoFoldLiteral(TokenList): token_type = 'no-fold-literal' as_ew_allowed = False class AddrSpec(TokenList): token_type = 'addr-spec' as_ew_allowed = False @property def local_part(self): return self[0].local_part @property def domain(self): if len(self) < 3: return None return self[-1].domain @property def value(self): if len(self) < 3: return self[0].value return self[0].value.rstrip()+self[1].value+self[2].value.lstrip() @property def addr_spec(self): nameset = set(self.local_part) if len(nameset) > len(nameset-DOT_ATOM_ENDS): lp = quote_string(self.local_part) else: lp = self.local_part if self.domain is not None: return lp + '@' + self.domain return lp class ObsLocalPart(TokenList): token_type = 'obs-local-part' as_ew_allowed = False class DisplayName(Phrase): token_type = 'display-name' ew_combine_allowed = False @property def display_name(self): res = TokenList(self) if len(res) == 0: return res.value if res[0].token_type == 'cfws': res.pop(0) else: if (isinstance(res[0], TokenList) and res[0][0].token_type == 'cfws'): res[0] = TokenList(res[0][1:]) if res[-1].token_type == 'cfws': res.pop() else: if (isinstance(res[-1], TokenList) and res[-1][-1].token_type == 'cfws'): res[-1] = TokenList(res[-1][:-1]) return res.value @property def value(self): quote = False if self.defects: quote = True else: for x in self: if x.token_type == 'quoted-string': quote = True if len(self) != 0 and quote: pre = post = '' if (self[0].token_type == 'cfws' or isinstance(self[0], TokenList) and self[0][0].token_type == 'cfws'): pre = ' ' if (self[-1].token_type == 'cfws' or isinstance(self[-1], TokenList) and self[-1][-1].token_type == 'cfws'): post = ' ' return pre+quote_string(self.display_name)+post else: return super().value class LocalPart(TokenList): token_type = 'local-part' as_ew_allowed = False @property def value(self): if self[0].token_type == "quoted-string": return self[0].quoted_value else: return self[0].value @property def local_part(self): # Strip whitespace from front, back, and around dots. res = [DOT] last = DOT last_is_tl = False for tok in self[0] + [DOT]: if tok.token_type == 'cfws': continue if (last_is_tl and tok.token_type == 'dot' and last[-1].token_type == 'cfws'): res[-1] = TokenList(last[:-1]) is_tl = isinstance(tok, TokenList) if (is_tl and last.token_type == 'dot' and tok[0].token_type == 'cfws'): res.append(TokenList(tok[1:])) else: res.append(tok) last = res[-1] last_is_tl = is_tl res = TokenList(res[1:-1]) return res.value class DomainLiteral(TokenList): token_type = 'domain-literal' as_ew_allowed = False @property def domain(self): return ''.join(super().value.split()) @property def ip(self): for x in self: if x.token_type == 'ptext': return x.value class MIMEVersion(TokenList): token_type = 'mime-version' major = None minor = None class Parameter(TokenList): token_type = 'parameter' sectioned = False extended = False charset = 'us-ascii' @property def section_number(self): # Because the first token, the attribute (name) eats CFWS, the second # token is always the section if there is one. return self[1].number if self.sectioned else 0 @property def param_value(self): # This is part of the "handle quoted extended parameters" hack. for token in self: if token.token_type == 'value': return token.stripped_value if token.token_type == 'quoted-string': for token in token: if token.token_type == 'bare-quoted-string': for token in token: if token.token_type == 'value': return token.stripped_value return '' class InvalidParameter(Parameter): token_type = 'invalid-parameter' class Attribute(TokenList): token_type = 'attribute' @property def stripped_value(self): for token in self: if token.token_type.endswith('attrtext'): return token.value class Section(TokenList): token_type = 'section' number = None class Value(TokenList): token_type = 'value' @property def stripped_value(self): token = self[0] if token.token_type == 'cfws': token = self[1] if token.token_type.endswith( ('quoted-string', 'attribute', 'extended-attribute')): return token.stripped_value return self.value class MimeParameters(TokenList): token_type = 'mime-parameters' syntactic_break = False @property def params(self): # The RFC specifically states that the ordering of parameters is not # guaranteed and may be reordered by the transport layer. So we have # to assume the RFC 2231 pieces can come in any order. However, we # output them in the order that we first see a given name, which gives # us a stable __str__. params = {} # Using order preserving dict from Python 3.7+ for token in self: if not token.token_type.endswith('parameter'): continue if token[0].token_type != 'attribute': continue name = token[0].value.strip() if name not in params: params[name] = [] params[name].append((token.section_number, token)) for name, parts in params.items(): parts = sorted(parts, key=itemgetter(0)) first_param = parts[0][1] charset = first_param.charset # Our arbitrary error recovery is to ignore duplicate parameters, # to use appearance order if there are duplicate rfc 2231 parts, # and to ignore gaps. This mimics the error recovery of get_param. if not first_param.extended and len(parts) > 1: if parts[1][0] == 0: parts[1][1].defects.append(errors.InvalidHeaderDefect( 'duplicate parameter name; duplicate(s) ignored')) parts = parts[:1] # Else assume the *0* was missing...note that this is different # from get_param, but we registered a defect for this earlier. value_parts = [] i = 0 for section_number, param in parts: if section_number != i: # We could get fancier here and look for a complete # duplicate extended parameter and ignore the second one # seen. But we're not doing that. The old code didn't. if not param.extended: param.defects.append(errors.InvalidHeaderDefect( 'duplicate parameter name; duplicate ignored')) continue else: param.defects.append(errors.InvalidHeaderDefect( "inconsistent RFC2231 parameter numbering")) i += 1 value = param.param_value if param.extended: try: value = urllib.parse.unquote_to_bytes(value) except UnicodeEncodeError: # source had surrogate escaped bytes. What we do now # is a bit of an open question. I'm not sure this is # the best choice, but it is what the old algorithm did value = urllib.parse.unquote(value, encoding='latin-1') else: try: value = value.decode(charset, 'surrogateescape') except (LookupError, UnicodeEncodeError): # XXX: there should really be a custom defect for # unknown character set to make it easy to find, # because otherwise unknown charset is a silent # failure. value = value.decode('us-ascii', 'surrogateescape') if utils._has_surrogates(value): param.defects.append(errors.UndecodableBytesDefect()) value_parts.append(value) value = ''.join(value_parts) yield name, value def __str__(self): params = [] for name, value in self.params: if value: params.append('{}={}'.format(name, quote_string(value))) else: params.append(name) params = '; '.join(params) return ' ' + params if params else '' class ParameterizedHeaderValue(TokenList): # Set this false so that the value doesn't wind up on a new line even # if it and the parameters would fit there but not on the first line. syntactic_break = False @property def params(self): for token in reversed(self): if token.token_type == 'mime-parameters': return token.params return {} class ContentType(ParameterizedHeaderValue): token_type = 'content-type' as_ew_allowed = False maintype = 'text' subtype = 'plain' class ContentDisposition(ParameterizedHeaderValue): token_type = 'content-disposition' as_ew_allowed = False content_disposition = None class ContentTransferEncoding(TokenList): token_type = 'content-transfer-encoding' as_ew_allowed = False cte = '7bit' class HeaderLabel(TokenList): token_type = 'header-label' as_ew_allowed = False class MsgID(TokenList): token_type = 'msg-id' as_ew_allowed = False def fold(self, policy): # message-id tokens may not be folded. return str(self) + policy.linesep class MessageID(MsgID): token_type = 'message-id' class InvalidMessageID(MessageID): token_type = 'invalid-message-id' class Header(TokenList): token_type = 'header' # # Terminal classes and instances # class Terminal(str): as_ew_allowed = True ew_combine_allowed = True syntactic_break = True def __new__(cls, value, token_type): self = super().__new__(cls, value) self.token_type = token_type self.defects = [] return self def __repr__(self): return "{}({})".format(self.__class__.__name__, super().__repr__()) def pprint(self): print(self.__class__.__name__ + '/' + self.token_type) @property def all_defects(self): return list(self.defects) def _pp(self, indent=''): return ["{}{}/{}({}){}".format( indent, self.__class__.__name__, self.token_type, super().__repr__(), '' if not self.defects else ' {}'.format(self.defects), )] def pop_trailing_ws(self): # This terminates the recursion. return None @property def comments(self): return [] def __getnewargs__(self): return(str(self), self.token_type) class WhiteSpaceTerminal(Terminal): @property def value(self): return ' ' def startswith_fws(self): return self and self[0] in WSP class ValueTerminal(Terminal): @property def value(self): return self def startswith_fws(self): return False class EWWhiteSpaceTerminal(WhiteSpaceTerminal): @property def value(self): return '' def __str__(self): return '' class _InvalidEwError(errors.HeaderParseError): """Invalid encoded word found while parsing headers.""" # XXX these need to become classes and used as instances so # that a program can't change them in a parse tree and screw # up other parse trees. Maybe should have tests for that, too. DOT = ValueTerminal('.', 'dot') ListSeparator = ValueTerminal(',', 'list-separator') ListSeparator.as_ew_allowed = False ListSeparator.syntactic_break = False RouteComponentMarker = ValueTerminal('@', 'route-component-marker') # # Parser # # Parse strings according to RFC822/2047/2822/5322 rules. # # This is a stateless parser. Each get_XXX function accepts a string and # returns either a Terminal or a TokenList representing the RFC object named # by the method and a string containing the remaining unparsed characters # from the input. Thus a parser method consumes the next syntactic construct # of a given type and returns a token representing the construct plus the # unparsed remainder of the input string. # # For example, if the first element of a structured header is a 'phrase', # then: # # phrase, value = get_phrase(value) # # returns the complete phrase from the start of the string value, plus any # characters left in the string after the phrase is removed. _wsp_splitter = re.compile(r'([{}]+)'.format(''.join(WSP))).split _non_atom_end_matcher = re.compile(r"[^{}]+".format( re.escape(''.join(ATOM_ENDS)))).match _non_printable_finder = re.compile(r"[\x00-\x20\x7F]").findall _non_token_end_matcher = re.compile(r"[^{}]+".format( re.escape(''.join(TOKEN_ENDS)))).match _non_attribute_end_matcher = re.compile(r"[^{}]+".format( re.escape(''.join(ATTRIBUTE_ENDS)))).match _non_extended_attribute_end_matcher = re.compile(r"[^{}]+".format( re.escape(''.join(EXTENDED_ATTRIBUTE_ENDS)))).match def _validate_xtext(xtext): """If input token contains ASCII non-printables, register a defect.""" non_printables = _non_printable_finder(xtext) if non_printables: xtext.defects.append(errors.NonPrintableDefect(non_printables)) if utils._has_surrogates(xtext): xtext.defects.append(errors.UndecodableBytesDefect( "Non-ASCII characters found in header token")) def _get_ptext_to_endchars(value, endchars): """Scan printables/quoted-pairs until endchars and return unquoted ptext. This function turns a run of qcontent, ccontent-without-comments, or dtext-with-quoted-printables into a single string by unquoting any quoted printables. It returns the string, the remaining value, and a flag that is True iff there were any quoted printables decoded. """ fragment, *remainder = _wsp_splitter(value, 1) vchars = [] escape = False had_qp = False for pos in range(len(fragment)): if fragment[pos] == '\\': if escape: escape = False had_qp = True else: escape = True continue if escape: escape = False elif fragment[pos] in endchars: break vchars.append(fragment[pos]) else: pos = pos + 1 return ''.join(vchars), ''.join([fragment[pos:]] + remainder), had_qp def get_fws(value): """FWS = 1*WSP This isn't the RFC definition. We're using fws to represent tokens where folding can be done, but when we are parsing the *un*folding has already been done so we don't need to watch out for CRLF. """ newvalue = value.lstrip() fws = WhiteSpaceTerminal(value[:len(value)-len(newvalue)], 'fws') return fws, newvalue def get_encoded_word(value, terminal_type='vtext'): """ encoded-word = "=?" charset "?" encoding "?" encoded-text "?=" """ ew = EncodedWord() if not value.startswith('=?'): raise errors.HeaderParseError( "expected encoded word but found {}".format(value)) tok, *remainder = value[2:].split('?=', 1) if tok == value[2:]: raise errors.HeaderParseError( "expected encoded word but found {}".format(value)) remstr = ''.join(remainder) if (len(remstr) > 1 and remstr[0] in hexdigits and remstr[1] in hexdigits and tok.count('?') < 2): # The ? after the CTE was followed by an encoded word escape (=XX). rest, *remainder = remstr.split('?=', 1) tok = tok + '?=' + rest if len(tok.split()) > 1: ew.defects.append(errors.InvalidHeaderDefect( "whitespace inside encoded word")) ew.cte = value value = ''.join(remainder) try: text, charset, lang, defects = _ew.decode('=?' + tok + '?=') except (ValueError, KeyError): raise _InvalidEwError( "encoded word format invalid: '{}'".format(ew.cte)) ew.charset = charset ew.lang = lang ew.defects.extend(defects) while text: if text[0] in WSP: token, text = get_fws(text) ew.append(token) continue chars, *remainder = _wsp_splitter(text, 1) vtext = ValueTerminal(chars, terminal_type) _validate_xtext(vtext) ew.append(vtext) text = ''.join(remainder) # Encoded words should be followed by a WS if value and value[0] not in WSP: ew.defects.append(errors.InvalidHeaderDefect( "missing trailing whitespace after encoded-word")) return ew, value def get_unstructured(value): """unstructured = (*([FWS] vchar) *WSP) / obs-unstruct obs-unstruct = *((*LF *CR *(obs-utext) *LF *CR)) / FWS) obs-utext = %d0 / obs-NO-WS-CTL / LF / CR obs-NO-WS-CTL is control characters except WSP/CR/LF. So, basically, we have printable runs, plus control characters or nulls in the obsolete syntax, separated by whitespace. Since RFC 2047 uses the obsolete syntax in its specification, but requires whitespace on either side of the encoded words, I can see no reason to need to separate the non-printable-non-whitespace from the printable runs if they occur, so we parse this into xtext tokens separated by WSP tokens. Because an 'unstructured' value must by definition constitute the entire value, this 'get' routine does not return a remaining value, only the parsed TokenList. """ # XXX: but what about bare CR and LF? They might signal the start or # end of an encoded word. YAGNI for now, since our current parsers # will never send us strings with bare CR or LF. unstructured = UnstructuredTokenList() while value: if value[0] in WSP: token, value = get_fws(value) unstructured.append(token) continue valid_ew = True if value.startswith('=?'): try: token, value = get_encoded_word(value, 'utext') except _InvalidEwError: valid_ew = False except errors.HeaderParseError: # XXX: Need to figure out how to register defects when # appropriate here. pass else: have_ws = True if len(unstructured) > 0: if unstructured[-1].token_type != 'fws': unstructured.defects.append(errors.InvalidHeaderDefect( "missing whitespace before encoded word")) have_ws = False if have_ws and len(unstructured) > 1: if unstructured[-2].token_type == 'encoded-word': unstructured[-1] = EWWhiteSpaceTerminal( unstructured[-1], 'fws') unstructured.append(token) continue tok, *remainder = _wsp_splitter(value, 1) # Split in the middle of an atom if there is a rfc2047 encoded word # which does not have WSP on both sides. The defect will be registered # the next time through the loop. # This needs to only be performed when the encoded word is valid; # otherwise, performing it on an invalid encoded word can cause # the parser to go in an infinite loop. if valid_ew and rfc2047_matcher.search(tok): tok, *remainder = value.partition('=?') vtext = ValueTerminal(tok, 'utext') _validate_xtext(vtext) unstructured.append(vtext) value = ''.join(remainder) return unstructured def get_qp_ctext(value): r"""ctext = This is not the RFC ctext, since we are handling nested comments in comment and unquoting quoted-pairs here. We allow anything except the '()' characters, but if we find any ASCII other than the RFC defined printable ASCII, a NonPrintableDefect is added to the token's defects list. Since quoted pairs are converted to their unquoted values, what is returned is a 'ptext' token. In this case it is a WhiteSpaceTerminal, so it's value is ' '. """ ptext, value, _ = _get_ptext_to_endchars(value, '()') ptext = WhiteSpaceTerminal(ptext, 'ptext') _validate_xtext(ptext) return ptext, value def get_qcontent(value): """qcontent = qtext / quoted-pair We allow anything except the DQUOTE character, but if we find any ASCII other than the RFC defined printable ASCII, a NonPrintableDefect is added to the token's defects list. Any quoted pairs are converted to their unquoted values, so what is returned is a 'ptext' token. In this case it is a ValueTerminal. """ ptext, value, _ = _get_ptext_to_endchars(value, '"') ptext = ValueTerminal(ptext, 'ptext') _validate_xtext(ptext) return ptext, value def get_atext(value): """atext = We allow any non-ATOM_ENDS in atext, but add an InvalidATextDefect to the token's defects list if we find non-atext characters. """ m = _non_atom_end_matcher(value) if not m: raise errors.HeaderParseError( "expected atext but found '{}'".format(value)) atext = m.group() value = value[len(atext):] atext = ValueTerminal(atext, 'atext') _validate_xtext(atext) return atext, value def get_bare_quoted_string(value): """bare-quoted-string = DQUOTE *([FWS] qcontent) [FWS] DQUOTE A quoted-string without the leading or trailing white space. Its value is the text between the quote marks, with whitespace preserved and quoted pairs decoded. """ if not value or value[0] != '"': raise errors.HeaderParseError( "expected '\"' but found '{}'".format(value)) bare_quoted_string = BareQuotedString() value = value[1:] if value and value[0] == '"': token, value = get_qcontent(value) bare_quoted_string.append(token) while value and value[0] != '"': if value[0] in WSP: token, value = get_fws(value) elif value[:2] == '=?': valid_ew = False try: token, value = get_encoded_word(value) bare_quoted_string.defects.append(errors.InvalidHeaderDefect( "encoded word inside quoted string")) valid_ew = True except errors.HeaderParseError: token, value = get_qcontent(value) # Collapse the whitespace between two encoded words that occur in a # bare-quoted-string. if valid_ew and len(bare_quoted_string) > 1: if (bare_quoted_string[-1].token_type == 'fws' and bare_quoted_string[-2].token_type == 'encoded-word'): bare_quoted_string[-1] = EWWhiteSpaceTerminal( bare_quoted_string[-1], 'fws') else: token, value = get_qcontent(value) bare_quoted_string.append(token) if not value: bare_quoted_string.defects.append(errors.InvalidHeaderDefect( "end of header inside quoted string")) return bare_quoted_string, value return bare_quoted_string, value[1:] def get_comment(value): """comment = "(" *([FWS] ccontent) [FWS] ")" ccontent = ctext / quoted-pair / comment We handle nested comments here, and quoted-pair in our qp-ctext routine. """ if value and value[0] != '(': raise errors.HeaderParseError( "expected '(' but found '{}'".format(value)) comment = Comment() value = value[1:] while value and value[0] != ")": if value[0] in WSP: token, value = get_fws(value) elif value[0] == '(': token, value = get_comment(value) else: token, value = get_qp_ctext(value) comment.append(token) if not value: comment.defects.append(errors.InvalidHeaderDefect( "end of header inside comment")) return comment, value return comment, value[1:] def get_cfws(value): """CFWS = (1*([FWS] comment) [FWS]) / FWS """ cfws = CFWSList() while value and value[0] in CFWS_LEADER: if value[0] in WSP: token, value = get_fws(value) else: token, value = get_comment(value) cfws.append(token) return cfws, value def get_quoted_string(value): """quoted-string = [CFWS] [CFWS] 'bare-quoted-string' is an intermediate class defined by this parser and not by the RFC grammar. It is the quoted string without any attached CFWS. """ quoted_string = QuotedString() if value and value[0] in CFWS_LEADER: token, value = get_cfws(value) quoted_string.append(token) token, value = get_bare_quoted_string(value) quoted_string.append(token) if value and value[0] in CFWS_LEADER: token, value = get_cfws(value) quoted_string.append(token) return quoted_string, value def get_atom(value): """atom = [CFWS] 1*atext [CFWS] An atom could be an rfc2047 encoded word. """ atom = Atom() if value and value[0] in CFWS_LEADER: token, value = get_cfws(value) atom.append(token) if value and value[0] in ATOM_ENDS: raise errors.HeaderParseError( "expected atom but found '{}'".format(value)) if value.startswith('=?'): try: token, value = get_encoded_word(value) except errors.HeaderParseError: # XXX: need to figure out how to register defects when # appropriate here. token, value = get_atext(value) else: token, value = get_atext(value) atom.append(token) if value and value[0] in CFWS_LEADER: token, value = get_cfws(value) atom.append(token) return atom, value def get_dot_atom_text(value): """ dot-text = 1*atext *("." 1*atext) """ dot_atom_text = DotAtomText() if not value or value[0] in ATOM_ENDS: raise errors.HeaderParseError("expected atom at a start of " "dot-atom-text but found '{}'".format(value)) while value and value[0] not in ATOM_ENDS: token, value = get_atext(value) dot_atom_text.append(token) if value and value[0] == '.': dot_atom_text.append(DOT) value = value[1:] if dot_atom_text[-1] is DOT: raise errors.HeaderParseError("expected atom at end of dot-atom-text " "but found '{}'".format('.'+value)) return dot_atom_text, value def get_dot_atom(value): """ dot-atom = [CFWS] dot-atom-text [CFWS] Any place we can have a dot atom, we could instead have an rfc2047 encoded word. """ dot_atom = DotAtom() if value[0] in CFWS_LEADER: token, value = get_cfws(value) dot_atom.append(token) if value.startswith('=?'): try: token, value = get_encoded_word(value) except errors.HeaderParseError: # XXX: need to figure out how to register defects when # appropriate here. token, value = get_dot_atom_text(value) else: token, value = get_dot_atom_text(value) dot_atom.append(token) if value and value[0] in CFWS_LEADER: token, value = get_cfws(value) dot_atom.append(token) return dot_atom, value def get_word(value): """word = atom / quoted-string Either atom or quoted-string may start with CFWS. We have to peel off this CFWS first to determine which type of word to parse. Afterward we splice the leading CFWS, if any, into the parsed sub-token. If neither an atom or a quoted-string is found before the next special, a HeaderParseError is raised. The token returned is either an Atom or a QuotedString, as appropriate. This means the 'word' level of the formal grammar is not represented in the parse tree; this is because having that extra layer when manipulating the parse tree is more confusing than it is helpful. """ if value[0] in CFWS_LEADER: leader, value = get_cfws(value) else: leader = None if not value: raise errors.HeaderParseError( "Expected 'atom' or 'quoted-string' but found nothing.") if value[0]=='"': token, value = get_quoted_string(value) elif value[0] in SPECIALS: raise errors.HeaderParseError("Expected 'atom' or 'quoted-string' " "but found '{}'".format(value)) else: token, value = get_atom(value) if leader is not None: token[:0] = [leader] return token, value def get_phrase(value): """ phrase = 1*word / obs-phrase obs-phrase = word *(word / "." / CFWS) This means a phrase can be a sequence of words, periods, and CFWS in any order as long as it starts with at least one word. If anything other than words is detected, an ObsoleteHeaderDefect is added to the token's defect list. We also accept a phrase that starts with CFWS followed by a dot; this is registered as an InvalidHeaderDefect, since it is not supported by even the obsolete grammar. """ phrase = Phrase() try: token, value = get_word(value) phrase.append(token) except errors.HeaderParseError: phrase.defects.append(errors.InvalidHeaderDefect( "phrase does not start with word")) while value and value[0] not in PHRASE_ENDS: if value[0]=='.': phrase.append(DOT) phrase.defects.append(errors.ObsoleteHeaderDefect( "period in 'phrase'")) value = value[1:] else: try: token, value = get_word(value) except errors.HeaderParseError: if value[0] in CFWS_LEADER: token, value = get_cfws(value) phrase.defects.append(errors.ObsoleteHeaderDefect( "comment found without atom")) else: raise phrase.append(token) return phrase, value def get_local_part(value): """ local-part = dot-atom / quoted-string / obs-local-part """ local_part = LocalPart() leader = None if value and value[0] in CFWS_LEADER: leader, value = get_cfws(value) if not value: raise errors.HeaderParseError( "expected local-part but found '{}'".format(value)) try: token, value = get_dot_atom(value) except errors.HeaderParseError: try: token, value = get_word(value) except errors.HeaderParseError: if value[0] != '\\' and value[0] in PHRASE_ENDS: raise token = TokenList() if leader is not None: token[:0] = [leader] local_part.append(token) if value and (value[0]=='\\' or value[0] not in PHRASE_ENDS): obs_local_part, value = get_obs_local_part(str(local_part) + value) if obs_local_part.token_type == 'invalid-obs-local-part': local_part.defects.append(errors.InvalidHeaderDefect( "local-part is not dot-atom, quoted-string, or obs-local-part")) else: local_part.defects.append(errors.ObsoleteHeaderDefect( "local-part is not a dot-atom (contains CFWS)")) local_part[0] = obs_local_part try: local_part.value.encode('ascii') except UnicodeEncodeError: local_part.defects.append(errors.NonASCIILocalPartDefect( "local-part contains non-ASCII characters)")) return local_part, value def get_obs_local_part(value): """ obs-local-part = word *("." word) """ obs_local_part = ObsLocalPart() last_non_ws_was_dot = False while value and (value[0]=='\\' or value[0] not in PHRASE_ENDS): if value[0] == '.': if last_non_ws_was_dot: obs_local_part.defects.append(errors.InvalidHeaderDefect( "invalid repeated '.'")) obs_local_part.append(DOT) last_non_ws_was_dot = True value = value[1:] continue elif value[0]=='\\': obs_local_part.append(ValueTerminal(value[0], 'misplaced-special')) value = value[1:] obs_local_part.defects.append(errors.InvalidHeaderDefect( "'\\' character outside of quoted-string/ccontent")) last_non_ws_was_dot = False continue if obs_local_part and obs_local_part[-1].token_type != 'dot': obs_local_part.defects.append(errors.InvalidHeaderDefect( "missing '.' between words")) try: token, value = get_word(value) last_non_ws_was_dot = False except errors.HeaderParseError: if value[0] not in CFWS_LEADER: raise token, value = get_cfws(value) obs_local_part.append(token) if not obs_local_part: raise errors.HeaderParseError( "expected obs-local-part but found '{}'".format(value)) if (obs_local_part[0].token_type == 'dot' or obs_local_part[0].token_type=='cfws' and len(obs_local_part) > 1 and obs_local_part[1].token_type=='dot'): obs_local_part.defects.append(errors.InvalidHeaderDefect( "Invalid leading '.' in local part")) if (obs_local_part[-1].token_type == 'dot' or obs_local_part[-1].token_type=='cfws' and len(obs_local_part) > 1 and obs_local_part[-2].token_type=='dot'): obs_local_part.defects.append(errors.InvalidHeaderDefect( "Invalid trailing '.' in local part")) if obs_local_part.defects: obs_local_part.token_type = 'invalid-obs-local-part' return obs_local_part, value def get_dtext(value): r""" dtext = / obs-dtext obs-dtext = obs-NO-WS-CTL / quoted-pair We allow anything except the excluded characters, but if we find any ASCII other than the RFC defined printable ASCII, a NonPrintableDefect is added to the token's defects list. Quoted pairs are converted to their unquoted values, so what is returned is a ptext token, in this case a ValueTerminal. If there were quoted-printables, an ObsoleteHeaderDefect is added to the returned token's defect list. """ ptext, value, had_qp = _get_ptext_to_endchars(value, '[]') ptext = ValueTerminal(ptext, 'ptext') if had_qp: ptext.defects.append(errors.ObsoleteHeaderDefect( "quoted printable found in domain-literal")) _validate_xtext(ptext) return ptext, value def _check_for_early_dl_end(value, domain_literal): if value: return False domain_literal.append(errors.InvalidHeaderDefect( "end of input inside domain-literal")) domain_literal.append(ValueTerminal(']', 'domain-literal-end')) return True def get_domain_literal(value): """ domain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS] """ domain_literal = DomainLiteral() if value[0] in CFWS_LEADER: token, value = get_cfws(value) domain_literal.append(token) if not value: raise errors.HeaderParseError("expected domain-literal") if value[0] != '[': raise errors.HeaderParseError("expected '[' at start of domain-literal " "but found '{}'".format(value)) value = value[1:] if _check_for_early_dl_end(value, domain_literal): return domain_literal, value domain_literal.append(ValueTerminal('[', 'domain-literal-start')) if value[0] in WSP: token, value = get_fws(value) domain_literal.append(token) token, value = get_dtext(value) domain_literal.append(token) if _check_for_early_dl_end(value, domain_literal): return domain_literal, value if value[0] in WSP: token, value = get_fws(value) domain_literal.append(token) if _check_for_early_dl_end(value, domain_literal): return domain_literal, value if value[0] != ']': raise errors.HeaderParseError("expected ']' at end of domain-literal " "but found '{}'".format(value)) domain_literal.append(ValueTerminal(']', 'domain-literal-end')) value = value[1:] if value and value[0] in CFWS_LEADER: token, value = get_cfws(value) domain_literal.append(token) return domain_literal, value def get_domain(value): """ domain = dot-atom / domain-literal / obs-domain obs-domain = atom *("." atom)) """ domain = Domain() leader = None if value and value[0] in CFWS_LEADER: leader, value = get_cfws(value) if not value: raise errors.HeaderParseError( "expected domain but found '{}'".format(value)) if value[0] == '[': token, value = get_domain_literal(value) if leader is not None: token[:0] = [leader] domain.append(token) return domain, value try: token, value = get_dot_atom(value) except errors.HeaderParseError: token, value = get_atom(value) if value and value[0] == '@': raise errors.HeaderParseError('Invalid Domain') if leader is not None: token[:0] = [leader] domain.append(token) if value and value[0] == '.': domain.defects.append(errors.ObsoleteHeaderDefect( "domain is not a dot-atom (contains CFWS)")) if domain[0].token_type == 'dot-atom': domain[:] = domain[0] while value and value[0] == '.': domain.append(DOT) token, value = get_atom(value[1:]) domain.append(token) return domain, value def get_addr_spec(value): """ addr-spec = local-part "@" domain """ addr_spec = AddrSpec() token, value = get_local_part(value) addr_spec.append(token) if not value or value[0] != '@': addr_spec.defects.append(errors.InvalidHeaderDefect( "addr-spec local part with no domain")) return addr_spec, value addr_spec.append(ValueTerminal('@', 'address-at-symbol')) token, value = get_domain(value[1:]) addr_spec.append(token) return addr_spec, value def get_obs_route(value): """ obs-route = obs-domain-list ":" obs-domain-list = *(CFWS / ",") "@" domain *("," [CFWS] ["@" domain]) Returns an obs-route token with the appropriate sub-tokens (that is, there is no obs-domain-list in the parse tree). """ obs_route = ObsRoute() while value and (value[0]==',' or value[0] in CFWS_LEADER): if value[0] in CFWS_LEADER: token, value = get_cfws(value) obs_route.append(token) elif value[0] == ',': obs_route.append(ListSeparator) value = value[1:] if not value or value[0] != '@': raise errors.HeaderParseError( "expected obs-route domain but found '{}'".format(value)) obs_route.append(RouteComponentMarker) token, value = get_domain(value[1:]) obs_route.append(token) while value and value[0]==',': obs_route.append(ListSeparator) value = value[1:] if not value: break if value[0] in CFWS_LEADER: token, value = get_cfws(value) obs_route.append(token) if not value: break if value[0] == '@': obs_route.append(RouteComponentMarker) token, value = get_domain(value[1:]) obs_route.append(token) if not value: raise errors.HeaderParseError("end of header while parsing obs-route") if value[0] != ':': raise errors.HeaderParseError( "expected ':' marking end of " "obs-route but found '{}'".format(value)) obs_route.append(ValueTerminal(':', 'end-of-obs-route-marker')) return obs_route, value[1:] def get_angle_addr(value): """ angle-addr = [CFWS] "<" addr-spec ">" [CFWS] / obs-angle-addr obs-angle-addr = [CFWS] "<" obs-route addr-spec ">" [CFWS] """ angle_addr = AngleAddr() if value and value[0] in CFWS_LEADER: token, value = get_cfws(value) angle_addr.append(token) if not value or value[0] != '<': raise errors.HeaderParseError( "expected angle-addr but found '{}'".format(value)) angle_addr.append(ValueTerminal('<', 'angle-addr-start')) value = value[1:] # Although it is not legal per RFC5322, SMTP uses '<>' in certain # circumstances. if value and value[0] == '>': angle_addr.append(ValueTerminal('>', 'angle-addr-end')) angle_addr.defects.append(errors.InvalidHeaderDefect( "null addr-spec in angle-addr")) value = value[1:] return angle_addr, value try: token, value = get_addr_spec(value) except errors.HeaderParseError: try: token, value = get_obs_route(value) angle_addr.defects.append(errors.ObsoleteHeaderDefect( "obsolete route specification in angle-addr")) except errors.HeaderParseError: raise errors.HeaderParseError( "expected addr-spec or obs-route but found '{}'".format(value)) angle_addr.append(token) token, value = get_addr_spec(value) angle_addr.append(token) if value and value[0] == '>': value = value[1:] else: angle_addr.defects.append(errors.InvalidHeaderDefect( "missing trailing '>' on angle-addr")) angle_addr.append(ValueTerminal('>', 'angle-addr-end')) if value and value[0] in CFWS_LEADER: token, value = get_cfws(value) angle_addr.append(token) return angle_addr, value def get_display_name(value): """ display-name = phrase Because this is simply a name-rule, we don't return a display-name token containing a phrase, but rather a display-name token with the content of the phrase. """ display_name = DisplayName() token, value = get_phrase(value) display_name.extend(token[:]) display_name.defects = token.defects[:] return display_name, value def get_name_addr(value): """ name-addr = [display-name] angle-addr """ name_addr = NameAddr() # Both the optional display name and the angle-addr can start with cfws. leader = None if not value: raise errors.HeaderParseError( "expected name-addr but found '{}'".format(value)) if value[0] in CFWS_LEADER: leader, value = get_cfws(value) if not value: raise errors.HeaderParseError( "expected name-addr but found '{}'".format(leader)) if value[0] != '<': if value[0] in PHRASE_ENDS: raise errors.HeaderParseError( "expected name-addr but found '{}'".format(value)) token, value = get_display_name(value) if not value: raise errors.HeaderParseError( "expected name-addr but found '{}'".format(token)) if leader is not None: if isinstance(token[0], TokenList): token[0][:0] = [leader] else: token[:0] = [leader] leader = None name_addr.append(token) token, value = get_angle_addr(value) if leader is not None: token[:0] = [leader] name_addr.append(token) return name_addr, value def get_mailbox(value): """ mailbox = name-addr / addr-spec """ # The only way to figure out if we are dealing with a name-addr or an # addr-spec is to try parsing each one. mailbox = Mailbox() try: token, value = get_name_addr(value) except errors.HeaderParseError: try: token, value = get_addr_spec(value) except errors.HeaderParseError: raise errors.HeaderParseError( "expected mailbox but found '{}'".format(value)) if any(isinstance(x, errors.InvalidHeaderDefect) for x in token.all_defects): mailbox.token_type = 'invalid-mailbox' mailbox.append(token) return mailbox, value def get_invalid_mailbox(value, endchars): """ Read everything up to one of the chars in endchars. This is outside the formal grammar. The InvalidMailbox TokenList that is returned acts like a Mailbox, but the data attributes are None. """ invalid_mailbox = InvalidMailbox() while value and value[0] not in endchars: if value[0] in PHRASE_ENDS: invalid_mailbox.append(ValueTerminal(value[0], 'misplaced-special')) value = value[1:] else: token, value = get_phrase(value) invalid_mailbox.append(token) return invalid_mailbox, value def get_mailbox_list(value): """ mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list obs-mbox-list = *([CFWS] ",") mailbox *("," [mailbox / CFWS]) For this routine we go outside the formal grammar in order to improve error handling. We recognize the end of the mailbox list only at the end of the value or at a ';' (the group terminator). This is so that we can turn invalid mailboxes into InvalidMailbox tokens and continue parsing any remaining valid mailboxes. We also allow all mailbox entries to be null, and this condition is handled appropriately at a higher level. """ mailbox_list = MailboxList() while value and value[0] != ';': try: token, value = get_mailbox(value) mailbox_list.append(token) except errors.HeaderParseError: leader = None if value[0] in CFWS_LEADER: leader, value = get_cfws(value) if not value or value[0] in ',;': mailbox_list.append(leader) mailbox_list.defects.append(errors.ObsoleteHeaderDefect( "empty element in mailbox-list")) else: token, value = get_invalid_mailbox(value, ',;') if leader is not None: token[:0] = [leader] mailbox_list.append(token) mailbox_list.defects.append(errors.InvalidHeaderDefect( "invalid mailbox in mailbox-list")) elif value[0] == ',': mailbox_list.defects.append(errors.ObsoleteHeaderDefect( "empty element in mailbox-list")) else: token, value = get_invalid_mailbox(value, ',;') if leader is not None: token[:0] = [leader] mailbox_list.append(token) mailbox_list.defects.append(errors.InvalidHeaderDefect( "invalid mailbox in mailbox-list")) if value and value[0] not in ',;': # Crap after mailbox; treat it as an invalid mailbox. # The mailbox info will still be available. mailbox = mailbox_list[-1] mailbox.token_type = 'invalid-mailbox' token, value = get_invalid_mailbox(value, ',;') mailbox.extend(token) mailbox_list.defects.append(errors.InvalidHeaderDefect( "invalid mailbox in mailbox-list")) if value and value[0] == ',': mailbox_list.append(ListSeparator) value = value[1:] return mailbox_list, value def get_group_list(value): """ group-list = mailbox-list / CFWS / obs-group-list obs-group-list = 1*([CFWS] ",") [CFWS] """ group_list = GroupList() if not value: group_list.defects.append(errors.InvalidHeaderDefect( "end of header before group-list")) return group_list, value leader = None if value and value[0] in CFWS_LEADER: leader, value = get_cfws(value) if not value: # This should never happen in email parsing, since CFWS-only is a # legal alternative to group-list in a group, which is the only # place group-list appears. group_list.defects.append(errors.InvalidHeaderDefect( "end of header in group-list")) group_list.append(leader) return group_list, value if value[0] == ';': group_list.append(leader) return group_list, value token, value = get_mailbox_list(value) if len(token.all_mailboxes)==0: if leader is not None: group_list.append(leader) group_list.extend(token) group_list.defects.append(errors.ObsoleteHeaderDefect( "group-list with empty entries")) return group_list, value if leader is not None: token[:0] = [leader] group_list.append(token) return group_list, value def get_group(value): """ group = display-name ":" [group-list] ";" [CFWS] """ group = Group() token, value = get_display_name(value) if not value or value[0] != ':': raise errors.HeaderParseError("expected ':' at end of group " "display name but found '{}'".format(value)) group.append(token) group.append(ValueTerminal(':', 'group-display-name-terminator')) value = value[1:] if value and value[0] == ';': group.append(ValueTerminal(';', 'group-terminator')) return group, value[1:] token, value = get_group_list(value) group.append(token) if not value: group.defects.append(errors.InvalidHeaderDefect( "end of header in group")) elif value[0] != ';': raise errors.HeaderParseError( "expected ';' at end of group but found {}".format(value)) group.append(ValueTerminal(';', 'group-terminator')) value = value[1:] if value and value[0] in CFWS_LEADER: token, value = get_cfws(value) group.append(token) return group, value def get_address(value): """ address = mailbox / group Note that counter-intuitively, an address can be either a single address or a list of addresses (a group). This is why the returned Address object has a 'mailboxes' attribute which treats a single address as a list of length one. When you need to differentiate between to two cases, extract the single element, which is either a mailbox or a group token. """ # The formal grammar isn't very helpful when parsing an address. mailbox # and group, especially when allowing for obsolete forms, start off very # similarly. It is only when you reach one of @, <, or : that you know # what you've got. So, we try each one in turn, starting with the more # likely of the two. We could perhaps make this more efficient by looking # for a phrase and then branching based on the next character, but that # would be a premature optimization. address = Address() try: token, value = get_group(value) except errors.HeaderParseError: try: token, value = get_mailbox(value) except errors.HeaderParseError: raise errors.HeaderParseError( "expected address but found '{}'".format(value)) address.append(token) return address, value def get_address_list(value): """ address_list = (address *("," address)) / obs-addr-list obs-addr-list = *([CFWS] ",") address *("," [address / CFWS]) We depart from the formal grammar here by continuing to parse until the end of the input, assuming the input to be entirely composed of an address-list. This is always true in email parsing, and allows us to skip invalid addresses to parse additional valid ones. """ address_list = AddressList() while value: try: token, value = get_address(value) address_list.append(token) except errors.HeaderParseError: leader = None if value[0] in CFWS_LEADER: leader, value = get_cfws(value) if not value or value[0] == ',': address_list.append(leader) address_list.defects.append(errors.ObsoleteHeaderDefect( "address-list entry with no content")) else: token, value = get_invalid_mailbox(value, ',') if leader is not None: token[:0] = [leader] address_list.append(Address([token])) address_list.defects.append(errors.InvalidHeaderDefect( "invalid address in address-list")) elif value[0] == ',': address_list.defects.append(errors.ObsoleteHeaderDefect( "empty element in address-list")) else: token, value = get_invalid_mailbox(value, ',') if leader is not None: token[:0] = [leader] address_list.append(Address([token])) address_list.defects.append(errors.InvalidHeaderDefect( "invalid address in address-list")) if value and value[0] != ',': # Crap after address; treat it as an invalid mailbox. # The mailbox info will still be available. mailbox = address_list[-1][0] mailbox.token_type = 'invalid-mailbox' token, value = get_invalid_mailbox(value, ',') mailbox.extend(token) address_list.defects.append(errors.InvalidHeaderDefect( "invalid address in address-list")) if value: # Must be a , at this point. address_list.append(ListSeparator) value = value[1:] return address_list, value def get_no_fold_literal(value): """ no-fold-literal = "[" *dtext "]" """ no_fold_literal = NoFoldLiteral() if not value: raise errors.HeaderParseError( "expected no-fold-literal but found '{}'".format(value)) if value[0] != '[': raise errors.HeaderParseError( "expected '[' at the start of no-fold-literal " "but found '{}'".format(value)) no_fold_literal.append(ValueTerminal('[', 'no-fold-literal-start')) value = value[1:] token, value = get_dtext(value) no_fold_literal.append(token) if not value or value[0] != ']': raise errors.HeaderParseError( "expected ']' at the end of no-fold-literal " "but found '{}'".format(value)) no_fold_literal.append(ValueTerminal(']', 'no-fold-literal-end')) return no_fold_literal, value[1:] def get_msg_id(value): """msg-id = [CFWS] "<" id-left '@' id-right ">" [CFWS] id-left = dot-atom-text / obs-id-left id-right = dot-atom-text / no-fold-literal / obs-id-right no-fold-literal = "[" *dtext "]" """ msg_id = MsgID() if value and value[0] in CFWS_LEADER: token, value = get_cfws(value) msg_id.append(token) if not value or value[0] != '<': raise errors.HeaderParseError( "expected msg-id but found '{}'".format(value)) msg_id.append(ValueTerminal('<', 'msg-id-start')) value = value[1:] # Parse id-left. try: token, value = get_dot_atom_text(value) except errors.HeaderParseError: try: # obs-id-left is same as local-part of add-spec. token, value = get_obs_local_part(value) msg_id.defects.append(errors.ObsoleteHeaderDefect( "obsolete id-left in msg-id")) except errors.HeaderParseError: raise errors.HeaderParseError( "expected dot-atom-text or obs-id-left" " but found '{}'".format(value)) msg_id.append(token) if not value or value[0] != '@': msg_id.defects.append(errors.InvalidHeaderDefect( "msg-id with no id-right")) # Even though there is no id-right, if the local part # ends with `>` let's just parse it too and return # along with the defect. if value and value[0] == '>': msg_id.append(ValueTerminal('>', 'msg-id-end')) value = value[1:] return msg_id, value msg_id.append(ValueTerminal('@', 'address-at-symbol')) value = value[1:] # Parse id-right. try: token, value = get_dot_atom_text(value) except errors.HeaderParseError: try: token, value = get_no_fold_literal(value) except errors.HeaderParseError: try: token, value = get_domain(value) msg_id.defects.append(errors.ObsoleteHeaderDefect( "obsolete id-right in msg-id")) except errors.HeaderParseError: raise errors.HeaderParseError( "expected dot-atom-text, no-fold-literal or obs-id-right" " but found '{}'".format(value)) msg_id.append(token) if value and value[0] == '>': value = value[1:] else: msg_id.defects.append(errors.InvalidHeaderDefect( "missing trailing '>' on msg-id")) msg_id.append(ValueTerminal('>', 'msg-id-end')) if value and value[0] in CFWS_LEADER: token, value = get_cfws(value) msg_id.append(token) return msg_id, value def parse_message_id(value): """message-id = "Message-ID:" msg-id CRLF """ message_id = MessageID() try: token, value = get_msg_id(value) message_id.append(token) except errors.HeaderParseError as ex: token = get_unstructured(value) message_id = InvalidMessageID(token) message_id.defects.append( errors.InvalidHeaderDefect("Invalid msg-id: {!r}".format(ex))) else: # Value after parsing a valid msg_id should be None. if value: message_id.defects.append(errors.InvalidHeaderDefect( "Unexpected {!r}".format(value))) return message_id # # XXX: As I begin to add additional header parsers, I'm realizing we probably # have two level of parser routines: the get_XXX methods that get a token in # the grammar, and parse_XXX methods that parse an entire field value. So # get_address_list above should really be a parse_ method, as probably should # be get_unstructured. # def parse_mime_version(value): """ mime-version = [CFWS] 1*digit [CFWS] "." [CFWS] 1*digit [CFWS] """ # The [CFWS] is implicit in the RFC 2045 BNF. # XXX: This routine is a bit verbose, should factor out a get_int method. mime_version = MIMEVersion() if not value: mime_version.defects.append(errors.HeaderMissingRequiredValue( "Missing MIME version number (eg: 1.0)")) return mime_version if value[0] in CFWS_LEADER: token, value = get_cfws(value) mime_version.append(token) if not value: mime_version.defects.append(errors.HeaderMissingRequiredValue( "Expected MIME version number but found only CFWS")) digits = '' while value and value[0] != '.' and value[0] not in CFWS_LEADER: digits += value[0] value = value[1:] if not digits.isdigit(): mime_version.defects.append(errors.InvalidHeaderDefect( "Expected MIME major version number but found {!r}".format(digits))) mime_version.append(ValueTerminal(digits, 'xtext')) else: mime_version.major = int(digits) mime_version.append(ValueTerminal(digits, 'digits')) if value and value[0] in CFWS_LEADER: token, value = get_cfws(value) mime_version.append(token) if not value or value[0] != '.': if mime_version.major is not None: mime_version.defects.append(errors.InvalidHeaderDefect( "Incomplete MIME version; found only major number")) if value: mime_version.append(ValueTerminal(value, 'xtext')) return mime_version mime_version.append(ValueTerminal('.', 'version-separator')) value = value[1:] if value and value[0] in CFWS_LEADER: token, value = get_cfws(value) mime_version.append(token) if not value: if mime_version.major is not None: mime_version.defects.append(errors.InvalidHeaderDefect( "Incomplete MIME version; found only major number")) return mime_version digits = '' while value and value[0] not in CFWS_LEADER: digits += value[0] value = value[1:] if not digits.isdigit(): mime_version.defects.append(errors.InvalidHeaderDefect( "Expected MIME minor version number but found {!r}".format(digits))) mime_version.append(ValueTerminal(digits, 'xtext')) else: mime_version.minor = int(digits) mime_version.append(ValueTerminal(digits, 'digits')) if value and value[0] in CFWS_LEADER: token, value = get_cfws(value) mime_version.append(token) if value: mime_version.defects.append(errors.InvalidHeaderDefect( "Excess non-CFWS text after MIME version")) mime_version.append(ValueTerminal(value, 'xtext')) return mime_version def get_invalid_parameter(value): """ Read everything up to the next ';'. This is outside the formal grammar. The InvalidParameter TokenList that is returned acts like a Parameter, but the data attributes are None. """ invalid_parameter = InvalidParameter() while value and value[0] != ';': if value[0] in PHRASE_ENDS: invalid_parameter.append(ValueTerminal(value[0], 'misplaced-special')) value = value[1:] else: token, value = get_phrase(value) invalid_parameter.append(token) return invalid_parameter, value def get_ttext(value): """ttext = We allow any non-TOKEN_ENDS in ttext, but add defects to the token's defects list if we find non-ttext characters. We also register defects for *any* non-printables even though the RFC doesn't exclude all of them, because we follow the spirit of RFC 5322. """ m = _non_token_end_matcher(value) if not m: raise errors.HeaderParseError( "expected ttext but found '{}'".format(value)) ttext = m.group() value = value[len(ttext):] ttext = ValueTerminal(ttext, 'ttext') _validate_xtext(ttext) return ttext, value def get_token(value): """token = [CFWS] 1*ttext [CFWS] The RFC equivalent of ttext is any US-ASCII chars except space, ctls, or tspecials. We also exclude tabs even though the RFC doesn't. The RFC implies the CFWS but is not explicit about it in the BNF. """ mtoken = Token() if value and value[0] in CFWS_LEADER: token, value = get_cfws(value) mtoken.append(token) if value and value[0] in TOKEN_ENDS: raise errors.HeaderParseError( "expected token but found '{}'".format(value)) token, value = get_ttext(value) mtoken.append(token) if value and value[0] in CFWS_LEADER: token, value = get_cfws(value) mtoken.append(token) return mtoken, value def get_attrtext(value): """attrtext = 1*(any non-ATTRIBUTE_ENDS character) We allow any non-ATTRIBUTE_ENDS in attrtext, but add defects to the token's defects list if we find non-attrtext characters. We also register defects for *any* non-printables even though the RFC doesn't exclude all of them, because we follow the spirit of RFC 5322. """ m = _non_attribute_end_matcher(value) if not m: raise errors.HeaderParseError( "expected attrtext but found {!r}".format(value)) attrtext = m.group() value = value[len(attrtext):] attrtext = ValueTerminal(attrtext, 'attrtext') _validate_xtext(attrtext) return attrtext, value def get_attribute(value): """ [CFWS] 1*attrtext [CFWS] This version of the BNF makes the CFWS explicit, and as usual we use a value terminal for the actual run of characters. The RFC equivalent of attrtext is the token characters, with the subtraction of '*', "'", and '%'. We include tab in the excluded set just as we do for token. """ attribute = Attribute() if value and value[0] in CFWS_LEADER: token, value = get_cfws(value) attribute.append(token) if value and value[0] in ATTRIBUTE_ENDS: raise errors.HeaderParseError( "expected token but found '{}'".format(value)) token, value = get_attrtext(value) attribute.append(token) if value and value[0] in CFWS_LEADER: token, value = get_cfws(value) attribute.append(token) return attribute, value def get_extended_attrtext(value): """attrtext = 1*(any non-ATTRIBUTE_ENDS character plus '%') This is a special parsing routine so that we get a value that includes % escapes as a single string (which we decode as a single string later). """ m = _non_extended_attribute_end_matcher(value) if not m: raise errors.HeaderParseError( "expected extended attrtext but found {!r}".format(value)) attrtext = m.group() value = value[len(attrtext):] attrtext = ValueTerminal(attrtext, 'extended-attrtext') _validate_xtext(attrtext) return attrtext, value def get_extended_attribute(value): """ [CFWS] 1*extended_attrtext [CFWS] This is like the non-extended version except we allow % characters, so that we can pick up an encoded value as a single string. """ # XXX: should we have an ExtendedAttribute TokenList? attribute = Attribute() if value and value[0] in CFWS_LEADER: token, value = get_cfws(value) attribute.append(token) if value and value[0] in EXTENDED_ATTRIBUTE_ENDS: raise errors.HeaderParseError( "expected token but found '{}'".format(value)) token, value = get_extended_attrtext(value) attribute.append(token) if value and value[0] in CFWS_LEADER: token, value = get_cfws(value) attribute.append(token) return attribute, value def get_section(value): """ '*' digits The formal BNF is more complicated because leading 0s are not allowed. We check for that and add a defect. We also assume no CFWS is allowed between the '*' and the digits, though the RFC is not crystal clear on that. The caller should already have dealt with leading CFWS. """ section = Section() if not value or value[0] != '*': raise errors.HeaderParseError("Expected section but found {}".format( value)) section.append(ValueTerminal('*', 'section-marker')) value = value[1:] if not value or not value[0].isdigit(): raise errors.HeaderParseError("Expected section number but " "found {}".format(value)) digits = '' while value and value[0].isdigit(): digits += value[0] value = value[1:] if digits[0] == '0' and digits != '0': section.defects.append(errors.InvalidHeaderDefect( "section number has an invalid leading 0")) section.number = int(digits) section.append(ValueTerminal(digits, 'digits')) return section, value def get_value(value): """ quoted-string / attribute """ v = Value() if not value: raise errors.HeaderParseError("Expected value but found end of string") leader = None if value[0] in CFWS_LEADER: leader, value = get_cfws(value) if not value: raise errors.HeaderParseError("Expected value but found " "only {}".format(leader)) if value[0] == '"': token, value = get_quoted_string(value) else: token, value = get_extended_attribute(value) if leader is not None: token[:0] = [leader] v.append(token) return v, value def get_parameter(value): """ attribute [section] ["*"] [CFWS] "=" value The CFWS is implied by the RFC but not made explicit in the BNF. This simplified form of the BNF from the RFC is made to conform with the RFC BNF through some extra checks. We do it this way because it makes both error recovery and working with the resulting parse tree easier. """ # It is possible CFWS would also be implicitly allowed between the section # and the 'extended-attribute' marker (the '*') , but we've never seen that # in the wild and we will therefore ignore the possibility. param = Parameter() token, value = get_attribute(value) param.append(token) if not value or value[0] == ';': param.defects.append(errors.InvalidHeaderDefect("Parameter contains " "name ({}) but no value".format(token))) return param, value if value[0] == '*': try: token, value = get_section(value) param.sectioned = True param.append(token) except errors.HeaderParseError: pass if not value: raise errors.HeaderParseError("Incomplete parameter") if value[0] == '*': param.append(ValueTerminal('*', 'extended-parameter-marker')) value = value[1:] param.extended = True if value[0] != '=': raise errors.HeaderParseError("Parameter not followed by '='") param.append(ValueTerminal('=', 'parameter-separator')) value = value[1:] if value and value[0] in CFWS_LEADER: token, value = get_cfws(value) param.append(token) remainder = None appendto = param if param.extended and value and value[0] == '"': # Now for some serious hackery to handle the common invalid case of # double quotes around an extended value. We also accept (with defect) # a value marked as encoded that isn't really. qstring, remainder = get_quoted_string(value) inner_value = qstring.stripped_value semi_valid = False if param.section_number == 0: if inner_value and inner_value[0] == "'": semi_valid = True else: token, rest = get_attrtext(inner_value) if rest and rest[0] == "'": semi_valid = True else: try: token, rest = get_extended_attrtext(inner_value) except: pass else: if not rest: semi_valid = True if semi_valid: param.defects.append(errors.InvalidHeaderDefect( "Quoted string value for extended parameter is invalid")) param.append(qstring) for t in qstring: if t.token_type == 'bare-quoted-string': t[:] = [] appendto = t break value = inner_value else: remainder = None param.defects.append(errors.InvalidHeaderDefect( "Parameter marked as extended but appears to have a " "quoted string value that is non-encoded")) if value and value[0] == "'": token = None else: token, value = get_value(value) if not param.extended or param.section_number > 0: if not value or value[0] != "'": appendto.append(token) if remainder is not None: assert not value, value value = remainder return param, value param.defects.append(errors.InvalidHeaderDefect( "Apparent initial-extended-value but attribute " "was not marked as extended or was not initial section")) if not value: # Assume the charset/lang is missing and the token is the value. param.defects.append(errors.InvalidHeaderDefect( "Missing required charset/lang delimiters")) appendto.append(token) if remainder is None: return param, value else: if token is not None: for t in token: if t.token_type == 'extended-attrtext': break t.token_type == 'attrtext' appendto.append(t) param.charset = t.value if value[0] != "'": raise errors.HeaderParseError("Expected RFC2231 char/lang encoding " "delimiter, but found {!r}".format(value)) appendto.append(ValueTerminal("'", 'RFC2231-delimiter')) value = value[1:] if value and value[0] != "'": token, value = get_attrtext(value) appendto.append(token) param.lang = token.value if not value or value[0] != "'": raise errors.HeaderParseError("Expected RFC2231 char/lang encoding " "delimiter, but found {}".format(value)) appendto.append(ValueTerminal("'", 'RFC2231-delimiter')) value = value[1:] if remainder is not None: # Treat the rest of value as bare quoted string content. v = Value() while value: if value[0] in WSP: token, value = get_fws(value) elif value[0] == '"': token = ValueTerminal('"', 'DQUOTE') value = value[1:] else: token, value = get_qcontent(value) v.append(token) token = v else: token, value = get_value(value) appendto.append(token) if remainder is not None: assert not value, value value = remainder return param, value def parse_mime_parameters(value): """ parameter *( ";" parameter ) That BNF is meant to indicate this routine should only be called after finding and handling the leading ';'. There is no corresponding rule in the formal RFC grammar, but it is more convenient for us for the set of parameters to be treated as its own TokenList. This is 'parse' routine because it consumes the remaining value, but it would never be called to parse a full header. Instead it is called to parse everything after the non-parameter value of a specific MIME header. """ mime_parameters = MimeParameters() while value: try: token, value = get_parameter(value) mime_parameters.append(token) except errors.HeaderParseError: leader = None if value[0] in CFWS_LEADER: leader, value = get_cfws(value) if not value: mime_parameters.append(leader) return mime_parameters if value[0] == ';': if leader is not None: mime_parameters.append(leader) mime_parameters.defects.append(errors.InvalidHeaderDefect( "parameter entry with no content")) else: token, value = get_invalid_parameter(value) if leader: token[:0] = [leader] mime_parameters.append(token) mime_parameters.defects.append(errors.InvalidHeaderDefect( "invalid parameter {!r}".format(token))) if value and value[0] != ';': # Junk after the otherwise valid parameter. Mark it as # invalid, but it will have a value. param = mime_parameters[-1] param.token_type = 'invalid-parameter' token, value = get_invalid_parameter(value) param.extend(token) mime_parameters.defects.append(errors.InvalidHeaderDefect( "parameter with invalid trailing text {!r}".format(token))) if value: # Must be a ';' at this point. mime_parameters.append(ValueTerminal(';', 'parameter-separator')) value = value[1:] return mime_parameters def _find_mime_parameters(tokenlist, value): """Do our best to find the parameters in an invalid MIME header """ while value and value[0] != ';': if value[0] in PHRASE_ENDS: tokenlist.append(ValueTerminal(value[0], 'misplaced-special')) value = value[1:] else: token, value = get_phrase(value) tokenlist.append(token) if not value: return tokenlist.append(ValueTerminal(';', 'parameter-separator')) tokenlist.append(parse_mime_parameters(value[1:])) def parse_content_type_header(value): """ maintype "/" subtype *( ";" parameter ) The maintype and substype are tokens. Theoretically they could be checked against the official IANA list + x-token, but we don't do that. """ ctype = ContentType() if not value: ctype.defects.append(errors.HeaderMissingRequiredValue( "Missing content type specification")) return ctype try: token, value = get_token(value) except errors.HeaderParseError: ctype.defects.append(errors.InvalidHeaderDefect( "Expected content maintype but found {!r}".format(value))) _find_mime_parameters(ctype, value) return ctype ctype.append(token) # XXX: If we really want to follow the formal grammar we should make # mantype and subtype specialized TokenLists here. Probably not worth it. if not value or value[0] != '/': ctype.defects.append(errors.InvalidHeaderDefect( "Invalid content type")) if value: _find_mime_parameters(ctype, value) return ctype ctype.maintype = token.value.strip().lower() ctype.append(ValueTerminal('/', 'content-type-separator')) value = value[1:] try: token, value = get_token(value) except errors.HeaderParseError: ctype.defects.append(errors.InvalidHeaderDefect( "Expected content subtype but found {!r}".format(value))) _find_mime_parameters(ctype, value) return ctype ctype.append(token) ctype.subtype = token.value.strip().lower() if not value: return ctype if value[0] != ';': ctype.defects.append(errors.InvalidHeaderDefect( "Only parameters are valid after content type, but " "found {!r}".format(value))) # The RFC requires that a syntactically invalid content-type be treated # as text/plain. Perhaps we should postel this, but we should probably # only do that if we were checking the subtype value against IANA. del ctype.maintype, ctype.subtype _find_mime_parameters(ctype, value) return ctype ctype.append(ValueTerminal(';', 'parameter-separator')) ctype.append(parse_mime_parameters(value[1:])) return ctype def parse_content_disposition_header(value): """ disposition-type *( ";" parameter ) """ disp_header = ContentDisposition() if not value: disp_header.defects.append(errors.HeaderMissingRequiredValue( "Missing content disposition")) return disp_header try: token, value = get_token(value) except errors.HeaderParseError: disp_header.defects.append(errors.InvalidHeaderDefect( "Expected content disposition but found {!r}".format(value))) _find_mime_parameters(disp_header, value) return disp_header disp_header.append(token) disp_header.content_disposition = token.value.strip().lower() if not value: return disp_header if value[0] != ';': disp_header.defects.append(errors.InvalidHeaderDefect( "Only parameters are valid after content disposition, but " "found {!r}".format(value))) _find_mime_parameters(disp_header, value) return disp_header disp_header.append(ValueTerminal(';', 'parameter-separator')) disp_header.append(parse_mime_parameters(value[1:])) return disp_header def parse_content_transfer_encoding_header(value): """ mechanism """ # We should probably validate the values, since the list is fixed. cte_header = ContentTransferEncoding() if not value: cte_header.defects.append(errors.HeaderMissingRequiredValue( "Missing content transfer encoding")) return cte_header try: token, value = get_token(value) except errors.HeaderParseError: cte_header.defects.append(errors.InvalidHeaderDefect( "Expected content transfer encoding but found {!r}".format(value))) else: cte_header.append(token) cte_header.cte = token.value.strip().lower() if not value: return cte_header while value: cte_header.defects.append(errors.InvalidHeaderDefect( "Extra text after content transfer encoding")) if value[0] in PHRASE_ENDS: cte_header.append(ValueTerminal(value[0], 'misplaced-special')) value = value[1:] else: token, value = get_phrase(value) cte_header.append(token) return cte_header # # Header folding # # Header folding is complex, with lots of rules and corner cases. The # following code does its best to obey the rules and handle the corner # cases, but you can be sure there are few bugs:) # # This folder generally canonicalizes as it goes, preferring the stringified # version of each token. The tokens contain information that supports the # folder, including which tokens can be encoded in which ways. # # Folded text is accumulated in a simple list of strings ('lines'), each # one of which should be less than policy.max_line_length ('maxlen'). # def _steal_trailing_WSP_if_exists(lines): wsp = '' if lines and lines[-1] and lines[-1][-1] in WSP: wsp = lines[-1][-1] lines[-1] = lines[-1][:-1] return wsp def _refold_parse_tree(parse_tree, *, policy): """Return string of contents of parse_tree folded according to RFC rules. """ # max_line_length 0/None means no limit, ie: infinitely long. maxlen = policy.max_line_length or sys.maxsize encoding = 'utf-8' if policy.utf8 else 'us-ascii' lines = [''] # Folded lines to be output leading_whitespace = '' # When we have whitespace between two encoded # words, we may need to encode the whitespace # at the beginning of the second word. last_ew = None # Points to the last encoded character if there's an ew on # the line last_charset = None wrap_as_ew_blocked = 0 want_encoding = False # This is set to True if we need to encode this part end_ew_not_allowed = Terminal('', 'wrap_as_ew_blocked') parts = list(parse_tree) while parts: part = parts.pop(0) if part is end_ew_not_allowed: wrap_as_ew_blocked -= 1 continue tstr = str(part) if not want_encoding: if part.token_type in ('ptext', 'vtext'): # Encode if tstr contains special characters. want_encoding = not SPECIALSNL.isdisjoint(tstr) else: # Encode if tstr contains newlines. want_encoding = not NLSET.isdisjoint(tstr) try: tstr.encode(encoding) charset = encoding except UnicodeEncodeError: if any(isinstance(x, errors.UndecodableBytesDefect) for x in part.all_defects): charset = 'unknown-8bit' else: # If policy.utf8 is false this should really be taken from a # 'charset' property on the policy. charset = 'utf-8' want_encoding = True if part.token_type == 'mime-parameters': # Mime parameter folding (using RFC2231) is extra special. _fold_mime_parameters(part, lines, maxlen, encoding) continue if want_encoding and not wrap_as_ew_blocked: if not part.as_ew_allowed: want_encoding = False last_ew = None if part.syntactic_break: encoded_part = part.fold(policy=policy)[:-len(policy.linesep)] if policy.linesep not in encoded_part: # It fits on a single line if len(encoded_part) > maxlen - len(lines[-1]): # But not on this one, so start a new one. newline = _steal_trailing_WSP_if_exists(lines) # XXX what if encoded_part has no leading FWS? lines.append(newline) lines[-1] += encoded_part continue # Either this is not a major syntactic break, so we don't # want it on a line by itself even if it fits, or it # doesn't fit on a line by itself. Either way, fall through # to unpacking the subparts and wrapping them. if not hasattr(part, 'encode'): # It's not a Terminal, do each piece individually. parts = list(part) + parts want_encoding = False continue elif part.as_ew_allowed: # It's a terminal, wrap it as an encoded word, possibly # combining it with previously encoded words if allowed. if (last_ew is not None and charset != last_charset and (last_charset == 'unknown-8bit' or last_charset == 'utf-8' and charset != 'us-ascii')): last_ew = None last_ew = _fold_as_ew(tstr, lines, maxlen, last_ew, part.ew_combine_allowed, charset, leading_whitespace) # This whitespace has been added to the lines in _fold_as_ew() # so clear it now. leading_whitespace = '' last_charset = charset want_encoding = False continue else: # It's a terminal which should be kept non-encoded # (e.g. a ListSeparator). last_ew = None want_encoding = False # fall through if len(tstr) <= maxlen - len(lines[-1]): lines[-1] += tstr continue # This part is too long to fit. The RFC wants us to break at # "major syntactic breaks", so unless we don't consider this # to be one, check if it will fit on the next line by itself. leading_whitespace = '' if (part.syntactic_break and len(tstr) + 1 <= maxlen): newline = _steal_trailing_WSP_if_exists(lines) if newline or part.startswith_fws(): # We're going to fold the data onto a new line here. Due to # the way encoded strings handle continuation lines, we need to # be prepared to encode any whitespace if the next line turns # out to start with an encoded word. lines.append(newline + tstr) whitespace_accumulator = [] for char in lines[-1]: if char not in WSP: break whitespace_accumulator.append(char) leading_whitespace = ''.join(whitespace_accumulator) last_ew = None continue if not hasattr(part, 'encode'): # It's not a terminal, try folding the subparts. newparts = list(part) if part.token_type == 'bare-quoted-string': # To fold a quoted string we need to create a list of terminal # tokens that will render the leading and trailing quotes # and use quoted pairs in the value as appropriate. newparts = ( [ValueTerminal('"', 'ptext')] + [ValueTerminal(make_quoted_pairs(p), 'ptext') for p in newparts] + [ValueTerminal('"', 'ptext')]) if part.token_type == 'comment': newparts = ( [ValueTerminal('(', 'ptext')] + [ValueTerminal(make_parenthesis_pairs(p), 'ptext') if p.token_type == 'ptext' else p for p in newparts] + [ValueTerminal(')', 'ptext')]) if not part.as_ew_allowed: wrap_as_ew_blocked += 1 newparts.append(end_ew_not_allowed) parts = newparts + parts continue if part.as_ew_allowed and not wrap_as_ew_blocked: # It doesn't need CTE encoding, but encode it anyway so we can # wrap it. parts.insert(0, part) want_encoding = True continue # We can't figure out how to wrap, it, so give up. newline = _steal_trailing_WSP_if_exists(lines) if newline or part.startswith_fws(): lines.append(newline + tstr) else: # We can't fold it onto the next line either... lines[-1] += tstr return policy.linesep.join(lines) + policy.linesep def _fold_as_ew(to_encode, lines, maxlen, last_ew, ew_combine_allowed, charset, leading_whitespace): """Fold string to_encode into lines as encoded word, combining if allowed. Return the new value for last_ew, or None if ew_combine_allowed is False. If there is already an encoded word in the last line of lines (indicated by a non-None value for last_ew) and ew_combine_allowed is true, decode the existing ew, combine it with to_encode, and re-encode. Otherwise, encode to_encode. In either case, split to_encode as necessary so that the encoded segments fit within maxlen. """ if last_ew is not None and ew_combine_allowed: to_encode = str( get_unstructured(lines[-1][last_ew:] + to_encode)) lines[-1] = lines[-1][:last_ew] elif to_encode[0] in WSP: # We're joining this to non-encoded text, so don't encode # the leading blank. leading_wsp = to_encode[0] to_encode = to_encode[1:] if (len(lines[-1]) == maxlen): lines.append(_steal_trailing_WSP_if_exists(lines)) lines[-1] += leading_wsp trailing_wsp = '' if to_encode[-1] in WSP: # Likewise for the trailing space. trailing_wsp = to_encode[-1] to_encode = to_encode[:-1] new_last_ew = len(lines[-1]) if last_ew is None else last_ew encode_as = 'utf-8' if charset == 'us-ascii' else charset # The RFC2047 chrome takes up 7 characters plus the length # of the charset name. chrome_len = len(encode_as) + 7 if (chrome_len + 1) >= maxlen: raise errors.HeaderParseError( "max_line_length is too small to fit an encoded word") while to_encode: remaining_space = maxlen - len(lines[-1]) text_space = remaining_space - chrome_len - len(leading_whitespace) if text_space <= 0: lines.append(' ') continue # If we are at the start of a continuation line, prepend whitespace # (we only want to do this when the line starts with an encoded word # but if we're folding in this helper function, then we know that we # are going to be writing out an encoded word.) if len(lines) > 1 and len(lines[-1]) == 1 and leading_whitespace: encoded_word = _ew.encode(leading_whitespace, charset=encode_as) lines[-1] += encoded_word leading_whitespace = '' to_encode_word = to_encode[:text_space] encoded_word = _ew.encode(to_encode_word, charset=encode_as) excess = len(encoded_word) - remaining_space while excess > 0: # Since the chunk to encode is guaranteed to fit into less than 100 characters, # shrinking it by one at a time shouldn't take long. to_encode_word = to_encode_word[:-1] encoded_word = _ew.encode(to_encode_word, charset=encode_as) excess = len(encoded_word) - remaining_space lines[-1] += encoded_word to_encode = to_encode[len(to_encode_word):] leading_whitespace = '' if to_encode: lines.append(' ') new_last_ew = len(lines[-1]) lines[-1] += trailing_wsp return new_last_ew if ew_combine_allowed else None def _fold_mime_parameters(part, lines, maxlen, encoding): """Fold TokenList 'part' into the 'lines' list as mime parameters. Using the decoded list of parameters and values, format them according to the RFC rules, including using RFC2231 encoding if the value cannot be expressed in 'encoding' and/or the parameter+value is too long to fit within 'maxlen'. """ # Special case for RFC2231 encoding: start from decoded values and use # RFC2231 encoding iff needed. # # Note that the 1 and 2s being added to the length calculations are # accounting for the possibly-needed spaces and semicolons we'll be adding. # for name, value in part.params: # XXX What if this ';' puts us over maxlen the first time through the # loop? We should split the header value onto a newline in that case, # but to do that we need to recognize the need earlier or reparse the # header, so I'm going to ignore that bug for now. It'll only put us # one character over. if not lines[-1].rstrip().endswith(';'): lines[-1] += ';' charset = encoding error_handler = 'strict' try: value.encode(encoding) encoding_required = False except UnicodeEncodeError: encoding_required = True if utils._has_surrogates(value): charset = 'unknown-8bit' error_handler = 'surrogateescape' else: charset = 'utf-8' if encoding_required: encoded_value = urllib.parse.quote( value, safe='', errors=error_handler) tstr = "{}*={}''{}".format(name, charset, encoded_value) else: tstr = '{}={}'.format(name, quote_string(value)) if len(lines[-1]) + len(tstr) + 1 < maxlen: lines[-1] = lines[-1] + ' ' + tstr continue elif len(tstr) + 2 <= maxlen: lines.append(' ' + tstr) continue # We need multiple sections. We are allowed to mix encoded and # non-encoded sections, but we aren't going to. We'll encode them all. section = 0 extra_chrome = charset + "''" while value: chrome_len = len(name) + len(str(section)) + 3 + len(extra_chrome) if maxlen <= chrome_len + 3: # We need room for the leading blank, the trailing semicolon, # and at least one character of the value. If we don't # have that, we'd be stuck, so in that case fall back to # the RFC standard width. maxlen = 78 splitpoint = maxchars = maxlen - chrome_len - 2 while True: partial = value[:splitpoint] encoded_value = urllib.parse.quote( partial, safe='', errors=error_handler) if len(encoded_value) <= maxchars: break splitpoint -= 1 lines.append(" {}*{}*={}{}".format( name, section, extra_chrome, encoded_value)) extra_chrome = '' section += 1 value = value[splitpoint:] if value: lines[-1] += ';' __init__.py000064400000005450152526700320006663 0ustar00# Copyright (C) 2001-2006 Python Software Foundation # Author: Barry Warsaw # Contact: email-sig@python.org """A package for parsing, handling, and generating email messages.""" __version__ = '4.0.3' __all__ = [ # Old names 'base64MIME', 'Charset', 'Encoders', 'Errors', 'Generator', 'Header', 'Iterators', 'Message', 'MIMEAudio', 'MIMEBase', 'MIMEImage', 'MIMEMessage', 'MIMEMultipart', 'MIMENonMultipart', 'MIMEText', 'Parser', 'quopriMIME', 'Utils', 'message_from_string', 'message_from_file', # new names 'base64mime', 'charset', 'encoders', 'errors', 'generator', 'header', 'iterators', 'message', 'mime', 'parser', 'quoprimime', 'utils', ] # Some convenience routines. Don't import Parser and Message as side-effects # of importing email since those cascadingly import most of the rest of the # email package. def message_from_string(s, *args, **kws): """Parse a string into a Message object model. Optional _class and strict are passed to the Parser constructor. """ from email.parser import Parser return Parser(*args, **kws).parsestr(s) def message_from_file(fp, *args, **kws): """Read a file and parse its contents into a Message object model. Optional _class and strict are passed to the Parser constructor. """ from email.parser import Parser return Parser(*args, **kws).parse(fp) # Lazy loading to provide name mapping from new-style names (PEP 8 compatible # email 4.0 module names), to old-style names (email 3.0 module names). import sys class LazyImporter(object): def __init__(self, module_name): self.__name__ = 'email.' + module_name def __getattr__(self, name): __import__(self.__name__) mod = sys.modules[self.__name__] self.__dict__.update(mod.__dict__) return getattr(mod, name) _LOWERNAMES = [ # email. -> email. 'Charset', 'Encoders', 'Errors', 'FeedParser', 'Generator', 'Header', 'Iterators', 'Message', 'Parser', 'Utils', 'base64MIME', 'quopriMIME', ] _MIMENAMES = [ # email.MIME -> email.mime. 'Audio', 'Base', 'Image', 'Message', 'Multipart', 'NonMultipart', 'Text', ] for _name in _LOWERNAMES: importer = LazyImporter(_name.lower()) sys.modules['email.' + _name] = importer setattr(sys.modules['email'], _name, importer) import email.mime for _name in _MIMENAMES: importer = LazyImporter('mime.' + _name.lower()) sys.modules['email.MIME' + _name] = importer setattr(sys.modules['email'], 'MIME' + _name, importer) setattr(sys.modules['email.mime'], _name, importer) parser.py000064400000006343152526700320006422 0ustar00# Copyright (C) 2001-2006 Python Software Foundation # Author: Barry Warsaw, Thomas Wouters, Anthony Baxter # Contact: email-sig@python.org """A parser of RFC 2822 and MIME email messages.""" __all__ = ['Parser', 'HeaderParser'] import warnings from cStringIO import StringIO from email.feedparser import FeedParser from email.message import Message class Parser: def __init__(self, *args, **kws): """Parser of RFC 2822 and MIME email messages. Creates an in-memory object tree representing the email message, which can then be manipulated and turned over to a Generator to return the textual representation of the message. The string must be formatted as a block of RFC 2822 headers and header continuation lines, optionally preceded by a `Unix-from' header. The header block is terminated either by the end of the string or by a blank line. _class is the class to instantiate for new message objects when they must be created. This class must have a constructor that can take zero arguments. Default is Message.Message. """ if len(args) >= 1: if '_class' in kws: raise TypeError("Multiple values for keyword arg '_class'") kws['_class'] = args[0] if len(args) == 2: if 'strict' in kws: raise TypeError("Multiple values for keyword arg 'strict'") kws['strict'] = args[1] if len(args) > 2: raise TypeError('Too many arguments') if '_class' in kws: self._class = kws['_class'] del kws['_class'] else: self._class = Message if 'strict' in kws: warnings.warn("'strict' argument is deprecated (and ignored)", DeprecationWarning, 2) del kws['strict'] if kws: raise TypeError('Unexpected keyword arguments') def parse(self, fp, headersonly=False): """Create a message structure from the data in a file. Reads all the data from the file and returns the root of the message structure. Optional headersonly is a flag specifying whether to stop parsing after reading the headers or not. The default is False, meaning it parses the entire contents of the file. """ feedparser = FeedParser(self._class) if headersonly: feedparser._set_headersonly() while True: data = fp.read(8192) if not data: break feedparser.feed(data) return feedparser.close() def parsestr(self, text, headersonly=False): """Create a message structure from a string. Returns the root of the message structure. Optional headersonly is a flag specifying whether to stop parsing after reading the headers or not. The default is False, meaning it parses the entire contents of the file. """ return self.parse(StringIO(text), headersonly=headersonly) class HeaderParser(Parser): def parse(self, fp, headersonly=True): return Parser.parse(self, fp, True) def parsestr(self, text, headersonly=True): return Parser.parsestr(self, text, True) message.py000064400000074003152526700320006550 0ustar00# Copyright (C) 2001-2006 Python Software Foundation # Author: Barry Warsaw # Contact: email-sig@python.org """Basic message object for the email package object model.""" __all__ = ['Message'] import re import uu import binascii import warnings from cStringIO import StringIO # Intrapackage imports import email.charset from email import utils from email import errors SEMISPACE = '; ' # Regular expression that matches `special' characters in parameters, the # existence of which force quoting of the parameter value. tspecials = re.compile(r'[ \(\)<>@,;:\\"/\[\]\?=]') # Helper functions def _splitparam(param): # Split header parameters. BAW: this may be too simple. It isn't # strictly RFC 2045 (section 5.1) compliant, but it catches most headers # found in the wild. We may eventually need a full fledged parser # eventually. a, sep, b = param.partition(';') if not sep: return a.strip(), None return a.strip(), b.strip() def _formatparam(param, value=None, quote=True): """Convenience function to format and return a key=value pair. This will quote the value if needed or if quote is true. If value is a three tuple (charset, language, value), it will be encoded according to RFC2231 rules. """ if value is not None and len(value) > 0: # A tuple is used for RFC 2231 encoded parameter values where items # are (charset, language, value). charset is a string, not a Charset # instance. if isinstance(value, tuple): # Encode as per RFC 2231 param += '*' value = utils.encode_rfc2231(value[2], value[0], value[1]) # BAW: Please check this. I think that if quote is set it should # force quoting even if not necessary. if quote or tspecials.search(value): return '%s="%s"' % (param, utils.quote(value)) else: return '%s=%s' % (param, value) else: return param def _parseparam(s): plist = [] while s[:1] == ';': s = s[1:] end = s.find(';') while end > 0 and (s.count('"', 0, end) - s.count('\\"', 0, end)) % 2: end = s.find(';', end + 1) if end < 0: end = len(s) f = s[:end] if '=' in f: i = f.index('=') f = f[:i].strip().lower() + '=' + f[i+1:].strip() plist.append(f.strip()) s = s[end:] return plist def _unquotevalue(value): # This is different than utils.collapse_rfc2231_value() because it doesn't # try to convert the value to a unicode. Message.get_param() and # Message.get_params() are both currently defined to return the tuple in # the face of RFC 2231 parameters. if isinstance(value, tuple): return value[0], value[1], utils.unquote(value[2]) else: return utils.unquote(value) class Message: """Basic message object. A message object is defined as something that has a bunch of RFC 2822 headers and a payload. It may optionally have an envelope header (a.k.a. Unix-From or From_ header). If the message is a container (i.e. a multipart or a message/rfc822), then the payload is a list of Message objects, otherwise it is a string. Message objects implement part of the `mapping' interface, which assumes there is exactly one occurrence of the header per message. Some headers do in fact appear multiple times (e.g. Received) and for those headers, you must use the explicit API to set or get all the headers. Not all of the mapping methods are implemented. """ def __init__(self): self._headers = [] self._unixfrom = None self._payload = None self._charset = None # Defaults for multipart messages self.preamble = self.epilogue = None self.defects = [] # Default content type self._default_type = 'text/plain' def __str__(self): """Return the entire formatted message as a string. This includes the headers, body, and envelope header. """ return self.as_string(unixfrom=True) def as_string(self, unixfrom=False): """Return the entire formatted message as a string. Optional `unixfrom' when True, means include the Unix From_ envelope header. This is a convenience method and may not generate the message exactly as you intend because by default it mangles lines that begin with "From ". For more flexibility, use the flatten() method of a Generator instance. """ from email.generator import Generator fp = StringIO() g = Generator(fp) g.flatten(self, unixfrom=unixfrom) return fp.getvalue() def is_multipart(self): """Return True if the message consists of multiple parts.""" return isinstance(self._payload, list) # # Unix From_ line # def set_unixfrom(self, unixfrom): self._unixfrom = unixfrom def get_unixfrom(self): return self._unixfrom # # Payload manipulation. # def attach(self, payload): """Add the given payload to the current payload. The current payload will always be a list of objects after this method is called. If you want to set the payload to a scalar object, use set_payload() instead. """ if self._payload is None: self._payload = [payload] else: self._payload.append(payload) def get_payload(self, i=None, decode=False): """Return a reference to the payload. The payload will either be a list object or a string. If you mutate the list object, you modify the message's payload in place. Optional i returns that index into the payload. Optional decode is a flag indicating whether the payload should be decoded or not, according to the Content-Transfer-Encoding header (default is False). When True and the message is not a multipart, the payload will be decoded if this header's value is `quoted-printable' or `base64'. If some other encoding is used, or the header is missing, or if the payload has bogus data (i.e. bogus base64 or uuencoded data), the payload is returned as-is. If the message is a multipart and the decode flag is True, then None is returned. """ if i is None: payload = self._payload elif not isinstance(self._payload, list): raise TypeError('Expected list, got %s' % type(self._payload)) else: payload = self._payload[i] if decode: if self.is_multipart(): return None cte = self.get('content-transfer-encoding', '').lower() if cte == 'quoted-printable': return utils._qdecode(payload) elif cte == 'base64': try: return utils._bdecode(payload) except binascii.Error: # Incorrect padding return payload elif cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue'): sfp = StringIO() try: uu.decode(StringIO(payload+'\n'), sfp, quiet=True) payload = sfp.getvalue() except uu.Error: # Some decoding problem return payload # Everything else, including encodings with 8bit or 7bit are returned # unchanged. return payload def set_payload(self, payload, charset=None): """Set the payload to the given value. Optional charset sets the message's default character set. See set_charset() for details. """ self._payload = payload if charset is not None: self.set_charset(charset) def set_charset(self, charset): """Set the charset of the payload to a given character set. charset can be a Charset instance, a string naming a character set, or None. If it is a string it will be converted to a Charset instance. If charset is None, the charset parameter will be removed from the Content-Type field. Anything else will generate a TypeError. The message will be assumed to be of type text/* encoded with charset.input_charset. It will be converted to charset.output_charset and encoded properly, if needed, when generating the plain text representation of the message. MIME headers (MIME-Version, Content-Type, Content-Transfer-Encoding) will be added as needed. """ if charset is None: self.del_param('charset') self._charset = None return if isinstance(charset, basestring): charset = email.charset.Charset(charset) if not isinstance(charset, email.charset.Charset): raise TypeError(charset) # BAW: should we accept strings that can serve as arguments to the # Charset constructor? self._charset = charset if 'MIME-Version' not in self: self.add_header('MIME-Version', '1.0') if 'Content-Type' not in self: self.add_header('Content-Type', 'text/plain', charset=charset.get_output_charset()) else: self.set_param('charset', charset.get_output_charset()) if isinstance(self._payload, unicode): self._payload = self._payload.encode(charset.output_charset) if str(charset) != charset.get_output_charset(): self._payload = charset.body_encode(self._payload) if 'Content-Transfer-Encoding' not in self: cte = charset.get_body_encoding() try: cte(self) except TypeError: self._payload = charset.body_encode(self._payload) self.add_header('Content-Transfer-Encoding', cte) def get_charset(self): """Return the Charset instance associated with the message's payload. """ return self._charset # # MAPPING INTERFACE (partial) # def __len__(self): """Return the total number of headers, including duplicates.""" return len(self._headers) def __getitem__(self, name): """Get a header value. Return None if the header is missing instead of raising an exception. Note that if the header appeared multiple times, exactly which occurrence gets returned is undefined. Use get_all() to get all the values matching a header field name. """ return self.get(name) def __setitem__(self, name, val): """Set the value of a header. Note: this does not overwrite an existing header with the same field name. Use __delitem__() first to delete any existing headers. """ self._headers.append((name, val)) def __delitem__(self, name): """Delete all occurrences of a header, if present. Does not raise an exception if the header is missing. """ name = name.lower() newheaders = [] for k, v in self._headers: if k.lower() != name: newheaders.append((k, v)) self._headers = newheaders def __contains__(self, name): return name.lower() in [k.lower() for k, v in self._headers] def has_key(self, name): """Return true if the message contains the header.""" missing = object() return self.get(name, missing) is not missing def keys(self): """Return a list of all the message's header field names. These will be sorted in the order they appeared in the original message, or were added to the message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. """ return [k for k, v in self._headers] def values(self): """Return a list of all the message's header values. These will be sorted in the order they appeared in the original message, or were added to the message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. """ return [v for k, v in self._headers] def items(self): """Get all the message's header fields and values. These will be sorted in the order they appeared in the original message, or were added to the message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. """ return self._headers[:] def get(self, name, failobj=None): """Get a header value. Like __getitem__() but return failobj instead of None when the field is missing. """ name = name.lower() for k, v in self._headers: if k.lower() == name: return v return failobj # # Additional useful stuff # def get_all(self, name, failobj=None): """Return a list of all the values for the named field. These will be sorted in the order they appeared in the original message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. If no such fields exist, failobj is returned (defaults to None). """ values = [] name = name.lower() for k, v in self._headers: if k.lower() == name: values.append(v) if not values: return failobj return values def add_header(self, _name, _value, **_params): """Extended header setting. name is the header field to add. keyword arguments can be used to set additional parameters for the header field, with underscores converted to dashes. Normally the parameter will be added as key="value" unless value is None, in which case only the key will be added. If a parameter value contains non-ASCII characters it must be specified as a three-tuple of (charset, language, value), in which case it will be encoded according to RFC2231 rules. Example: msg.add_header('content-disposition', 'attachment', filename='bud.gif') """ parts = [] for k, v in _params.items(): if v is None: parts.append(k.replace('_', '-')) else: parts.append(_formatparam(k.replace('_', '-'), v)) if _value is not None: parts.insert(0, _value) self._headers.append((_name, SEMISPACE.join(parts))) def replace_header(self, _name, _value): """Replace a header. Replace the first matching header found in the message, retaining header order and case. If no matching header was found, a KeyError is raised. """ _name = _name.lower() for i, (k, v) in zip(range(len(self._headers)), self._headers): if k.lower() == _name: self._headers[i] = (k, _value) break else: raise KeyError(_name) # # Use these three methods instead of the three above. # def get_content_type(self): """Return the message's content type. The returned string is coerced to lower case of the form `maintype/subtype'. If there was no Content-Type header in the message, the default type as given by get_default_type() will be returned. Since according to RFC 2045, messages always have a default type this will always return a value. RFC 2045 defines a message's default type to be text/plain unless it appears inside a multipart/digest container, in which case it would be message/rfc822. """ missing = object() value = self.get('content-type', missing) if value is missing: # This should have no parameters return self.get_default_type() ctype = _splitparam(value)[0].lower() # RFC 2045, section 5.2 says if its invalid, use text/plain if ctype.count('/') != 1: return 'text/plain' return ctype def get_content_maintype(self): """Return the message's main content type. This is the `maintype' part of the string returned by get_content_type(). """ ctype = self.get_content_type() return ctype.split('/')[0] def get_content_subtype(self): """Returns the message's sub-content type. This is the `subtype' part of the string returned by get_content_type(). """ ctype = self.get_content_type() return ctype.split('/')[1] def get_default_type(self): """Return the `default' content type. Most messages have a default content type of text/plain, except for messages that are subparts of multipart/digest containers. Such subparts have a default content type of message/rfc822. """ return self._default_type def set_default_type(self, ctype): """Set the `default' content type. ctype should be either "text/plain" or "message/rfc822", although this is not enforced. The default content type is not stored in the Content-Type header. """ self._default_type = ctype def _get_params_preserve(self, failobj, header): # Like get_params() but preserves the quoting of values. BAW: # should this be part of the public interface? missing = object() value = self.get(header, missing) if value is missing: return failobj params = [] for p in _parseparam(';' + value): try: name, val = p.split('=', 1) name = name.strip() val = val.strip() except ValueError: # Must have been a bare attribute name = p.strip() val = '' params.append((name, val)) params = utils.decode_params(params) return params def get_params(self, failobj=None, header='content-type', unquote=True): """Return the message's Content-Type parameters, as a list. The elements of the returned list are 2-tuples of key/value pairs, as split on the `=' sign. The left hand side of the `=' is the key, while the right hand side is the value. If there is no `=' sign in the parameter the value is the empty string. The value is as described in the get_param() method. Optional failobj is the object to return if there is no Content-Type header. Optional header is the header to search instead of Content-Type. If unquote is True, the value is unquoted. """ missing = object() params = self._get_params_preserve(missing, header) if params is missing: return failobj if unquote: return [(k, _unquotevalue(v)) for k, v in params] else: return params def get_param(self, param, failobj=None, header='content-type', unquote=True): """Return the parameter value if found in the Content-Type header. Optional failobj is the object to return if there is no Content-Type header, or the Content-Type header has no such parameter. Optional header is the header to search instead of Content-Type. Parameter keys are always compared case insensitively. The return value can either be a string, or a 3-tuple if the parameter was RFC 2231 encoded. When it's a 3-tuple, the elements of the value are of the form (CHARSET, LANGUAGE, VALUE). Note that both CHARSET and LANGUAGE can be None, in which case you should consider VALUE to be encoded in the us-ascii charset. You can usually ignore LANGUAGE. Your application should be prepared to deal with 3-tuple return values, and can convert the parameter to a Unicode string like so: param = msg.get_param('foo') if isinstance(param, tuple): param = unicode(param[2], param[0] or 'us-ascii') In any case, the parameter value (either the returned string, or the VALUE item in the 3-tuple) is always unquoted, unless unquote is set to False. """ if header not in self: return failobj for k, v in self._get_params_preserve(failobj, header): if k.lower() == param.lower(): if unquote: return _unquotevalue(v) else: return v return failobj def set_param(self, param, value, header='Content-Type', requote=True, charset=None, language=''): """Set a parameter in the Content-Type header. If the parameter already exists in the header, its value will be replaced with the new value. If header is Content-Type and has not yet been defined for this message, it will be set to "text/plain" and the new parameter and value will be appended as per RFC 2045. An alternate header can be specified in the header argument, and all parameters will be quoted as necessary unless requote is False. If charset is specified, the parameter will be encoded according to RFC 2231. Optional language specifies the RFC 2231 language, defaulting to the empty string. Both charset and language should be strings. """ if not isinstance(value, tuple) and charset: value = (charset, language, value) if header not in self and header.lower() == 'content-type': ctype = 'text/plain' else: ctype = self.get(header) if not self.get_param(param, header=header): if not ctype: ctype = _formatparam(param, value, requote) else: ctype = SEMISPACE.join( [ctype, _formatparam(param, value, requote)]) else: ctype = '' for old_param, old_value in self.get_params(header=header, unquote=requote): append_param = '' if old_param.lower() == param.lower(): append_param = _formatparam(param, value, requote) else: append_param = _formatparam(old_param, old_value, requote) if not ctype: ctype = append_param else: ctype = SEMISPACE.join([ctype, append_param]) if ctype != self.get(header): del self[header] self[header] = ctype def del_param(self, param, header='content-type', requote=True): """Remove the given parameter completely from the Content-Type header. The header will be re-written in place without the parameter or its value. All values will be quoted as necessary unless requote is False. Optional header specifies an alternative to the Content-Type header. """ if header not in self: return new_ctype = '' for p, v in self.get_params(header=header, unquote=requote): if p.lower() != param.lower(): if not new_ctype: new_ctype = _formatparam(p, v, requote) else: new_ctype = SEMISPACE.join([new_ctype, _formatparam(p, v, requote)]) if new_ctype != self.get(header): del self[header] self[header] = new_ctype def set_type(self, type, header='Content-Type', requote=True): """Set the main type and subtype for the Content-Type header. type must be a string in the form "maintype/subtype", otherwise a ValueError is raised. This method replaces the Content-Type header, keeping all the parameters in place. If requote is False, this leaves the existing header's quoting as is. Otherwise, the parameters will be quoted (the default). An alternative header can be specified in the header argument. When the Content-Type header is set, we'll always also add a MIME-Version header. """ # BAW: should we be strict? if not type.count('/') == 1: raise ValueError # Set the Content-Type, you get a MIME-Version if header.lower() == 'content-type': del self['mime-version'] self['MIME-Version'] = '1.0' if header not in self: self[header] = type return params = self.get_params(header=header, unquote=requote) del self[header] self[header] = type # Skip the first param; it's the old type. for p, v in params[1:]: self.set_param(p, v, header, requote) def get_filename(self, failobj=None): """Return the filename associated with the payload if present. The filename is extracted from the Content-Disposition header's `filename' parameter, and it is unquoted. If that header is missing the `filename' parameter, this method falls back to looking for the `name' parameter. """ missing = object() filename = self.get_param('filename', missing, 'content-disposition') if filename is missing: filename = self.get_param('name', missing, 'content-type') if filename is missing: return failobj return utils.collapse_rfc2231_value(filename).strip() def get_boundary(self, failobj=None): """Return the boundary associated with the payload if present. The boundary is extracted from the Content-Type header's `boundary' parameter, and it is unquoted. """ missing = object() boundary = self.get_param('boundary', missing) if boundary is missing: return failobj # RFC 2046 says that boundaries may begin but not end in w/s return utils.collapse_rfc2231_value(boundary).rstrip() def set_boundary(self, boundary): """Set the boundary parameter in Content-Type to 'boundary'. This is subtly different than deleting the Content-Type header and adding a new one with a new boundary parameter via add_header(). The main difference is that using the set_boundary() method preserves the order of the Content-Type header in the original message. HeaderParseError is raised if the message has no Content-Type header. """ missing = object() params = self._get_params_preserve(missing, 'content-type') if params is missing: # There was no Content-Type header, and we don't know what type # to set it to, so raise an exception. raise errors.HeaderParseError('No Content-Type header found') newparams = [] foundp = False for pk, pv in params: if pk.lower() == 'boundary': newparams.append(('boundary', '"%s"' % boundary)) foundp = True else: newparams.append((pk, pv)) if not foundp: # The original Content-Type header had no boundary attribute. # Tack one on the end. BAW: should we raise an exception # instead??? newparams.append(('boundary', '"%s"' % boundary)) # Replace the existing Content-Type header with the new value newheaders = [] for h, v in self._headers: if h.lower() == 'content-type': parts = [] for k, v in newparams: if v == '': parts.append(k) else: parts.append('%s=%s' % (k, v)) newheaders.append((h, SEMISPACE.join(parts))) else: newheaders.append((h, v)) self._headers = newheaders def get_content_charset(self, failobj=None): """Return the charset parameter of the Content-Type header. The returned string is always coerced to lower case. If there is no Content-Type header, or if that header has no charset parameter, failobj is returned. """ missing = object() charset = self.get_param('charset', missing) if charset is missing: return failobj if isinstance(charset, tuple): # RFC 2231 encoded, so decode it, and it better end up as ascii. pcharset = charset[0] or 'us-ascii' try: # LookupError will be raised if the charset isn't known to # Python. UnicodeError will be raised if the encoded text # contains a character not in the charset. charset = unicode(charset[2], pcharset).encode('us-ascii') except (LookupError, UnicodeError): charset = charset[2] # charset character must be in us-ascii range try: if isinstance(charset, str): charset = unicode(charset, 'us-ascii') charset = charset.encode('us-ascii') except UnicodeError: return failobj # RFC 2046, $4.1.2 says charsets are not case sensitive return charset.lower() def get_charsets(self, failobj=None): """Return a list containing the charset(s) used in this message. The returned list of items describes the Content-Type headers' charset parameter for this message and all the subparts in its payload. Each item will either be a string (the value of the charset parameter in the Content-Type header of that part) or the value of the 'failobj' parameter (defaults to None), if the part does not have a main MIME type of "text", or the charset is not defined. The list will contain one string for each part of the message, plus one for the container message (i.e. self), so that a non-multipart message will still return a list of length 1. """ return [part.get_content_charset(failobj) for part in self.walk()] # I.e. def walk(self): ... from email.iterators import walk iterators.pyo000064400000004476152531624710007332 0ustar00 {fc@skdZdddgZddlZddlmZdZedZd dd Z dd ed Z dS( s1Various types of useful iterators and generators.tbody_line_iteratorttyped_subpart_iteratortwalkiN(tStringIOccsK|V|jrGx3|jD]"}x|jD] }|Vq1WqWndS(sWalk over the message tree, yielding each subpart. The walk is performed in depth-first order. This method is a generator. N(t is_multipartt get_payloadR(tselftsubpartt subsubpart((s'/usr/lib64/python2.7/email/iterators.pyRs  ccs[xT|jD]F}|jd|}t|tr xt|D] }|VqAWq q WdS(sIterate over the parts, returning string payloads line-by-line. Optional decode (default False) is passed through to .get_payload(). tdecodeN(RRt isinstancet basestringR(tmsgR Rtpayloadtline((s'/usr/lib64/python2.7/email/iterators.pyR#s ttextccsVxO|jD]A}|j|kr |dksC|j|krN|VqNq q WdS(sIterate over the subparts with a given MIME type. Use `maintype' as the main MIME type to match against; this defaults to "text". Optional `subtype' is the MIME subtype to match against; if omitted, only the main type is matched. N(Rtget_content_maintypetNonetget_content_subtype(R tmaintypetsubtypeR((s'/usr/lib64/python2.7/email/iterators.pyR/sicCs|dkrtj}nd|d}|||jI|rW|d|jIJn|J|jrx.|jD]}t|||d|qtWndS(sA handy debugging aidt is[%s]iN(Rtsyststdouttget_content_typetget_default_typeRRt _structure(R tfptleveltinclude_defaultttabR((s'/usr/lib64/python2.7/email/iterators.pyR=s   ( t__doc__t__all__Rt cStringIORRtFalseRRRR(((s'/usr/lib64/python2.7/email/iterators.pyts    errors.pyo000064400000006711152531624710006624 0ustar00 {fc@s(dZdefdYZdefdYZdefdYZdefdYZd eefd YZd efd YZd ddYZ de fdYZ de fdYZ de fdYZ de fdYZ de fdYZde fdYZdS(s email package exception classes.t MessageErrorcBseZdZRS(s+Base class for errors in the email package.(t__name__t __module__t__doc__(((s$/usr/lib64/python2.7/email/errors.pyR stMessageParseErrorcBseZdZRS(s&Base class for message parsing errors.(RRR(((s$/usr/lib64/python2.7/email/errors.pyR stHeaderParseErrorcBseZdZRS(sError while parsing headers.(RRR(((s$/usr/lib64/python2.7/email/errors.pyRst BoundaryErrorcBseZdZRS(s#Couldn't find terminating boundary.(RRR(((s$/usr/lib64/python2.7/email/errors.pyRstMultipartConversionErrorcBseZdZRS(s(Conversion to a multipart is prohibited.(RRR(((s$/usr/lib64/python2.7/email/errors.pyRst CharsetErrorcBseZdZRS(sAn illegal charset was given.(RRR(((s$/usr/lib64/python2.7/email/errors.pyRst MessageDefectcBseZdZddZRS(s Base class for a message defect.cCs ||_dS(N(tline(tselfR ((s$/usr/lib64/python2.7/email/errors.pyt__init__&sN(RRRtNoneR (((s$/usr/lib64/python2.7/email/errors.pyR #stNoBoundaryInMultipartDefectcBseZdZRS(sBA message claimed to be a multipart but had no boundary parameter.(RRR(((s$/usr/lib64/python2.7/email/errors.pyR)stStartBoundaryNotFoundDefectcBseZdZRS(s+The claimed start boundary was never found.(RRR(((s$/usr/lib64/python2.7/email/errors.pyR,st#FirstHeaderLineIsContinuationDefectcBseZdZRS(s;A message had a continuation line as its first header line.(RRR(((s$/usr/lib64/python2.7/email/errors.pyR/stMisplacedEnvelopeHeaderDefectcBseZdZRS(s?A 'Unix-from' header was found in the middle of a header block.(RRR(((s$/usr/lib64/python2.7/email/errors.pyR2stMalformedHeaderDefectcBseZdZRS(sDFound a header that was missing a colon, or was otherwise malformed.(RRR(((s$/usr/lib64/python2.7/email/errors.pyR5st!MultipartInvariantViolationDefectcBseZdZRS(s?A message claimed to be a multipart but no subparts were found.(RRR(((s$/usr/lib64/python2.7/email/errors.pyR8sN((Rt ExceptionRRRRt TypeErrorRRR RRRRRR(((s$/usr/lib64/python2.7/email/errors.pytsmessage.pyo000064400000070004152531624710006730 0ustar00 {fc@sdZdgZddlZddlZddlZddlZddlmZddlZ ddl m Z ddl m Z dZ ej dZd Zded Zd Zd Zddd YZdS(s8Basic message object for the email package object model.tMessageiN(tStringIO(tutils(terrorss; s[ \(\)<>@,;:\\"/\[\]\?=]cCsD|jd\}}}|s.|jdfS|j|jfS(Nt;(t partitiontstriptNone(tparamtatseptb((s%/usr/lib64/python2.7/email/message.pyt _splitparamscCs|dk rt|dkrt|tr[|d7}tj|d|d|d}n|sptj|rd|tj|fSd||fSn|SdS(sConvenience function to format and return a key=value pair. This will quote the value if needed or if quote is true. If value is a three tuple (charset, language, value), it will be encoded according to RFC2231 rules. it*iis%s="%s"s%s=%sN( Rtlent isinstancettupleRtencode_rfc2231t tspecialstsearchtquote(RtvalueR((s%/usr/lib64/python2.7/email/message.pyt _formatparam&s $cCsg}x|d dkr|d}|jd}xR|dkr|jdd||jdd|dr|jd|d}q5W|dkrt|}n|| }d|kr|jd}|| jjd||dj}n|j|j||}q W|S(NiRit"s\"it=(tfindtcountRtindexRtlowertappend(tstplisttendtfti((s%/usr/lib64/python2.7/email/message.pyt _parseparam>s ;   /cCsBt|tr1|d|dtj|dfStj|SdS(Niii(RRRtunquote(R((s%/usr/lib64/python2.7/email/message.pyt _unquotevaluePs"cBseZdZdZdZedZdZdZdZ dZ d.edZ d.d Z d Zd Zd Zd ZdZdZdZdZdZdZdZd.dZd.dZdZdZdZdZdZdZ dZ!dZ"d.de#d Z$d.de#d!Z%d"e#d.d#d$Z&de#d%Z'd"e#d&Z(d.d'Z)d.d(Z*d)Z+d.d*Z,d.d+Z-d,d-l.m/Z/RS(/sBasic message object. A message object is defined as something that has a bunch of RFC 2822 headers and a payload. It may optionally have an envelope header (a.k.a. Unix-From or From_ header). If the message is a container (i.e. a multipart or a message/rfc822), then the payload is a list of Message objects, otherwise it is a string. Message objects implement part of the `mapping' interface, which assumes there is exactly one occurrence of the header per message. Some headers do in fact appear multiple times (e.g. Received) and for those headers, you must use the explicit API to set or get all the headers. Not all of the mapping methods are implemented. cCsJg|_d|_d|_d|_d|_|_g|_d|_dS(Ns text/plain( t_headersRt _unixfromt_payloadt_charsettpreambletepiloguetdefectst _default_type(tself((s%/usr/lib64/python2.7/email/message.pyt__init__ks     cCs|jdtS(swReturn the entire formatted message as a string. This includes the headers, body, and envelope header. tunixfrom(t as_stringtTrue(R.((s%/usr/lib64/python2.7/email/message.pyt__str__vscCsBddlm}t}||}|j|d||jS(sReturn the entire formatted message as a string. Optional `unixfrom' when True, means include the Unix From_ envelope header. This is a convenience method and may not generate the message exactly as you intend because by default it mangles lines that begin with "From ". For more flexibility, use the flatten() method of a Generator instance. i(t GeneratorR0(temail.generatorR4Rtflattentgetvalue(R.R0R4tfptg((s%/usr/lib64/python2.7/email/message.pyR1|s   cCst|jtS(s6Return True if the message consists of multiple parts.(RR(tlist(R.((s%/usr/lib64/python2.7/email/message.pyt is_multipartscCs ||_dS(N(R'(R.R0((s%/usr/lib64/python2.7/email/message.pyt set_unixfromscCs|jS(N(R'(R.((s%/usr/lib64/python2.7/email/message.pyt get_unixfromscCs2|jdkr|g|_n|jj|dS(sAdd the given payload to the current payload. The current payload will always be a list of objects after this method is called. If you want to set the payload to a scalar object, use set_payload() instead. N(R(RR(R.tpayload((s%/usr/lib64/python2.7/email/message.pytattachscCs9|d kr|j}n;t|jtsFtdt|jn |j|}|r5|jrid S|jddj}|dkrt j |S|dkryt j |SWq2t j k r|SXq5|d kr5t}y0tjt|d |d t|j}Wq2tj k r.|SXq5n|S(sZReturn a reference to the payload. The payload will either be a list object or a string. If you mutate the list object, you modify the message's payload in place. Optional i returns that index into the payload. Optional decode is a flag indicating whether the payload should be decoded or not, according to the Content-Transfer-Encoding header (default is False). When True and the message is not a multipart, the payload will be decoded if this header's value is `quoted-printable' or `base64'. If some other encoding is used, or the header is missing, or if the payload has bogus data (i.e. bogus base64 or uuencoded data), the payload is returned as-is. If the message is a multipart and the decode flag is True, then None is returned. sExpected list, got %sscontent-transfer-encodingtsquoted-printabletbase64s x-uuencodetuuencodetuuesx-uues tquietN(s x-uuencodeRBRCsx-uue(RR(RR:t TypeErrorttypeR;tgetRRt_qdecodet_bdecodetbinasciitErrorRtuutdecodeR2R7(R.R"RMR>tctetsfp((s%/usr/lib64/python2.7/email/message.pyt get_payloads0           cCs)||_|dk r%|j|ndS(sSet the payload to the given value. Optional charset sets the message's default character set. See set_charset() for details. N(R(Rt set_charset(R.R>tcharset((s%/usr/lib64/python2.7/email/message.pyt set_payloads  cCs|dkr&|jdd|_dSt|trJtjj|}nt|tjjsnt|n||_d|kr|j ddnd|kr|j ddd|j n|j d|j t|j t r|j j|j|_ nt||j kr4|j|j |_ nd|kr|j}y||Wqtk r|j|j |_ |j d|qXndS(sSet the charset of the payload to a given character set. charset can be a Charset instance, a string naming a character set, or None. If it is a string it will be converted to a Charset instance. If charset is None, the charset parameter will be removed from the Content-Type field. Anything else will generate a TypeError. The message will be assumed to be of type text/* encoded with charset.input_charset. It will be converted to charset.output_charset and encoded properly, if needed, when generating the plain text representation of the message. MIME headers (MIME-Version, Content-Type, Content-Transfer-Encoding) will be added as needed. RRNs MIME-Versions1.0s Content-Types text/plainsContent-Transfer-Encoding(Rt del_paramR)Rt basestringtemailRRtCharsetREt add_headertget_output_charsett set_paramR(tunicodetencodetoutput_charsettstrt body_encodetget_body_encoding(R.RRRN((s%/usr/lib64/python2.7/email/message.pyRQs4         cCs|jS(sKReturn the Charset instance associated with the message's payload. (R)(R.((s%/usr/lib64/python2.7/email/message.pyt get_charsetscCs t|jS(s9Return the total number of headers, including duplicates.(RR&(R.((s%/usr/lib64/python2.7/email/message.pyt__len__scCs |j|S(s-Get a header value. Return None if the header is missing instead of raising an exception. Note that if the header appeared multiple times, exactly which occurrence gets returned is undefined. Use get_all() to get all the values matching a header field name. (RG(R.tname((s%/usr/lib64/python2.7/email/message.pyt __getitem__s cCs|jj||fdS(sSet the value of a header. Note: this does not overwrite an existing header with the same field name. Use __delitem__() first to delete any existing headers. N(R&R(R.Rctval((s%/usr/lib64/python2.7/email/message.pyt __setitem__(scCsa|j}g}x?|jD]4\}}|j|kr|j||fqqW||_dS(swDelete all occurrences of a header, if present. Does not raise an exception if the header is missing. N(RR&R(R.Rct newheaderstktv((s%/usr/lib64/python2.7/email/message.pyt __delitem__0s  cCs2|jg|jD]\}}|j^qkS(N(RR&(R.RcRhRi((s%/usr/lib64/python2.7/email/message.pyt __contains__<scCst}|j|||k S(s/Return true if the message contains the header.(tobjectRG(R.Rctmissing((s%/usr/lib64/python2.7/email/message.pythas_key?s cCs g|jD]\}}|^q S(s.Return a list of all the message's header field names. These will be sorted in the order they appeared in the original message, or were added to the message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. (R&(R.RhRi((s%/usr/lib64/python2.7/email/message.pytkeysDscCs g|jD]\}}|^q S(s)Return a list of all the message's header values. These will be sorted in the order they appeared in the original message, or were added to the message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. (R&(R.RhRi((s%/usr/lib64/python2.7/email/message.pytvaluesNscCs|jS(s'Get all the message's header fields and values. These will be sorted in the order they appeared in the original message, or were added to the message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. (R&(R.((s%/usr/lib64/python2.7/email/message.pytitemsXscCs@|j}x-|jD]"\}}|j|kr|SqW|S(s~Get a header value. Like __getitem__() but return failobj instead of None when the field is missing. (RR&(R.RctfailobjRhRi((s%/usr/lib64/python2.7/email/message.pyRGbs  cCs\g}|j}x9|jD].\}}|j|kr|j|qqW|sX|S|S(sQReturn a list of all the values for the named field. These will be sorted in the order they appeared in the original message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. If no such fields exist, failobj is returned (defaults to None). (RR&R(R.RcRrRpRhRi((s%/usr/lib64/python2.7/email/message.pytget_allrs  cKsg}xd|jD]V\}}|dkrG|j|jddq|jt|jdd|qW|dk r|jd|n|jj|tj|fdS(sExtended header setting. name is the header field to add. keyword arguments can be used to set additional parameters for the header field, with underscores converted to dashes. Normally the parameter will be added as key="value" unless value is None, in which case only the key will be added. If a parameter value contains non-ASCII characters it must be specified as a three-tuple of (charset, language, value), in which case it will be encoded according to RFC2231 rules. Example: msg.add_header('content-disposition', 'attachment', filename='bud.gif') t_t-iN( RqRRtreplaceRtinsertR&t SEMISPACEtjoin(R.t_namet_valuet_paramstpartsRhRi((s%/usr/lib64/python2.7/email/message.pyRXs & cCs}|j}xjttt|j|jD];\}\}}|j|kr.||f|j|Remove the given parameter completely from the Content-Type header. The header will be re-written in place without the parameter or its value. All values will be quoted as necessary unless requote is False. Optional header specifies an alternative to the Content-Type header. NR@RR$(RRRRxRyRG(R.RRRt new_ctypeRRi((s%/usr/lib64/python2.7/email/message.pyRTks % cCs|jddkstn|jdkrD|d=d|dt}|jd|}||kr+|Stj|jS(sReturn the boundary associated with the payload if present. The boundary is extracted from the Content-Type header's `boundary' parameter, and it is unquoted. tboundary(RlRRRtrstrip(R.RrRmR((s%/usr/lib64/python2.7/email/message.pyt get_boundarys   c Cst}|j|d}||kr9tjdng}t}xY|D]Q\}}|jdkr|jdd|ft}qL|j||fqLW|s|jdd|fng}x|jD]\} } | jdkr^g} xG|D]?\} } | dkr$| j| q| jd| | fqW|j| t j | fq|j| | fqW||_dS(sSet the boundary parameter in Content-Type to 'boundary'. This is subtly different than deleting the Content-Type header and adding a new one with a new boundary parameter via add_header(). The main difference is that using the set_boundary() method preserves the order of the Content-Type header in the original message. HeaderParseError is raised if the message has no Content-Type header. s content-typesNo Content-Type header foundRs"%s"R@s%s=%sN( RlRRtHeaderParseErrortFalseRRR2R&RxRy( R.RRmRt newparamstfoundptpktpvRgthRiR}Rh((s%/usr/lib64/python2.7/email/message.pyt set_boundarys0    cCst}|jd|}||kr+|St|tr|dpGd}y t|d|jd}Wqttfk r|d}qXny4t|trt|d}n|jd}Wntk r|SX|j S(sReturn the charset parameter of the Content-Type header. The returned string is always coerced to lower case. If there is no Content-Type header, or if that header has no charset parameter, failobj is returned. RRisus-asciii( RlRRRR[R\t LookupErrort UnicodeErrorR^R(R.RrRmRRtpcharset((s%/usr/lib64/python2.7/email/message.pytget_content_charsets"    cCs&g|jD]}|j|^q S(sReturn a list containing the charset(s) used in this message. The returned list of items describes the Content-Type headers' charset parameter for this message and all the subparts in its payload. Each item will either be a string (the value of the charset parameter in the Content-Type header of that part) or the value of the 'failobj' parameter (defaults to None), if the part does not have a main MIME type of "text", or the charset is not defined. The list will contain one string for each part of the message, plus one for the container message (i.e. self), so that a non-multipart message will still return a list of length 1. (twalkR(R.Rrtpart((s%/usr/lib64/python2.7/email/message.pyt get_charsets si(RN(0t__name__t __module__t__doc__R/R3RR1R;R<R=R?RRPRSRQRaRbRdRfRjRkRnRoRpRqRGRsRXRRRRRRRR2RRRZRTRRRRRRtemail.iteratorsR(((s%/usr/lib64/python2.7/email/message.pyR\sX      2 -            #/  -  ((Rt__all__treRLRJtwarningst cStringIORt email.charsetRVRRRxtcompileRR RR2RR#R%R(((s%/usr/lib64/python2.7/email/message.pyts          mime/application.pyo000064400000003060152531624710010534 0ustar00 {fc@sIdZdgZddlmZddlmZdefdYZdS(s5Class representing application/* type MIME documents.tMIMEApplicationi(tencoders(tMIMENonMultipartcBs eZdZdejdZRS(s2Class for generating application/* MIME documents.s octet-streamcKsL|dkrtdntj|d|||j|||dS(sCreate an application/* type MIME document. _data is a string containing the raw application data. _subtype is the MIME content type subtype, defaulting to 'octet-stream'. _encoder is a function which will perform the actual encoding for transport of the application data, defaulting to base64 encoding. Any additional keyword arguments are passed to the base class constructor, which turns them into parameters on the Content-Type header. s Invalid application MIME subtypet applicationN(tNonet TypeErrorRt__init__t set_payload(tselft_datat_subtypet_encodert_params((s./usr/lib64/python2.7/email/mime/application.pyRs   (t__name__t __module__t__doc__Rt encode_base64R(((s./usr/lib64/python2.7/email/mime/application.pyR sN(Rt__all__temailRtemail.mime.nonmultipartRR(((s./usr/lib64/python2.7/email/mime/application.pyts mime/message.pyo000064400000002650152531624710007661 0ustar00 {fc@sIdZdgZddlmZddlmZdefdYZdS(s,Class representing message/* MIME documents.t MIMEMessagei(tmessage(tMIMENonMultipartcBseZdZddZRS(s,Class representing message/* MIME documents.trfc822cCsXtj|d|t|tjs4tdntjj|||jddS(sCreate a message/* type MIME document. _msg is a message object and must be an instance of Message, or a derived class of Message, otherwise a TypeError is raised. Optional _subtype defines the subtype of the contained message. The default is "rfc822" (this is defined by the MIME standard, even though the term "rfc822" is technically outdated by RFC 2822). Rs&Argument is not an instance of Messagesmessage/rfc822N(Rt__init__t isinstanceRtMessaget TypeErrortattachtset_default_type(tselft_msgt_subtype((s*/usr/lib64/python2.7/email/mime/message.pyRs (t__name__t __module__t__doc__R(((s*/usr/lib64/python2.7/email/mime/message.pyRsN(Rt__all__temailRtemail.mime.nonmultipartRR(((s*/usr/lib64/python2.7/email/mime/message.pyts mime/nonmultipart.pyc000064400000001570152531624710010755 0ustar00 {fc@sIdZdgZddlmZddlmZdefdYZdS(s9Base class for MIME type messages that are not multipart.tMIMENonMultiparti(terrors(tMIMEBasecBseZdZdZRS(s0Base class for MIME non-multipart type messages.cCstjddS(Ns4Cannot attach additional subparts to non-multipart/*(RtMultipartConversionError(tselftpayload((s//usr/lib64/python2.7/email/mime/nonmultipart.pytattachs(t__name__t __module__t__doc__R(((s//usr/lib64/python2.7/email/mime/nonmultipart.pyRsN(R t__all__temailRtemail.mime.baseRR(((s//usr/lib64/python2.7/email/mime/nonmultipart.pyts mime/audio.pyc000064400000005535152531624710007327 0ustar00 {fc@sdZdgZddlZddlmZddlmZddlmZidd6d d 6d d 6d d 6Z dZ defdYZ dS(s/Class representing audio/* type MIME documents.t MIMEAudioiN(tStringIO(tencoders(tMIMENonMultiparttbasictausx-wavtwavsx-aifftaifftaifccCsZ|d }t|}x=tjD]2}|||}|dk r tj|dSq WdS(sTry to identify a sound file type. sndhdr.what() has a pretty cruddy interface, unfortunately. This is why we re-do it here. It would be easier to reverse engineer the Unix 'file' command and use the standard 'magic' file, as shipped with a modern Unix. iiN(RtsndhdrtteststNonet_sndhdr_MIMEmaptget(tdatathdrtfakefilettestfntres((s(/usr/lib64/python2.7/email/mime/audio.pyt_whatsnds   cBs eZdZdejdZRS(s,Class for generating audio/* MIME documents.cKsg|dkrt|}n|dkr6tdntj|d|||j|||dS(s Create an audio/* type MIME document. _audiodata is a string containing the raw audio data. If this data can be decoded by the standard Python `sndhdr' module, then the subtype will be automatically included in the Content-Type header. Otherwise, you can specify the specific audio subtype via the _subtype parameter. If _subtype is not given, and no subtype can be guessed, a TypeError is raised. _encoder is a function which will perform the actual encoding for transport of the image data. It takes one argument, which is this Image instance. It should use get_payload() and set_payload() to change the payload to the encoded form. It should also add any Content-Transfer-Encoding or other headers to the message as necessary. The default encoding is Base64. Any additional keyword arguments are passed to the base class constructor, which turns them into parameters on the Content-Type header. s!Could not find audio MIME subtypetaudioN(R Rt TypeErrorRt__init__t set_payload(tselft _audiodatat_subtypet_encodert_params((s(/usr/lib64/python2.7/email/mime/audio.pyR-s   N(t__name__t __module__t__doc__R Rt encode_base64R(((s(/usr/lib64/python2.7/email/mime/audio.pyR*s( Rt__all__R t cStringIORtemailRtemail.mime.nonmultipartRR RR(((s(/usr/lib64/python2.7/email/mime/audio.pyts     mime/base.pyo000064400000002134152531624710007144 0ustar00 {fc@s<dZdgZddlmZdejfdYZdS(s$Base class for MIME specializations.tMIMEBasei(tmessagecBseZdZdZRS(s$Base class for MIME specializations.cKsAtjj|d||f}|jd||d|ds mime/__init__.pyc000064400000000202152531624710007747 0ustar00 {fc@sdS(N((((s+/usr/lib64/python2.7/email/mime/__init__.pyttmime/nonmultipart.pyo000064400000001570152531624710010771 0ustar00 {fc@sIdZdgZddlmZddlmZdefdYZdS(s9Base class for MIME type messages that are not multipart.tMIMENonMultiparti(terrors(tMIMEBasecBseZdZdZRS(s0Base class for MIME non-multipart type messages.cCstjddS(Ns4Cannot attach additional subparts to non-multipart/*(RtMultipartConversionError(tselftpayload((s//usr/lib64/python2.7/email/mime/nonmultipart.pytattachs(t__name__t __module__t__doc__R(((s//usr/lib64/python2.7/email/mime/nonmultipart.pyRsN(R t__all__temailRtemail.mime.baseRR(((s//usr/lib64/python2.7/email/mime/nonmultipart.pyts mime/audio.pyo000064400000005535152531624710007343 0ustar00 {fc@sdZdgZddlZddlmZddlmZddlmZidd6d d 6d d 6d d 6Z dZ defdYZ dS(s/Class representing audio/* type MIME documents.t MIMEAudioiN(tStringIO(tencoders(tMIMENonMultiparttbasictausx-wavtwavsx-aifftaifftaifccCsZ|d }t|}x=tjD]2}|||}|dk r tj|dSq WdS(sTry to identify a sound file type. sndhdr.what() has a pretty cruddy interface, unfortunately. This is why we re-do it here. It would be easier to reverse engineer the Unix 'file' command and use the standard 'magic' file, as shipped with a modern Unix. iiN(RtsndhdrtteststNonet_sndhdr_MIMEmaptget(tdatathdrtfakefilettestfntres((s(/usr/lib64/python2.7/email/mime/audio.pyt_whatsnds   cBs eZdZdejdZRS(s,Class for generating audio/* MIME documents.cKsg|dkrt|}n|dkr6tdntj|d|||j|||dS(s Create an audio/* type MIME document. _audiodata is a string containing the raw audio data. If this data can be decoded by the standard Python `sndhdr' module, then the subtype will be automatically included in the Content-Type header. Otherwise, you can specify the specific audio subtype via the _subtype parameter. If _subtype is not given, and no subtype can be guessed, a TypeError is raised. _encoder is a function which will perform the actual encoding for transport of the image data. It takes one argument, which is this Image instance. It should use get_payload() and set_payload() to change the payload to the encoded form. It should also add any Content-Transfer-Encoding or other headers to the message as necessary. The default encoding is Base64. Any additional keyword arguments are passed to the base class constructor, which turns them into parameters on the Content-Type header. s!Could not find audio MIME subtypetaudioN(R Rt TypeErrorRt__init__t set_payload(tselft _audiodatat_subtypet_encodert_params((s(/usr/lib64/python2.7/email/mime/audio.pyR-s   N(t__name__t __module__t__doc__R Rt encode_base64R(((s(/usr/lib64/python2.7/email/mime/audio.pyR*s( Rt__all__R t cStringIORtemailRtemail.mime.nonmultipartRR RR(((s(/usr/lib64/python2.7/email/mime/audio.pyts     mime/image.pyc000064400000004001152531624710007273 0ustar00 {fc@sUdZdgZddlZddlmZddlmZdefdYZdS(s/Class representing image/* type MIME documents.t MIMEImageiN(tencoders(tMIMENonMultipartcBs eZdZdejdZRS(s1Class for generating image/* type MIME documents.cKsm|dkr!tjd|}n|dkr<tdntj|d|||j|||dS(sCreate an image/* type MIME document. _imagedata is a string containing the raw image data. If this data can be decoded by the standard Python `imghdr' module, then the subtype will be automatically included in the Content-Type header. Otherwise, you can specify the specific image subtype via the _subtype parameter. _encoder is a function which will perform the actual encoding for transport of the image data. It takes one argument, which is this Image instance. It should use get_payload() and set_payload() to change the payload to the encoded form. It should also add any Content-Transfer-Encoding or other headers to the message as necessary. The default encoding is Base64. Any additional keyword arguments are passed to the base class constructor, which turns them into parameters on the Content-Type header. s"Could not guess image MIME subtypetimageN(tNonetimghdrtwhatt TypeErrorRt__init__t set_payload(tselft _imagedatat_subtypet_encodert_params((s(/usr/lib64/python2.7/email/mime/image.pyRs   N(t__name__t __module__t__doc__RRt encode_base64R(((s(/usr/lib64/python2.7/email/mime/image.pyRs(Rt__all__RtemailRtemail.mime.nonmultipartRR(((s(/usr/lib64/python2.7/email/mime/image.pyts   mime/message.pyc000064400000002650152531624710007645 0ustar00 {fc@sIdZdgZddlmZddlmZdefdYZdS(s,Class representing message/* MIME documents.t MIMEMessagei(tmessage(tMIMENonMultipartcBseZdZddZRS(s,Class representing message/* MIME documents.trfc822cCsXtj|d|t|tjs4tdntjj|||jddS(sCreate a message/* type MIME document. _msg is a message object and must be an instance of Message, or a derived class of Message, otherwise a TypeError is raised. Optional _subtype defines the subtype of the contained message. The default is "rfc822" (this is defined by the MIME standard, even though the term "rfc822" is technically outdated by RFC 2822). Rs&Argument is not an instance of Messagesmessage/rfc822N(Rt__init__t isinstanceRtMessaget TypeErrortattachtset_default_type(tselft_msgt_subtype((s*/usr/lib64/python2.7/email/mime/message.pyRs (t__name__t __module__t__doc__R(((s*/usr/lib64/python2.7/email/mime/message.pyRsN(Rt__all__temailRtemail.mime.nonmultipartRR(((s*/usr/lib64/python2.7/email/mime/message.pyts mime/base.pyc000064400000002134152531624710007130 0ustar00 {fc@s<dZdgZddlmZdejfdYZdS(s$Base class for MIME specializations.tMIMEBasei(tmessagecBseZdZdZRS(s$Base class for MIME specializations.cKsAtjj|d||f}|jd||d|ds mime/image.pyo000064400000004001152531624710007307 0ustar00 {fc@sUdZdgZddlZddlmZddlmZdefdYZdS(s/Class representing image/* type MIME documents.t MIMEImageiN(tencoders(tMIMENonMultipartcBs eZdZdejdZRS(s1Class for generating image/* type MIME documents.cKsm|dkr!tjd|}n|dkr<tdntj|d|||j|||dS(sCreate an image/* type MIME document. _imagedata is a string containing the raw image data. If this data can be decoded by the standard Python `imghdr' module, then the subtype will be automatically included in the Content-Type header. Otherwise, you can specify the specific image subtype via the _subtype parameter. _encoder is a function which will perform the actual encoding for transport of the image data. It takes one argument, which is this Image instance. It should use get_payload() and set_payload() to change the payload to the encoded form. It should also add any Content-Transfer-Encoding or other headers to the message as necessary. The default encoding is Base64. Any additional keyword arguments are passed to the base class constructor, which turns them into parameters on the Content-Type header. s"Could not guess image MIME subtypetimageN(tNonetimghdrtwhatt TypeErrorRt__init__t set_payload(tselft _imagedatat_subtypet_encodert_params((s(/usr/lib64/python2.7/email/mime/image.pyRs   N(t__name__t __module__t__doc__RRt encode_base64R(((s(/usr/lib64/python2.7/email/mime/image.pyRs(Rt__all__RtemailRtemail.mime.nonmultipartRR(((s(/usr/lib64/python2.7/email/mime/image.pyts   mime/text.pyo000064400000002434152531624710007221 0ustar00 {fc@sIdZdgZddlmZddlmZdefdYZdS(s.Class representing text/* type MIME documents.tMIMETexti(tencode_7or8bit(tMIMENonMultipartcBseZdZdddZRS(s0Class for generating text/* type MIME documents.tplainsus-asciicCs1tj|d|i|d6|j||dS(s~Create a text/* type MIME document. _text is the string for this message object. _subtype is the MIME sub content type, defaulting to "plain". _charset is the character set parameter added to the Content-Type header. This defaults to "us-ascii". Note that as a side-effect, the Content-Transfer-Encoding header will also be set. ttexttcharsetN(Rt__init__t set_payload(tselft_textt_subtypet_charset((s'/usr/lib64/python2.7/email/mime/text.pyRs (t__name__t __module__t__doc__R(((s'/usr/lib64/python2.7/email/mime/text.pyRsN(Rt__all__temail.encodersRtemail.mime.nonmultipartRR(((s'/usr/lib64/python2.7/email/mime/text.pyts mime/__init__.pyo000064400000000202152531624710007763 0ustar00 {fc@sdS(N((((s+/usr/lib64/python2.7/email/mime/__init__.pyttmime/text.pyc000064400000002434152531624710007205 0ustar00 {fc@sIdZdgZddlmZddlmZdefdYZdS(s.Class representing text/* type MIME documents.tMIMETexti(tencode_7or8bit(tMIMENonMultipartcBseZdZdddZRS(s0Class for generating text/* type MIME documents.tplainsus-asciicCs1tj|d|i|d6|j||dS(s~Create a text/* type MIME document. _text is the string for this message object. _subtype is the MIME sub content type, defaulting to "plain". _charset is the character set parameter added to the Content-Type header. This defaults to "us-ascii". Note that as a side-effect, the Content-Transfer-Encoding header will also be set. ttexttcharsetN(Rt__init__t set_payload(tselft_textt_subtypet_charset((s'/usr/lib64/python2.7/email/mime/text.pyRs (t__name__t __module__t__doc__R(((s'/usr/lib64/python2.7/email/mime/text.pyRsN(Rt__all__temail.encodersRtemail.mime.nonmultipartRR(((s'/usr/lib64/python2.7/email/mime/text.pyts mime/application.pyc000064400000003060152531624710010520 0ustar00 {fc@sIdZdgZddlmZddlmZdefdYZdS(s5Class representing application/* type MIME documents.tMIMEApplicationi(tencoders(tMIMENonMultipartcBs eZdZdejdZRS(s2Class for generating application/* MIME documents.s octet-streamcKsL|dkrtdntj|d|||j|||dS(sCreate an application/* type MIME document. _data is a string containing the raw application data. _subtype is the MIME content type subtype, defaulting to 'octet-stream'. _encoder is a function which will perform the actual encoding for transport of the application data, defaulting to base64 encoding. Any additional keyword arguments are passed to the base class constructor, which turns them into parameters on the Content-Type header. s Invalid application MIME subtypet applicationN(tNonet TypeErrorRt__init__t set_payload(tselft_datat_subtypet_encodert_params((s./usr/lib64/python2.7/email/mime/application.pyRs   (t__name__t __module__t__doc__Rt encode_base64R(((s./usr/lib64/python2.7/email/mime/application.pyR sN(Rt__all__temailRtemail.mime.nonmultipartRR(((s./usr/lib64/python2.7/email/mime/application.pyts mime/multipart.pyo000064400000003205152531624710010253 0ustar00 {fc@s9dZdgZddlmZdefdYZdS(s.Base class for MIME multipart/* type messages.t MIMEMultiparti(tMIMEBasecBs eZdZddddZRS(s.Base class for MIME multipart/* type messages.tmixedcKs`tj|d||g|_|rFx|D]}|j|q,Wn|r\|j|ndS(sCreates a multipart/* type message. By default, creates a multipart/mixed message, with proper Content-Type and MIME-Version headers. _subtype is the subtype of the multipart content type, defaulting to `mixed'. boundary is the multipart boundary string. By default it is calculated as needed. _subparts is a sequence of initial subparts for the payload. It must be an iterable object, such as a list. You can always attach new subparts to the message by using the attach() method. Additional parameters for the Content-Type header are taken from the keyword arguments (or passed into the _params argument). t multipartN(Rt__init__t_payloadtattacht set_boundary(tselft_subtypetboundaryt _subpartst_paramstp((s,/usr/lib64/python2.7/email/mime/multipart.pyRs  N(t__name__t __module__t__doc__tNoneR(((s,/usr/lib64/python2.7/email/mime/multipart.pyR sN(Rt__all__temail.mime.baseRR(((s,/usr/lib64/python2.7/email/mime/multipart.pyts mime/multipart.pyc000064400000003205152531624710010237 0ustar00 {fc@s9dZdgZddlmZdefdYZdS(s.Base class for MIME multipart/* type messages.t MIMEMultiparti(tMIMEBasecBs eZdZddddZRS(s.Base class for MIME multipart/* type messages.tmixedcKs`tj|d||g|_|rFx|D]}|j|q,Wn|r\|j|ndS(sCreates a multipart/* type message. By default, creates a multipart/mixed message, with proper Content-Type and MIME-Version headers. _subtype is the subtype of the multipart content type, defaulting to `mixed'. boundary is the multipart boundary string. By default it is calculated as needed. _subparts is a sequence of initial subparts for the payload. It must be an iterable object, such as a list. You can always attach new subparts to the message by using the attach() method. Additional parameters for the Content-Type header are taken from the keyword arguments (or passed into the _params argument). t multipartN(Rt__init__t_payloadtattacht set_boundary(tselft_subtypetboundaryt _subpartst_paramstp((s,/usr/lib64/python2.7/email/mime/multipart.pyRs  N(t__name__t __module__t__doc__tNoneR(((s,/usr/lib64/python2.7/email/mime/multipart.pyR sN(Rt__all__temail.mime.baseRR(((s,/usr/lib64/python2.7/email/mime/multipart.pyts header.pyc000064400000032536152531624710006530 0ustar00 {fc@s6dZdddgZddlZddlZddlZddlZddlmZddl m Z dZ d Z d Z d d Zd Zd Ze dZe dZejdejejBejBZejdZejdZejjZdZeed dZdfdYZdZ dZ!dS(s+Header encoding and decoding functionality.tHeadert decode_headert make_headeriN(tHeaderParseError(tCharsets t u iuiLsus-asciisutf-8s =\? # literal =? (?P[^?]*?) # non-greedy up to the next ? is the charset \? # literal ? (?P[qb]) # either a "q" or a "b", case insensitive \? # literal ? (?P.*?) # non-greedy up to the next ?= is the encoded string \?= # literal ?= (?=[ \t]|$) # whitespace or the end of the string s[\041-\176]+:$s \n[^ \t]+:c CsGt|}tj|s(|d fgSg}d}x |jD]}tj|so|j|d fqAntj|}x|r>|jdj}|r|r|ddd kr|ddt |d f|dAppend a string to the MIME header. Optional charset, if given, should be a Charset instance or the name of a character set (which will be converted to a Charset instance). A value of None (the default) means that the charset given in the constructor is used. s may be a byte string or a Unicode string. If it is a byte string (i.e. isinstance(s, str) is true), then charset is the encoding of that byte string, and a UnicodeError will be raised if the string cannot be decoded with that charset. If s is a Unicode string, then charset is a hint specifying the character set of the characters in the string. In this case, when producing an RFC 2822 compliant header using RFC 2047 rules, the Unicode string will be encoded using the following charsets in order: us-ascii, the charset hint, utf-8. The first character set not to provoke a UnicodeError is used. Optional `errors' is passed as the third argument to any unicode() or ustr.encode() call. t8bitsus-asciisutf-8 conversion failedN(R R/R*RR t input_codecR>t output_codecR;R.tUTF8t UnicodeErrortFalsetAssertionErrorR3R(R7R"R#R8tincodectustrtoutcodec((s$/usr/lib64/python2.7/email/header.pyRs(    cCs0|j|}|j|t}|j|}||krI||fgS|dkrb||fgS|dkr|j||||S|t|kr|}|j|| t} |j||t} nt|||\} } |j| } |j| t} | |fg} | |j| ||j |S(NRHsus-ascii( t to_splittabletfrom_splittabletTruetencoded_header_lent _split_asciiRRMt _binsplitt_splitR6(R7R"R#R't splitcharst splittableR%telentsplitpnttfirsttlastt fsplittabletfencodedtchunk((s$/usr/lib64/python2.7/email/header.pyRX s$    cCs8t|||j|j|}t||gt|S(N(RVR6R0tzipR(R7R"R#tfirstlenRYtchunks((s$/usr/lib64/python2.7/email/header.pyRVNsc Csg}x|D]\}}|s%q n|dks@|jdkrI|}n|j|}|rz|djdrzd}nd}t||||q Wt|j}|j|S(NiRR(R theader_encodingt header_encodetendswitht _max_appendtNLR0R@( R7t newchunksR'RdRR#R"textratjoiner((s$/usr/lib64/python2.7/email/header.pyt_encode_chunksSs   s;, c Csg}|j}d}x~|jD]s\}}||d}||jdkrW|}n||j||||7}|d\}} | j|}qW|j||} tj| rtdj| n| S(sEncode a message header into an RFC-compliant format. There are many issues involved in converting a given string for use in an email header. Only certain character sets are readable in most email clients, and as header strings can only contain a subset of 7-bit ASCII, care must be taken to properly convert and encode (with Base64 or quoted-printable) header strings. In addition, there is a 75-character length limit on any given encoded header field, so line-wrapping must be performed, even with double-byte character sets. This method will do its best to convert the string to the correct character set used in email, and encode and line wrap it safely with the appropriate scheme for that character set. If the given charset is not known or an error occurs during conversion, this function will return the header untouched. Optional splitchars is a string containing characters to split long ASCII lines on, in rough support of RFC 2822's `highest level syntactic breaks'. This doesn't affect RFC 2047 encoded lines. iiRis8header value appears to contain an embedded header: {!r}( R5R3RURXRmt_embeded_headerR Rtformat( R7RYRjR'tlastlenR"R#t targetlent lastchunkt lastcharsettvalue((s$/usr/lib64/python2.7/email/header.pyR;vs   N( t__name__t __module__R R:R<RDRFRGRRXRVRmR;(((s$/usr/lib64/python2.7/email/header.pyRs3    7 .  #cCs|g}|}xi|jD][}|j}t||krV|j||}qnx4|D]}||kr]Pq]q]W|j||}qtjd|} |dkr|} nd} | d} t| } t|jdt} g}d}x]| j|D]L}|t dt|d| }t|}| }|dkr|rt|dkrt j |dr|j|||7}q|||kr:|r|j| j || n||kr|dkrt ||||d}|j|d |dg}n |g}| t|d}|}q|j|||7}qW|r|j| j |qqW|S( Ns%s\s*s;,RRs iii(R tlstripRRtretcompileR1R2RtmaxtfcretmatchR@RVtextend(R"RctrestlenR)RYtlinestmaxlenRtchtcreteolRltjoinlentwslentthistlinelentparttcurlentpartlent onfirstlinetsubl((s$/usr/lib64/python2.7/email/header.pyRVs^         ! %       c Csd}t|}xf||krz||dd?}|j|| t}|j|}||krm|}q|d}qW|j|| t}|j||t} || fS(Nii(RRSRTRURM( RZR#R'titjtmRatchunklenR]R^((s$/usr/lib64/python2.7/email/header.pyRWs    ("t__doc__t__all__RxRtemail.quoprimimeRtemail.base64mimet email.errorsRt email.charsetRRiRR=R2R?R4R.RKRytVERBOSEt IGNORECASEt MULTILINER R{RnRRhRR RRRVRW(((s$/usr/lib64/python2.7/email/header.pyts:           <  F_parseaddr.pyc000064400000033105152531624710007375 0ustar00 {fc@sddZddddgZddlZddlZdZdZd Zd d d d dddddddddddddddddddd gZd!d"d#d$d%d&d'gZid(d)6d(d*6d(d+6d(d,6d-d.6d/d06d1d26d-d36d4d56d1d66d7d86d4d96d:d;6d7d<6Z d=Z d>Z d?Z d@Z dAfdBYZdCefdDYZdS(EscEmail address parsing code. Lifted directly from rfc822.py. This should eventually be rewritten. t mktime_tzt parsedatet parsedate_tztquoteiNt ts, tjantfebtmartaprtmaytjuntjultaugtseptocttnovtdectjanuarytfebruarytmarchtapriltjunetjulytaugustt septembertoctobertnovembertdecembertmonttuetwedtthutfritsattsunitUTtUTCtGMTtZiptASTitADTi tESTtEDTitCSTtCDTiDtMSTtMDTitPSTtPDTc Cs|j}|djds5|djtkr?|d=n8|djd}|dkrw|d|d|ddS|d }|\}}}}}|j}|t kr||j}}|t krdSnt j |d}|d kr|d 8}n|d dkr|d }n|jd }|dkr||}}n|d dkr,|d }n|dj sL||}}n|d dkri|d }n|jd }t|d kr|\} } d} n(t|dkr|\} } } ndSy@t |}t |}t | } t | } t | } Wnt k rdSX|dkrN|dkrA|d7}qN|d7}nd} |j}|tkryt|} n$yt |} Wnt k rnX| r| dkrd } | } nd} | | dd| dd} n|||| | | ddd | f S(sQConvert a date string to a time tuple. Accounts for military timezones. it,iit-it+Rii it:it0idiDiliii<N(tsplittendswithtlowert _daynamestrfindtlentfindtappendtNonet _monthnamestindextisdigittintt ValueErrortuppert _timezones(tdatatitstufftstddtmmtyyttmttztthhttmmttssttzoffsetttzsign((s(/usr/lib64/python2.7/email/_parseaddr.pyR-s )                               !cCs+t|}t|tr#|d S|SdS(s&Convert a time string to a time tuple.i N(Rt isinstancettuple(RGtt((s(/usr/lib64/python2.7/email/_parseaddr.pyRs cCsD|ddkr%tj|d dStj|}||dSdS(sETurn a 10-tuple as returned by parsedate_tz() into a POSIX timestamp.i iiN(i(R?ttimetmktimetcalendarttimegm(RGRW((s(/usr/lib64/python2.7/email/_parseaddr.pyRscCs|jddjddS(sPrepare string to be used in a quoted string. Turns backslash and double quote characters into quoted pairs. These are the only characters that need to be quoted inside a quoted string. Does not add the surrounding double quotes. s\s\\t"s\"(treplace(tstr((s(/usr/lib64/python2.7/email/_parseaddr.pyRst AddrlistClasscBseZdZdZdZdZdZdZdZdZ e dZ d Z d Z d Zdd Zd ZRS(sAddress parser class by Ben Escoto. To understand what this class does, it helps to have a copy of RFC 2822 in front of you. Note: this class interface is deprecated and may be removed in the future. Use rfc822.AddressList instead. cCsd|_d|_d|_d|_|j|j|_|j|j|j|_|jjdd|_||_g|_ dS(sInitialize a new instance. `field' is an unparsed address header field, containing one or more addresses. s ()<>@,:;."[]is s t.RN( tspecialstpostLWStCRtFWStatomendsR]t phraseendstfieldt commentlist(tselfRh((s(/usr/lib64/python2.7/email/_parseaddr.pyt__init__s     cCsx{|jt|jkr}|j|j|jdkrJ|jd7_q|j|jdkry|jj|jqPqWdS(s*Parse up to the start of the next address.s it(N(RbR<RhRcRiR>t getcomment(Rj((s(/usr/lib64/python2.7/email/_parseaddr.pytgotonexts cCsUg}xH|jt|jkrP|j}|r@||7}q |jdq W|S(sVParse all addresses. Returns a list containing all of the addresses. R(RR(RbR<Rht getaddressR>(Rjtresulttad((s(/usr/lib64/python2.7/email/_parseaddr.pyt getaddrlists  cCsg|_|j|j}|j}|j}|jg}|jt|jkr|rPtj|j|dfg}qPn|j|jdkr||_||_|j}tj|j|fg}nz|j|jdkrg}t|j}|jd7_x=|jt|jkr|j|j|krm|j|jdkrm|jd7_Pn||j }qWn|j|jdkr|j }|jrtj|ddj|jd |fg}qPtj||fg}nS|r%tj|j|dfg}n+|j|j|j krP|jd7_n|j|jt|jkr|j|jd kr|jd7_n|S( sParse the next address.is.@R5it;tt@R5(RhRbtFalseRnR<t getdomaintTrueRy(Rjt expectroutetadlist((s(/usr/lib64/python2.7/email/_parseaddr.pyRzs.     cCs\g}|jx|jt|jkr|j|jdkr`|jd|jd7_nf|j|jdkr|jdt|jn0|j|j|jkrPn|j|j|jqW|jt|jks|j|jdkrt j |S|jd|jd7_|j|j }|sKt St j ||S(sParse an RFC 2822 addr-spec.R`iR\s"%s"R( RnRbR<RhR>RtgetquoteRftgetatomt EMPTYSTRINGRxR(Rjtaslisttdomain((s(/usr/lib64/python2.7/email/_parseaddr.pyRy<s*   .    cCs7g}x!|jt|jkr)|j|j|jkrL|jd7_q |j|jdkr{|jj|jq |j|jdkr|j|jq |j|jdkr|jd7_|jdq |j|jdkrtS|j|j|j krPq |j|j q Wtj |S(s-Get the complete domain name from an address.iRlt[R`R( RbR<RhRcRiR>RmtgetdomainliteralRRfRRx(Rjtsdlist((s(/usr/lib64/python2.7/email/_parseaddr.pyRZs"cCs-|j|j|krdSdg}t}|jd7_x|jt|jkr|ry|j|j|jt}n|j|j|kr|jd7_Pnk|r|j|jdkr|j|jq;n6|j|jdkrt}n|j|j|j|jd7_q;Wtj|S(sParse a header fragment delimited by special characters. `beginchar' is the start character for the fragment. If self is not looking at an instance of `beginchar' then getdelimited returns the empty string. `endchars' is a sequence of allowable end-delimiting characters. Parsing stops when one of these is encountered. If `allowcomments' is non-zero, embedded RFC 2822 comments are allowed within the parsed fragment. RiRls\( RhRbRR<R>RmRRRx(Rjt beginchartendcharst allowcommentstslistR((s(/usr/lib64/python2.7/email/_parseaddr.pyt getdelimitedqs(    cCs|jddtS(s1Get a quote-delimited fragment from self's field.R\s" (RR(Rj((s(/usr/lib64/python2.7/email/_parseaddr.pyRscCs|jddtS(s7Get a parenthesis-delimited fragment from self's field.Rls) (RR(Rj((s(/usr/lib64/python2.7/email/_parseaddr.pyRmscCsd|jddtS(s!Parse an RFC 2822 domain-literal.s[%s]Rs] (RR(Rj((s(/usr/lib64/python2.7/email/_parseaddr.pyRscCsdg}|dkr!|j}nx\|jt|jkr|j|j|krVPn|j|j|j|jd7_q$Wtj|S(sParse an RFC 2822 atom. Optional atomends specifies a different set of end token delimiters (the default is to use self.atomends). This is used e.g. in getphraselist() since phrase endings must not include the `.' (which is legal in phrases).RiN(R?RfRbR<RhR>RRx(RjRftatomlist((s(/usr/lib64/python2.7/email/_parseaddr.pyRs   cCsg}x|jt|jkr|j|j|jkrL|jd7_q |j|jdkrx|j|jq |j|jdkr|jj|jq |j|j|jkrPq |j|j |jq W|S(sParse a sequence of RFC 2822 phrases. A phrase is a sequence of words, which are in turn either RFC 2822 atoms or quoted-strings. Phrases are canonicalized by squeezing all runs of continuous whitespace into one space. iR\Rl( RbR<RhReR>RRiRmRgR(RjR}((s(/usr/lib64/python2.7/email/_parseaddr.pyRvsN(t__name__t __module__t__doc__RkRnRrRoRzRyRRRRRmRR?RRv(((s(/usr/lib64/python2.7/email/_parseaddr.pyR_s   ;   %    t AddressListcBsMeZdZdZdZdZdZdZdZdZ RS(s@An AddressList encapsulates a list of parsed RFC 2822 addresses.cCs5tj|||r(|j|_n g|_dS(N(R_RkRrt addresslist(RjRh((s(/usr/lib64/python2.7/email/_parseaddr.pyRkscCs t|jS(N(R<R(Rj((s(/usr/lib64/python2.7/email/_parseaddr.pyt__len__scCsStd}|j|_x3|jD](}||jkr#|jj|q#q#W|S(N(RR?RR>(Rjtothertnewaddrtx((s(/usr/lib64/python2.7/email/_parseaddr.pyt__add__s   cCs:x3|jD](}||jkr |jj|q q W|S(N(RR>(RjRR((s(/usr/lib64/python2.7/email/_parseaddr.pyt__iadd__scCsFtd}x3|jD](}||jkr|jj|qqW|S(N(RR?RR>(RjRRR((s(/usr/lib64/python2.7/email/_parseaddr.pyt__sub__s  cCs:x3|jD](}||jkr |jj|q q W|S(N(Rtremove(RjRR((s(/usr/lib64/python2.7/email/_parseaddr.pyt__isub__scCs |j|S(N(R(RjRA((s(/usr/lib64/python2.7/email/_parseaddr.pyt __getitem__s( RRRRkRRRRRR(((s(/usr/lib64/python2.7/email/_parseaddr.pyRs     (Rt__all__RXRZRwRt COMMASPACER@R:RFRRRRR_R(((s(/usr/lib64/python2.7/email/_parseaddr.pyts4  b "feedparser.pyo000064400000025454152531624710007435 0ustar00 {fc@sdZdgZddlZddlmZddlmZejdZejdZejdZ ejdZ ejd Z d Z d Z eZd efd YZdddYZdS(sFeedParser - An email feed parser. The feed parser implements an interface for incrementally parsing an email message, line by line. This has advantages for certain applications, such as those reading email messages off a socket. FeedParser.feed() is the primary interface for pushing new data into the parser. It returns when there's nothing more it can do with the available data. When you have no more data to push into the parser, call .close(). This completes the parsing and returns the root message object. The other advantage of this parser is that it will never raise a parsing exception. Instead, when it finds something unexpected, it adds a 'defect' to the current message. Defects are just instances that live on the message object's .defects attribute. t FeedParseriN(terrors(tmessages | | s( | | )s ( | | )\Zs(^(From |[\041-\071\073-\176]{1,}:|[\t ])ts tBufferedSubFilecBsqeZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z RS( skA file-ish object that can have new data loaded into it. You can also push and pop line-matching predicates onto a stack. When the current predicate matches the current line, a false EOF response (i.e. empty string) is returned instead. This lets the parser adhere to a simple abstraction -- it parses until EOF closes the current message. cCs(g|_g|_g|_t|_dS(N(t_partialt_linest _eofstacktFalset_closed(tself((s(/usr/lib64/python2.7/email/feedparser.pyt__init__3s   cCs|jj|dS(N(Rtappend(R tpred((s(/usr/lib64/python2.7/email/feedparser.pytpush_eof_matcher=scCs |jjS(N(Rtpop(R ((s(/usr/lib64/python2.7/email/feedparser.pytpop_eof_matcher@scCs8|jdj|jjtg|_t|_dS(NR(t pushlinestjoinRt splitlinestTrueR (R ((s(/usr/lib64/python2.7/email/feedparser.pytcloseCs" cCsn|js|jrdStS|jj}x>|jdddD]&}||r@|jj|dSq@W|S(NRi(RR t NeedMoreDataRRR (R tlinetateof((s(/usr/lib64/python2.7/email/feedparser.pytreadlineIs   cCs|jj|dS(N(RR (R R((s(/usr/lib64/python2.7/email/feedparser.pyt unreadline[scCs|jt}| s*|djd r=|j|7_dS|jr|jj|ddj|jjt|dd+|j2n|djds|jg|_n|j|dS( s$Push some new data into this object.is s NRii(s s (RRtendswithRR RRR(R tdatatparts((s(/usr/lib64/python2.7/email/feedparser.pytpush`s " cCs|ddd|jd*dS(Nii(R(R tlines((s(/usr/lib64/python2.7/email/feedparser.pyRxscCs|jS(N(R (R ((s(/usr/lib64/python2.7/email/feedparser.pyt is_closed|scCs|S(N((R ((s(/usr/lib64/python2.7/email/feedparser.pyt__iter__scCs%|j}|dkr!tn|S(NR(Rt StopIteration(R R((s(/usr/lib64/python2.7/email/feedparser.pytnexts   (t__name__t __module__t__doc__R RRRRRRRR R!R#(((s(/usr/lib64/python2.7/email/feedparser.pyR+s         cBseeZdZejdZdZdZdZdZ dZ dZ dZ d Z RS( sA feed-style parser of email.cCsO||_t|_g|_|jj|_d|_d|_ t |_ dS(s@_factory is called with no arguments to create a new message objN( t_factoryRt_inputt _msgstackt _parsegenR#t_parsetNonet_curt_lastRt _headersonly(R R'((s(/usr/lib64/python2.7/email/feedparser.pyR s     cCs t|_dS(N(RR/(R ((s(/usr/lib64/python2.7/email/feedparser.pyt_set_headersonlyscCs|jj||jdS(sPush more data into the parser.N(R(Rt _call_parse(R R((s(/usr/lib64/python2.7/email/feedparser.pytfeedscCs&y|jWntk r!nXdS(N(R+R"(R ((s(/usr/lib64/python2.7/email/feedparser.pyR1s cCs_|jj|j|j}|jdkr[|j r[|jjtj n|S(s<Parse all remaining data and return the root message object.t multipart( R(RR1t _pop_messagetget_content_maintypet is_multiparttdefectsR Rt!MultipartInvariantViolationDefect(R troot((s(/usr/lib64/python2.7/email/feedparser.pyRs    cCs|j}|jr:|jjdkr:|jdn|jrZ|jdj|n|jj|||_||_dS(Nsmultipart/digestsmessage/rfc822i(R'R-tget_content_typetset_default_typeR)tattachR R.(R tmsg((s(/usr/lib64/python2.7/email/feedparser.pyt _new_messages   cCs8|jj}|jr+|jd|_n d|_|S(Ni(R)RR-R,(R tretval((s(/usr/lib64/python2.7/email/feedparser.pyR4s   ccs|jg}xj|jD]_}|tkr7tVqntj|sltj|sh|jj|nPn|j|qW|j||j rg}xMt r|jj }|tkrtVqn|dkrPn|j|qW|j j tj|dS|j jdkrxt r |jjtjx,|jD]}|tkratVqDnPqDW|j}|jjx1t r|jj }|tkrtVqnPqWx1t r|jj }|tkrtVqnPqW|dkrPn|jj|qWdS|j jdkrax,|jD]}|tkrNtVq1nPq1W|jdS|j jdkr.|j j}|dkr|j jjtjg}x5|jD]*}|tkrtVqn|j|qW|j j tj|dSd|}tjdtj|d}t } g} t} xt r|jj }|tkrptVqDn|dkrPn|j|} | r| jdr| jd } Pn| r7| r| d } t j!| }|r| t"|jd  | d n|j|q>W|j j tj|dS( NRsmessage/delivery-statusRR3s--s(?Ps4)(?P--)?(?P[ \t]*)(?P\r\n|\r|\n)?$tendtlinesepii(+R>R(RtheaderREtmatchtNLCRERR t_parse_headersR/RRR-t set_payloadt EMPTYSTRINGRR:RR*R4RR5t get_boundaryR,R7RtNoBoundaryInMultipartDefecttretcompiletescapeRtgroupt NLCRE_eoltsearchtlentpreambleR.tepiloguet get_payloadt isinstancet basestringtStartBoundaryNotFoundDefectt NLCRE_bol(R theadersRRR?R=tboundaryt separatort boundaryretcapturing_preambleRQRAtmotlastlineteolmoRRR@tpayloadt firstlinetbolmo((s(/usr/lib64/python2.7/email/feedparser.pyR*sJ                          !             # c Csd}g}xt|D]\}}|ddkrv|sctj|}|jjj|qn|j|qn|rtj|d jd}||j|R4R*RE(((s(/usr/lib64/python2.7/email/feedparser.pyRs     ((R&t__all__RJtemailRRRKRDRWRNt NLCRE_crackRBRGtNLtobjectRRR(((s(/usr/lib64/python2.7/email/feedparser.pyts   _charset.pyo000064400000032266152531624710006745 0ustar00 {fc@sddddgZddlZddlZddlZddlmZddlmZdZd Z d Z d Z d Z ieedfd 6eedfd6eedfd6eedfd6eedfd6eedfd6eedfd6eedfd6eedfd6eedfd6eedfd6eedfd6dAd 6e e dfd6e e dfd6e ddfd6e ddfd6e ddfd6e e dfd6e e dfd6de dfd 6Zid d!6d d"6dd#6dd$6dd%6dd&6dd'6dd(6dd)6dd*6dd+6dd,6dd-6dd.6dd/6dd06dd16dd26dd36dd46d5d66dd76d8d96d d:6Zid;d6d<d6dd 6Zdddd=Zd>Zd?ZddBd@YZdS(CtCharsett add_aliast add_charsett add_codeciN(terrors(tencode_7or8bitiiiisus-asciis iso-8859-1s iso-8859-2s iso-8859-3s iso-8859-4s iso-8859-9s iso-8859-10s iso-8859-13s iso-8859-14s iso-8859-15s iso-8859-16s windows-1252tvisciitbig5tgb2312s iso-2022-jpseuc-jpt shift_jisskoi8-rsutf-8t8bittlatin_1slatin-1tlatin_2slatin-2tlatin_3slatin-3tlatin_4slatin-4tlatin_5slatin-5tlatin_6slatin-6tlatin_7slatin-7tlatin_8slatin-8tlatin_9slatin-9tlatin_10slatin-10sks_c_5601-1987tcp949teuc_jpseuc-krteuc_krtasciit eucgb2312_cntbig5_twcCs2|tkrtdn|||ft|Add character set properties to the global registry. charset is the input character set, and must be the canonical name of a character set. Optional header_enc and body_enc is either Charset.QP for quoted-printable, Charset.BASE64 for base64 encoding, Charset.SHORTEST for the shortest of qp or base64 encoding, or None for no encoding. SHORTEST is only valid for header_enc. It describes how message headers and message bodies in the input charset are to be encoded. Default is no encoding. Optional output_charset is the character set that the output should be in. Conversions will proceed from input charset, to Unicode, to the output charset when the method Charset.convert() is called. The default is to output in the same character set as the input. Both input_charset and output_charset must have Unicode codec entries in the module's charset-to-codec mapping; use add_codec(charset, codecname) to add codecs the module does not know about. See the codecs module's documentation for more information. s!SHORTEST not allowed for body_encN(tSHORTESTt ValueErrortCHARSETS(tcharsett header_enctbody_enctoutput_charset((s%/usr/lib64/python2.7/email/charset.pyRls cCs|t|t__repr__RARBRERGRItTrueRMRNRZtFalseR\R](((s%/usr/lib64/python2.7/email/charset.pyRs+ &          (NNN((t__all__R-temail.base64mimeROtemail.quoprimimeRtemail.encodersRRDR3RRSRaR4RR"R%RRRR(((s%/usr/lib64/python2.7/email/charset.pyts       quoprimime.pyo000064400000021222152531624710007471 0ustar00 {fc@s5dZddddddddd d d d d dgZddlZddlmZddlmZdZdZdZ ej dZ ej dZ dZ dZdZdZddZdZdZd ed!ed"Zed!ed#ZeZeZed$ZeZeZd%Zd&ZdS('sFQuoted-printable content transfer encoding per RFCs 2045-2047. This module handles the content transfer encoding method defined in RFC 2045 to encode US ASCII-like 8-bit data called `quoted-printable'. It is used to safely encode text that is in a character set similar to the 7-bit US ASCII character set, but that includes some 8-bit characters that are normally not allowed in email bodies or headers. Quoted-printable is very space-inefficient for encoding binary files; use the email.base64mime module for that instead. This module provides an interface to encode and decode both headers and bodies with quoted-printable encoding. RFC 2045 defines a method for including character set information in an `encoded-word' in a header. This method is commonly used for 8-bit real names in To:/From:/Cc: etc. fields, as well as Subject: lines. This module does not do the line wrapping or end-of-line character conversion necessary for proper internationalized headers; it only does dumb encoding and decoding. To deal with the various line wrapping issues, use the email.header module. t body_decodet body_encodetbody_quopri_checktbody_quopri_lentdecodet decodestringtencodet encodestringt header_decodet header_encodetheader_quopri_checktheader_quopri_lentquotetunquoteiN(t hexdigits(tfix_eolss s is[^-a-zA-Z0-9!*+/ ]s [^ !-<>-~\t]cCsttj|S(sBReturn True if the character should be escaped with header quopri.(tboolthqretmatch(tc((s(/usr/lib64/python2.7/email/quoprimime.pyR ?scCsttj|S(s@Return True if the character should be escaped with body quopri.(RtbqreR(R((s(/usr/lib64/python2.7/email/quoprimime.pyRDscCsAd}x4|D],}tj|r/|d7}q |d7}q W|S(s?Return the length of str when it is encoded with header quopri.iii(RR(tstcountR((s(/usr/lib64/python2.7/email/quoprimime.pyR Is   cCsAd}x4|D],}tj|r/|d7}q |d7}q W|S(s=Return the length of str when it is encoded with body quopri.iii(RR(tstrRR((s(/usr/lib64/python2.7/email/quoprimime.pyRTs   tcCsj|s|j|jnJt|dt||krS|dc||7Zd?ZddBd@YZdS(CtCharsett add_aliast add_charsett add_codeciN(terrors(tencode_7or8bitiiiisus-asciis iso-8859-1s iso-8859-2s iso-8859-3s iso-8859-4s iso-8859-9s iso-8859-10s iso-8859-13s iso-8859-14s iso-8859-15s iso-8859-16s windows-1252tvisciitbig5tgb2312s iso-2022-jpseuc-jpt shift_jisskoi8-rsutf-8t8bittlatin_1slatin-1tlatin_2slatin-2tlatin_3slatin-3tlatin_4slatin-4tlatin_5slatin-5tlatin_6slatin-6tlatin_7slatin-7tlatin_8slatin-8tlatin_9slatin-9tlatin_10slatin-10sks_c_5601-1987tcp949teuc_jpseuc-krteuc_krtasciit eucgb2312_cntbig5_twcCs2|tkrtdn|||ft|Add character set properties to the global registry. charset is the input character set, and must be the canonical name of a character set. Optional header_enc and body_enc is either Charset.QP for quoted-printable, Charset.BASE64 for base64 encoding, Charset.SHORTEST for the shortest of qp or base64 encoding, or None for no encoding. SHORTEST is only valid for header_enc. It describes how message headers and message bodies in the input charset are to be encoded. Default is no encoding. Optional output_charset is the character set that the output should be in. Conversions will proceed from input charset, to Unicode, to the output charset when the method Charset.convert() is called. The default is to output in the same character set as the input. Both input_charset and output_charset must have Unicode codec entries in the module's charset-to-codec mapping; use add_codec(charset, codecname) to add codecs the module does not know about. See the codecs module's documentation for more information. s!SHORTEST not allowed for body_encN(tSHORTESTt ValueErrortCHARSETS(tcharsett header_enctbody_enctoutput_charset((s%/usr/lib64/python2.7/email/charset.pyRls cCs|t|t__repr__RARBRFRHRJtTrueRNROR[tFalseR]R^(((s%/usr/lib64/python2.7/email/charset.pyRs+ &          (NNN((t__all__R-temail.base64mimeRPtemail.quoprimimeRtemail.encodersRRER3RRTRbR4RR"R%RRRR(((s%/usr/lib64/python2.7/email/charset.pyts       __init__.pyc000064400000005470152531624710007034 0ustar00 {fc @sdZdZdddddddd d d d d ddddddddddddddddddd d!g Zd"Zd#Zd$d%lZd&efd'YZdddd(dddd ddddg Zd)d*d+d d,d-d.gZ xHeD]@Z ee j Z e ej d/e s        iterators.pyc000064400000004476152531624710007316 0ustar00 {fc@skdZdddgZddlZddlmZdZedZd dd Z dd ed Z dS( s1Various types of useful iterators and generators.tbody_line_iteratorttyped_subpart_iteratortwalkiN(tStringIOccsK|V|jrGx3|jD]"}x|jD] }|Vq1WqWndS(sWalk over the message tree, yielding each subpart. The walk is performed in depth-first order. This method is a generator. N(t is_multipartt get_payloadR(tselftsubpartt subsubpart((s'/usr/lib64/python2.7/email/iterators.pyRs  ccs[xT|jD]F}|jd|}t|tr xt|D] }|VqAWq q WdS(sIterate over the parts, returning string payloads line-by-line. Optional decode (default False) is passed through to .get_payload(). tdecodeN(RRt isinstancet basestringR(tmsgR Rtpayloadtline((s'/usr/lib64/python2.7/email/iterators.pyR#s ttextccsVxO|jD]A}|j|kr |dksC|j|krN|VqNq q WdS(sIterate over the subparts with a given MIME type. Use `maintype' as the main MIME type to match against; this defaults to "text". Optional `subtype' is the MIME subtype to match against; if omitted, only the main type is matched. N(Rtget_content_maintypetNonetget_content_subtype(R tmaintypetsubtypeR((s'/usr/lib64/python2.7/email/iterators.pyR/sicCs|dkrtj}nd|d}|||jI|rW|d|jIJn|J|jrx.|jD]}t|||d|qtWndS(sA handy debugging aidt is[%s]iN(Rtsyststdouttget_content_typetget_default_typeRRt _structure(R tfptleveltinclude_defaultttabR((s'/usr/lib64/python2.7/email/iterators.pyR=s   ( t__doc__t__all__Rt cStringIORRtFalseRRRR(((s'/usr/lib64/python2.7/email/iterators.pyts    quoprimime.pyc000064400000021222152531624710007455 0ustar00 {fc@s5dZddddddddd d d d d dgZddlZddlmZddlmZdZdZdZ ej dZ ej dZ dZ dZdZdZddZdZdZd ed!ed"Zed!ed#ZeZeZed$ZeZeZd%Zd&ZdS('sFQuoted-printable content transfer encoding per RFCs 2045-2047. This module handles the content transfer encoding method defined in RFC 2045 to encode US ASCII-like 8-bit data called `quoted-printable'. It is used to safely encode text that is in a character set similar to the 7-bit US ASCII character set, but that includes some 8-bit characters that are normally not allowed in email bodies or headers. Quoted-printable is very space-inefficient for encoding binary files; use the email.base64mime module for that instead. This module provides an interface to encode and decode both headers and bodies with quoted-printable encoding. RFC 2045 defines a method for including character set information in an `encoded-word' in a header. This method is commonly used for 8-bit real names in To:/From:/Cc: etc. fields, as well as Subject: lines. This module does not do the line wrapping or end-of-line character conversion necessary for proper internationalized headers; it only does dumb encoding and decoding. To deal with the various line wrapping issues, use the email.header module. t body_decodet body_encodetbody_quopri_checktbody_quopri_lentdecodet decodestringtencodet encodestringt header_decodet header_encodetheader_quopri_checktheader_quopri_lentquotetunquoteiN(t hexdigits(tfix_eolss s is[^-a-zA-Z0-9!*+/ ]s [^ !-<>-~\t]cCsttj|S(sBReturn True if the character should be escaped with header quopri.(tboolthqretmatch(tc((s(/usr/lib64/python2.7/email/quoprimime.pyR ?scCsttj|S(s@Return True if the character should be escaped with body quopri.(RtbqreR(R((s(/usr/lib64/python2.7/email/quoprimime.pyRDscCsAd}x4|D],}tj|r/|d7}q |d7}q W|S(s?Return the length of str when it is encoded with header quopri.iii(RR(tstcountR((s(/usr/lib64/python2.7/email/quoprimime.pyR Is   cCsAd}x4|D],}tj|r/|d7}q |d7}q W|S(s=Return the length of str when it is encoded with body quopri.iii(RR(tstrRR((s(/usr/lib64/python2.7/email/quoprimime.pyRTs   tcCsj|s|j|jnJt|dt||krS|dc||7@,:;".]s [][\\()"]cCs|S(N((ts((s#/usr/lib64/python2.7/email/utils.pyt _identity:scCs|s |Stj|S(sDecodes a base64 string. This function is equivalent to base64.decodestring and it's retained only for backward compatibility. It used to remove the last \n of the decoded string, if it had any (see issue 7143). (tbase64R(R((s#/usr/lib64/python2.7/email/utils.pyt_bdecode>scCs.tjdt|}tjdt|}|S(s-Replace all line-ending characters with \r\n.s (?s %s%s%s <%s>(t specialsretsearcht escapesreR(tpairtnametaddresstquotes((s#/usr/lib64/python2.7/email/utils.pyRUs  cCs"tj|}t|}|jS(s7Return a list of (REALNAME, EMAIL) for each fieldvalue.(t COMMASPACEtjoint _AddressListt addresslist(t fieldvaluestallta((s#/usr/lib64/python2.7/email/utils.pyRhs s_ =\? # literal =? (?P[^?]*?) # non-greedy up to the next ? is the charset \? # literal ? (?P[qb]) # either a "q" or a "b", case insensitive \? # literal ? (?P.*?) # non-greedy up to the next ?= is the atom \?= # literal ?= c CsM|d$krtj}n|rtj|}tjrO|drOtj}n tj}tt|d\}}|dkrd}nd}d|||df}n$tj|}|rd}nd }d d d d ddddg|d|dddddddddddddg |d d |d|d!|d"|d#|fS(%sReturns a date string as specified by RFC 2822, e.g.: Fri, 09 Nov 2001 01:08:47 -0000 Optional timeval if given is a floating point time value as accepted by gmtime() and localtime(), otherwise the current time is used. Optional localtime is a flag that when True, interprets timeval, and returns a date relative to the local timezone instead of UTC, properly taking daylight savings time into account. Optional argument usegmt means that the timezone is written out as an ascii string, not numeric one (so "GMT" instead of "+0000"). This is needed for HTTP, and is only used when localtime==False. iiit-t+s %s%02d%02di<tGMTs-0000s"%s, %02d %s %04d %02d:%02d:%02d %stMontTuetWedtThutFritSattSuniitJantFebtMartAprtMaytJuntJultAugtSeptOcttNovtDeciiiiN( tNonettimet localtimetdaylighttaltzonettimezonetdivmodtabstgmtime( ttimevalRCtusegmttnowtoffsetthourstminutestsigntzone((s#/usr/lib64/python2.7/email/utils.pyR|s.       !cCsyttjd}tj}tjd}|dkrFd}n d|}tj}d|||||f}|S(sReturns a string suitable for RFC 2822 compliant Message-ID, e.g: <142480216486.20800.16526388040877946887@nightshade.la.mastaler.com> Optional idstring if given is a string used to strengthen the uniqueness of the message id. idi@Rt.s<%d.%d.%d%s@%s>N( tintRBtostgetpidtrandomt getrandbitsRAtsockettgetfqdn(tidstringRJtpidtrandinttidhosttmsgid((s#/usr/lib64/python2.7/email/utils.pyRs     cCs|s dSt|S(N(RAt _parsedate(tdata((s#/usr/lib64/python2.7/email/utils.pyR scCs|s dSt|S(N(RAt _parsedate_tz(R`((s#/usr/lib64/python2.7/email/utils.pyR scCs!t|j}|sdS|dS(s Parse addr into its constituent realname and email address parts. Return a tuple of realname and email address, unless the parse fails, in which case return a 2-tuple of ('', ''). Ri(RR(R&R'(taddrtaddrs((s#/usr/lib64/python2.7/email/utils.pyR scCst|dkr|jdrS|jdrS|dd!jddjddS|jdr|jdr|dd!Sn|S( sRemove quotes from a string.iRis\\s\s\"t(tlent startswithtendswithtreplace(tstr((s#/usr/lib64/python2.7/email/utils.pyR s #cCs5|jtd}t|dkr1dd|fS|S(s#Decode string according to RFC 2231iN(tsplittTICKRfRA(Rtparts((s#/usr/lib64/python2.7/email/utils.pyRs cCscddl}|j|dd}|dkr=|dkr=|S|dkrRd}nd|||fS(sEncode string according to RFC 2231. If neither charset nor language is given, then s is returned as-is. If charset is given but not language, the string is encoded using the empty string for language. iNtsafeRs%s'%s'%s(turllibR RA(RtcharsettlanguageRo((s#/usr/lib64/python2.7/email/utils.pyRs   s&^(?P\w+)\*((?P[0-9]+)\*?)?$c Cs|}g}i}|jd\}}|j||fx|r|jd\}}|jdrqt}nt}t|}tj|}|r|jdd\}}|dk rt |}n|j |gj|||fq>|j|dt |fq>W|rx|j D]\}}g}t} |jxB|D]:\}} }|rztj| } t} n|j| qMWt tj|}| rt|\} } }|j|| | d|ffq$|j|d|fq$Wn|S(sDecode parameters list according to RFC 2231. params is a sequence of 2-tuples containing (param name, string value). it*R!tnums"%s"N(tpoptappendRhtTruetFalseR trfc2231_continuationtmatchtgroupRARSt setdefaultR titemstsortRot EMPTYSTRINGR%R( tparamst new_paramstrfc2231_paramsR!tvaluetencodedtmoRst continuationstextendedRRpRq((s#/usr/lib64/python2.7/email/utils.pyR sD    %!  #Risus-asciicCsut|trgt|d}|dp,d}yt|||SWqqtk rct|||SXn t|SdS(Niisus-ascii(t isinstancettupleR tunicodet LookupError(Rterrorstfallback_charsettrawvalRp((s#/usr/lib64/python2.7/email/utils.pyR>s (4t__doc__t__all__RTRRBRRVRXRotwarningstemail._parseaddrR RR&RR R_R RatquopriRt_qdecodetemail.encodersRRR$R~t UEMPTYSTRINGRRltcompileRRRRRRRtVERBOSEt IGNORECASEtecreRARwRRR R RRRxRR(((s#/usr/lib64/python2.7/email/utils.pytsl            5      5message.pyc000064400000070004152531624710006714 0ustar00 {fc@sdZdgZddlZddlZddlZddlZddlmZddlZ ddl m Z ddl m Z dZ ej dZd Zded Zd Zd Zddd YZdS(s8Basic message object for the email package object model.tMessageiN(tStringIO(tutils(terrorss; s[ \(\)<>@,;:\\"/\[\]\?=]cCsD|jd\}}}|s.|jdfS|j|jfS(Nt;(t partitiontstriptNone(tparamtatseptb((s%/usr/lib64/python2.7/email/message.pyt _splitparamscCs|dk rt|dkrt|tr[|d7}tj|d|d|d}n|sptj|rd|tj|fSd||fSn|SdS(sConvenience function to format and return a key=value pair. This will quote the value if needed or if quote is true. If value is a three tuple (charset, language, value), it will be encoded according to RFC2231 rules. it*iis%s="%s"s%s=%sN( Rtlent isinstancettupleRtencode_rfc2231t tspecialstsearchtquote(RtvalueR((s%/usr/lib64/python2.7/email/message.pyt _formatparam&s $cCsg}x|d dkr|d}|jd}xR|dkr|jdd||jdd|dr|jd|d}q5W|dkrt|}n|| }d|kr|jd}|| jjd||dj}n|j|j||}q W|S(NiRit"s\"it=(tfindtcountRtindexRtlowertappend(tstplisttendtfti((s%/usr/lib64/python2.7/email/message.pyt _parseparam>s ;   /cCsBt|tr1|d|dtj|dfStj|SdS(Niii(RRRtunquote(R((s%/usr/lib64/python2.7/email/message.pyt _unquotevaluePs"cBseZdZdZdZedZdZdZdZ dZ d.edZ d.d Z d Zd Zd Zd ZdZdZdZdZdZdZdZd.dZd.dZdZdZdZdZdZdZ dZ!dZ"d.de#d Z$d.de#d!Z%d"e#d.d#d$Z&de#d%Z'd"e#d&Z(d.d'Z)d.d(Z*d)Z+d.d*Z,d.d+Z-d,d-l.m/Z/RS(/sBasic message object. A message object is defined as something that has a bunch of RFC 2822 headers and a payload. It may optionally have an envelope header (a.k.a. Unix-From or From_ header). If the message is a container (i.e. a multipart or a message/rfc822), then the payload is a list of Message objects, otherwise it is a string. Message objects implement part of the `mapping' interface, which assumes there is exactly one occurrence of the header per message. Some headers do in fact appear multiple times (e.g. Received) and for those headers, you must use the explicit API to set or get all the headers. Not all of the mapping methods are implemented. cCsJg|_d|_d|_d|_d|_|_g|_d|_dS(Ns text/plain( t_headersRt _unixfromt_payloadt_charsettpreambletepiloguetdefectst _default_type(tself((s%/usr/lib64/python2.7/email/message.pyt__init__ks     cCs|jdtS(swReturn the entire formatted message as a string. This includes the headers, body, and envelope header. tunixfrom(t as_stringtTrue(R.((s%/usr/lib64/python2.7/email/message.pyt__str__vscCsBddlm}t}||}|j|d||jS(sReturn the entire formatted message as a string. Optional `unixfrom' when True, means include the Unix From_ envelope header. This is a convenience method and may not generate the message exactly as you intend because by default it mangles lines that begin with "From ". For more flexibility, use the flatten() method of a Generator instance. i(t GeneratorR0(temail.generatorR4Rtflattentgetvalue(R.R0R4tfptg((s%/usr/lib64/python2.7/email/message.pyR1|s   cCst|jtS(s6Return True if the message consists of multiple parts.(RR(tlist(R.((s%/usr/lib64/python2.7/email/message.pyt is_multipartscCs ||_dS(N(R'(R.R0((s%/usr/lib64/python2.7/email/message.pyt set_unixfromscCs|jS(N(R'(R.((s%/usr/lib64/python2.7/email/message.pyt get_unixfromscCs2|jdkr|g|_n|jj|dS(sAdd the given payload to the current payload. The current payload will always be a list of objects after this method is called. If you want to set the payload to a scalar object, use set_payload() instead. N(R(RR(R.tpayload((s%/usr/lib64/python2.7/email/message.pytattachscCs9|d kr|j}n;t|jtsFtdt|jn |j|}|r5|jrid S|jddj}|dkrt j |S|dkryt j |SWq2t j k r|SXq5|d kr5t}y0tjt|d |d t|j}Wq2tj k r.|SXq5n|S(sZReturn a reference to the payload. The payload will either be a list object or a string. If you mutate the list object, you modify the message's payload in place. Optional i returns that index into the payload. Optional decode is a flag indicating whether the payload should be decoded or not, according to the Content-Transfer-Encoding header (default is False). When True and the message is not a multipart, the payload will be decoded if this header's value is `quoted-printable' or `base64'. If some other encoding is used, or the header is missing, or if the payload has bogus data (i.e. bogus base64 or uuencoded data), the payload is returned as-is. If the message is a multipart and the decode flag is True, then None is returned. sExpected list, got %sscontent-transfer-encodingtsquoted-printabletbase64s x-uuencodetuuencodetuuesx-uues tquietN(s x-uuencodeRBRCsx-uue(RR(RR:t TypeErrorttypeR;tgetRRt_qdecodet_bdecodetbinasciitErrorRtuutdecodeR2R7(R.R"RMR>tctetsfp((s%/usr/lib64/python2.7/email/message.pyt get_payloads0           cCs)||_|dk r%|j|ndS(sSet the payload to the given value. Optional charset sets the message's default character set. See set_charset() for details. N(R(Rt set_charset(R.R>tcharset((s%/usr/lib64/python2.7/email/message.pyt set_payloads  cCs|dkr&|jdd|_dSt|trJtjj|}nt|tjjsnt|n||_d|kr|j ddnd|kr|j ddd|j n|j d|j t|j t r|j j|j|_ nt||j kr4|j|j |_ nd|kr|j}y||Wqtk r|j|j |_ |j d|qXndS(sSet the charset of the payload to a given character set. charset can be a Charset instance, a string naming a character set, or None. If it is a string it will be converted to a Charset instance. If charset is None, the charset parameter will be removed from the Content-Type field. Anything else will generate a TypeError. The message will be assumed to be of type text/* encoded with charset.input_charset. It will be converted to charset.output_charset and encoded properly, if needed, when generating the plain text representation of the message. MIME headers (MIME-Version, Content-Type, Content-Transfer-Encoding) will be added as needed. RRNs MIME-Versions1.0s Content-Types text/plainsContent-Transfer-Encoding(Rt del_paramR)Rt basestringtemailRRtCharsetREt add_headertget_output_charsett set_paramR(tunicodetencodetoutput_charsettstrt body_encodetget_body_encoding(R.RRRN((s%/usr/lib64/python2.7/email/message.pyRQs4         cCs|jS(sKReturn the Charset instance associated with the message's payload. (R)(R.((s%/usr/lib64/python2.7/email/message.pyt get_charsetscCs t|jS(s9Return the total number of headers, including duplicates.(RR&(R.((s%/usr/lib64/python2.7/email/message.pyt__len__scCs |j|S(s-Get a header value. Return None if the header is missing instead of raising an exception. Note that if the header appeared multiple times, exactly which occurrence gets returned is undefined. Use get_all() to get all the values matching a header field name. (RG(R.tname((s%/usr/lib64/python2.7/email/message.pyt __getitem__s cCs|jj||fdS(sSet the value of a header. Note: this does not overwrite an existing header with the same field name. Use __delitem__() first to delete any existing headers. N(R&R(R.Rctval((s%/usr/lib64/python2.7/email/message.pyt __setitem__(scCsa|j}g}x?|jD]4\}}|j|kr|j||fqqW||_dS(swDelete all occurrences of a header, if present. Does not raise an exception if the header is missing. N(RR&R(R.Rct newheaderstktv((s%/usr/lib64/python2.7/email/message.pyt __delitem__0s  cCs2|jg|jD]\}}|j^qkS(N(RR&(R.RcRhRi((s%/usr/lib64/python2.7/email/message.pyt __contains__<scCst}|j|||k S(s/Return true if the message contains the header.(tobjectRG(R.Rctmissing((s%/usr/lib64/python2.7/email/message.pythas_key?s cCs g|jD]\}}|^q S(s.Return a list of all the message's header field names. These will be sorted in the order they appeared in the original message, or were added to the message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. (R&(R.RhRi((s%/usr/lib64/python2.7/email/message.pytkeysDscCs g|jD]\}}|^q S(s)Return a list of all the message's header values. These will be sorted in the order they appeared in the original message, or were added to the message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. (R&(R.RhRi((s%/usr/lib64/python2.7/email/message.pytvaluesNscCs|jS(s'Get all the message's header fields and values. These will be sorted in the order they appeared in the original message, or were added to the message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. (R&(R.((s%/usr/lib64/python2.7/email/message.pytitemsXscCs@|j}x-|jD]"\}}|j|kr|SqW|S(s~Get a header value. Like __getitem__() but return failobj instead of None when the field is missing. (RR&(R.RctfailobjRhRi((s%/usr/lib64/python2.7/email/message.pyRGbs  cCs\g}|j}x9|jD].\}}|j|kr|j|qqW|sX|S|S(sQReturn a list of all the values for the named field. These will be sorted in the order they appeared in the original message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. If no such fields exist, failobj is returned (defaults to None). (RR&R(R.RcRrRpRhRi((s%/usr/lib64/python2.7/email/message.pytget_allrs  cKsg}xd|jD]V\}}|dkrG|j|jddq|jt|jdd|qW|dk r|jd|n|jj|tj|fdS(sExtended header setting. name is the header field to add. keyword arguments can be used to set additional parameters for the header field, with underscores converted to dashes. Normally the parameter will be added as key="value" unless value is None, in which case only the key will be added. If a parameter value contains non-ASCII characters it must be specified as a three-tuple of (charset, language, value), in which case it will be encoded according to RFC2231 rules. Example: msg.add_header('content-disposition', 'attachment', filename='bud.gif') t_t-iN( RqRRtreplaceRtinsertR&t SEMISPACEtjoin(R.t_namet_valuet_paramstpartsRhRi((s%/usr/lib64/python2.7/email/message.pyRXs & cCs}|j}xjttt|j|jD];\}\}}|j|kr.||f|j|Remove the given parameter completely from the Content-Type header. The header will be re-written in place without the parameter or its value. All values will be quoted as necessary unless requote is False. Optional header specifies an alternative to the Content-Type header. NR@RR$(RRRRxRyRG(R.RRRt new_ctypeRRi((s%/usr/lib64/python2.7/email/message.pyRTks % cCs|jddkstn|jdkrD|d=d|dt}|jd|}||kr+|Stj|jS(sReturn the boundary associated with the payload if present. The boundary is extracted from the Content-Type header's `boundary' parameter, and it is unquoted. tboundary(RlRRRtrstrip(R.RrRmR((s%/usr/lib64/python2.7/email/message.pyt get_boundarys   c Cst}|j|d}||kr9tjdng}t}xY|D]Q\}}|jdkr|jdd|ft}qL|j||fqLW|s|jdd|fng}x|jD]\} } | jdkr^g} xG|D]?\} } | dkr$| j| q| jd| | fqW|j| t j | fq|j| | fqW||_dS(sSet the boundary parameter in Content-Type to 'boundary'. This is subtly different than deleting the Content-Type header and adding a new one with a new boundary parameter via add_header(). The main difference is that using the set_boundary() method preserves the order of the Content-Type header in the original message. HeaderParseError is raised if the message has no Content-Type header. s content-typesNo Content-Type header foundRs"%s"R@s%s=%sN( RlRRtHeaderParseErrortFalseRRR2R&RxRy( R.RRmRt newparamstfoundptpktpvRgthRiR}Rh((s%/usr/lib64/python2.7/email/message.pyt set_boundarys0    cCst}|jd|}||kr+|St|tr|dpGd}y t|d|jd}Wqttfk r|d}qXny4t|trt|d}n|jd}Wntk r|SX|j S(sReturn the charset parameter of the Content-Type header. The returned string is always coerced to lower case. If there is no Content-Type header, or if that header has no charset parameter, failobj is returned. RRisus-asciii( RlRRRR[R\t LookupErrort UnicodeErrorR^R(R.RrRmRRtpcharset((s%/usr/lib64/python2.7/email/message.pytget_content_charsets"    cCs&g|jD]}|j|^q S(sReturn a list containing the charset(s) used in this message. The returned list of items describes the Content-Type headers' charset parameter for this message and all the subparts in its payload. Each item will either be a string (the value of the charset parameter in the Content-Type header of that part) or the value of the 'failobj' parameter (defaults to None), if the part does not have a main MIME type of "text", or the charset is not defined. The list will contain one string for each part of the message, plus one for the container message (i.e. self), so that a non-multipart message will still return a list of length 1. (twalkR(R.Rrtpart((s%/usr/lib64/python2.7/email/message.pyt get_charsets si(RN(0t__name__t __module__t__doc__R/R3RR1R;R<R=R?RRPRSRQRaRbRdRfRjRkRnRoRpRqRGRsRXRRRRRRRR2RRRZRTRRRRRRtemail.iteratorsR(((s%/usr/lib64/python2.7/email/message.pyR\sX      2 -            #/  -  ((Rt__all__treRLRJtwarningst cStringIORt email.charsetRVRRRxtcompileRR RR2RR#R%R(((s%/usr/lib64/python2.7/email/message.pyts          encoders.pyo000064400000004270152531624710007110 0ustar00 {fc@sndZddddgZddlZddlmZdZd Zd Zd Z d Z d Z dS(s Encodings and related functions.tencode_7or8bitt encode_base64t encode_noopt encode_quopriiN(t encodestringcCs"t|dt}|jddS(Nt quotetabst s=20(t _encodestringtTruetreplace(tstenc((s&/usr/lib64/python2.7/email/encoders.pyt_qencodescCsL|s |S|ddk}tj|}| rH|ddkrH|d S|S(Nis (tbase64R(R t hasnewlinetvalue((s&/usr/lib64/python2.7/email/encoders.pyt_bencodescCs3|j}t|}|j|d|ds    encoders.pyc000064400000004270152531624710007074 0ustar00 {fc@sndZddddgZddlZddlmZdZd Zd Zd Z d Z d Z dS(s Encodings and related functions.tencode_7or8bitt encode_base64t encode_noopt encode_quopriiN(t encodestringcCs"t|dt}|jddS(Nt quotetabst s=20(t _encodestringtTruetreplace(tstenc((s&/usr/lib64/python2.7/email/encoders.pyt_qencodescCsL|s |S|ddk}tj|}| rH|ddkrH|d S|S(Nis (tbase64R(R t hasnewlinetvalue((s&/usr/lib64/python2.7/email/encoders.pyt_bencodescCs3|j}t|}|j|d|ds    generator.pyo000064400000024214152531624710007274 0ustar00 {fc@sdZddgZddlZddlZddlZddlZddlZddlmZddl m Z dZ dZ ej d ejZd Zdfd YZd Zdefd YZeeejdZdeZedZdS(s:Classes to generate plain text from a message object tree.t GeneratortDecodedGeneratoriN(tStringIO(tHeadert_s s^From cCs<t|tr8yt|dWq8tk r4tSXntS(Nsus-ascii(t isinstancetstrtunicodet UnicodeErrortTruetFalse(ts((s'/usr/lib64/python2.7/email/generator.pyt _is8bitstrings  cBseZdZeddZdZedZdZdZ dZ dZ d Z e Z d Zd Zd Zd ZRS(sGenerates output from a Message object tree. This basic generator writes the message to the given file object as plain text. iNcCs||_||_||_dS(sCreate the generator for message flattening. outfp is the output file-like object for writing the message to. It must have a write() method. Optional mangle_from_ is a flag that, when True (the default), escapes From_ lines in the body of the message by putting a `>' in front of them. Optional maxheaderlen specifies the longest length for a non-continued header. When a header line is longer (in characters, with tabs expanded to 8 spaces) than maxheaderlen, the header will split as defined in the Header class. Set maxheaderlen to zero to disable header wrapping. The default is 78, as recommended (but not required) by RFC 2822. N(t_fpt _mangle_from_t _maxheaderlen(tselftoutfpt mangle_from_t maxheaderlen((s'/usr/lib64/python2.7/email/generator.pyt__init__*s  cCs|jj|dS(N(R twrite(RR ((s'/usr/lib64/python2.7/email/generator.pyR?scCsU|rD|j}|s4dtjtj}n|j|IJn|j|dS(sPrint the message object tree rooted at msg to the output file specified when the Generator instance was created. unixfrom is a flag that forces the printing of a Unix From_ delimiter before the first object in the message tree. If the original message has no From_ delimiter, a `standard' one is crafted. By default, this is False to inhibit the printing of any From_ delimiter. Note that for subobjects, no From_ line is printed. s From nobody N(t get_unixfromttimetctimeR t_write(Rtmsgtunixfromtufrom((s'/usr/lib64/python2.7/email/generator.pytflattenCs  cCs|j||j|jS(s1Clone this generator with the exact same options.(t __class__RR(Rtfp((s'/usr/lib64/python2.7/email/generator.pytcloneUscCs|j}z!t|_}|j|Wd||_Xt|dd}|dkre|j|n |||jj|jdS(Nt_write_headers(R Rt _dispatchtgetattrtNoneR!Rtgetvalue(RRtoldfptsfptmeth((s'/usr/lib64/python2.7/email/generator.pyR]s    cCs|j}|j}tj||fjdd}t|d|d}|dkr|jdd}t|d|d}|dkr|j}qn||dS(Nt-Rt_handle_(tget_content_maintypetget_content_subtypet UNDERSCOREtjointreplaceR#R$t _writeBody(RRtmaintsubtspecificR(tgeneric((s'/usr/lib64/python2.7/email/generator.pyR"xs  !  c Csx|jD]\}}|jd|I|jdkrI|j|IJq t|trn|j|jIJq t|r|j|IJq |jt|d|jd|jIJq W|jJdS(Ns%s:it maxlinelent header_name(titemsR RRRtencodeR (RRthtv((s'/usr/lib64/python2.7/email/generator.pyR!s  "cCsv|j}|dkrdSt|tsDtdt|n|jrbtjd|}n|j j |dS(Nsstring payload expected: %ss>From ( t get_payloadR$Rt basestringt TypeErrorttypeRtfcreR2R R(RRtpayload((s'/usr/lib64/python2.7/email/generator.pyt _handle_texts   c Cs g}|j}|dkr'g}n>t|trJ|jj|dSt|tse|g}nxL|D]D}t}|j|}|j |dt |j |j qlW|j }|stj|}t|}|j|n|jdk r:|jr!tjd|j} n |j} |j| IJn|jd|IJ|rm|jj|jdnx/|D]'} |jd|IJ|jj| qtW|jjd|dt|jdk r|jrtjd|j} n |j} |jj| ndS(NRs>From s--is --(R;R$RR<R RtlistRR RR tappendR%t get_boundarytNLR.t_make_boundaryt set_boundarytpreambleRR?R2tpoptepilogue( RRtmsgtextstsubpartstpartR tgtboundarytalltextRHt body_partRJ((s'/usr/lib64/python2.7/email/generator.pyt_handle_multipartsH             cCs4|j}zd|_|j|Wd||_XdS(Ni(RRR(RRtold_maxheaderlen((s'/usr/lib64/python2.7/email/generator.pyt_handle_multipart_signeds   cCsg}x|jD]}t}|j|}|j|dt|j}|jd}|r|ddkr|jtj |d q|j|qW|j j tj |dS(NRs it( R;RR RR R%tsplitRCRER.R R(RRtblocksRMR RNttexttlines((s'/usr/lib64/python2.7/email/generator.pyt_handle_message_delivery_statuss  cCsrt}|j|}|j}t|tr^|j|jddt|j}n|jj |dS(NiR( RR R;RRBRR R%R R(RRR RNR@((s'/usr/lib64/python2.7/email/generator.pyt_handle_messages  (t__name__t __module__t__doc__R RRR RR RR"R!RAR0RRRTRZR[(((s'/usr/lib64/python2.7/email/generator.pyR s       9 sD[Non-text (%(type)s) part of message omitted, filename %(filename)s]cBs)eZdZedddZdZRS(sGenerates a text representation of a message. Like the Generator base class, except that non-text parts are substituted with a format string representing the part. iNcCs;tj|||||dkr.t|_n ||_dS(sLike Generator.__init__() except that an additional optional argument is allowed. Walks through all subparts of a message. If the subpart is of main type `text', then it prints the decoded payload of the subpart. Otherwise, fmt is a format string that is used instead of the message payload. fmt is expanded with the following keywords (in %(keyword)s format): type : Full MIME type of the non-text part maintype : Main MIME type of the non-text part subtype : Sub-MIME type of the non-text part filename : Filename of the non-text part description: Description associated with the non-text part encoding : Content transfer encoding of the non-text part The default value for fmt is None, meaning [Non-text (%(type)s) part of message omitted, filename %(filename)s] N(RRR$t_FMTt_fmt(RRRRtfmt((s'/usr/lib64/python2.7/email/generator.pyR.s  cCsx|jD]}|j}|dkrD||jdtIJq |dkrSq ||ji|jd6|jd6|jd6|jdd6|jd d d 6|jd d d6IJq WdS(NRXtdecodet multipartR>tmaintypetsubtypes [no filename]tfilenamesContent-Descriptions[no description]t descriptionsContent-Transfer-Encodings [no encoding]tencoding( twalkR+R;R R`tget_content_typeR,t get_filenametget(RRRMRd((s'/usr/lib64/python2.7/email/generator.pyR"Js          N(R\R]R^R R$RR"(((s'/usr/lib64/python2.7/email/generator.pyR(sis%%0%ddcCstjtj}d t|d}|dkr4|S|}d}xatrtjdtj |dtj }|j |sPn|dt |}|d7}qCW|S( Nt=is==is^--s(--)?$t.is===============( trandomt randrangetsystmaxintR`R$R tretcompiletescapet MULTILINEtsearchR(RXttokenROtbtcountertcre((s'/usr/lib64/python2.7/email/generator.pyRFds  &(R^t__all__RsRqRRotwarningst cStringIORt email.headerRR-RERtRvR?R RR_RtlentreprRrt_widthR`R$RF(((s'/usr/lib64/python2.7/email/generator.pyts&       9 base64mime.pyc000064400000012313152531624710007223 0ustar00 {fc@sdZddddddddgZd d lmZmZd d lmZd Zd ZdZ dZ dZ de dedZ ededZeZeZddZeZeZdS(sBase64 content transfer encoding per RFCs 2045-2047. This module handles the content transfer encoding method defined in RFC 2045 to encode arbitrary 8-bit data using the three 8-bit bytes in four 7-bit characters encoding known as Base64. It is used in the MIME standards for email to attach images, audio, and text using some 8-bit character sets to messages. This module provides an interface to encode and decode both headers and bodies with Base64 encoding. RFC 2045 defines a method for including character set information in an `encoded-word' in a header. This method is commonly used for 8-bit real names in To:, From:, Cc:, etc. fields, as well as Subject: lines. This module does not do the line wrapping or end-of-line character conversion necessary for proper internationalized headers; it only does dumb encoding and decoding. To deal with the various line wrapping issues, use the email.header module. t base64_lent body_decodet body_encodetdecodet decodestringtencodet encodestringt header_encodei(t b2a_base64t a2b_base64(tfix_eolss s ticCs<tt|d\}}|d}|r8|d7}n|S(s6Return the length of s when it is encoded with base64.ii(tdivmodtlen(tst groups_of_3tleftovertn((s(/usr/lib64/python2.7/email/base64mime.pyR4s   s iso-8859-1iLc Cs|s |S|st|}ng}|t|t}|dd}x>tdt||D]$}|jt||||!q`Wg} xA|D]9} | jtr| d } n| jd|| fqW|d} | j| S(s0Encode a single header line with Base64 encoding in a given charset. Defined in RFC 2045, this Base64 encoding is identical to normal Base64 encoding, except that each line must be intelligently wrapped (respecting the Base64 encoding), and subsequent lines must start with a space. charset names the character set to use to encode the header. It defaults to iso-8859-1. End-of-line characters (\r, \n, \r\n) will be automatically converted to the canonical email line separator \r\n unless the keep_eols parameter is True (the default is False). Each line of the header will be terminated in the value of eol, which defaults to "\n". Set this to "\r\n" if you are using the result of this function directly in email. The resulting string will be in the form: "=?charset?b?WW/5ciBtYXp66XLrIHf8eiBhIGhhbXBzdGHuciBBIFlv+XIgbWF6euly?=\n =?charset?b?6yB3/HogYSBoYW1wc3Rh7nIgQkMgWW/5ciBtYXp66XLrIHf8eiBhIGhh?=" with each line wrapped at, at most, maxlinelen characters (defaults to 76 characters). iiiis =?%s?b?%s?=t ( R R tMISC_LENtrangetappendRtendswithtNLtjoin( theadertcharsett keep_eolst maxlinelenteoltbase64edt max_encodedt max_unencodedtitlinestlinetjoiner((s(/usr/lib64/python2.7/email/base64mime.pyR@s "   cCs|s |S|st|}ng}|dd}xptdt||D]V}t||||!}|jtr|tkr|d |}n|j|qLWtj|S(sEncode a string with base64. Each line will be wrapped at, at most, maxlinelen characters (defaults to 76 characters). If binary is False, end-of-line characters will be converted to the canonical email end-of-line sequence \r\n. Otherwise they will be left verbatim (this is the default). Each line of encoded text will end with eol, which defaults to "\n". Set this to "\r\n" if you will be using the result of this function directly in an email. iiii( R RR RRRRt EMPTYSTRINGR(RtbinaryRRtencvecR R!tenc((s(/usr/lib64/python2.7/email/base64mime.pyRzscCs0|s |St|}|r,|jt|S|S(sDecode a raw base64 string. If convert_eols is set to a string value, all canonical email linefeeds, e.g. "\r\n", in the decoded text will be converted to the value of convert_eols. os.linesep is a good choice for convert_eols if you are decoding a text attachment. This function does not parse a full MIME header value encoded with base64 (like =?iso-8859-1?b?bmloISBuaWgh?=) -- please use the high level email.header class for that functionality. (R treplacetCRLF(Rt convert_eolstdec((s(/usr/lib64/python2.7/email/base64mime.pyRs  N(t__doc__t__all__tbinasciiRR t email.utilsR R*RR%RRtFalseRtTrueRRRtNoneRRR(((s(/usr/lib64/python2.7/email/base64mime.pyts.  9! __init__.pyo000064400000005470152531624710007050 0ustar00 {fc @sdZdZdddddddd d d d d ddddddddddddddddddd d!g Zd"Zd#Zd$d%lZd&efd'YZdddd(dddd ddddg Zd)d*d+d d,d-d.gZ xHeD]@Z ee j Z e ej d/e s        feedparser.pyc000064400000025607152531624710007421 0ustar00 {fc@sdZdgZddlZddlmZddlmZejdZejdZejdZ ejdZ ejd Z d Z d Z eZd efd YZdddYZdS(sFeedParser - An email feed parser. The feed parser implements an interface for incrementally parsing an email message, line by line. This has advantages for certain applications, such as those reading email messages off a socket. FeedParser.feed() is the primary interface for pushing new data into the parser. It returns when there's nothing more it can do with the available data. When you have no more data to push into the parser, call .close(). This completes the parsing and returns the root message object. The other advantage of this parser is that it will never raise a parsing exception. Instead, when it finds something unexpected, it adds a 'defect' to the current message. Defects are just instances that live on the message object's .defects attribute. t FeedParseriN(terrors(tmessages | | s( | | )s ( | | )\Zs(^(From |[\041-\071\073-\176]{1,}:|[\t ])ts tBufferedSubFilecBsqeZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z RS( skA file-ish object that can have new data loaded into it. You can also push and pop line-matching predicates onto a stack. When the current predicate matches the current line, a false EOF response (i.e. empty string) is returned instead. This lets the parser adhere to a simple abstraction -- it parses until EOF closes the current message. cCs(g|_g|_g|_t|_dS(N(t_partialt_linest _eofstacktFalset_closed(tself((s(/usr/lib64/python2.7/email/feedparser.pyt__init__3s   cCs|jj|dS(N(Rtappend(R tpred((s(/usr/lib64/python2.7/email/feedparser.pytpush_eof_matcher=scCs |jjS(N(Rtpop(R ((s(/usr/lib64/python2.7/email/feedparser.pytpop_eof_matcher@scCs8|jdj|jjtg|_t|_dS(NR(t pushlinestjoinRt splitlinestTrueR (R ((s(/usr/lib64/python2.7/email/feedparser.pytcloseCs" cCsn|js|jrdStS|jj}x>|jdddD]&}||r@|jj|dSq@W|S(NRi(RR t NeedMoreDataRRR (R tlinetateof((s(/usr/lib64/python2.7/email/feedparser.pytreadlineIs   cCs&|tk st|jj|dS(N(RtAssertionErrorRR (R R((s(/usr/lib64/python2.7/email/feedparser.pyt unreadline[scCs|jt}| s*|djd r=|j|7_dS|jr|jj|ddj|jjt|dd+|j2n|djds|jg|_n|j|dS( s$Push some new data into this object.is s NRii(s s (RRtendswithRR RRR(R tdatatparts((s(/usr/lib64/python2.7/email/feedparser.pytpush`s " cCs|ddd|jd*dS(Nii(R(R tlines((s(/usr/lib64/python2.7/email/feedparser.pyRxscCs|jS(N(R (R ((s(/usr/lib64/python2.7/email/feedparser.pyt is_closed|scCs|S(N((R ((s(/usr/lib64/python2.7/email/feedparser.pyt__iter__scCs%|j}|dkr!tn|S(NR(Rt StopIteration(R R((s(/usr/lib64/python2.7/email/feedparser.pytnexts   (t__name__t __module__t__doc__R RRRRRRRR!R"R$(((s(/usr/lib64/python2.7/email/feedparser.pyR+s         cBseeZdZejdZdZdZdZdZ dZ dZ dZ d Z RS( sA feed-style parser of email.cCsO||_t|_g|_|jj|_d|_d|_ t |_ dS(s@_factory is called with no arguments to create a new message objN( t_factoryRt_inputt _msgstackt _parsegenR$t_parsetNonet_curt_lastRt _headersonly(R R(((s(/usr/lib64/python2.7/email/feedparser.pyR s     cCs t|_dS(N(RR0(R ((s(/usr/lib64/python2.7/email/feedparser.pyt_set_headersonlyscCs|jj||jdS(sPush more data into the parser.N(R)Rt _call_parse(R R((s(/usr/lib64/python2.7/email/feedparser.pytfeedscCs&y|jWntk r!nXdS(N(R,R#(R ((s(/usr/lib64/python2.7/email/feedparser.pyR2s cCso|jj|j|j}|j s3t|jdkrk|j rk|jj t j n|S(s<Parse all remaining data and return the root message object.t multipart( R)RR2t _pop_messageR*Rtget_content_maintypet is_multiparttdefectsR Rt!MultipartInvariantViolationDefect(R troot((s(/usr/lib64/python2.7/email/feedparser.pyRs    cCs|j}|jr:|jjdkr:|jdn|jrZ|jdj|n|jj|||_||_dS(Nsmultipart/digestsmessage/rfc822i(R(R.tget_content_typetset_default_typeR*tattachR R/(R tmsg((s(/usr/lib64/python2.7/email/feedparser.pyt _new_messages   cCs8|jj}|jr+|jd|_n d|_|S(Ni(R*RR.R-(R tretval((s(/usr/lib64/python2.7/email/feedparser.pyR5s   ccs|jg}xj|jD]_}|tkr7tVqntj|sltj|sh|jj|nPn|j|qW|j||j rg}xMt r|jj }|tkrtVqn|dkrPn|j|qW|j j tj|dS|j jdkrxt r |jjtjx,|jD]}|tkratVqDnPqDW|j}|jjx1t r|jj }|tkrtVqnPqWx1t r|jj }|tkrtVqnPqW|dkrPn|jj|qWdS|j jdkrax,|jD]}|tkrNtVq1nPq1W|jdS|j jdkr:|j j}|dkr|j jjtjg}x5|jD]*}|tkrtVqn|j|qW|j j tj|dSd|}tjdtj|d}t } g} t} xt r|jj }|tkrptVqDn|dkrPn|j|} | r| jdr| jd } Pn| r7| r| d } t j!| }|r| t"|jd  | d s4)(?P--)?(?P[ \t]*)(?P\r\n|\r|\n)?$tendtlinesepii(,R?R)RtheaderREtmatchtNLCRERR t_parse_headersR0RRR.t set_payloadt EMPTYSTRINGRR;RR+R5RR6t get_boundaryR-R8RtNoBoundaryInMultipartDefecttretcompiletescapeRtgroupt NLCRE_eoltsearchtlentpreambleR/tepiloguet get_payloadt isinstancet basestringRtStartBoundaryNotFoundDefectt NLCRE_bol(R theadersRR R@R>tboundaryt separatort boundaryretcapturing_preambleRRRBtmotlastlineteolmoRSRAtpayloadt firstlinetbolmo((s(/usr/lib64/python2.7/email/feedparser.pyR+sL                          !              # c Csd}g}xt|D]\}}|ddkrv|sctj|}|jjj|qn|j|qn|rtj|d jd}||j|s   _errors.pyc000064400000006711152531624710006610 0ustar00 {fc@s(dZdefdYZdefdYZdefdYZdefdYZd eefd YZd efd YZd ddYZ de fdYZ de fdYZ de fdYZ de fdYZ de fdYZde fdYZdS(s email package exception classes.t MessageErrorcBseZdZRS(s+Base class for errors in the email package.(t__name__t __module__t__doc__(((s$/usr/lib64/python2.7/email/errors.pyR stMessageParseErrorcBseZdZRS(s&Base class for message parsing errors.(RRR(((s$/usr/lib64/python2.7/email/errors.pyR stHeaderParseErrorcBseZdZRS(sError while parsing headers.(RRR(((s$/usr/lib64/python2.7/email/errors.pyRst BoundaryErrorcBseZdZRS(s#Couldn't find terminating boundary.(RRR(((s$/usr/lib64/python2.7/email/errors.pyRstMultipartConversionErrorcBseZdZRS(s(Conversion to a multipart is prohibited.(RRR(((s$/usr/lib64/python2.7/email/errors.pyRst CharsetErrorcBseZdZRS(sAn illegal charset was given.(RRR(((s$/usr/lib64/python2.7/email/errors.pyRst MessageDefectcBseZdZddZRS(s Base class for a message defect.cCs ||_dS(N(tline(tselfR ((s$/usr/lib64/python2.7/email/errors.pyt__init__&sN(RRRtNoneR (((s$/usr/lib64/python2.7/email/errors.pyR #stNoBoundaryInMultipartDefectcBseZdZRS(sBA message claimed to be a multipart but had no boundary parameter.(RRR(((s$/usr/lib64/python2.7/email/errors.pyR)stStartBoundaryNotFoundDefectcBseZdZRS(s+The claimed start boundary was never found.(RRR(((s$/usr/lib64/python2.7/email/errors.pyR,st#FirstHeaderLineIsContinuationDefectcBseZdZRS(s;A message had a continuation line as its first header line.(RRR(((s$/usr/lib64/python2.7/email/errors.pyR/stMisplacedEnvelopeHeaderDefectcBseZdZRS(s?A 'Unix-from' header was found in the middle of a header block.(RRR(((s$/usr/lib64/python2.7/email/errors.pyR2stMalformedHeaderDefectcBseZdZRS(sDFound a header that was missing a colon, or was otherwise malformed.(RRR(((s$/usr/lib64/python2.7/email/errors.pyR5st!MultipartInvariantViolationDefectcBseZdZRS(s?A message claimed to be a multipart but no subparts were found.(RRR(((s$/usr/lib64/python2.7/email/errors.pyR8sN((Rt ExceptionRRRRt TypeErrorRRR RRRRRR(((s$/usr/lib64/python2.7/email/errors.pytsbase64mime.pyo000064400000012313152531624710007237 0ustar00 {fc@sdZddddddddgZd d lmZmZd d lmZd Zd ZdZ dZ dZ de dedZ ededZeZeZddZeZeZdS(sBase64 content transfer encoding per RFCs 2045-2047. This module handles the content transfer encoding method defined in RFC 2045 to encode arbitrary 8-bit data using the three 8-bit bytes in four 7-bit characters encoding known as Base64. It is used in the MIME standards for email to attach images, audio, and text using some 8-bit character sets to messages. This module provides an interface to encode and decode both headers and bodies with Base64 encoding. RFC 2045 defines a method for including character set information in an `encoded-word' in a header. This method is commonly used for 8-bit real names in To:, From:, Cc:, etc. fields, as well as Subject: lines. This module does not do the line wrapping or end-of-line character conversion necessary for proper internationalized headers; it only does dumb encoding and decoding. To deal with the various line wrapping issues, use the email.header module. t base64_lent body_decodet body_encodetdecodet decodestringtencodet encodestringt header_encodei(t b2a_base64t a2b_base64(tfix_eolss s ticCs<tt|d\}}|d}|r8|d7}n|S(s6Return the length of s when it is encoded with base64.ii(tdivmodtlen(tst groups_of_3tleftovertn((s(/usr/lib64/python2.7/email/base64mime.pyR4s   s iso-8859-1iLc Cs|s |S|st|}ng}|t|t}|dd}x>tdt||D]$}|jt||||!q`Wg} xA|D]9} | jtr| d } n| jd|| fqW|d} | j| S(s0Encode a single header line with Base64 encoding in a given charset. Defined in RFC 2045, this Base64 encoding is identical to normal Base64 encoding, except that each line must be intelligently wrapped (respecting the Base64 encoding), and subsequent lines must start with a space. charset names the character set to use to encode the header. It defaults to iso-8859-1. End-of-line characters (\r, \n, \r\n) will be automatically converted to the canonical email line separator \r\n unless the keep_eols parameter is True (the default is False). Each line of the header will be terminated in the value of eol, which defaults to "\n". Set this to "\r\n" if you are using the result of this function directly in email. The resulting string will be in the form: "=?charset?b?WW/5ciBtYXp66XLrIHf8eiBhIGhhbXBzdGHuciBBIFlv+XIgbWF6euly?=\n =?charset?b?6yB3/HogYSBoYW1wc3Rh7nIgQkMgWW/5ciBtYXp66XLrIHf8eiBhIGhh?=" with each line wrapped at, at most, maxlinelen characters (defaults to 76 characters). iiiis =?%s?b?%s?=t ( R R tMISC_LENtrangetappendRtendswithtNLtjoin( theadertcharsett keep_eolst maxlinelenteoltbase64edt max_encodedt max_unencodedtitlinestlinetjoiner((s(/usr/lib64/python2.7/email/base64mime.pyR@s "   cCs|s |S|st|}ng}|dd}xptdt||D]V}t||||!}|jtr|tkr|d |}n|j|qLWtj|S(sEncode a string with base64. Each line will be wrapped at, at most, maxlinelen characters (defaults to 76 characters). If binary is False, end-of-line characters will be converted to the canonical email end-of-line sequence \r\n. Otherwise they will be left verbatim (this is the default). Each line of encoded text will end with eol, which defaults to "\n". Set this to "\r\n" if you will be using the result of this function directly in an email. iiii( R RR RRRRt EMPTYSTRINGR(RtbinaryRRtencvecR R!tenc((s(/usr/lib64/python2.7/email/base64mime.pyRzscCs0|s |St|}|r,|jt|S|S(sDecode a raw base64 string. If convert_eols is set to a string value, all canonical email linefeeds, e.g. "\r\n", in the decoded text will be converted to the value of convert_eols. os.linesep is a good choice for convert_eols if you are decoding a text attachment. This function does not parse a full MIME header value encoded with base64 (like =?iso-8859-1?b?bmloISBuaWgh?=) -- please use the high level email.header class for that functionality. (R treplacetCRLF(Rt convert_eolstdec((s(/usr/lib64/python2.7/email/base64mime.pyRs  N(t__doc__t__all__tbinasciiRR t email.utilsR R*RR%RRtFalseRtTrueRRRtNoneRRR(((s(/usr/lib64/python2.7/email/base64mime.pyts.  9! utils.pyc000064400000022154152531624710006433 0ustar00 {fc @sdZddddddddd d d d d g ZddlZddlZddlZddlZddlZddlZddlZddl Z ddl m Z ddl m Z ddl mZddl mZddl mZddlmZddlmZmZdZdZdZdZdZejdZejdZ dZ!dZ"d Z#d!Z$d"Z%ejd#ej&ej'BZ(de*e*d$Z+dd%Z,d&Zd'Zd(Z-d)Z.d*Z/ddd+Z0ejd,Z1d-Z2d.d/d0Z3dS(1sMiscellaneous utilities.tcollapse_rfc2231_valuet decode_paramstdecode_rfc2231tencode_rfc2231t formataddrt formatdatet getaddressest make_msgidt mktime_tzt parseaddrt parsedatet parsedate_tztunquoteiN(tquote(t AddressList(R(R (R (t decodestring(t_bencodet_qencodes, tus t's[][\\()<>@,:;".]s [][\\()"]cCs|S(N((ts((s#/usr/lib64/python2.7/email/utils.pyt _identity:scCs|s |Stj|S(sDecodes a base64 string. This function is equivalent to base64.decodestring and it's retained only for backward compatibility. It used to remove the last \n of the decoded string, if it had any (see issue 7143). (tbase64R(R((s#/usr/lib64/python2.7/email/utils.pyt_bdecode>scCs.tjdt|}tjdt|}|S(s-Replace all line-ending characters with \r\n.s (?s %s%s%s <%s>(t specialsretsearcht escapesreR(tpairtnametaddresstquotes((s#/usr/lib64/python2.7/email/utils.pyRUs  cCs"tj|}t|}|jS(s7Return a list of (REALNAME, EMAIL) for each fieldvalue.(t COMMASPACEtjoint _AddressListt addresslist(t fieldvaluestallta((s#/usr/lib64/python2.7/email/utils.pyRhs s_ =\? # literal =? (?P[^?]*?) # non-greedy up to the next ? is the charset \? # literal ? (?P[qb]) # either a "q" or a "b", case insensitive \? # literal ? (?P.*?) # non-greedy up to the next ?= is the atom \?= # literal ?= c CsM|d$krtj}n|rtj|}tjrO|drOtj}n tj}tt|d\}}|dkrd}nd}d|||df}n$tj|}|rd}nd }d d d d ddddg|d|dddddddddddddg |d d |d|d!|d"|d#|fS(%sReturns a date string as specified by RFC 2822, e.g.: Fri, 09 Nov 2001 01:08:47 -0000 Optional timeval if given is a floating point time value as accepted by gmtime() and localtime(), otherwise the current time is used. Optional localtime is a flag that when True, interprets timeval, and returns a date relative to the local timezone instead of UTC, properly taking daylight savings time into account. Optional argument usegmt means that the timezone is written out as an ascii string, not numeric one (so "GMT" instead of "+0000"). This is needed for HTTP, and is only used when localtime==False. iiit-t+s %s%02d%02di<tGMTs-0000s"%s, %02d %s %04d %02d:%02d:%02d %stMontTuetWedtThutFritSattSuniitJantFebtMartAprtMaytJuntJultAugtSeptOcttNovtDeciiiiN( tNonettimet localtimetdaylighttaltzonettimezonetdivmodtabstgmtime( ttimevalRCtusegmttnowtoffsetthourstminutestsigntzone((s#/usr/lib64/python2.7/email/utils.pyR|s.       !cCsyttjd}tj}tjd}|dkrFd}n d|}tj}d|||||f}|S(sReturns a string suitable for RFC 2822 compliant Message-ID, e.g: <142480216486.20800.16526388040877946887@nightshade.la.mastaler.com> Optional idstring if given is a string used to strengthen the uniqueness of the message id. idi@Rt.s<%d.%d.%d%s@%s>N( tintRBtostgetpidtrandomt getrandbitsRAtsockettgetfqdn(tidstringRJtpidtrandinttidhosttmsgid((s#/usr/lib64/python2.7/email/utils.pyRs     cCs|s dSt|S(N(RAt _parsedate(tdata((s#/usr/lib64/python2.7/email/utils.pyR scCs|s dSt|S(N(RAt _parsedate_tz(R`((s#/usr/lib64/python2.7/email/utils.pyR scCs!t|j}|sdS|dS(s Parse addr into its constituent realname and email address parts. Return a tuple of realname and email address, unless the parse fails, in which case return a 2-tuple of ('', ''). Ri(RR(R&R'(taddrtaddrs((s#/usr/lib64/python2.7/email/utils.pyR scCst|dkr|jdrS|jdrS|dd!jddjddS|jdr|jdr|dd!Sn|S( sRemove quotes from a string.iRis\\s\s\"t(tlent startswithtendswithtreplace(tstr((s#/usr/lib64/python2.7/email/utils.pyR s #cCs5|jtd}t|dkr1dd|fS|S(s#Decode string according to RFC 2231iN(tsplittTICKRfRA(Rtparts((s#/usr/lib64/python2.7/email/utils.pyRs cCscddl}|j|dd}|dkr=|dkr=|S|dkrRd}nd|||fS(sEncode string according to RFC 2231. If neither charset nor language is given, then s is returned as-is. If charset is given but not language, the string is encoded using the empty string for language. iNtsafeRs%s'%s'%s(turllibR RA(RtcharsettlanguageRo((s#/usr/lib64/python2.7/email/utils.pyRs   s&^(?P\w+)\*((?P[0-9]+)\*?)?$c Cs|}g}i}|jd\}}|j||fx|r|jd\}}|jdrqt}nt}t|}tj|}|r|jdd\}}|dk rt |}n|j |gj|||fq>|j|dt |fq>W|rx|j D]\}}g}t} |jxB|D]:\}} }|rztj| } t} n|j| qMWt tj|}| rt|\} } }|j|| | d|ffq$|j|d|fq$Wn|S(sDecode parameters list according to RFC 2231. params is a sequence of 2-tuples containing (param name, string value). it*R!tnums"%s"N(tpoptappendRhtTruetFalseR trfc2231_continuationtmatchtgroupRARSt setdefaultR titemstsortRot EMPTYSTRINGR%R( tparamst new_paramstrfc2231_paramsR!tvaluetencodedtmoRst continuationstextendedRRpRq((s#/usr/lib64/python2.7/email/utils.pyR sD    %!  #Risus-asciicCsut|trgt|d}|dp,d}yt|||SWqqtk rct|||SXn t|SdS(Niisus-ascii(t isinstancettupleR tunicodet LookupError(Rterrorstfallback_charsettrawvalRp((s#/usr/lib64/python2.7/email/utils.pyR>s (4t__doc__t__all__RTRRBRRVRXRotwarningstemail._parseaddrR RR&RR R_R RatquopriRt_qdecodetemail.encodersRRR$R~t UEMPTYSTRINGRRltcompileRRRRRRRtVERBOSEt IGNORECASEtecreRARwRRR R RRRxRR(((s#/usr/lib64/python2.7/email/utils.pytsl            5      5_parseaddr.pyo000064400000033105152531624710007411 0ustar00 {fc@sddZddddgZddlZddlZdZdZd Zd d d d dddddddddddddddddddd gZd!d"d#d$d%d&d'gZid(d)6d(d*6d(d+6d(d,6d-d.6d/d06d1d26d-d36d4d56d1d66d7d86d4d96d:d;6d7d<6Z d=Z d>Z d?Z d@Z dAfdBYZdCefdDYZdS(EscEmail address parsing code. Lifted directly from rfc822.py. This should eventually be rewritten. t mktime_tzt parsedatet parsedate_tztquoteiNt ts, tjantfebtmartaprtmaytjuntjultaugtseptocttnovtdectjanuarytfebruarytmarchtapriltjunetjulytaugustt septembertoctobertnovembertdecembertmonttuetwedtthutfritsattsunitUTtUTCtGMTtZiptASTitADTi tESTtEDTitCSTtCDTiDtMSTtMDTitPSTtPDTc Cs|j}|djds5|djtkr?|d=n8|djd}|dkrw|d|d|ddS|d }|\}}}}}|j}|t kr||j}}|t krdSnt j |d}|d kr|d 8}n|d dkr|d }n|jd }|dkr||}}n|d dkr,|d }n|dj sL||}}n|d dkri|d }n|jd }t|d kr|\} } d} n(t|dkr|\} } } ndSy@t |}t |}t | } t | } t | } Wnt k rdSX|dkrN|dkrA|d7}qN|d7}nd} |j}|tkryt|} n$yt |} Wnt k rnX| r| dkrd } | } nd} | | dd| dd} n|||| | | ddd | f S(sQConvert a date string to a time tuple. Accounts for military timezones. it,iit-it+Rii it:it0idiDiliii<N(tsplittendswithtlowert _daynamestrfindtlentfindtappendtNonet _monthnamestindextisdigittintt ValueErrortuppert _timezones(tdatatitstufftstddtmmtyyttmttztthhttmmttssttzoffsetttzsign((s(/usr/lib64/python2.7/email/_parseaddr.pyR-s )                               !cCs+t|}t|tr#|d S|SdS(s&Convert a time string to a time tuple.i N(Rt isinstancettuple(RGtt((s(/usr/lib64/python2.7/email/_parseaddr.pyRs cCsD|ddkr%tj|d dStj|}||dSdS(sETurn a 10-tuple as returned by parsedate_tz() into a POSIX timestamp.i iiN(i(R?ttimetmktimetcalendarttimegm(RGRW((s(/usr/lib64/python2.7/email/_parseaddr.pyRscCs|jddjddS(sPrepare string to be used in a quoted string. Turns backslash and double quote characters into quoted pairs. These are the only characters that need to be quoted inside a quoted string. Does not add the surrounding double quotes. s\s\\t"s\"(treplace(tstr((s(/usr/lib64/python2.7/email/_parseaddr.pyRst AddrlistClasscBseZdZdZdZdZdZdZdZdZ e dZ d Z d Z d Zdd Zd ZRS(sAddress parser class by Ben Escoto. To understand what this class does, it helps to have a copy of RFC 2822 in front of you. Note: this class interface is deprecated and may be removed in the future. Use rfc822.AddressList instead. cCsd|_d|_d|_d|_|j|j|_|j|j|j|_|jjdd|_||_g|_ dS(sInitialize a new instance. `field' is an unparsed address header field, containing one or more addresses. s ()<>@,:;."[]is s t.RN( tspecialstpostLWStCRtFWStatomendsR]t phraseendstfieldt commentlist(tselfRh((s(/usr/lib64/python2.7/email/_parseaddr.pyt__init__s     cCsx{|jt|jkr}|j|j|jdkrJ|jd7_q|j|jdkry|jj|jqPqWdS(s*Parse up to the start of the next address.s it(N(RbR<RhRcRiR>t getcomment(Rj((s(/usr/lib64/python2.7/email/_parseaddr.pytgotonexts cCsUg}xH|jt|jkrP|j}|r@||7}q |jdq W|S(sVParse all addresses. Returns a list containing all of the addresses. R(RR(RbR<Rht getaddressR>(Rjtresulttad((s(/usr/lib64/python2.7/email/_parseaddr.pyt getaddrlists  cCsg|_|j|j}|j}|j}|jg}|jt|jkr|rPtj|j|dfg}qPn|j|jdkr||_||_|j}tj|j|fg}nz|j|jdkrg}t|j}|jd7_x=|jt|jkr|j|j|krm|j|jdkrm|jd7_Pn||j }qWn|j|jdkr|j }|jrtj|ddj|jd |fg}qPtj||fg}nS|r%tj|j|dfg}n+|j|j|j krP|jd7_n|j|jt|jkr|j|jd kr|jd7_n|S( sParse the next address.is.@R5it;tt@R5(RhRbtFalseRnR<t getdomaintTrueRy(Rjt expectroutetadlist((s(/usr/lib64/python2.7/email/_parseaddr.pyRzs.     cCs\g}|jx|jt|jkr|j|jdkr`|jd|jd7_nf|j|jdkr|jdt|jn0|j|j|jkrPn|j|j|jqW|jt|jks|j|jdkrt j |S|jd|jd7_|j|j }|sKt St j ||S(sParse an RFC 2822 addr-spec.R`iR\s"%s"R( RnRbR<RhR>RtgetquoteRftgetatomt EMPTYSTRINGRxR(Rjtaslisttdomain((s(/usr/lib64/python2.7/email/_parseaddr.pyRy<s*   .    cCs7g}x!|jt|jkr)|j|j|jkrL|jd7_q |j|jdkr{|jj|jq |j|jdkr|j|jq |j|jdkr|jd7_|jdq |j|jdkrtS|j|j|j krPq |j|j q Wtj |S(s-Get the complete domain name from an address.iRlt[R`R( RbR<RhRcRiR>RmtgetdomainliteralRRfRRx(Rjtsdlist((s(/usr/lib64/python2.7/email/_parseaddr.pyRZs"cCs-|j|j|krdSdg}t}|jd7_x|jt|jkr|ry|j|j|jt}n|j|j|kr|jd7_Pnk|r|j|jdkr|j|jq;n6|j|jdkrt}n|j|j|j|jd7_q;Wtj|S(sParse a header fragment delimited by special characters. `beginchar' is the start character for the fragment. If self is not looking at an instance of `beginchar' then getdelimited returns the empty string. `endchars' is a sequence of allowable end-delimiting characters. Parsing stops when one of these is encountered. If `allowcomments' is non-zero, embedded RFC 2822 comments are allowed within the parsed fragment. RiRls\( RhRbRR<R>RmRRRx(Rjt beginchartendcharst allowcommentstslistR((s(/usr/lib64/python2.7/email/_parseaddr.pyt getdelimitedqs(    cCs|jddtS(s1Get a quote-delimited fragment from self's field.R\s" (RR(Rj((s(/usr/lib64/python2.7/email/_parseaddr.pyRscCs|jddtS(s7Get a parenthesis-delimited fragment from self's field.Rls) (RR(Rj((s(/usr/lib64/python2.7/email/_parseaddr.pyRmscCsd|jddtS(s!Parse an RFC 2822 domain-literal.s[%s]Rs] (RR(Rj((s(/usr/lib64/python2.7/email/_parseaddr.pyRscCsdg}|dkr!|j}nx\|jt|jkr|j|j|krVPn|j|j|j|jd7_q$Wtj|S(sParse an RFC 2822 atom. Optional atomends specifies a different set of end token delimiters (the default is to use self.atomends). This is used e.g. in getphraselist() since phrase endings must not include the `.' (which is legal in phrases).RiN(R?RfRbR<RhR>RRx(RjRftatomlist((s(/usr/lib64/python2.7/email/_parseaddr.pyRs   cCsg}x|jt|jkr|j|j|jkrL|jd7_q |j|jdkrx|j|jq |j|jdkr|jj|jq |j|j|jkrPq |j|j |jq W|S(sParse a sequence of RFC 2822 phrases. A phrase is a sequence of words, which are in turn either RFC 2822 atoms or quoted-strings. Phrases are canonicalized by squeezing all runs of continuous whitespace into one space. iR\Rl( RbR<RhReR>RRiRmRgR(RjR}((s(/usr/lib64/python2.7/email/_parseaddr.pyRvsN(t__name__t __module__t__doc__RkRnRrRoRzRyRRRRRmRR?RRv(((s(/usr/lib64/python2.7/email/_parseaddr.pyR_s   ;   %    t AddressListcBsMeZdZdZdZdZdZdZdZdZ RS(s@An AddressList encapsulates a list of parsed RFC 2822 addresses.cCs5tj|||r(|j|_n g|_dS(N(R_RkRrt addresslist(RjRh((s(/usr/lib64/python2.7/email/_parseaddr.pyRkscCs t|jS(N(R<R(Rj((s(/usr/lib64/python2.7/email/_parseaddr.pyt__len__scCsStd}|j|_x3|jD](}||jkr#|jj|q#q#W|S(N(RR?RR>(Rjtothertnewaddrtx((s(/usr/lib64/python2.7/email/_parseaddr.pyt__add__s   cCs:x3|jD](}||jkr |jj|q q W|S(N(RR>(RjRR((s(/usr/lib64/python2.7/email/_parseaddr.pyt__iadd__scCsFtd}x3|jD](}||jkr|jj|qqW|S(N(RR?RR>(RjRRR((s(/usr/lib64/python2.7/email/_parseaddr.pyt__sub__s  cCs:x3|jD](}||jkr |jj|q q W|S(N(Rtremove(RjRR((s(/usr/lib64/python2.7/email/_parseaddr.pyt__isub__scCs |j|S(N(R(RjRA((s(/usr/lib64/python2.7/email/_parseaddr.pyt __getitem__s( RRRRkRRRRRR(((s(/usr/lib64/python2.7/email/_parseaddr.pyRs     (Rt__all__RXRZRwRt COMMASPACER@R:RFRRRRR_R(((s(/usr/lib64/python2.7/email/_parseaddr.pyts4  b "parser.pyo000064400000007364152531624710006611 0ustar00 {fc@s{dZddgZddlZddlmZddlmZddlmZdd dYZ de fd YZ dS( s-A parser of RFC 2822 and MIME email messages.tParsert HeaderParseriN(tStringIO(t FeedParser(tMessagecBs)eZdZedZedZRS(cOs t|dkr>d|kr-tdn|d|ds  Egenerator.pyc000064400000024214152531624710007260 0ustar00 {fc@sdZddgZddlZddlZddlZddlZddlZddlmZddl m Z dZ dZ ej d ejZd Zdfd YZd Zdefd YZeeejdZdeZedZdS(s:Classes to generate plain text from a message object tree.t GeneratortDecodedGeneratoriN(tStringIO(tHeadert_s s^From cCs<t|tr8yt|dWq8tk r4tSXntS(Nsus-ascii(t isinstancetstrtunicodet UnicodeErrortTruetFalse(ts((s'/usr/lib64/python2.7/email/generator.pyt _is8bitstrings  cBseZdZeddZdZedZdZdZ dZ dZ d Z e Z d Zd Zd Zd ZRS(sGenerates output from a Message object tree. This basic generator writes the message to the given file object as plain text. iNcCs||_||_||_dS(sCreate the generator for message flattening. outfp is the output file-like object for writing the message to. It must have a write() method. Optional mangle_from_ is a flag that, when True (the default), escapes From_ lines in the body of the message by putting a `>' in front of them. Optional maxheaderlen specifies the longest length for a non-continued header. When a header line is longer (in characters, with tabs expanded to 8 spaces) than maxheaderlen, the header will split as defined in the Header class. Set maxheaderlen to zero to disable header wrapping. The default is 78, as recommended (but not required) by RFC 2822. N(t_fpt _mangle_from_t _maxheaderlen(tselftoutfpt mangle_from_t maxheaderlen((s'/usr/lib64/python2.7/email/generator.pyt__init__*s  cCs|jj|dS(N(R twrite(RR ((s'/usr/lib64/python2.7/email/generator.pyR?scCsU|rD|j}|s4dtjtj}n|j|IJn|j|dS(sPrint the message object tree rooted at msg to the output file specified when the Generator instance was created. unixfrom is a flag that forces the printing of a Unix From_ delimiter before the first object in the message tree. If the original message has no From_ delimiter, a `standard' one is crafted. By default, this is False to inhibit the printing of any From_ delimiter. Note that for subobjects, no From_ line is printed. s From nobody N(t get_unixfromttimetctimeR t_write(Rtmsgtunixfromtufrom((s'/usr/lib64/python2.7/email/generator.pytflattenCs  cCs|j||j|jS(s1Clone this generator with the exact same options.(t __class__RR(Rtfp((s'/usr/lib64/python2.7/email/generator.pytcloneUscCs|j}z!t|_}|j|Wd||_Xt|dd}|dkre|j|n |||jj|jdS(Nt_write_headers(R Rt _dispatchtgetattrtNoneR!Rtgetvalue(RRtoldfptsfptmeth((s'/usr/lib64/python2.7/email/generator.pyR]s    cCs|j}|j}tj||fjdd}t|d|d}|dkr|jdd}t|d|d}|dkr|j}qn||dS(Nt-Rt_handle_(tget_content_maintypetget_content_subtypet UNDERSCOREtjointreplaceR#R$t _writeBody(RRtmaintsubtspecificR(tgeneric((s'/usr/lib64/python2.7/email/generator.pyR"xs  !  c Csx|jD]\}}|jd|I|jdkrI|j|IJq t|trn|j|jIJq t|r|j|IJq |jt|d|jd|jIJq W|jJdS(Ns%s:it maxlinelent header_name(titemsR RRRtencodeR (RRthtv((s'/usr/lib64/python2.7/email/generator.pyR!s  "cCsv|j}|dkrdSt|tsDtdt|n|jrbtjd|}n|j j |dS(Nsstring payload expected: %ss>From ( t get_payloadR$Rt basestringt TypeErrorttypeRtfcreR2R R(RRtpayload((s'/usr/lib64/python2.7/email/generator.pyt _handle_texts   c Cs g}|j}|dkr'g}n>t|trJ|jj|dSt|tse|g}nxL|D]D}t}|j|}|j |dt |j |j qlW|j }|stj|}t|}|j|n|jdk r:|jr!tjd|j} n |j} |j| IJn|jd|IJ|rm|jj|jdnx/|D]'} |jd|IJ|jj| qtW|jjd|dt|jdk r|jrtjd|j} n |j} |jj| ndS(NRs>From s--is --(R;R$RR<R RtlistRR RR tappendR%t get_boundarytNLR.t_make_boundaryt set_boundarytpreambleRR?R2tpoptepilogue( RRtmsgtextstsubpartstpartR tgtboundarytalltextRHt body_partRJ((s'/usr/lib64/python2.7/email/generator.pyt_handle_multipartsH             cCs4|j}zd|_|j|Wd||_XdS(Ni(RRR(RRtold_maxheaderlen((s'/usr/lib64/python2.7/email/generator.pyt_handle_multipart_signeds   cCsg}x|jD]}t}|j|}|j|dt|j}|jd}|r|ddkr|jtj |d q|j|qW|j j tj |dS(NRs it( R;RR RR R%tsplitRCRER.R R(RRtblocksRMR RNttexttlines((s'/usr/lib64/python2.7/email/generator.pyt_handle_message_delivery_statuss  cCsrt}|j|}|j}t|tr^|j|jddt|j}n|jj |dS(NiR( RR R;RRBRR R%R R(RRR RNR@((s'/usr/lib64/python2.7/email/generator.pyt_handle_messages  (t__name__t __module__t__doc__R RRR RR RR"R!RAR0RRRTRZR[(((s'/usr/lib64/python2.7/email/generator.pyR s       9 sD[Non-text (%(type)s) part of message omitted, filename %(filename)s]cBs)eZdZedddZdZRS(sGenerates a text representation of a message. Like the Generator base class, except that non-text parts are substituted with a format string representing the part. iNcCs;tj|||||dkr.t|_n ||_dS(sLike Generator.__init__() except that an additional optional argument is allowed. Walks through all subparts of a message. If the subpart is of main type `text', then it prints the decoded payload of the subpart. Otherwise, fmt is a format string that is used instead of the message payload. fmt is expanded with the following keywords (in %(keyword)s format): type : Full MIME type of the non-text part maintype : Main MIME type of the non-text part subtype : Sub-MIME type of the non-text part filename : Filename of the non-text part description: Description associated with the non-text part encoding : Content transfer encoding of the non-text part The default value for fmt is None, meaning [Non-text (%(type)s) part of message omitted, filename %(filename)s] N(RRR$t_FMTt_fmt(RRRRtfmt((s'/usr/lib64/python2.7/email/generator.pyR.s  cCsx|jD]}|j}|dkrD||jdtIJq |dkrSq ||ji|jd6|jd6|jd6|jdd6|jd d d 6|jd d d6IJq WdS(NRXtdecodet multipartR>tmaintypetsubtypes [no filename]tfilenamesContent-Descriptions[no description]t descriptionsContent-Transfer-Encodings [no encoding]tencoding( twalkR+R;R R`tget_content_typeR,t get_filenametget(RRRMRd((s'/usr/lib64/python2.7/email/generator.pyR"Js          N(R\R]R^R R$RR"(((s'/usr/lib64/python2.7/email/generator.pyR(sis%%0%ddcCstjtj}d t|d}|dkr4|S|}d}xatrtjdtj |dtj }|j |sPn|dt |}|d7}qCW|S( Nt=is==is^--s(--)?$t.is===============( trandomt randrangetsystmaxintR`R$R tretcompiletescapet MULTILINEtsearchR(RXttokenROtbtcountertcre((s'/usr/lib64/python2.7/email/generator.pyRFds  &(R^t__all__RsRqRRotwarningst cStringIORt email.headerRR-RERtRvR?R RR_RtlentreprRrt_widthR`R$RF(((s'/usr/lib64/python2.7/email/generator.pyts&       9 header.pyo000064400000032430152531624710006535 0ustar00 {fc@s6dZdddgZddlZddlZddlZddlZddlmZddl m Z dZ d Z d Z d d Zd Zd Ze dZe dZejdejejBejBZejdZejdZejjZdZeed dZdfdYZdZ dZ!dS(s+Header encoding and decoding functionality.tHeadert decode_headert make_headeriN(tHeaderParseError(tCharsets t u iuiLsus-asciisutf-8s =\? # literal =? (?P[^?]*?) # non-greedy up to the next ? is the charset \? # literal ? (?P[qb]) # either a "q" or a "b", case insensitive \? # literal ? (?P.*?) # non-greedy up to the next ?= is the encoded string \?= # literal ?= (?=[ \t]|$) # whitespace or the end of the string s[\041-\176]+:$s \n[^ \t]+:c CsGt|}tj|s(|d fgSg}d}x |jD]}tj|so|j|d fqAntj|}x|r>|jdj}|r|r|ddd kr|ddt |d f|dAppend a string to the MIME header. Optional charset, if given, should be a Charset instance or the name of a character set (which will be converted to a Charset instance). A value of None (the default) means that the charset given in the constructor is used. s may be a byte string or a Unicode string. If it is a byte string (i.e. isinstance(s, str) is true), then charset is the encoding of that byte string, and a UnicodeError will be raised if the string cannot be decoded with that charset. If s is a Unicode string, then charset is a hint specifying the character set of the characters in the string. In this case, when producing an RFC 2822 compliant header using RFC 2047 rules, the Unicode string will be encoded using the following charsets in order: us-ascii, the charset hint, utf-8. The first character set not to provoke a UnicodeError is used. Optional `errors' is passed as the third argument to any unicode() or ustr.encode() call. t8bitsus-asciiN(R R/R*RR t input_codecR>t output_codecR;R.tUTF8t UnicodeErrorR3R(R7R"R#R8tincodectustrtoutcodec((s$/usr/lib64/python2.7/email/header.pyRs(    cCs0|j|}|j|t}|j|}||krI||fgS|dkrb||fgS|dkr|j||||S|t|kr|}|j|| t} |j||t} nt|||\} } |j| } |j| t} | |fg} | |j| ||j |S(NRHsus-ascii( t to_splittabletfrom_splittabletTruetencoded_header_lent _split_asciiRtFalset _binsplitt_splitR6(R7R"R#R't splitcharst splittableR%telentsplitpnttfirsttlastt fsplittabletfencodedtchunk((s$/usr/lib64/python2.7/email/header.pyRW s$    cCs8t|||j|j|}t||gt|S(N(RTR6R0tzipR(R7R"R#tfirstlenRXtchunks((s$/usr/lib64/python2.7/email/header.pyRTNsc Csg}x|D]\}}|s%q n|dks@|jdkrI|}n|j|}|rz|djdrzd}nd}t||||q Wt|j}|j|S(NiRR(R theader_encodingt header_encodetendswitht _max_appendtNLR0R@( R7t newchunksR'RcRR#R"textratjoiner((s$/usr/lib64/python2.7/email/header.pyt_encode_chunksSs   s;, c Csg}|j}d}x~|jD]s\}}||d}||jdkrW|}n||j||||7}|d\}} | j|}qW|j||} tj| rtdj| n| S(sEncode a message header into an RFC-compliant format. There are many issues involved in converting a given string for use in an email header. Only certain character sets are readable in most email clients, and as header strings can only contain a subset of 7-bit ASCII, care must be taken to properly convert and encode (with Base64 or quoted-printable) header strings. In addition, there is a 75-character length limit on any given encoded header field, so line-wrapping must be performed, even with double-byte character sets. This method will do its best to convert the string to the correct character set used in email, and encode and line wrap it safely with the appropriate scheme for that character set. If the given charset is not known or an error occurs during conversion, this function will return the header untouched. Optional splitchars is a string containing characters to split long ASCII lines on, in rough support of RFC 2822's `highest level syntactic breaks'. This doesn't affect RFC 2047 encoded lines. iiRis8header value appears to contain an embedded header: {!r}( R5R3RSRWRlt_embeded_headerR Rtformat( R7RXRiR'tlastlenR"R#t targetlent lastchunkt lastcharsettvalue((s$/usr/lib64/python2.7/email/header.pyR;vs   N( t__name__t __module__R R:R<RDRFRGRRWRTRlR;(((s$/usr/lib64/python2.7/email/header.pyRs3    7 .  #cCs|g}|}xi|jD][}|j}t||krV|j||}qnx4|D]}||kr]Pq]q]W|j||}qtjd|} |dkr|} nd} | d} t| } t|jdt} g}d}x]| j|D]L}|t dt|d| }t|}| }|dkr|rt|dkrt j |dr|j|||7}q|||kr:|r|j| j || n||kr|dkrt ||||d}|j|d |dg}n |g}| t|d}|}q|j|||7}qW|r|j| j |qqW|S( Ns%s\s*s;,RRs iii(R tlstripRRtretcompileR1R2RtmaxtfcretmatchR@RTtextend(R"RbtrestlenR)RXtlinestmaxlenRtchtcreteolRktjoinlentwslentthistlinelentparttcurlentpartlent onfirstlinetsubl((s$/usr/lib64/python2.7/email/header.pyRTs^         ! %       c Csd}t|}xf||krz||dd?}|j|| t}|j|}||krm|}q|d}qW|j|| t}|j||t} || fS(Nii(RRQRRRSRU( RYR#R'titjtmR`tchunklenR\R]((s$/usr/lib64/python2.7/email/header.pyRVs    ("t__doc__t__all__RwRtemail.quoprimimeRtemail.base64mimet email.errorsRt email.charsetRRhRR=R2R?R4R.RKRxtVERBOSEt IGNORECASEt MULTILINER RzRmRRgRR RRRTRV(((s$/usr/lib64/python2.7/email/header.pyts:           <  Fparser.pyc000064400000007364152531624710006575 0ustar00 {fc@s{dZddgZddlZddlmZddlmZddlmZdd dYZ de fd YZ dS( s-A parser of RFC 2822 and MIME email messages.tParsert HeaderParseriN(tStringIO(t FeedParser(tMessagecBs)eZdZedZedZRS(cOs t|dkr>d|kr-tdn|d|ds  E