Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
286 changes: 286 additions & 0 deletions src/kerf/qcow2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,286 @@
# Copyright 2026 Saeed Nourian
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
qcow2 image decoding.

Pure Python, no external commands. See docs/interop/qcow2.rst in the
QEMU source tree for the format.
"""

import struct
import contextlib
import importlib
import io
import zlib
import os
import secrets
from dataclasses import dataclass
from typing import BinaryIO, Optional, Tuple

from .exceptions import KerfError


class Qcow2Error(KerfError):
"""Raised when a qcow2 image is malformed or uses an unsupported feature."""


QCOW2_MAGIC = b"QFI\xfb"

# Header bytes 0-71, big endian: magic, version, backing_file_offset,
# backing_file_size, cluster_bits, size, crypt_method, l1_size,
# l1_table_offset, refcount_table_offset, refcount_table_clusters,
# nb_snapshots, snapshots_offset
_HEADER_V2 = struct.Struct(">4sIQIIQIIQQIIQ")
# Header bytes 72-103, version 3 only: incompatible_features,
# compatible_features, autoclear_features, refcount_order, header_length
_HEADER_V3 = struct.Struct(">QQQII")
_COMPRESSION_TYPE_OFFSET = 104

_MIN_CLUSTER_BITS = 9
_MAX_CLUSTER_BITS = 21 # QEMU refuses clusters above 2 MiB
_MAX_L1_BYTES = 32 * 1024 * 1024 # QEMU's own limit

INCOMPAT_CORRUPT = 1 << 1
INCOMPAT_EXTERNAL_DATA = 1 << 2
INCOMPAT_COMPRESSION_TYPE = 1 << 3
INCOMPAT_EXTENDED_L2 = 1 << 4
_KNOWN_INCOMPAT = 0x1F # dirty (bit 0) is fine, we never read refcounts

COMPRESSION_DEFLATE = 0
COMPRESSION_ZSTD = 1


@dataclass(frozen=True)
class Qcow2Header:
"""The fields of a qcow2 header that decoding needs."""
version: int
cluster_bits: int
size: int
l1_size: int
l1_table_offset: int
compression_type: int

@property
def cluster_size(self) -> int:
return 1 << self.cluster_bits


def parse_header(data: bytes, file_size: int) -> Qcow2Header:
"""
Parse and validate a qcow2 header.

Args:
data: The start of the image, at least its first 512 bytes
file_size: Size of the whole image file, to bound the offsets

