Files
mtusi2026lab4/src/images.py
T

140 lines
5.3 KiB
Python

import struct
import zlib
from PIL import Image
from config import settings
from errors import ApiError
SIGNATURES = {'image/png': b'\x89PNG\r\n\x1a\n', 'image/jpeg': b'\xff\xd8\xff'}
FORMATS = {'image/png': 'PNG', 'image/jpeg': 'JPEG'}
FORBIDDEN_FILENAME = set('/\\\x7f') | {chr(code) for code in range(32)} | {chr(code) for code in range(0x80, 0xa0)}
Image.MAX_IMAGE_PIXELS = settings.max_image_pixels
def check_filename(filename):
if filename is None or not 1 <= len(filename) <= 255 or not filename.strip() \
or any(char in FORBIDDEN_FILENAME for char in filename):
raise ApiError(400, 'Некорректный filename: 1–255 символов без /, \\ и управляющих символов')
try:
filename.encode('utf-8')
except UnicodeEncodeError:
raise ApiError(400, 'Некорректный filename') from None
def check_content_type(header):
content_type = (header or '').split(';')[0].strip().lower()
if content_type not in SIGNATURES:
raise ApiError(415, 'Принимаются только сырые байты image/png или image/jpeg')
return content_type
CHANNELS = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}
ADAM7 = ((0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2))
def png_rows(ihdr):
width, height, depth, color, _, _, interlace = struct.unpack('>IIBBBBB', ihdr)
bits = depth * CHANNELS[color]
if interlace:
passes = [(-(-(width - x0) // dx), -(-(height - y0) // dy)) for x0, y0, dx, dy in ADAM7]
else:
passes = [(width, height)]
return [((w * bits + 7) // 8 + 1, h) for w, h in passes if w > 0 and h > 0]
class PixelData:
def __init__(self, ihdr, piece):
self.rows = png_rows(ihdr)
self.expected = sum(length * count for length, count in self.rows)
self.inflater = zlib.decompressobj()
self.piece = piece
self.total = 0
self.segment = 0
self.offset = 0
def feed(self, data):
while data:
if self.inflater.eof:
return
out = self.inflater.decompress(data, self.piece)
data = self.inflater.unconsumed_tail
self.check(out)
def check(self, out):
self.total += len(out)
if self.total > self.expected:
raise ValueError('PNG pixel data is longer than IHDR allows')
while out:
length, count = self.rows[self.segment]
take = min(len(out), length * count - self.offset)
part, out = out[:take], out[take:]
filters = part[(-self.offset) % length::length]
if filters and max(filters) > 4:
raise ValueError('PNG row has an invalid filter type')
self.offset += take
if self.offset == length * count:
self.segment, self.offset = self.segment + 1, 0
def finish(self):
if not self.inflater.eof or self.total != self.expected:
raise ValueError('PNG pixel data is truncated')
def verify_png(fileobj, piece=64 * 1024):
"""Потоково: CRC каждого чанка и распаковка IDAT кусками по piece байт без хранения пикселей."""
fileobj.seek(8)
pixels = None
while True:
header = fileobj.read(8)
if len(header) < 8:
raise ValueError('PNG ended before IEND')
length, kind = struct.unpack('>I4s', header)
if pixels is None and kind != b'IHDR':
raise ValueError('PNG must start with IHDR')
crc = zlib.crc32(kind)
left = length
while left:
data = fileobj.read(min(piece, left))
if not data:
raise ValueError('PNG chunk is truncated')
crc = zlib.crc32(data, crc)
left -= len(data)
if kind == b'IHDR':
pixels = PixelData(data, piece)
elif kind == b'IDAT':
pixels.feed(data)
stored = fileobj.read(4)
if len(stored) < 4 or struct.unpack('>I', stored)[0] != crc & 0xffffffff:
raise ValueError('PNG chunk CRC mismatch')
if kind == b'IEND':
pixels.finish()
return
def inspect(fileobj, content_type):
fileobj.seek(0)
if not fileobj.read(8).startswith(SIGNATURES[content_type]):
raise ApiError(415, 'Содержимое файла не соответствует ' + content_type)
fileobj.seek(0)
try:
with Image.open(fileobj, formats=[FORMATS[content_type]]) as image:
width, height = image.size
if width * height > settings.max_image_pixels:
raise ApiError(413, 'Изображение больше %d пикселей' % settings.max_image_pixels)
if content_type == 'image/png':
verify_png(fileobj)
else:
image.draft('L', (max(1, width // 8), max(1, height // 8)))
image.load()
except ApiError:
raise
except Image.DecompressionBombError:
raise ApiError(413, 'Изображение больше %d пикселей' % settings.max_image_pixels) from None
except Exception:
raise ApiError(415, 'Файл повреждён или не является изображением ' + content_type) from None
finally:
fileobj.seek(0)
return width, height