multipartparser.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  1. """
  2. Multi-part parsing for file uploads.
  3. Exposes one class, ``MultiPartParser``, which feeds chunks of uploaded data to
  4. file upload handlers for processing.
  5. """
  6. import base64
  7. import binascii
  8. import cgi
  9. import collections
  10. import html
  11. from urllib.parse import unquote
  12. from django.conf import settings
  13. from django.core.exceptions import (
  14. RequestDataTooBig, SuspiciousMultipartForm, TooManyFieldsSent,
  15. )
  16. from django.core.files.uploadhandler import (
  17. SkipFile, StopFutureHandlers, StopUpload,
  18. )
  19. from django.utils.datastructures import MultiValueDict
  20. from django.utils.encoding import force_str
  21. __all__ = ('MultiPartParser', 'MultiPartParserError', 'InputStreamExhausted')
  22. class MultiPartParserError(Exception):
  23. pass
  24. class InputStreamExhausted(Exception):
  25. """
  26. No more reads are allowed from this device.
  27. """
  28. pass
  29. RAW = "raw"
  30. FILE = "file"
  31. FIELD = "field"
  32. class MultiPartParser:
  33. """
  34. A rfc2388 multipart/form-data parser.
  35. ``MultiValueDict.parse()`` reads the input stream in ``chunk_size`` chunks
  36. and returns a tuple of ``(MultiValueDict(POST), MultiValueDict(FILES))``.
  37. """
  38. def __init__(self, META, input_data, upload_handlers, encoding=None):
  39. """
  40. Initialize the MultiPartParser object.
  41. :META:
  42. The standard ``META`` dictionary in Django request objects.
  43. :input_data:
  44. The raw post data, as a file-like object.
  45. :upload_handlers:
  46. A list of UploadHandler instances that perform operations on the
  47. uploaded data.
  48. :encoding:
  49. The encoding with which to treat the incoming data.
  50. """
  51. # Content-Type should contain multipart and the boundary information.
  52. content_type = META.get('CONTENT_TYPE', '')
  53. if not content_type.startswith('multipart/'):
  54. raise MultiPartParserError('Invalid Content-Type: %s' % content_type)
  55. # Parse the header to get the boundary to split the parts.
  56. try:
  57. ctypes, opts = parse_header(content_type.encode('ascii'))
  58. except UnicodeEncodeError:
  59. raise MultiPartParserError('Invalid non-ASCII Content-Type in multipart: %s' % force_str(content_type))
  60. boundary = opts.get('boundary')
  61. if not boundary or not cgi.valid_boundary(boundary):
  62. raise MultiPartParserError('Invalid boundary in multipart: %s' % force_str(boundary))
  63. # Content-Length should contain the length of the body we are about
  64. # to receive.
  65. try:
  66. content_length = int(META.get('CONTENT_LENGTH', 0))
  67. except (ValueError, TypeError):
  68. content_length = 0
  69. if content_length < 0:
  70. # This means we shouldn't continue...raise an error.
  71. raise MultiPartParserError("Invalid content length: %r" % content_length)
  72. if isinstance(boundary, str):
  73. boundary = boundary.encode('ascii')
  74. self._boundary = boundary
  75. self._input_data = input_data
  76. # For compatibility with low-level network APIs (with 32-bit integers),
  77. # the chunk size should be < 2^31, but still divisible by 4.
  78. possible_sizes = [x.chunk_size for x in upload_handlers if x.chunk_size]
  79. self._chunk_size = min([2 ** 31 - 4] + possible_sizes)
  80. self._meta = META
  81. self._encoding = encoding or settings.DEFAULT_CHARSET
  82. self._content_length = content_length
  83. self._upload_handlers = upload_handlers
  84. def parse(self):
  85. """
  86. Parse the POST data and break it into a FILES MultiValueDict and a POST
  87. MultiValueDict.
  88. Return a tuple containing the POST and FILES dictionary, respectively.
  89. """
  90. from django.http import QueryDict
  91. encoding = self._encoding
  92. handlers = self._upload_handlers
  93. # HTTP spec says that Content-Length >= 0 is valid
  94. # handling content-length == 0 before continuing
  95. if self._content_length == 0:
  96. return QueryDict(encoding=self._encoding), MultiValueDict()
  97. # See if any of the handlers take care of the parsing.
  98. # This allows overriding everything if need be.
  99. for handler in handlers:
  100. result = handler.handle_raw_input(
  101. self._input_data,
  102. self._meta,
  103. self._content_length,
  104. self._boundary,
  105. encoding,
  106. )
  107. # Check to see if it was handled
  108. if result is not None:
  109. return result[0], result[1]
  110. # Create the data structures to be used later.
  111. self._post = QueryDict(mutable=True)
  112. self._files = MultiValueDict()
  113. # Instantiate the parser and stream:
  114. stream = LazyStream(ChunkIter(self._input_data, self._chunk_size))
  115. # Whether or not to signal a file-completion at the beginning of the loop.
  116. old_field_name = None
  117. counters = [0] * len(handlers)
  118. # Number of bytes that have been read.
  119. num_bytes_read = 0
  120. # To count the number of keys in the request.
  121. num_post_keys = 0
  122. # To limit the amount of data read from the request.
  123. read_size = None
  124. # Whether a file upload is finished.
  125. uploaded_file = True
  126. try:
  127. for item_type, meta_data, field_stream in Parser(stream, self._boundary):
  128. if old_field_name:
  129. # We run this at the beginning of the next loop
  130. # since we cannot be sure a file is complete until
  131. # we hit the next boundary/part of the multipart content.
  132. self.handle_file_complete(old_field_name, counters)
  133. old_field_name = None
  134. uploaded_file = True
  135. try:
  136. disposition = meta_data['content-disposition'][1]
  137. field_name = disposition['name'].strip()
  138. except (KeyError, IndexError, AttributeError):
  139. continue
  140. transfer_encoding = meta_data.get('content-transfer-encoding')
  141. if transfer_encoding is not None:
  142. transfer_encoding = transfer_encoding[0].strip()
  143. field_name = force_str(field_name, encoding, errors='replace')
  144. if item_type == FIELD:
  145. # Avoid storing more than DATA_UPLOAD_MAX_NUMBER_FIELDS.
  146. num_post_keys += 1
  147. if (settings.DATA_UPLOAD_MAX_NUMBER_FIELDS is not None and
  148. settings.DATA_UPLOAD_MAX_NUMBER_FIELDS < num_post_keys):
  149. raise TooManyFieldsSent(
  150. 'The number of GET/POST parameters exceeded '
  151. 'settings.DATA_UPLOAD_MAX_NUMBER_FIELDS.'
  152. )
  153. # Avoid reading more than DATA_UPLOAD_MAX_MEMORY_SIZE.
  154. if settings.DATA_UPLOAD_MAX_MEMORY_SIZE is not None:
  155. read_size = settings.DATA_UPLOAD_MAX_MEMORY_SIZE - num_bytes_read
  156. # This is a post field, we can just set it in the post
  157. if transfer_encoding == 'base64':
  158. raw_data = field_stream.read(size=read_size)
  159. num_bytes_read += len(raw_data)
  160. try:
  161. data = base64.b64decode(raw_data)
  162. except binascii.Error:
  163. data = raw_data
  164. else:
  165. data = field_stream.read(size=read_size)
  166. num_bytes_read += len(data)
  167. # Add two here to make the check consistent with the
  168. # x-www-form-urlencoded check that includes '&='.
  169. num_bytes_read += len(field_name) + 2
  170. if (settings.DATA_UPLOAD_MAX_MEMORY_SIZE is not None and
  171. num_bytes_read > settings.DATA_UPLOAD_MAX_MEMORY_SIZE):
  172. raise RequestDataTooBig('Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE.')
  173. self._post.appendlist(field_name, force_str(data, encoding, errors='replace'))
  174. elif item_type == FILE:
  175. # This is a file, use the handler...
  176. file_name = disposition.get('filename')
  177. if file_name:
  178. file_name = force_str(file_name, encoding, errors='replace')
  179. file_name = self.sanitize_file_name(file_name)
  180. if not file_name:
  181. continue
  182. content_type, content_type_extra = meta_data.get('content-type', ('', {}))
  183. content_type = content_type.strip()
  184. charset = content_type_extra.get('charset')
  185. try:
  186. content_length = int(meta_data.get('content-length')[0])
  187. except (IndexError, TypeError, ValueError):
  188. content_length = None
  189. counters = [0] * len(handlers)
  190. uploaded_file = False
  191. try:
  192. for handler in handlers:
  193. try:
  194. handler.new_file(
  195. field_name, file_name, content_type,
  196. content_length, charset, content_type_extra,
  197. )
  198. except StopFutureHandlers:
  199. break
  200. for chunk in field_stream:
  201. if transfer_encoding == 'base64':
  202. # We only special-case base64 transfer encoding
  203. # We should always decode base64 chunks by multiple of 4,
  204. # ignoring whitespace.
  205. stripped_chunk = b"".join(chunk.split())
  206. remaining = len(stripped_chunk) % 4
  207. while remaining != 0:
  208. over_chunk = field_stream.read(4 - remaining)
  209. if not over_chunk:
  210. break
  211. stripped_chunk += b"".join(over_chunk.split())
  212. remaining = len(stripped_chunk) % 4
  213. try:
  214. chunk = base64.b64decode(stripped_chunk)
  215. except Exception as exc:
  216. # Since this is only a chunk, any error is an unfixable error.
  217. raise MultiPartParserError("Could not decode base64 data.") from exc
  218. for i, handler in enumerate(handlers):
  219. chunk_length = len(chunk)
  220. chunk = handler.receive_data_chunk(chunk, counters[i])
  221. counters[i] += chunk_length
  222. if chunk is None:
  223. # Don't continue if the chunk received by
  224. # the handler is None.
  225. break
  226. except SkipFile:
  227. self._close_files()
  228. # Just use up the rest of this file...
  229. exhaust(field_stream)
  230. else:
  231. # Handle file upload completions on next iteration.
  232. old_field_name = field_name
  233. else:
  234. # If this is neither a FIELD or a FILE, just exhaust the stream.
  235. exhaust(stream)
  236. except StopUpload as e:
  237. self._close_files()
  238. if not e.connection_reset:
  239. exhaust(self._input_data)
  240. else:
  241. if not uploaded_file:
  242. for handler in handlers:
  243. handler.upload_interrupted()
  244. # Make sure that the request data is all fed
  245. exhaust(self._input_data)
  246. # Signal that the upload has completed.
  247. # any() shortcircuits if a handler's upload_complete() returns a value.
  248. any(handler.upload_complete() for handler in handlers)
  249. self._post._mutable = False
  250. return self._post, self._files
  251. def handle_file_complete(self, old_field_name, counters):
  252. """
  253. Handle all the signaling that takes place when a file is complete.
  254. """
  255. for i, handler in enumerate(self._upload_handlers):
  256. file_obj = handler.file_complete(counters[i])
  257. if file_obj:
  258. # If it returns a file object, then set the files dict.
  259. self._files.appendlist(force_str(old_field_name, self._encoding, errors='replace'), file_obj)
  260. break
  261. def sanitize_file_name(self, file_name):
  262. """
  263. Sanitize the filename of an upload.
  264. Remove all possible path separators, even though that might remove more
  265. than actually required by the target system. Filenames that could
  266. potentially cause problems (current/parent dir) are also discarded.
  267. It should be noted that this function could still return a "filepath"
  268. like "C:some_file.txt" which is handled later on by the storage layer.
  269. So while this function does sanitize filenames to some extent, the
  270. resulting filename should still be considered as untrusted user input.
  271. """
  272. file_name = html.unescape(file_name)
  273. file_name = file_name.rsplit('/')[-1]
  274. file_name = file_name.rsplit('\\')[-1]
  275. if file_name in {'', '.', '..'}:
  276. return None
  277. return file_name
  278. IE_sanitize = sanitize_file_name
  279. def _close_files(self):
  280. # Free up all file handles.
  281. # FIXME: this currently assumes that upload handlers store the file as 'file'
  282. # We should document that... (Maybe add handler.free_file to complement new_file)
  283. for handler in self._upload_handlers:
  284. if hasattr(handler, 'file'):
  285. handler.file.close()
  286. class LazyStream:
  287. """
  288. The LazyStream wrapper allows one to get and "unget" bytes from a stream.
  289. Given a producer object (an iterator that yields bytestrings), the
  290. LazyStream object will support iteration, reading, and keeping a "look-back"
  291. variable in case you need to "unget" some bytes.
  292. """
  293. def __init__(self, producer, length=None):
  294. """
  295. Every LazyStream must have a producer when instantiated.
  296. A producer is an iterable that returns a string each time it
  297. is called.
  298. """
  299. self._producer = producer
  300. self._empty = False
  301. self._leftover = b''
  302. self.length = length
  303. self.position = 0
  304. self._remaining = length
  305. self._unget_history = []
  306. def tell(self):
  307. return self.position
  308. def read(self, size=None):
  309. def parts():
  310. remaining = self._remaining if size is None else size
  311. # do the whole thing in one shot if no limit was provided.
  312. if remaining is None:
  313. yield b''.join(self)
  314. return
  315. # otherwise do some bookkeeping to return exactly enough
  316. # of the stream and stashing any extra content we get from
  317. # the producer
  318. while remaining != 0:
  319. assert remaining > 0, 'remaining bytes to read should never go negative'
  320. try:
  321. chunk = next(self)
  322. except StopIteration:
  323. return
  324. else:
  325. emitting = chunk[:remaining]
  326. self.unget(chunk[remaining:])
  327. remaining -= len(emitting)
  328. yield emitting
  329. return b''.join(parts())
  330. def __next__(self):
  331. """
  332. Used when the exact number of bytes to read is unimportant.
  333. Return whatever chunk is conveniently returned from the iterator.
  334. Useful to avoid unnecessary bookkeeping if performance is an issue.
  335. """
  336. if self._leftover:
  337. output = self._leftover
  338. self._leftover = b''
  339. else:
  340. output = next(self._producer)
  341. self._unget_history = []
  342. self.position += len(output)
  343. return output
  344. def close(self):
  345. """
  346. Used to invalidate/disable this lazy stream.
  347. Replace the producer with an empty list. Any leftover bytes that have
  348. already been read will still be reported upon read() and/or next().
  349. """
  350. self._producer = []
  351. def __iter__(self):
  352. return self
  353. def unget(self, bytes):
  354. """
  355. Place bytes back onto the front of the lazy stream.
  356. Future calls to read() will return those bytes first. The
  357. stream position and thus tell() will be rewound.
  358. """
  359. if not bytes:
  360. return
  361. self._update_unget_history(len(bytes))
  362. self.position -= len(bytes)
  363. self._leftover = bytes + self._leftover
  364. def _update_unget_history(self, num_bytes):
  365. """
  366. Update the unget history as a sanity check to see if we've pushed
  367. back the same number of bytes in one chunk. If we keep ungetting the
  368. same number of bytes many times (here, 50), we're mostly likely in an
  369. infinite loop of some sort. This is usually caused by a
  370. maliciously-malformed MIME request.
  371. """
  372. self._unget_history = [num_bytes] + self._unget_history[:49]
  373. number_equal = len([
  374. current_number for current_number in self._unget_history
  375. if current_number == num_bytes
  376. ])
  377. if number_equal > 40:
  378. raise SuspiciousMultipartForm(
  379. "The multipart parser got stuck, which shouldn't happen with"
  380. " normal uploaded files. Check for malicious upload activity;"
  381. " if there is none, report this to the Django developers."
  382. )
  383. class ChunkIter:
  384. """
  385. An iterable that will yield chunks of data. Given a file-like object as the
  386. constructor, yield chunks of read operations from that object.
  387. """
  388. def __init__(self, flo, chunk_size=64 * 1024):
  389. self.flo = flo
  390. self.chunk_size = chunk_size
  391. def __next__(self):
  392. try:
  393. data = self.flo.read(self.chunk_size)
  394. except InputStreamExhausted:
  395. raise StopIteration()
  396. if data:
  397. return data
  398. else:
  399. raise StopIteration()
  400. def __iter__(self):
  401. return self
  402. class InterBoundaryIter:
  403. """
  404. A Producer that will iterate over boundaries.
  405. """
  406. def __init__(self, stream, boundary):
  407. self._stream = stream
  408. self._boundary = boundary
  409. def __iter__(self):
  410. return self
  411. def __next__(self):
  412. try:
  413. return LazyStream(BoundaryIter(self._stream, self._boundary))
  414. except InputStreamExhausted:
  415. raise StopIteration()
  416. class BoundaryIter:
  417. """
  418. A Producer that is sensitive to boundaries.
  419. Will happily yield bytes until a boundary is found. Will yield the bytes
  420. before the boundary, throw away the boundary bytes themselves, and push the
  421. post-boundary bytes back on the stream.
  422. The future calls to next() after locating the boundary will raise a
  423. StopIteration exception.
  424. """
  425. def __init__(self, stream, boundary):
  426. self._stream = stream
  427. self._boundary = boundary
  428. self._done = False
  429. # rollback an additional six bytes because the format is like
  430. # this: CRLF<boundary>[--CRLF]
  431. self._rollback = len(boundary) + 6
  432. # Try to use mx fast string search if available. Otherwise
  433. # use Python find. Wrap the latter for consistency.
  434. unused_char = self._stream.read(1)
  435. if not unused_char:
  436. raise InputStreamExhausted()
  437. self._stream.unget(unused_char)
  438. def __iter__(self):
  439. return self
  440. def __next__(self):
  441. if self._done:
  442. raise StopIteration()
  443. stream = self._stream
  444. rollback = self._rollback
  445. bytes_read = 0
  446. chunks = []
  447. for bytes in stream:
  448. bytes_read += len(bytes)
  449. chunks.append(bytes)
  450. if bytes_read > rollback:
  451. break
  452. if not bytes:
  453. break
  454. else:
  455. self._done = True
  456. if not chunks:
  457. raise StopIteration()
  458. chunk = b''.join(chunks)
  459. boundary = self._find_boundary(chunk)
  460. if boundary:
  461. end, next = boundary
  462. stream.unget(chunk[next:])
  463. self._done = True
  464. return chunk[:end]
  465. else:
  466. # make sure we don't treat a partial boundary (and
  467. # its separators) as data
  468. if not chunk[:-rollback]: # and len(chunk) >= (len(self._boundary) + 6):
  469. # There's nothing left, we should just return and mark as done.
  470. self._done = True
  471. return chunk
  472. else:
  473. stream.unget(chunk[-rollback:])
  474. return chunk[:-rollback]
  475. def _find_boundary(self, data):
  476. """
  477. Find a multipart boundary in data.
  478. Should no boundary exist in the data, return None. Otherwise, return
  479. a tuple containing the indices of the following:
  480. * the end of current encapsulation
  481. * the start of the next encapsulation
  482. """
  483. index = data.find(self._boundary)
  484. if index < 0:
  485. return None
  486. else:
  487. end = index
  488. next = index + len(self._boundary)
  489. # backup over CRLF
  490. last = max(0, end - 1)
  491. if data[last:last + 1] == b'\n':
  492. end -= 1
  493. last = max(0, end - 1)
  494. if data[last:last + 1] == b'\r':
  495. end -= 1
  496. return end, next
  497. def exhaust(stream_or_iterable):
  498. """Exhaust an iterator or stream."""
  499. try:
  500. iterator = iter(stream_or_iterable)
  501. except TypeError:
  502. iterator = ChunkIter(stream_or_iterable, 16384)
  503. collections.deque(iterator, maxlen=0) # consume iterator quickly.
  504. def parse_boundary_stream(stream, max_header_size):
  505. """
  506. Parse one and exactly one stream that encapsulates a boundary.
  507. """
  508. # Stream at beginning of header, look for end of header
  509. # and parse it if found. The header must fit within one
  510. # chunk.
  511. chunk = stream.read(max_header_size)
  512. # 'find' returns the top of these four bytes, so we'll
  513. # need to munch them later to prevent them from polluting
  514. # the payload.
  515. header_end = chunk.find(b'\r\n\r\n')
  516. def _parse_header(line):
  517. main_value_pair, params = parse_header(line)
  518. try:
  519. name, value = main_value_pair.split(':', 1)
  520. except ValueError:
  521. raise ValueError("Invalid header: %r" % line)
  522. return name, (value, params)
  523. if header_end == -1:
  524. # we find no header, so we just mark this fact and pass on
  525. # the stream verbatim
  526. stream.unget(chunk)
  527. return (RAW, {}, stream)
  528. header = chunk[:header_end]
  529. # here we place any excess chunk back onto the stream, as
  530. # well as throwing away the CRLFCRLF bytes from above.
  531. stream.unget(chunk[header_end + 4:])
  532. TYPE = RAW
  533. outdict = {}
  534. # Eliminate blank lines
  535. for line in header.split(b'\r\n'):
  536. # This terminology ("main value" and "dictionary of
  537. # parameters") is from the Python docs.
  538. try:
  539. name, (value, params) = _parse_header(line)
  540. except ValueError:
  541. continue
  542. if name == 'content-disposition':
  543. TYPE = FIELD
  544. if params.get('filename'):
  545. TYPE = FILE
  546. outdict[name] = value, params
  547. if TYPE == RAW:
  548. stream.unget(chunk)
  549. return (TYPE, outdict, stream)
  550. class Parser:
  551. def __init__(self, stream, boundary):
  552. self._stream = stream
  553. self._separator = b'--' + boundary
  554. def __iter__(self):
  555. boundarystream = InterBoundaryIter(self._stream, self._separator)
  556. for sub_stream in boundarystream:
  557. # Iterate over each part
  558. yield parse_boundary_stream(sub_stream, 1024)
  559. def parse_header(line):
  560. """
  561. Parse the header into a key-value.
  562. Input (line): bytes, output: str for key/name, bytes for values which
  563. will be decoded later.
  564. """
  565. plist = _parse_header_params(b';' + line)
  566. key = plist.pop(0).lower().decode('ascii')
  567. pdict = {}
  568. for p in plist:
  569. i = p.find(b'=')
  570. if i >= 0:
  571. has_encoding = False
  572. name = p[:i].strip().lower().decode('ascii')
  573. if name.endswith('*'):
  574. # Lang/encoding embedded in the value (like "filename*=UTF-8''file.ext")
  575. # http://tools.ietf.org/html/rfc2231#section-4
  576. name = name[:-1]
  577. if p.count(b"'") == 2:
  578. has_encoding = True
  579. value = p[i + 1:].strip()
  580. if len(value) >= 2 and value[:1] == value[-1:] == b'"':
  581. value = value[1:-1]
  582. value = value.replace(b'\\\\', b'\\').replace(b'\\"', b'"')
  583. if has_encoding:
  584. encoding, lang, value = value.split(b"'")
  585. value = unquote(value.decode(), encoding=encoding.decode())
  586. pdict[name] = value
  587. return key, pdict
  588. def _parse_header_params(s):
  589. plist = []
  590. while s[:1] == b';':
  591. s = s[1:]
  592. end = s.find(b';')
  593. while end > 0 and s.count(b'"', 0, end) % 2:
  594. end = s.find(b';', end + 1)
  595. if end < 0:
  596. end = len(s)
  597. f = s[:end]
  598. plist.append(f.strip())
  599. s = s[end:]
  600. return plist