annotate CSP2/CSP2_env/env-d9b9114564458d9d-741b3de822f2aaca6c6caa4325c4afce/lib/python3.8/email/feedparser.py @ 69:33d812a61356

planemo upload commit 2e9511a184a1ca667c7be0c6321a36dc4e3d116d
author jpayne
date Tue, 18 Mar 2025 17:55:14 -0400
parents
children
rev   line source
jpayne@69 1 # Copyright (C) 2004-2006 Python Software Foundation
jpayne@69 2 # Authors: Baxter, Wouters and Warsaw
jpayne@69 3 # Contact: email-sig@python.org
jpayne@69 4
jpayne@69 5 """FeedParser - An email feed parser.
jpayne@69 6
jpayne@69 7 The feed parser implements an interface for incrementally parsing an email
jpayne@69 8 message, line by line. This has advantages for certain applications, such as
jpayne@69 9 those reading email messages off a socket.
jpayne@69 10
jpayne@69 11 FeedParser.feed() is the primary interface for pushing new data into the
jpayne@69 12 parser. It returns when there's nothing more it can do with the available
jpayne@69 13 data. When you have no more data to push into the parser, call .close().
jpayne@69 14 This completes the parsing and returns the root message object.
jpayne@69 15
jpayne@69 16 The other advantage of this parser is that it will never raise a parsing
jpayne@69 17 exception. Instead, when it finds something unexpected, it adds a 'defect' to
jpayne@69 18 the current message. Defects are just instances that live on the message
jpayne@69 19 object's .defects attribute.
jpayne@69 20 """
jpayne@69 21
jpayne@69 22 __all__ = ['FeedParser', 'BytesFeedParser']
jpayne@69 23
jpayne@69 24 import re
jpayne@69 25
jpayne@69 26 from email import errors
jpayne@69 27 from email._policybase import compat32
jpayne@69 28 from collections import deque
jpayne@69 29 from io import StringIO
jpayne@69 30
jpayne@69 31 NLCRE = re.compile(r'\r\n|\r|\n')
jpayne@69 32 NLCRE_bol = re.compile(r'(\r\n|\r|\n)')
jpayne@69 33 NLCRE_eol = re.compile(r'(\r\n|\r|\n)\Z')
jpayne@69 34 NLCRE_crack = re.compile(r'(\r\n|\r|\n)')
jpayne@69 35 # RFC 2822 $3.6.8 Optional fields. ftext is %d33-57 / %d59-126, Any character
jpayne@69 36 # except controls, SP, and ":".
jpayne@69 37 headerRE = re.compile(r'^(From |[\041-\071\073-\176]*:|[\t ])')
jpayne@69 38 EMPTYSTRING = ''
jpayne@69 39 NL = '\n'
jpayne@69 40
jpayne@69 41 NeedMoreData = object()
jpayne@69 42
jpayne@69 43
jpayne@69 44
jpayne@69 45 class BufferedSubFile(object):
jpayne@69 46 """A file-ish object that can have new data loaded into it.
jpayne@69 47
jpayne@69 48 You can also push and pop line-matching predicates onto a stack. When the
jpayne@69 49 current predicate matches the current line, a false EOF response
jpayne@69 50 (i.e. empty string) is returned instead. This lets the parser adhere to a
jpayne@69 51 simple abstraction -- it parses until EOF closes the current message.
jpayne@69 52 """
jpayne@69 53 def __init__(self):
jpayne@69 54 # Text stream of the last partial line pushed into this object.
jpayne@69 55 # See issue 22233 for why this is a text stream and not a list.
jpayne@69 56 self._partial = StringIO(newline='')
jpayne@69 57 # A deque of full, pushed lines
jpayne@69 58 self._lines = deque()
jpayne@69 59 # The stack of false-EOF checking predicates.
jpayne@69 60 self._eofstack = []
jpayne@69 61 # A flag indicating whether the file has been closed or not.
jpayne@69 62 self._closed = False
jpayne@69 63
jpayne@69 64 def push_eof_matcher(self, pred):
jpayne@69 65 self._eofstack.append(pred)
jpayne@69 66
jpayne@69 67 def pop_eof_matcher(self):
jpayne@69 68 return self._eofstack.pop()
jpayne@69 69
jpayne@69 70 def close(self):
jpayne@69 71 # Don't forget any trailing partial line.
jpayne@69 72 self._partial.seek(0)
jpayne@69 73 self.pushlines(self._partial.readlines())
jpayne@69 74 self._partial.seek(0)
jpayne@69 75 self._partial.truncate()
jpayne@69 76 self._closed = True
jpayne@69 77
jpayne@69 78 def readline(self):
jpayne@69 79 if not self._lines:
jpayne@69 80 if self._closed:
jpayne@69 81 return ''
jpayne@69 82 return NeedMoreData
jpayne@69 83 # Pop the line off the stack and see if it matches the current
jpayne@69 84 # false-EOF predicate.
jpayne@69 85 line = self._lines.popleft()
jpayne@69 86 # RFC 2046, section 5.1.2 requires us to recognize outer level
jpayne@69 87 # boundaries at any level of inner nesting. Do this, but be sure it's
jpayne@69 88 # in the order of most to least nested.
jpayne@69 89 for ateof in reversed(self._eofstack):
jpayne@69 90 if ateof(line):
jpayne@69 91 # We're at the false EOF. But push the last line back first.
jpayne@69 92 self._lines.appendleft(line)
jpayne@69 93 return ''
jpayne@69 94 return line
jpayne@69 95
jpayne@69 96 def unreadline(self, line):
jpayne@69 97 # Let the consumer push a line back into the buffer.
jpayne@69 98 assert line is not NeedMoreData
jpayne@69 99 self._lines.appendleft(line)
jpayne@69 100
jpayne@69 101 def push(self, data):
jpayne@69 102 """Push some new data into this object."""
jpayne@69 103 self._partial.write(data)
jpayne@69 104 if '\n' not in data and '\r' not in data:
jpayne@69 105 # No new complete lines, wait for more.
jpayne@69 106 return
jpayne@69 107
jpayne@69 108 # Crack into lines, preserving the linesep characters.
jpayne@69 109 self._partial.seek(0)
jpayne@69 110 parts = self._partial.readlines()
jpayne@69 111 self._partial.seek(0)
jpayne@69 112 self._partial.truncate()
jpayne@69 113
jpayne@69 114 # If the last element of the list does not end in a newline, then treat
jpayne@69 115 # it as a partial line. We only check for '\n' here because a line
jpayne@69 116 # ending with '\r' might be a line that was split in the middle of a
jpayne@69 117 # '\r\n' sequence (see bugs 1555570 and 1721862).
jpayne@69 118 if not parts[-1].endswith('\n'):
jpayne@69 119 self._partial.write(parts.pop())
jpayne@69 120 self.pushlines(parts)
jpayne@69 121
jpayne@69 122 def pushlines(self, lines):
jpayne@69 123 self._lines.extend(lines)
jpayne@69 124
jpayne@69 125 def __iter__(self):
jpayne@69 126 return self
jpayne@69 127
jpayne@69 128 def __next__(self):
jpayne@69 129 line = self.readline()
jpayne@69 130 if line == '':
jpayne@69 131 raise StopIteration
jpayne@69 132 return line
jpayne@69 133
jpayne@69 134
jpayne@69 135
jpayne@69 136 class FeedParser:
jpayne@69 137 """A feed-style parser of email."""
jpayne@69 138
jpayne@69 139 def __init__(self, _factory=None, *, policy=compat32):
jpayne@69 140 """_factory is called with no arguments to create a new message obj
jpayne@69 141
jpayne@69 142 The policy keyword specifies a policy object that controls a number of
jpayne@69 143 aspects of the parser's operation. The default policy maintains
jpayne@69 144 backward compatibility.
jpayne@69 145
jpayne@69 146 """
jpayne@69 147 self.policy = policy
jpayne@69 148 self._old_style_factory = False
jpayne@69 149 if _factory is None:
jpayne@69 150 if policy.message_factory is None:
jpayne@69 151 from email.message import Message
jpayne@69 152 self._factory = Message
jpayne@69 153 else:
jpayne@69 154 self._factory = policy.message_factory
jpayne@69 155 else:
jpayne@69 156 self._factory = _factory
jpayne@69 157 try:
jpayne@69 158 _factory(policy=self.policy)
jpayne@69 159 except TypeError:
jpayne@69 160 # Assume this is an old-style factory
jpayne@69 161 self._old_style_factory = True
jpayne@69 162 self._input = BufferedSubFile()
jpayne@69 163 self._msgstack = []
jpayne@69 164 self._parse = self._parsegen().__next__
jpayne@69 165 self._cur = None
jpayne@69 166 self._last = None
jpayne@69 167 self._headersonly = False
jpayne@69 168
jpayne@69 169 # Non-public interface for supporting Parser's headersonly flag
jpayne@69 170 def _set_headersonly(self):
jpayne@69 171 self._headersonly = True
jpayne@69 172
jpayne@69 173 def feed(self, data):
jpayne@69 174 """Push more data into the parser."""
jpayne@69 175 self._input.push(data)
jpayne@69 176 self._call_parse()
jpayne@69 177
jpayne@69 178 def _call_parse(self):
jpayne@69 179 try:
jpayne@69 180 self._parse()
jpayne@69 181 except StopIteration:
jpayne@69 182 pass
jpayne@69 183
jpayne@69 184 def close(self):
jpayne@69 185 """Parse all remaining data and return the root message object."""
jpayne@69 186 self._input.close()
jpayne@69 187 self._call_parse()
jpayne@69 188 root = self._pop_message()
jpayne@69 189 assert not self._msgstack
jpayne@69 190 # Look for final set of defects
jpayne@69 191 if root.get_content_maintype() == 'multipart' \
jpayne@69 192 and not root.is_multipart():
jpayne@69 193 defect = errors.MultipartInvariantViolationDefect()
jpayne@69 194 self.policy.handle_defect(root, defect)
jpayne@69 195 return root
jpayne@69 196
jpayne@69 197 def _new_message(self):
jpayne@69 198 if self._old_style_factory:
jpayne@69 199 msg = self._factory()
jpayne@69 200 else:
jpayne@69 201 msg = self._factory(policy=self.policy)
jpayne@69 202 if self._cur and self._cur.get_content_type() == 'multipart/digest':
jpayne@69 203 msg.set_default_type('message/rfc822')
jpayne@69 204 if self._msgstack:
jpayne@69 205 self._msgstack[-1].attach(msg)
jpayne@69 206 self._msgstack.append(msg)
jpayne@69 207 self._cur = msg
jpayne@69 208 self._last = msg
jpayne@69 209
jpayne@69 210 def _pop_message(self):
jpayne@69 211 retval = self._msgstack.pop()
jpayne@69 212 if self._msgstack:
jpayne@69 213 self._cur = self._msgstack[-1]
jpayne@69 214 else:
jpayne@69 215 self._cur = None
jpayne@69 216 return retval
jpayne@69 217
jpayne@69 218 def _parsegen(self):
jpayne@69 219 # Create a new message and start by parsing headers.
jpayne@69 220 self._new_message()
jpayne@69 221 headers = []
jpayne@69 222 # Collect the headers, searching for a line that doesn't match the RFC
jpayne@69 223 # 2822 header or continuation pattern (including an empty line).
jpayne@69 224 for line in self._input:
jpayne@69 225 if line is NeedMoreData:
jpayne@69 226 yield NeedMoreData
jpayne@69 227 continue
jpayne@69 228 if not headerRE.match(line):
jpayne@69 229 # If we saw the RFC defined header/body separator
jpayne@69 230 # (i.e. newline), just throw it away. Otherwise the line is
jpayne@69 231 # part of the body so push it back.
jpayne@69 232 if not NLCRE.match(line):
jpayne@69 233 defect = errors.MissingHeaderBodySeparatorDefect()
jpayne@69 234 self.policy.handle_defect(self._cur, defect)
jpayne@69 235 self._input.unreadline(line)
jpayne@69 236 break
jpayne@69 237 headers.append(line)
jpayne@69 238 # Done with the headers, so parse them and figure out what we're
jpayne@69 239 # supposed to see in the body of the message.
jpayne@69 240 self._parse_headers(headers)
jpayne@69 241 # Headers-only parsing is a backwards compatibility hack, which was
jpayne@69 242 # necessary in the older parser, which could raise errors. All
jpayne@69 243 # remaining lines in the input are thrown into the message body.
jpayne@69 244 if self._headersonly:
jpayne@69 245 lines = []
jpayne@69 246 while True:
jpayne@69 247 line = self._input.readline()
jpayne@69 248 if line is NeedMoreData:
jpayne@69 249 yield NeedMoreData
jpayne@69 250 continue
jpayne@69 251 if line == '':
jpayne@69 252 break
jpayne@69 253 lines.append(line)
jpayne@69 254 self._cur.set_payload(EMPTYSTRING.join(lines))
jpayne@69 255 return
jpayne@69 256 if self._cur.get_content_type() == 'message/delivery-status':
jpayne@69 257 # message/delivery-status contains blocks of headers separated by
jpayne@69 258 # a blank line. We'll represent each header block as a separate
jpayne@69 259 # nested message object, but the processing is a bit different
jpayne@69 260 # than standard message/* types because there is no body for the
jpayne@69 261 # nested messages. A blank line separates the subparts.
jpayne@69 262 while True:
jpayne@69 263 self._input.push_eof_matcher(NLCRE.match)
jpayne@69 264 for retval in self._parsegen():
jpayne@69 265 if retval is NeedMoreData:
jpayne@69 266 yield NeedMoreData
jpayne@69 267 continue
jpayne@69 268 break
jpayne@69 269 msg = self._pop_message()
jpayne@69 270 # We need to pop the EOF matcher in order to tell if we're at
jpayne@69 271 # the end of the current file, not the end of the last block
jpayne@69 272 # of message headers.
jpayne@69 273 self._input.pop_eof_matcher()
jpayne@69 274 # The input stream must be sitting at the newline or at the
jpayne@69 275 # EOF. We want to see if we're at the end of this subpart, so
jpayne@69 276 # first consume the blank line, then test the next line to see
jpayne@69 277 # if we're at this subpart's EOF.
jpayne@69 278 while True:
jpayne@69 279 line = self._input.readline()
jpayne@69 280 if line is NeedMoreData:
jpayne@69 281 yield NeedMoreData
jpayne@69 282 continue
jpayne@69 283 break
jpayne@69 284 while True:
jpayne@69 285 line = self._input.readline()
jpayne@69 286 if line is NeedMoreData:
jpayne@69 287 yield NeedMoreData
jpayne@69 288 continue
jpayne@69 289 break
jpayne@69 290 if line == '':
jpayne@69 291 break
jpayne@69 292 # Not at EOF so this is a line we're going to need.
jpayne@69 293 self._input.unreadline(line)
jpayne@69 294 return
jpayne@69 295 if self._cur.get_content_maintype() == 'message':
jpayne@69 296 # The message claims to be a message/* type, then what follows is
jpayne@69 297 # another RFC 2822 message.
jpayne@69 298 for retval in self._parsegen():
jpayne@69 299 if retval is NeedMoreData:
jpayne@69 300 yield NeedMoreData
jpayne@69 301 continue
jpayne@69 302 break
jpayne@69 303 self._pop_message()
jpayne@69 304 return
jpayne@69 305 if self._cur.get_content_maintype() == 'multipart':
jpayne@69 306 boundary = self._cur.get_boundary()
jpayne@69 307 if boundary is None:
jpayne@69 308 # The message /claims/ to be a multipart but it has not
jpayne@69 309 # defined a boundary. That's a problem which we'll handle by
jpayne@69 310 # reading everything until the EOF and marking the message as
jpayne@69 311 # defective.
jpayne@69 312 defect = errors.NoBoundaryInMultipartDefect()
jpayne@69 313 self.policy.handle_defect(self._cur, defect)
jpayne@69 314 lines = []
jpayne@69 315 for line in self._input:
jpayne@69 316 if line is NeedMoreData:
jpayne@69 317 yield NeedMoreData
jpayne@69 318 continue
jpayne@69 319 lines.append(line)
jpayne@69 320 self._cur.set_payload(EMPTYSTRING.join(lines))
jpayne@69 321 return
jpayne@69 322 # Make sure a valid content type was specified per RFC 2045:6.4.
jpayne@69 323 if (str(self._cur.get('content-transfer-encoding', '8bit')).lower()
jpayne@69 324 not in ('7bit', '8bit', 'binary')):
jpayne@69 325 defect = errors.InvalidMultipartContentTransferEncodingDefect()
jpayne@69 326 self.policy.handle_defect(self._cur, defect)
jpayne@69 327 # Create a line match predicate which matches the inter-part
jpayne@69 328 # boundary as well as the end-of-multipart boundary. Don't push
jpayne@69 329 # this onto the input stream until we've scanned past the
jpayne@69 330 # preamble.
jpayne@69 331 separator = '--' + boundary
jpayne@69 332 boundaryre = re.compile(
jpayne@69 333 '(?P<sep>' + re.escape(separator) +
jpayne@69 334 r')(?P<end>--)?(?P<ws>[ \t]*)(?P<linesep>\r\n|\r|\n)?$')
jpayne@69 335 capturing_preamble = True
jpayne@69 336 preamble = []
jpayne@69 337 linesep = False
jpayne@69 338 close_boundary_seen = False
jpayne@69 339 while True:
jpayne@69 340 line = self._input.readline()
jpayne@69 341 if line is NeedMoreData:
jpayne@69 342 yield NeedMoreData
jpayne@69 343 continue
jpayne@69 344 if line == '':
jpayne@69 345 break
jpayne@69 346 mo = boundaryre.match(line)
jpayne@69 347 if mo:
jpayne@69 348 # If we're looking at the end boundary, we're done with
jpayne@69 349 # this multipart. If there was a newline at the end of
jpayne@69 350 # the closing boundary, then we need to initialize the
jpayne@69 351 # epilogue with the empty string (see below).
jpayne@69 352 if mo.group('end'):
jpayne@69 353 close_boundary_seen = True
jpayne@69 354 linesep = mo.group('linesep')
jpayne@69 355 break
jpayne@69 356 # We saw an inter-part boundary. Were we in the preamble?
jpayne@69 357 if capturing_preamble:
jpayne@69 358 if preamble:
jpayne@69 359 # According to RFC 2046, the last newline belongs
jpayne@69 360 # to the boundary.
jpayne@69 361 lastline = preamble[-1]
jpayne@69 362 eolmo = NLCRE_eol.search(lastline)
jpayne@69 363 if eolmo:
jpayne@69 364 preamble[-1] = lastline[:-len(eolmo.group(0))]
jpayne@69 365 self._cur.preamble = EMPTYSTRING.join(preamble)
jpayne@69 366 capturing_preamble = False
jpayne@69 367 self._input.unreadline(line)
jpayne@69 368 continue
jpayne@69 369 # We saw a boundary separating two parts. Consume any
jpayne@69 370 # multiple boundary lines that may be following. Our
jpayne@69 371 # interpretation of RFC 2046 BNF grammar does not produce
jpayne@69 372 # body parts within such double boundaries.
jpayne@69 373 while True:
jpayne@69 374 line = self._input.readline()
jpayne@69 375 if line is NeedMoreData:
jpayne@69 376 yield NeedMoreData
jpayne@69 377 continue
jpayne@69 378 mo = boundaryre.match(line)
jpayne@69 379 if not mo:
jpayne@69 380 self._input.unreadline(line)
jpayne@69 381 break
jpayne@69 382 # Recurse to parse this subpart; the input stream points
jpayne@69 383 # at the subpart's first line.
jpayne@69 384 self._input.push_eof_matcher(boundaryre.match)
jpayne@69 385 for retval in self._parsegen():
jpayne@69 386 if retval is NeedMoreData:
jpayne@69 387 yield NeedMoreData
jpayne@69 388 continue
jpayne@69 389 break
jpayne@69 390 # Because of RFC 2046, the newline preceding the boundary
jpayne@69 391 # separator actually belongs to the boundary, not the
jpayne@69 392 # previous subpart's payload (or epilogue if the previous
jpayne@69 393 # part is a multipart).
jpayne@69 394 if self._last.get_content_maintype() == 'multipart':
jpayne@69 395 epilogue = self._last.epilogue
jpayne@69 396 if epilogue == '':
jpayne@69 397 self._last.epilogue = None
jpayne@69 398 elif epilogue is not None:
jpayne@69 399 mo = NLCRE_eol.search(epilogue)
jpayne@69 400 if mo:
jpayne@69 401 end = len(mo.group(0))
jpayne@69 402 self._last.epilogue = epilogue[:-end]
jpayne@69 403 else:
jpayne@69 404 payload = self._last._payload
jpayne@69 405 if isinstance(payload, str):
jpayne@69 406 mo = NLCRE_eol.search(payload)
jpayne@69 407 if mo:
jpayne@69 408 payload = payload[:-len(mo.group(0))]
jpayne@69 409 self._last._payload = payload
jpayne@69 410 self._input.pop_eof_matcher()
jpayne@69 411 self._pop_message()
jpayne@69 412 # Set the multipart up for newline cleansing, which will
jpayne@69 413 # happen if we're in a nested multipart.
jpayne@69 414 self._last = self._cur
jpayne@69 415 else:
jpayne@69 416 # I think we must be in the preamble
jpayne@69 417 assert capturing_preamble
jpayne@69 418 preamble.append(line)
jpayne@69 419 # We've seen either the EOF or the end boundary. If we're still
jpayne@69 420 # capturing the preamble, we never saw the start boundary. Note
jpayne@69 421 # that as a defect and store the captured text as the payload.
jpayne@69 422 if capturing_preamble:
jpayne@69 423 defect = errors.StartBoundaryNotFoundDefect()
jpayne@69 424 self.policy.handle_defect(self._cur, defect)
jpayne@69 425 self._cur.set_payload(EMPTYSTRING.join(preamble))
jpayne@69 426 epilogue = []
jpayne@69 427 for line in self._input:
jpayne@69 428 if line is NeedMoreData:
jpayne@69 429 yield NeedMoreData
jpayne@69 430 continue
jpayne@69 431 self._cur.epilogue = EMPTYSTRING.join(epilogue)
jpayne@69 432 return
jpayne@69 433 # If we're not processing the preamble, then we might have seen
jpayne@69 434 # EOF without seeing that end boundary...that is also a defect.
jpayne@69 435 if not close_boundary_seen:
jpayne@69 436 defect = errors.CloseBoundaryNotFoundDefect()
jpayne@69 437 self.policy.handle_defect(self._cur, defect)
jpayne@69 438 return
jpayne@69 439 # Everything from here to the EOF is epilogue. If the end boundary
jpayne@69 440 # ended in a newline, we'll need to make sure the epilogue isn't
jpayne@69 441 # None
jpayne@69 442 if linesep:
jpayne@69 443 epilogue = ['']
jpayne@69 444 else:
jpayne@69 445 epilogue = []
jpayne@69 446 for line in self._input:
jpayne@69 447 if line is NeedMoreData:
jpayne@69 448 yield NeedMoreData
jpayne@69 449 continue
jpayne@69 450 epilogue.append(line)
jpayne@69 451 # Any CRLF at the front of the epilogue is not technically part of
jpayne@69 452 # the epilogue. Also, watch out for an empty string epilogue,
jpayne@69 453 # which means a single newline.
jpayne@69 454 if epilogue:
jpayne@69 455 firstline = epilogue[0]
jpayne@69 456 bolmo = NLCRE_bol.match(firstline)
jpayne@69 457 if bolmo:
jpayne@69 458 epilogue[0] = firstline[len(bolmo.group(0)):]
jpayne@69 459 self._cur.epilogue = EMPTYSTRING.join(epilogue)
jpayne@69 460 return
jpayne@69 461 # Otherwise, it's some non-multipart type, so the entire rest of the
jpayne@69 462 # file contents becomes the payload.
jpayne@69 463 lines = []
jpayne@69 464 for line in self._input:
jpayne@69 465 if line is NeedMoreData:
jpayne@69 466 yield NeedMoreData
jpayne@69 467 continue
jpayne@69 468 lines.append(line)
jpayne@69 469 self._cur.set_payload(EMPTYSTRING.join(lines))
jpayne@69 470
jpayne@69 471 def _parse_headers(self, lines):
jpayne@69 472 # Passed a list of lines that make up the headers for the current msg
jpayne@69 473 lastheader = ''
jpayne@69 474 lastvalue = []
jpayne@69 475 for lineno, line in enumerate(lines):
jpayne@69 476 # Check for continuation
jpayne@69 477 if line[0] in ' \t':
jpayne@69 478 if not lastheader:
jpayne@69 479 # The first line of the headers was a continuation. This
jpayne@69 480 # is illegal, so let's note the defect, store the illegal
jpayne@69 481 # line, and ignore it for purposes of headers.
jpayne@69 482 defect = errors.FirstHeaderLineIsContinuationDefect(line)
jpayne@69 483 self.policy.handle_defect(self._cur, defect)
jpayne@69 484 continue
jpayne@69 485 lastvalue.append(line)
jpayne@69 486 continue
jpayne@69 487 if lastheader:
jpayne@69 488 self._cur.set_raw(*self.policy.header_source_parse(lastvalue))
jpayne@69 489 lastheader, lastvalue = '', []
jpayne@69 490 # Check for envelope header, i.e. unix-from
jpayne@69 491 if line.startswith('From '):
jpayne@69 492 if lineno == 0:
jpayne@69 493 # Strip off the trailing newline
jpayne@69 494 mo = NLCRE_eol.search(line)
jpayne@69 495 if mo:
jpayne@69 496 line = line[:-len(mo.group(0))]
jpayne@69 497 self._cur.set_unixfrom(line)
jpayne@69 498 continue
jpayne@69 499 elif lineno == len(lines) - 1:
jpayne@69 500 # Something looking like a unix-from at the end - it's
jpayne@69 501 # probably the first line of the body, so push back the
jpayne@69 502 # line and stop.
jpayne@69 503 self._input.unreadline(line)
jpayne@69 504 return
jpayne@69 505 else:
jpayne@69 506 # Weirdly placed unix-from line. Note this as a defect
jpayne@69 507 # and ignore it.
jpayne@69 508 defect = errors.MisplacedEnvelopeHeaderDefect(line)
jpayne@69 509 self._cur.defects.append(defect)
jpayne@69 510 continue
jpayne@69 511 # Split the line on the colon separating field name from value.
jpayne@69 512 # There will always be a colon, because if there wasn't the part of
jpayne@69 513 # the parser that calls us would have started parsing the body.
jpayne@69 514 i = line.find(':')
jpayne@69 515
jpayne@69 516 # If the colon is on the start of the line the header is clearly
jpayne@69 517 # malformed, but we might be able to salvage the rest of the
jpayne@69 518 # message. Track the error but keep going.
jpayne@69 519 if i == 0:
jpayne@69 520 defect = errors.InvalidHeaderDefect("Missing header name.")
jpayne@69 521 self._cur.defects.append(defect)
jpayne@69 522 continue
jpayne@69 523
jpayne@69 524 assert i>0, "_parse_headers fed line with no : and no leading WS"
jpayne@69 525 lastheader = line[:i]
jpayne@69 526 lastvalue = [line]
jpayne@69 527 # Done with all the lines, so handle the last header.
jpayne@69 528 if lastheader:
jpayne@69 529 self._cur.set_raw(*self.policy.header_source_parse(lastvalue))
jpayne@69 530
jpayne@69 531
jpayne@69 532 class BytesFeedParser(FeedParser):
jpayne@69 533 """Like FeedParser, but feed accepts bytes."""
jpayne@69 534
jpayne@69 535 def feed(self, data):
jpayne@69 536 super().feed(data.decode('ascii', 'surrogateescape'))