forked from mtusi2026/mtusi2026lab4
Байты лежат в SeaweedFS, метаданные в Postgres. Другая реплика скачивает тот же объект, потому что локальный диск API не является источником файла.
108 lines
3.3 KiB
Python
108 lines
3.3 KiB
Python
"""PNG/JPEG checks that reject bad files before a full pixel decode."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import io
|
|
from typing import Optional, Tuple
|
|
|
|
from PIL import Image, ImageFile, UnidentifiedImageError
|
|
|
|
from app import config
|
|
|
|
ImageFile.LOAD_TRUNCATED_IMAGES = False
|
|
_PNG = b"\x89PNG\r\n\x1a\n"
|
|
_JPEG = b"\xff\xd8\xff"
|
|
_SOF = {0xC0, 0xC1, 0xC2}
|
|
|
|
|
|
class ImageRejected(Exception):
|
|
def __init__(self, status: int, message: str) -> None:
|
|
super().__init__(message)
|
|
self.status = status
|
|
self.message = message
|
|
|
|
|
|
def _reject(status: int, message: str) -> None:
|
|
raise ImageRejected(status, message)
|
|
|
|
|
|
def sniff(data: bytes) -> Optional[str]:
|
|
if data.startswith(_PNG):
|
|
return "image/png"
|
|
if data.startswith(_JPEG):
|
|
return "image/jpeg"
|
|
return None
|
|
|
|
|
|
def _png_size(data: bytes) -> Tuple[int, int]:
|
|
if len(data) < 24 or data[12:16] != b"IHDR":
|
|
_reject(415, "unsupported or damaged image")
|
|
length = int.from_bytes(data[8:12], "big")
|
|
if length != 13 or len(data) < 33:
|
|
_reject(415, "unsupported or damaged image")
|
|
width = int.from_bytes(data[16:20], "big")
|
|
height = int.from_bytes(data[20:24], "big")
|
|
return width, height
|
|
|
|
|
|
def _jpeg_size(data: bytes) -> Tuple[int, int]:
|
|
index = 2
|
|
size = len(data)
|
|
while index < size:
|
|
if data[index] != 0xFF:
|
|
_reject(415, "unsupported or damaged image")
|
|
while index < size and data[index] == 0xFF:
|
|
index += 1
|
|
if index >= size:
|
|
break
|
|
marker = data[index]
|
|
index += 1
|
|
if marker in (0xD8, 0xD9, 0x01) or 0xD0 <= marker <= 0xD7:
|
|
continue
|
|
if index + 1 >= size:
|
|
break
|
|
segment = int.from_bytes(data[index : index + 2], "big")
|
|
if segment < 2 or index + segment > size:
|
|
_reject(415, "unsupported or damaged image")
|
|
if marker in _SOF:
|
|
if segment < 7:
|
|
_reject(415, "unsupported or damaged image")
|
|
height = int.from_bytes(data[index + 3 : index + 5], "big")
|
|
width = int.from_bytes(data[index + 5 : index + 7], "big")
|
|
return width, height
|
|
if marker == 0xDA:
|
|
break
|
|
index += segment
|
|
_reject(415, "unsupported or damaged image")
|
|
return 0, 0
|
|
|
|
|
|
def _check_pixels(width: int, height: int) -> None:
|
|
limit = config.MAX_IMAGE_PIXELS
|
|
if width <= 0 or height <= 0:
|
|
_reject(415, "unsupported or damaged image")
|
|
if width > limit or height > limit or width * height > limit:
|
|
_reject(413, "image dimensions exceed the limit")
|
|
|
|
|
|
def _verify(data: bytes) -> None:
|
|
Image.MAX_IMAGE_PIXELS = config.MAX_IMAGE_PIXELS
|
|
try:
|
|
with Image.open(io.BytesIO(data)) as image:
|
|
image.verify()
|
|
except Image.DecompressionBombError:
|
|
_reject(413, "image dimensions exceed the limit")
|
|
except (UnidentifiedImageError, OSError, ValueError, SyntaxError):
|
|
_reject(415, "unsupported or damaged image")
|
|
|
|
|
|
def inspect_image(data: bytes, declared: str) -> str:
|
|
"""Return the sniffed content type or raise ImageRejected (413 or 415)."""
|
|
found = sniff(data)
|
|
if found is None or found != declared:
|
|
_reject(415, "unsupported or damaged image")
|
|
width, height = _png_size(data) if found == "image/png" else _jpeg_size(data)
|
|
_check_pixels(width, height)
|
|
_verify(data)
|
|
return found
|