forked from mtusi2026/mtusi2026lab5
80 lines
3.0 KiB
Python
80 lines
3.0 KiB
Python
from __future__ import annotations
|
||
|
||
import unicodedata
|
||
import warnings
|
||
from typing import BinaryIO, Optional, Tuple
|
||
|
||
from PIL import Image
|
||
|
||
from app import config
|
||
from app.errors import ApiError, payload_too_large, unsupported_media_type
|
||
|
||
# Pillow itself refuses > 2x this value; our own check below rejects anything above it before decoding.
|
||
Image.MAX_IMAGE_PIXELS = config.MAX_IMAGE_PIXELS
|
||
Image.LOAD_TRUNCATED_IMAGES = False
|
||
|
||
PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
|
||
JPEG_MAGIC = b"\xff\xd8\xff"
|
||
FORMATS = {"image/png": "PNG", "image/jpeg": "JPEG"}
|
||
SNIFF_BYTES = 8
|
||
|
||
# Bidi overrides/isolates make "gpj.exe" look like "exe.jpg"; reject them together with control characters.
|
||
_BIDI_CONTROLS = set("")
|
||
|
||
|
||
def validate_filename(name: Optional[str]) -> str:
|
||
bad = ApiError(400, "invalid_request", "filename must be 1-255 characters without path separators or control characters")
|
||
if name is None or not 1 <= len(name) <= 255 or not name.strip() or name in (".", ".."):
|
||
raise bad
|
||
for ch in name:
|
||
if ch in "/\\" or ch in _BIDI_CONTROLS or unicodedata.category(ch) in ("Cc", "Zl", "Zp"):
|
||
raise bad
|
||
return name
|
||
|
||
|
||
def declared_type(header: Optional[str]) -> str:
|
||
media = (header or "").split(";", 1)[0].strip().lower()
|
||
if media not in FORMATS:
|
||
raise unsupported_media_type("Content-Type must be image/png or image/jpeg")
|
||
return media
|
||
|
||
|
||
def sniff(head: bytes) -> Optional[str]:
|
||
if head.startswith(PNG_MAGIC):
|
||
return "image/png"
|
||
if head.startswith(JPEG_MAGIC):
|
||
return "image/jpeg"
|
||
return None
|
||
|
||
|
||
def _open(fp: BinaryIO, fmt: str) -> Image.Image:
|
||
fp.seek(0)
|
||
return Image.open(fp, formats=[fmt])
|
||
|
||
|
||
def inspect(fp: BinaryIO, content_type: str) -> Tuple[int, int]:
|
||
"""Cheap synchronous checks before 202: format by content, dimensions from the header, pixel limit
|
||
before any decoding, PNG chunk CRCs (no IDAT inflation). Full decoding is the worker's job (lab5): a file
|
||
that passes these checks but cannot be decoded ends as status=failed, error_code=invalid_image.
|
||
"""
|
||
fmt = FORMATS[content_type]
|
||
corrupt = unsupported_media_type("file is not a valid " + fmt + " image")
|
||
try:
|
||
with warnings.catch_warnings():
|
||
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||
with _open(fp, fmt) as im:
|
||
width, height = im.size
|
||
if width < 1 or height < 1:
|
||
raise corrupt
|
||
if width * height > config.MAX_IMAGE_PIXELS:
|
||
raise payload_too_large("image exceeds %d pixels" % config.MAX_IMAGE_PIXELS)
|
||
if fmt == "PNG":
|
||
im.verify() # chunk structure and CRCs; the object is unusable afterwards
|
||
except ApiError:
|
||
raise
|
||
except (Image.DecompressionBombError, Image.DecompressionBombWarning):
|
||
raise payload_too_large("image exceeds %d pixels" % config.MAX_IMAGE_PIXELS) from None
|
||
except (OSError, SyntaxError, ValueError, EOFError, MemoryError):
|
||
raise corrupt from None
|
||
return width, height
|