"""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, Optional from .errors import payload_too_large, unsupported_media_type MAX_UPLOAD_BYTES = 10_485_760 MAX_IMAGE_PIXELS = 40_000_000 # SOF/IHDR almost always sit in the first tens of kilobytes. The rest of the # object is hashed and stored without being held as one Python bytes object. INSPECT_PREFIX = 256 * 1024 _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} class _NeedMore(Exception): """The prefix does not yet contain a complete PNG IHDR or JPEG SOF.""" 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) -> str: if len(data) < 8: if _PNG.startswith(data): raise _NeedMore() _reject() if not data.startswith(_PNG): _reject() if len(data) < 24: raise _NeedMore() 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) return 'image/png' def _jpeg_size(data: bytes) -> str: if len(data) < 2: if b'\xff\xd8'.startswith(data): raise _NeedMore() _reject() if 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): raise _NeedMore() 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): raise _NeedMore() segment_length = int.from_bytes(data[index:index + 2], 'big') if segment_length < 2: _reject() if index + segment_length > len(data): raise _NeedMore() # 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 'image/jpeg' index += segment_length _reject() def inspect_prefix(data: bytes, *, complete: bool) -> Optional[str]: """Return image/png or image/jpeg, or None if `complete` is false and more bytes are required.""" if not data: if complete: _reject() return None try: if data[0] == 0x89: return _png_size(data) if data[0] == 0xFF: return _jpeg_size(data) _reject() except _NeedMore: if complete: _reject() return None def inspect_image(data: bytes) -> str: """Return image/png or image/jpeg after a header check. Raises 413 or 415.""" result = inspect_prefix(data, complete=True) if result is None: _reject() return result