Fix iTunesCDB header: always generate proper mhfd header

- Remove broken header-preservation logic (was reusing all-zero header)
- Always write header with correct total_size at offset 8
- Add version field 0x00020002 at offset 12
- Delete old iTunesDB (iTunesDB.old) to avoid firmware confusion
This commit is contained in:
Maksim Totmin 2026-05-31 18:47:36 +07:00
parent ab912c2e49
commit 75ea0204ff

View File

@ -1103,47 +1103,19 @@ class Nano7Database:
# Compute new SHA1 hash
new_hash = hashlib.sha1(lib_data).hexdigest()
# Read existing iTunesCDB to extract the header (first bytes before zlib)
if not os.path.exists(self.cdb_path):
header = b"\x00" * 244
header = b"mhfd" + struct.pack("<I", 244) + header[8:]
compressed = zlib.compress(lib_data)
with open(self.cdb_path, "wb") as f:
f.write(header + compressed)
logger.info(f"Created iTunesCDB: compressed={len(compressed)} bytes")
else:
with open(self.cdb_path, "rb") as f:
cdb_data = f.read()
total_size = 244 + len(compressed)
# Find zlib header (0x78 0x9c is most common, but also check 0x78 0xda and 0x78 0x01)
zlib_offset = -1
for pattern in [b"\x78\x9c", b"\x78\xda", b"\x78\x01", b"\x78\x5e"]:
zlib_offset = cdb_data.find(pattern)
if zlib_offset >= 0:
break
if zlib_offset == -1:
logger.error("Could not find zlib header in iTunesCDB")
return
header = cdb_data[:zlib_offset]
# Compress Library.itdb
compressed = zlib.compress(lib_data)
# Build proper mhfd header
header = bytearray(244)
header[0:4] = b"mhfd"
struct.pack_into("<I", header, 4, 244)
struct.pack_into("<I", header, 8, total_size)
struct.pack_into("<I", header, 12, 0x00020002)
# Write new iTunesCDB
with open(self.cdb_path, "wb") as f:
f.write(header + compressed)
# Update hash in iTunesCDB.ext
if not os.path.exists(self.cdb_ext_path):
ext_content = f"[iTunesCDB]\nitunesdb_hash={new_hash}\n"
else:
with open(self.cdb_ext_path, "r") as f:
ext_content = f.read()
new_ext_content = re.sub(r"itunesdb_hash=\w+", f"itunesdb_hash={new_hash}", ext_content)
with open(self.cdb_ext_path, "w") as f:
f.write(new_ext_content)
f.write(bytes(header) + compressed)
logger.info(f"Synced iTunesCDB: hash={new_hash}, compressed={len(compressed)} bytes")