Raises:
Qcow2Error: If the image is malformed or needs an unsupported feature
"""
if len(data) < _HEADER_V2.size:
raise Qcow2Error("file is too small to be a qcow2 image")

(magic, version, backing_offset, _backing_size, cluster_bits, size,
crypt_method, l1_size, l1_offset, _refcount_offset, _refcount_clusters,
_nb_snapshots, _snapshots_offset) = _HEADER_V2.unpack_from(data)

if magic != QCOW2_MAGIC:
raise Qcow2Error("not a qcow2 image (bad magic)")
if version not in (2, 3):
raise Qcow2Error(f"unsupported qcow2 version {version}")
if not _MIN_CLUSTER_BITS <= cluster_bits <= _MAX_CLUSTER_BITS:
raise Qcow2Error(f"invalid qcow2 cluster size (cluster_bits={cluster_bits})")
if backing_offset:
raise Qcow2Error("qcow2 backing files are not supported")
if crypt_method:
raise Qcow2Error("qcow2 encryption is not supported")

compression = COMPRESSION_DEFLATE
if version == 3:
v3_end = _HEADER_V2.size + _HEADER_V3.size
if len(data) < v3_end:
raise Qcow2Error("truncated qcow2 version 3 header")
incompat, _compat, _autoclear, _refcount_order, header_length = (
_HEADER_V3.unpack_from(data, _HEADER_V2.size))
if header_length < v3_end or header_length % 8 or header_length > len(data):
raise Qcow2Error(f"invalid qcow2 header length {header_length}")
if incompat & ~_KNOWN_INCOMPAT:
raise Qcow2Error(
f"qcow2 image uses unknown incompatible features {incompat & ~_KNOWN_INCOMPAT:#x}")
if incompat & INCOMPAT_CORRUPT:
raise Qcow2Error("qcow2 image is marked corrupt")
if incompat & INCOMPAT_EXTERNAL_DATA:
raise Qcow2Error("qcow2 external data files are not supported")
if incompat & INCOMPAT_EXTENDED_L2:
raise Qcow2Error("qcow2 extended L2 entries are not supported")
if incompat & INCOMPAT_COMPRESSION_TYPE:
# The field only exists if header_length reaches past it
if header_length > _COMPRESSION_TYPE_OFFSET:
compression = data[_COMPRESSION_TYPE_OFFSET]
if compression != COMPRESSION_ZSTD:
raise Qcow2Error(f"unknown qcow2 compression type {compression}")

cluster_size = 1 << cluster_bits
l2_entries = cluster_size // 8
clusters = (size + cluster_size - 1) >> cluster_bits
l1_needed = (clusters + l2_entries - 1) // l2_entries
if l1_size < l1_needed or l1_size * 8 > _MAX_L1_BYTES:
raise Qcow2Error(f"invalid qcow2 L1 table size {l1_size}")
if l1_offset % cluster_size or l1_offset + l1_size * 8 > file_size:
raise Qcow2Error("qcow2 L1 table lies outside the file")

return Qcow2Header(version, cluster_bits, size, l1_size, l1_offset, compression)



_OFFSET_MASK = 0x00FFFFFFFFFFFE00 # bits 9-55 of an L1/L2 entry
_COMPRESSED = 1 << 62
_ZERO_FLAG = 1
_HEADER_READ = 4096


def _zstd_decompress(data: bytes, limit: int) -> bytes:
"""Decompress one zstd frame, ignoring whatever follows it."""
try:
zstandard = importlib.import_module("zstandard")
except ImportError:
raise Qcow2Error(
"the Python module 'zstandard' is required to decompress this image"
) from None
try:
reader = zstandard.ZstdDecompressor().stream_reader(
io.BytesIO(data), read_across_frames=False
)
# One byte past the limit, so an oversized frame is detectable
return reader.read(limit + 1)
except zstandard.ZstdError as err:
raise Qcow2Error(f"cannot decompress qcow2 zstd cluster: {err}") from err


def _decompress(header: Qcow2Header, data: bytes) -> bytes:
"""Decompress one compressed cluster, which must expand to a full cluster."""
limit = header.cluster_size
if header.compression_type == COMPRESSION_ZSTD:
out = _zstd_decompress(data, limit)
else:
try:
# Raw deflate: qcow2 stores no zlib header
inflater = zlib.decompressobj(-zlib.MAX_WBITS)
out = inflater.decompress(data, limit)
if len(out) == limit:
# One more byte of output means the cluster is oversized
out += inflater.decompress(inflater.unconsumed_tail, 1)
except zlib.error as err:
raise Qcow2Error(f"cannot decompress qcow2 cluster: {err}") from err
if len(out) != limit:
raise Qcow2Error(
f"qcow2 compressed cluster is truncated or corrupt "
f"(expected {limit} bytes, got {'more' if len(out) > limit else len(out)})"
)
return out


def _read_table(src: BinaryIO, offset: int, count: int, header: Qcow2Header, file_size: int) -> Tuple[int, ...]:
"""Read a table of 64-bit big endian entries (an L1 or L2 table)."""
if offset % header.cluster_size or offset + count * 8 > file_size:
raise Qcow2Error("qcow2 table lies outside the file")
src.seek(offset)
raw = src.read(count * 8)
if len(raw) != count * 8:
raise Qcow2Error("qcow2 table is truncated")
return struct.unpack(f">{count}Q", raw)


def _cluster_data(src: BinaryIO, header: Qcow2Header, entry: int, file_size: int) -> Optional[bytes]:
"""Return the bytes of the cluster an L2 entry describes, None if all zeros."""
cluster_size = header.cluster_size
if entry & _COMPRESSED:
shift = 62 - (header.cluster_bits - 8)
offset = entry & ((1 << shift) - 1)
extra_sectors = (entry >> shift) & ((1 << (header.cluster_bits - 8)) - 1)
size = min((extra_sectors + 1) * 512 - (offset & 511), file_size - offset)
if size <= 0:
raise Qcow2Error("qcow2 compressed cluster lies outside the file")
src.seek(offset)
data = _decompress(header, src.read(size))
else:
if entry & _ZERO_FLAG:
return None
host = entry & _OFFSET_MASK
if not host:
return None # unallocated; no backing file, so it reads as zeros
if host % cluster_size or host + cluster_size > file_size:
raise Qcow2Error("qcow2 data cluster lies outside the file")
src.seek(host)
data = src.read(cluster_size)
return None if data.count(0) == len(data) else data


def _write_clusters(src: BinaryIO, out: BinaryIO, header: Qcow2Header,
l1_table: Tuple[int, ...], file_size: int) -> None:
"""Write every data cluster of the image to its place in the raw file."""
per_l2 = header.cluster_size // 8
out.truncate(header.size)
for l1_index, l1_entry in enumerate(l1_table):
first_guest = (l1_index * per_l2) << header.cluster_bits
if first_guest >= header.size:
break # the rest of the L1 table lies past the end of the disk
l2_offset = l1_entry & _OFFSET_MASK
if not l2_offset:
continue # no L2 table: every cluster below it is zeros
l2_table = _read_table(src, l2_offset, per_l2, header, file_size)
for l2_index, entry in enumerate(l2_table):
guest = first_guest + (l2_index << header.cluster_bits)
if guest >= header.size:
break
data = _cluster_data(src, header, entry, file_size)
if data:
out.seek(guest)
out.write(data[:header.size - guest])


def convert_to_raw(source: str, dest: str) -> int:
"""
Decode a qcow2 image into a sparse raw disk image.

Only clusters that hold data are written, so the output stays sparse.
The output is written to a temporary file and moved to dest on success,
so if decoding fails, dest is left exactly as it was.

Returns:
The virtual size of the disk in bytes

Raises:
Qcow2Error: If the image is malformed or uses an unsupported feature
"""
if os.path.exists(dest) and os.path.samefile(source, dest):
raise Qcow2Error("source and destination are the same file")
with open(source, "rb") as src:
file_size = os.fstat(src.fileno()).st_size
header = parse_header(src.read(_HEADER_READ), file_size)
l1_table = _read_table(src, header.l1_table_offset, header.l1_size,
header, file_size)
# Decode into a temporary file next to dest and move it into place on
# success, so a failure never touches a pre-existing dest
tmp_name = f"{dest}.{secrets.token_hex(8)}.tmp"
fd = os.open(tmp_name, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o666)
try:
with os.fdopen(fd, "wb") as out:
_write_clusters(src, out, header, l1_table, file_size)
os.replace(tmp_name, dest)
except BaseException:
with contextlib.suppress(OSError):
os.unlink(tmp_name)
raise
return header.size
Loading