Files
mtusi2026lab4/src/images.py
T

187 lines
7.2 KiB
Python

"""Проверка PNG и JPEG по содержимому. Файл читается блоками, пиксели в память не распаковываются.
Размер изображения берётся из заголовка до любой работы с данными, поэтому decompression bomb
отсекается сразу. Данные PNG проверяются потоково: CRC каждого блока и распаковка с выбрасыванием
результата. У JPEG проверяется структура маркеров, но не содержимое сжатых данных: порча внутри скана
этой проверкой не обнаруживается.
"""
import struct
import zlib
BLOCK = 64 * 1024
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
JPEG_SIGNATURE = b"\xff\xd8\xff"
# допустимая глубина цвета для каждого типа PNG и число каналов
PNG_COLOR_TYPES = {0: ((1, 2, 4, 8, 16), 1), 2: ((8, 16), 3), 3: ((1, 2, 4, 8), 1), 4: ((8, 16), 2), 6: ((8, 16), 4)}
# все маркеры SOF, кроме DHT (C4), JPG (C8) и DAC (CC), которые попадают в тот же диапазон
JPEG_SOF = set(range(0xC0, 0xD0)) - {0xC4, 0xC8, 0xCC}
class NotAnImage(Exception):
pass
class TooManyPixels(Exception):
pass
def inspect(file, max_pixels: int) -> str:
"""Возвращает настоящий тип файла или бросает NotAnImage / TooManyPixels."""
file.seek(0)
head = file.read(8)
try:
if head == PNG_SIGNATURE:
check_png(file, max_pixels)
return "image/png"
if head[:3] == JPEG_SIGNATURE:
file.seek(2)
check_jpeg(file, max_pixels)
return "image/jpeg"
except (struct.error, zlib.error, ValueError) as error:
raise NotAnImage() from error
raise NotAnImage()
def check_size(width: int, height: int, max_pixels: int) -> None:
if width == 0 or height == 0:
raise NotAnImage()
if width * height > max_pixels:
raise TooManyPixels()
def png_raw_size(width: int, height: int, bits_per_pixel: int) -> int:
"""Размер распакованных данных без чересстрочности: строки плюс байт фильтра на каждую."""
return height * (1 + (width * bits_per_pixel + 7) // 8)
def check_png(file, max_pixels: int) -> None:
inflater = zlib.decompressobj()
header = None
limit = 0
unpacked = 0
interlaced = False
seen_data = False
while True:
length, kind = struct.unpack(">I4s", read_exact(file, 8))
if length >= 2**31 or (header is None and kind != b"IHDR"):
raise NotAnImage()
crc = zlib.crc32(kind)
remaining = length
body = b""
while remaining:
block = file.read(min(BLOCK, remaining))
if not block:
raise NotAnImage()
remaining -= len(block)
crc = zlib.crc32(block, crc)
if kind == b"IHDR":
body += block
elif kind == b"IDAT":
seen_data = True
unpacked += inflate(inflater, block, limit - unpacked)
if struct.unpack(">I", read_exact(file, 4))[0] != crc:
raise NotAnImage()
if kind == b"IHDR":
if header is not None or length != 13:
raise NotAnImage()
header = struct.unpack(">IIBBBBB", body)
width, height, depth, color, compression, filtering, interlace = header
depths, channels = PNG_COLOR_TYPES.get(color, ((), 0))
if depth not in depths or compression != 0 or filtering != 0 or interlace not in (0, 1):
raise NotAnImage()
check_size(width, height, max_pixels)
interlaced = interlace == 1
limit = png_raw_size(width, height, depth * channels)
if interlaced:
# чересстрочная запись длиннее: у каждого из семи проходов свои байты фильтра
limit += 7 * height + limit // 4
elif kind == b"IEND":
break
if not seen_data or not inflater.eof or file.read(1):
raise NotAnImage()
if not interlaced and unpacked != limit:
raise NotAnImage()
def inflate(inflater, block: bytes, allowed: int) -> int:
"""Распаковывает блок, не накапливая результат. Возвращает, сколько байт получилось."""
total = 0
while block and not inflater.eof:
chunk = inflater.decompress(block, BLOCK)
total += len(chunk)
if total > allowed:
raise NotAnImage()
block = inflater.unconsumed_tail
return total
def check_jpeg(file, max_pixels: int) -> None:
file.seek(0, 2)
end = file.tell()
file.seek(2)
seen_frame = False
seen_scan = False
while True:
if read_exact(file, 1) != b"\xff":
raise NotAnImage()
marker = 0xFF
while marker == 0xFF: # перед маркером разрешены байты-заполнители
marker = read_exact(file, 1)[0]
if marker == 0xD9: # конец изображения; данные после него допустимы, так делают камеры
if seen_scan:
return
raise NotAnImage()
if 0xD0 <= marker <= 0xD7 or marker == 0x01:
continue
if marker == 0x00 or marker == 0xD8:
raise NotAnImage()
length = struct.unpack(">H", read_exact(file, 2))[0]
if length < 2 or file.tell() + length - 2 > end:
raise NotAnImage()
if marker in JPEG_SOF:
if seen_frame or length < 8:
raise NotAnImage()
height, width = struct.unpack(">xHH", read_exact(file, 5))
check_size(width, height, max_pixels)
seen_frame = True
file.seek(length - 7, 1)
else:
file.seek(length - 2, 1)
if marker == 0xDA:
if not seen_frame:
raise NotAnImage()
seen_scan = True
skip_scan(file)
def skip_scan(file) -> None:
"""Проходит сжатые данные скана и оставляет файл на следующем маркере."""
while True:
start = file.tell()
block = file.read(BLOCK)
if len(block) < 2:
raise NotAnImage()
position = 0
while True:
position = block.find(b"\xff", position)
if position < 0:
break
if position + 1 == len(block): # маркер разрезан границей блока
file.seek(start + position)
break
following = block[position + 1]
if following == 0x00 or 0xD0 <= following <= 0xD7:
position += 2
elif following == 0xFF:
position += 1
else:
file.seek(start + position)
return
def read_exact(file, size: int) -> bytes:
data = file.read(size)
if len(data) != size:
raise NotAnImage()
return data