forked from mtusi2026/mtusi2026lab5
89 lines
3.7 KiB
Python
89 lines
3.7 KiB
Python
"""Проверка изображения по содержимому, без доверия к Content-Type клиента."""
|
|
from __future__ import annotations
|
|
|
|
import struct
|
|
import warnings
|
|
from dataclasses import dataclass
|
|
|
|
from PIL import Image, UnidentifiedImageError
|
|
|
|
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
|
|
JPEG_SIGNATURE = b"\xff\xd8\xff"
|
|
|
|
|
|
class UnsupportedImage(ValueError):
|
|
"""Не PNG/JPEG или файл повреждён."""
|
|
|
|
|
|
class ImageTooLarge(ValueError):
|
|
"""Пиксельный предел контракта превышен."""
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class ImageInfo:
|
|
content_type: str
|
|
width: int
|
|
height: int
|
|
|
|
|
|
def detect_content_type(head: bytes) -> str | None:
|
|
"""MIME по первым байтам, а не по заголовку запроса."""
|
|
if head.startswith(PNG_SIGNATURE):
|
|
return "image/png"
|
|
if head.startswith(JPEG_SIGNATURE):
|
|
return "image/jpeg"
|
|
return None
|
|
|
|
|
|
def inspect_image(path: str, *, expected_content_type: str, max_pixels: int) -> ImageInfo:
|
|
"""Проверяет сигнатуру, формат, целостность и число пикселей.
|
|
|
|
Размеры читаются из заголовка и проверяются до полной распаковки; для
|
|
отсечения бомб Pillow получает те же пределы, а предупреждение о бомбе
|
|
превращается в `ImageTooLarge`. Полное декодирование в этой лабораторной
|
|
не требуется: вариантов изображения нет.
|
|
"""
|
|
with open(path, "rb") as probe:
|
|
head = probe.read(len(PNG_SIGNATURE))
|
|
detected = detect_content_type(head)
|
|
if detected is None:
|
|
raise UnsupportedImage("Содержимое не является PNG/JPEG")
|
|
if detected != expected_content_type:
|
|
raise UnsupportedImage("Content-Type не совпадает с содержимым")
|
|
|
|
try:
|
|
with warnings.catch_warnings():
|
|
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
|
with Image.open(path) as image:
|
|
width, height = image.size
|
|
image_format = image.format
|
|
if width <= 0 or height <= 0:
|
|
raise UnsupportedImage("Некорректные размеры изображения")
|
|
if width * height > max_pixels:
|
|
raise ImageTooLarge("Изображение превышает предел пикселей")
|
|
if image_format not in ("PNG", "JPEG"):
|
|
raise UnsupportedImage("Формат изображения не PNG/JPEG")
|
|
image.verify()
|
|
except (UnsupportedImage, ImageTooLarge):
|
|
raise
|
|
except Image.DecompressionBombWarning as exc:
|
|
raise ImageTooLarge("Изображение превышает предел пикселей") from exc
|
|
except Image.DecompressionBombError as exc:
|
|
raise ImageTooLarge("Изображение превышает предел пикселей") from exc
|
|
except (
|
|
UnidentifiedImageError,
|
|
OSError,
|
|
SyntaxError,
|
|
ValueError,
|
|
struct.error,
|
|
IndexError,
|
|
OverflowError,
|
|
) as exc:
|
|
raise UnsupportedImage("Изображение повреждено") from exc
|
|
|
|
if detected == "image/png" and image_format != "PNG":
|
|
raise UnsupportedImage("Расширение и формат PNG не совпали")
|
|
if detected == "image/jpeg" and image_format != "JPEG":
|
|
raise UnsupportedImage("Расширение и формат JPEG не совпали")
|
|
return ImageInfo(content_type=detected, width=width, height=height)
|