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

Only read a maximum of 100 bytes at a time in IMT header #6623

Merged
merged 2 commits into from Oct 12, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Binary file added Tests/images/bw_gradient.imt
Binary file not shown.
19 changes: 19 additions & 0 deletions Tests/test_file_imt.py
@@ -0,0 +1,19 @@
import io

import pytest

from PIL import Image, ImtImagePlugin

from .helper import assert_image_equal_tofile


def test_sanity():
with Image.open("Tests/images/bw_gradient.imt") as im:
assert_image_equal_tofile(im, "Tests/images/bw_gradient.png")


@pytest.mark.parametrize("data", (b"\n", b"\n-", b"width 1\n"))
def test_invalid_file(data):
with io.BytesIO(data) as fp:
with pytest.raises(SyntaxError):
ImtImagePlugin.ImtImageFile(fp)
30 changes: 21 additions & 9 deletions src/PIL/ImtImagePlugin.py
Expand Up @@ -39,32 +39,44 @@ def _open(self):
# Quick rejection: if there's not a LF among the first
# 100 bytes, this is (probably) not a text header.

if b"\n" not in self.fp.read(100):
buffer = self.fp.read(100)
if b"\n" not in buffer:
raise SyntaxError("not an IM file")
self.fp.seek(0)

xsize = ysize = 0

while True:

s = self.fp.read(1)
if buffer:
s = buffer[:1]
buffer = buffer[1:]
else:
s = self.fp.read(1)
if not s:
break

if s == b"\x0C":

# image data begins
self.tile = [
("raw", (0, 0) + self.size, self.fp.tell(), (self.mode, 0, 1))
(
"raw",
(0, 0) + self.size,
self.fp.tell() - len(buffer),
(self.mode, 0, 1),
)
]

break

else:

# read key/value pair
# FIXME: dangerous, may read whole file
s = s + self.fp.readline()
if b"\n" not in buffer:
buffer += self.fp.read(100)
lines = buffer.split(b"\n")
s += lines.pop(0)
buffer = b"\n".join(lines)
if len(s) == 1 or len(s) > 100:
break
if s[0] == ord(b"*"):
Expand All @@ -74,13 +86,13 @@ def _open(self):
if not m:
break
k, v = m.group(1, 2)
if k == "width":
if k == b"width":
xsize = int(v)
self._size = xsize, ysize
elif k == "height":
elif k == b"height":
ysize = int(v)
self._size = xsize, ysize
elif k == "pixel" and v == "n8":
elif k == b"pixel" and v == b"n8":
self.mode = "L"


Expand Down