""" Проверка загруженного изображения ПО СОДЕРЖИМОМУ (lab4). Порядок важен: сначала дешёвые проверки, потом дорогие. 1. Сигнатура (magic bytes) → реальный тип. Не PNG/JPEG или не совпадает с заявленным Content-Type → 415 (подмена MIME). 2. Размеры из заголовка (PNG IHDR / JPEG SOF) → width × height ≤ MAX_IMAGE_PIXELS, иначе 413. Это делается ДО распаковки пикселей: «декомпрессионная бомба» (маленький файл, огромная картинка) отсекается, не заняв память. 3. Целостность → повреждённый файл даёт 415: - PNG: потоково читаем чанки, сверяем CRC каждого, распаковываем IDAT кусками по 64 КиБ и только СЧИТАЕМ байты (пиксели не храним). Объём распакованных данных должен ровно совпасть с тем, что следует из IHDR; лишнее сверх ожидаемого не распаковываем вообще. - JPEG: Pillow в режиме draft (декодирование в масштабе 1/8) — весь поток проверяется декодером, а памяти нужно в ~64 раза меньше. Памяти на проверку: O(64 КиБ) для PNG и ~(пиксели/64)×3 байт для JPEG, независимо от размера файла. """ from __future__ import annotations import struct import warnings import zlib from dataclasses import dataclass from typing import BinaryIO from PIL import Image, ImageFile PNG_SIG = b"\x89PNG\r\n\x1a\n" JPEG_SIG = b"\xff\xd8\xff" CHUNK = 64 * 1024 # Усечённый файл — ошибка, а не «догрузим серым». ImageFile.LOAD_TRUNCATED_IMAGES = False # Предупреждение Pillow о «бомбе» превращаем в исключение (→ 413), а не в строку лога. warnings.simplefilter("error", Image.DecompressionBombWarning) class ImageTooLarge(Exception): """Слишком много пикселей → 413.""" class BadImage(Exception): """Не PNG/JPEG, тип не совпадает с Content-Type или файл повреждён → 415.""" @dataclass(frozen=True) class ImageInfo: content_type: str width: int height: int def sniff(head: bytes) -> str | None: """Реальный тип по первым байтам. Расширение и заголовок клиента не учитываются.""" if head.startswith(PNG_SIG): return "image/png" if head.startswith(JPEG_SIG): return "image/jpeg" return None def inspect(f: BinaryIO, declared_type: str, max_pixels: int) -> ImageInfo: """Проверить файл (seekable) и вернуть реальный тип и размеры. Бросает ImageTooLarge или BadImage. Блокирующая: вызывать в пуле потоков.""" f.seek(0) actual = sniff(f.read(16)) if actual is None: raise BadImage("not a PNG or JPEG") if actual != declared_type: raise BadImage("content does not match Content-Type") f.seek(0) try: if actual == "image/png": w, h = _check_png(f, max_pixels) else: w, h = _check_jpeg(f, max_pixels) except (ImageTooLarge, BadImage): raise except (zlib.error, struct.error, ValueError, OSError, EOFError, IndexError) as exc: # Любая ошибка разбора содержимого клиента — это битый файл (415), а не 500. raise BadImage("corrupt image data") from exc return ImageInfo(actual, w, h) # --------------------------------------------------------------------- PNG # color type → число каналов; допустимые глубины цвета (спецификация PNG, 11.2.2) _PNG_CHANNELS = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4} _PNG_DEPTHS = {0: {1, 2, 4, 8, 16}, 2: {8, 16}, 3: {1, 2, 4, 8}, 4: {8, 16}, 6: {8, 16}} # Adam7: (x0, y0, dx, dy) семи проходов _ADAM7 = ((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)) def _png_layout(w: int, h: int, bits_per_pixel: int, interlaced: bool) -> list[tuple[int, int]]: """Список (число строк, длина строки с байтом фильтра) для всех проходов.""" def stride(width: int) -> int: return 1 + (width * bits_per_pixel + 7) // 8 if not interlaced: return [(h, stride(w))] out = [] for x0, y0, dx, dy in _ADAM7: pw = (w - x0 + dx - 1) // dx if w > x0 else 0 ph = (h - y0 + dy - 1) // dy if h > y0 else 0 if pw and ph: out.append((ph, stride(pw))) return out def _read_exact(f: BinaryIO, n: int) -> bytes: data = f.read(n) if len(data) != n: raise BadImage("truncated PNG") return data def _check_png(f: BinaryIO, max_pixels: int) -> tuple[int, int]: if f.read(8) != PNG_SIG: raise BadImage("bad PNG signature") width = height = 0 layout: list[tuple[int, int]] = [] expected = produced = 0 seg = row_left = 0 # позиция для проверки байтов фильтра строк inflater = None seen_ihdr = seen_plte = seen_idat = seen_iend = False color_type = 0 def consume(raw: bytes) -> None: """Учесть распакованные байты: длина и байт фильтра в начале каждой строки.""" nonlocal produced, seg, row_left produced += len(raw) if produced > expected: raise BadImage("PNG image data is longer than declared") pos = 0 while pos < len(raw): if row_left == 0: # начало новой строки: байт фильтра 0..4 if raw[pos] > 4: raise BadImage("bad PNG filter type") rows, stride = layout[seg] layout[seg] = (rows - 1, stride) if layout[seg][0] == 0: seg += 1 row_left = stride take = min(row_left, len(raw) - pos) row_left -= take pos += take def feed(data: bytes) -> None: """Распаковать порциями ≤64 КиБ: бомба внутри IDAT не займёт память. Цикл продолжается, пока zlib отдаёт полный буфер (могут остаться данные).""" while True: out = inflater.decompress(data, CHUNK) consume(out) data = inflater.unconsumed_tail if inflater.eof or (not data and len(out) < CHUNK): return while not seen_iend: length, ctype = struct.unpack(">I4s", _read_exact(f, 8)) if length > 0x7FFFFFFF or not ctype.isalpha(): raise BadImage("bad PNG chunk") crc = zlib.crc32(ctype) if not seen_ihdr and ctype != b"IHDR": raise BadImage("PNG must start with IHDR") if ctype == b"IHDR": if seen_ihdr or length != 13: raise BadImage("bad IHDR") data = _read_exact(f, 13) crc = zlib.crc32(data, crc) width, height, depth, color_type, comp, filt, interlace = struct.unpack(">IIBBBBB", data) if width == 0 or height == 0 or width > 0x7FFFFFFF or height > 0x7FFFFFFF: raise BadImage("bad PNG dimensions") # Лимит пикселей — ДО распаковки данных. if width * height > max_pixels: raise ImageTooLarge(f"{width}x{height} exceeds pixel limit") if color_type not in _PNG_CHANNELS or depth not in _PNG_DEPTHS[color_type] \ or comp != 0 or filt != 0 or interlace not in (0, 1): raise BadImage("unsupported PNG header") layout = _png_layout(width, height, depth * _PNG_CHANNELS[color_type], interlace == 1) expected = sum(rows * stride for rows, stride in layout) inflater = zlib.decompressobj() seen_ihdr = True else: left = length while left: part = _read_exact(f, min(CHUNK, left)) left -= len(part) crc = zlib.crc32(part, crc) if ctype == b"IDAT": if inflater is None or inflater.eof: raise BadImage("unexpected PNG data") feed(part) if ctype == b"IDAT": seen_idat = True elif ctype == b"PLTE": seen_plte = True elif ctype == b"IEND": seen_iend = True stored_crc = struct.unpack(">I", _read_exact(f, 4))[0] if stored_crc != crc & 0xFFFFFFFF: raise BadImage("PNG CRC mismatch") if not seen_idat or inflater is None: raise BadImage("PNG has no image data") if color_type == 3 and not seen_plte: raise BadImage("palette PNG without PLTE") if not inflater.eof or produced != expected: raise BadImage("PNG image data is incomplete") return width, height # -------------------------------------------------------------------- JPEG def _check_jpeg(f: BinaryIO, max_pixels: int) -> tuple[int, int]: # Страховка Pillow от бомб; основной лимит проверяем сами ниже. Image.MAX_IMAGE_PIXELS = max_pixels try: with Image.open(f, formats=["JPEG"]) as img: # читает только заголовок width, height = img.size if width <= 0 or height <= 0: raise BadImage("bad JPEG dimensions") if width * height > max_pixels: raise ImageTooLarge(f"{width}x{height} exceeds pixel limit") # Декодируем весь поток в масштабе 1/8: битый/усечённый файл даст ошибку, # а памяти нужно (W/8)×(H/8)×3 байт вместо W×H×3. img.draft("RGB", (max(1, width // 8), max(1, height // 8))) img.load() except (Image.DecompressionBombError, Image.DecompressionBombWarning) as exc: raise ImageTooLarge("pixel limit") from exc except (ImageTooLarge, BadImage): raise except (OSError, SyntaxError, ValueError, struct.error, EOFError, IndexError) as exc: raise BadImage("corrupt JPEG") from exc return width, height