forked from mtusi2026/mtusi2026lab4
282 lines
13 KiB
Python
282 lines
13 KiB
Python
"""Проверка PNG и JPEG по содержимому, память ограничена.
|
|
|
|
Размер изображения берётся из заголовка до любой работы с данными, поэтому decompression bomb
|
|
отсекается сразу.
|
|
|
|
PNG проверяется потоково без декодера: CRC блоков, порядок блоков, распаковка с выбрасыванием
|
|
результата, байт фильтра в начале каждой строки, точный объём данных. Память не зависит от размера
|
|
изображения, поэтому Pillow здесь не нужен.
|
|
|
|
JPEG так проверить нельзя: чтобы понять, что в скане настоящие данные, их надо декодировать. Поэтому
|
|
сначала идёт быстрый разбор маркеров, а потом настоящий декодер с уменьшением в 8 раз. Обычный JPEG
|
|
при этом занимает несколько МБ. Прогрессивный хранит коэффициенты всего изображения, это до 2 байт на
|
|
отсчёт, то есть до 320 МБ на 40 млн пикселей CMYK, поэтому декодирование идёт по одному на реплику.
|
|
"""
|
|
import struct
|
|
import threading
|
|
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}
|
|
# кодирование Хаффмана: минимум 1 бит на блок. У арифметического (C9-CF) нижней границы нет
|
|
JPEG_HUFFMAN_SOF = {0xC0, 0xC1, 0xC2}
|
|
# каждый скан заставляет декодер пройти всё изображение, а в 10 MiB их можно уместить тысячи;
|
|
# настоящим файлам хватает нескольких десятков
|
|
MAX_JPEG_SCANS = 100
|
|
PNG_CRITICAL_CHUNKS = {b"IHDR", b"PLTE", b"IDAT", b"IEND"}
|
|
# проходы Adam7: первая колонка, первая строка, шаг по колонкам, шаг по строкам
|
|
ADAM7_PASSES = ((0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2))
|
|
|
|
# см. начало файла: не больше одного тяжёлого декодирования на реплику
|
|
decode_lock = threading.Lock()
|
|
|
|
|
|
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_structure(file, max_pixels)
|
|
decode_jpeg(file)
|
|
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_passes(width: int, height: int, bits_per_pixel: int, interlaced: bool) -> list:
|
|
"""Группы строк распакованных данных: (длина строки вместе с байтом фильтра, число строк)."""
|
|
if not interlaced:
|
|
return [(1 + (width * bits_per_pixel + 7) // 8, height)]
|
|
passes = []
|
|
for column, row, column_step, row_step in ADAM7_PASSES:
|
|
columns = (width - column + column_step - 1) // column_step
|
|
rows = (height - row + row_step - 1) // row_step
|
|
if columns > 0 and rows > 0: # у маленького изображения часть проходов пуста
|
|
passes.append((1 + (columns * bits_per_pixel + 7) // 8, rows))
|
|
return passes
|
|
|
|
|
|
class ScanlineFilters:
|
|
"""Следит за байтами фильтра в распакованном потоке, сами данные не хранит."""
|
|
|
|
def __init__(self, passes: list):
|
|
self.passes = iter(passes)
|
|
self.position = 0 # смещение начала следующего блока в распакованном потоке
|
|
self.next_filter = 0 # смещение следующего байта фильтра
|
|
self.row_size, self.rows_left = next(self.passes, (0, 0))
|
|
self.expected = sum(size * rows for size, rows in passes)
|
|
|
|
def feed(self, block: bytes) -> None:
|
|
end = self.position + len(block)
|
|
if end > self.expected:
|
|
raise NotAnImage()
|
|
while self.rows_left and self.next_filter < end:
|
|
start = self.next_filter - self.position
|
|
rows = min(self.rows_left, (len(block) - start + self.row_size - 1) // self.row_size)
|
|
# срез вместо цикла: строк может быть 40 млн, а Python проходит их слишком долго
|
|
if max(block[start:start + rows * self.row_size:self.row_size]) > 4:
|
|
raise NotAnImage()
|
|
self.next_filter += rows * self.row_size
|
|
self.rows_left -= rows
|
|
if not self.rows_left:
|
|
self.row_size, self.rows_left = next(self.passes, (0, 0))
|
|
self.position = end
|
|
|
|
|
|
def check_png(file, max_pixels: int) -> None:
|
|
inflater = zlib.decompressobj()
|
|
filters = None
|
|
seen_palette = False
|
|
seen_data = False
|
|
data_finished = False
|
|
color = None
|
|
while True:
|
|
length, kind = struct.unpack(">I4s", read_exact(file, 8))
|
|
if length >= 2**31 or not kind.isalpha() or (filters is None and kind != b"IHDR"):
|
|
raise NotAnImage()
|
|
# заглавная первая буква значит «без понимания этого блока файл читать нельзя»
|
|
if kind[0] < 0x61 and kind not in PNG_CRITICAL_CHUNKS:
|
|
raise NotAnImage()
|
|
if kind == b"IDAT":
|
|
if data_finished or (color == 3 and not seen_palette):
|
|
raise NotAnImage()
|
|
elif seen_data:
|
|
data_finished = True # блоки IDAT должны идти подряд
|
|
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" and len(body) <= 13:
|
|
body += block
|
|
elif kind == b"IDAT":
|
|
seen_data = True
|
|
inflate(inflater, block, filters)
|
|
if struct.unpack(">I", read_exact(file, 4))[0] != crc:
|
|
raise NotAnImage()
|
|
if kind == b"IHDR":
|
|
if filters is not None or length != 13:
|
|
raise NotAnImage()
|
|
width, height, depth, color, compression, filtering, interlace = struct.unpack(">IIBBBBB", body)
|
|
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)
|
|
filters = ScanlineFilters(png_passes(width, height, depth * channels, interlace == 1))
|
|
elif kind == b"PLTE":
|
|
if seen_palette or seen_data or color in (0, 4) or length == 0 or length % 3 or length > 768:
|
|
raise NotAnImage()
|
|
seen_palette = True
|
|
elif kind == b"IEND":
|
|
if length != 0:
|
|
raise NotAnImage()
|
|
break
|
|
if not seen_data or not inflater.eof or inflater.unused_data or file.read(1):
|
|
raise NotAnImage()
|
|
if filters.position != filters.expected:
|
|
raise NotAnImage()
|
|
|
|
|
|
def inflate(inflater, block: bytes, filters: ScanlineFilters) -> None:
|
|
"""Распаковывает блок и проверяет строки, не накапливая результат."""
|
|
while block and not inflater.eof:
|
|
filters.feed(inflater.decompress(block, BLOCK))
|
|
block = inflater.unconsumed_tail
|
|
|
|
|
|
def check_jpeg_structure(file, max_pixels: int) -> None:
|
|
"""Быстрая проверка маркеров: размер, число сканов, объём данных. Содержимое проверит декодер."""
|
|
file.seek(0, 2)
|
|
end = file.tell()
|
|
file.seek(2)
|
|
frame = None
|
|
scans = 0
|
|
scan_bytes = 0
|
|
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: # конец изображения; данные после него допустимы, так делают камеры
|
|
break
|
|
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()
|
|
segment = read_exact(file, length - 2)
|
|
if marker in JPEG_SOF:
|
|
if frame is not None:
|
|
raise NotAnImage()
|
|
frame = marker, parse_frame(segment, max_pixels)
|
|
if marker == 0xDA:
|
|
scans += 1
|
|
if frame is None or scans > MAX_JPEG_SCANS:
|
|
raise NotAnImage()
|
|
scan_bytes += skip_scan(file)
|
|
if frame is None or not scans:
|
|
raise NotAnImage()
|
|
# без этой проверки декодер принял бы заголовки с почти пустым сканом: конец данных он считает предупреждением
|
|
if frame[0] in JPEG_HUFFMAN_SOF and scan_bytes * 8 < frame[1]:
|
|
raise NotAnImage()
|
|
|
|
|
|
def parse_frame(segment: bytes, max_pixels: int) -> int:
|
|
"""Проверяет заголовок кадра и возвращает число блоков изображения."""
|
|
if len(segment) < 6:
|
|
raise NotAnImage()
|
|
_, height, width, components = struct.unpack(">BHHB", segment[:6])
|
|
if components not in (1, 3, 4) or len(segment) != 6 + 3 * components:
|
|
raise NotAnImage()
|
|
check_size(width, height, max_pixels)
|
|
sampling = [segment[7 + 3 * index] for index in range(components)]
|
|
horizontal = [value >> 4 for value in sampling]
|
|
vertical = [value & 0x0F for value in sampling]
|
|
if not all(1 <= value <= 4 for value in horizontal + vertical):
|
|
raise NotAnImage()
|
|
mcu_columns = (width + 8 * max(horizontal) - 1) // (8 * max(horizontal))
|
|
mcu_rows = (height + 8 * max(vertical) - 1) // (8 * max(vertical))
|
|
return mcu_columns * mcu_rows * sum(h * v for h, v in zip(horizontal, vertical))
|
|
|
|
|
|
def skip_scan(file) -> int:
|
|
"""Проходит сжатые данные скана, оставляет файл на следующем маркере и возвращает их объём."""
|
|
begin = file.tell()
|
|
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 start + position - begin
|
|
|
|
|
|
def decode_jpeg(file) -> None:
|
|
"""Настоящее декодирование с уменьшением: файл принимается, только если декодер дошёл до конца."""
|
|
from PIL import Image # здесь, а не в начале файла: разбор PNG декодера не требует
|
|
|
|
file.seek(0)
|
|
with decode_lock:
|
|
try:
|
|
with Image.open(file, formats=["JPEG"]) as image:
|
|
image.draft(None, (max(1, image.width // 8), max(1, image.height // 8)))
|
|
image.load()
|
|
except MemoryError:
|
|
raise
|
|
except Exception as error: # у декодера нет единого исключения: OSError, SyntaxError, ValueError и другие
|
|
raise NotAnImage() from error
|
|
|
|
|
|
def read_exact(file, size: int) -> bytes:
|
|
data = file.read(size)
|
|
if len(data) != size:
|
|
raise NotAnImage()
|
|
return data
|