Files
mtusi2026lab4/app/images.py
T

85 lines
2.8 KiB
Python

"""PNG/JPEG checks that look at the header only.
Dimensions come from IHDR or a JPEG SOF marker. The compressed pixel data is never unpacked,
so a small file cannot expand into an unbounded bitmap before the pixel limit is applied.
"""
from typing import NoReturn
from .errors import payload_too_large, unsupported_media_type
MAX_UPLOAD_BYTES = 10_485_760
MAX_IMAGE_PIXELS = 40_000_000
_PNG = b'\x89PNG\r\n\x1a\n'
# SOF markers that carry width and height. DHT/DAC/JPG are skipped by the length field.
_JPEG_SOF = {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF}
def _reject() -> NoReturn:
raise unsupported_media_type('Файл не является PNG или JPEG')
def _check_pixels(width: int, height: int) -> None:
if width <= 0 or height <= 0:
_reject()
if width > MAX_IMAGE_PIXELS or height > MAX_IMAGE_PIXELS or width * height > MAX_IMAGE_PIXELS:
raise payload_too_large('Изображение превышает 40 миллионов пикселей')
def _png_size(data: bytes) -> None:
if len(data) < 24 or not data.startswith(_PNG):
_reject()
if int.from_bytes(data[8:12], 'big') != 13 or data[12:16] != b'IHDR':
_reject()
width = int.from_bytes(data[16:20], 'big')
height = int.from_bytes(data[20:24], 'big')
_check_pixels(width, height)
def _jpeg_size(data: bytes) -> None:
if len(data) < 4 or data[0:2] != b'\xff\xd8':
_reject()
index = 2
while index < len(data):
if data[index] != 0xFF:
_reject()
index += 1
while index < len(data) and data[index] == 0xFF:
index += 1
if index >= len(data):
break
marker = data[index]
index += 1
if marker in (0x01, 0xD8, 0xD9) or 0xD0 <= marker <= 0xD7:
if marker == 0xD9:
break
continue
if index + 2 > len(data):
break
segment_length = int.from_bytes(data[index:index + 2], 'big')
if segment_length < 2 or index + segment_length > len(data):
_reject()
# Start of scan: entropy-coded bytes follow. Dimensions must already have been seen.
if marker == 0xDA:
break
if marker in _JPEG_SOF:
if segment_length < 7:
_reject()
height = int.from_bytes(data[index + 3:index + 5], 'big')
width = int.from_bytes(data[index + 5:index + 7], 'big')
_check_pixels(width, height)
return
index += segment_length
_reject()
def inspect_image(data: bytes) -> str:
"""Return image/png or image/jpeg after a header check. Raises 413 or 415."""
if data.startswith(_PNG):
_png_size(data)
return 'image/png'
if data.startswith(b'\xff\xd8'):
_jpeg_size(data)
return 'image/jpeg'
_reject()