Skip to content

Commit

Permalink
ROB: Tolerate comments in arrays (#2856)
Browse files Browse the repository at this point in the history
Closes #2843.
  • Loading branch information
pubpub-zz authored Sep 19, 2024
1 parent c4cdb5c commit 7e4a0d6
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 6 deletions.
2 changes: 2 additions & 0 deletions pypdf/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,8 @@ def skip_over_comment(stream: StreamType) -> None:
if tok == b"%":
while tok not in (b"\n", b"\r"):
tok = stream.read(1)
if tok == b"":
raise PdfStreamError("File ended unexpectedly.")


def read_until_regex(stream: StreamType, regex: Pattern[bytes]) -> bytes:
Expand Down
11 changes: 5 additions & 6 deletions pypdf/generic/_data_structures.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,10 @@ def read_from_stream(
tok = stream.read(1)
while tok.isspace():
tok = stream.read(1)
if tok == b"%":
stream.seek(-1, 1)
skip_over_comment(stream)
continue
stream.seek(-1, 1)
# check for array ending
peek_ahead = stream.read(1)
Expand Down Expand Up @@ -1341,12 +1345,7 @@ def read_object(
return NullObject.read_from_stream(stream)
elif tok == b"%":
# comment
while tok not in (b"\r", b"\n"):
tok = stream.read(1)
# Prevents an infinite loop by raising an error if the stream is at
# the EOF
if len(tok) <= 0:
raise PdfStreamError("File ended unexpectedly.")
skip_over_comment(stream)
tok = read_non_whitespace(stream)
stream.seek(-1, 1)
return read_object(stream, pdf, forced_encoding)
Expand Down
16 changes: 16 additions & 0 deletions tests/test_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
EmptyFileError,
FileNotDecryptedError,
PdfReadError,
PdfStreamError,
WrongPasswordError,
)
from pypdf.generic import (
Expand Down Expand Up @@ -1641,3 +1642,18 @@ def test_truncated_files(caplog):
reader = PdfReader(BytesIO(b[:-6]))
assert "CAUTION: startxref found while searching for %%EOF" in caplog.text
assert reader._startxref < 100993


@pytest.mark.enable_socket()
def test_comments_in_array(caplog):
"""Cf #2843: this deals with comments"""
url = "https://github.com/user-attachments/files/16992416/crash-2347912aa2a6f0fab5df4ebc8a424735d5d0d128.pdf"
name = "iss2843.pdf" # reused
b = get_data_from_url(url, name=name)
reader = PdfReader(BytesIO(b))
reader.pages[0]
assert caplog.text == ""
reader = PdfReader(BytesIO(b))
reader.stream = BytesIO(b[:1149])
with pytest.raises(PdfStreamError):
reader.pages[0]

0 comments on commit 7e4a0d6

Please sign in to comment.