Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ROB: tolerate comments in arrays #2856

Merged
merged 1 commit into from
Sep 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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]
Loading