#include "zip-archive.h" #include #include #include namespace { // ZIP signatures, little-endian on disk whatever the host is. constexpr quint32 kEndOfCentralDir = 0x06054b50; constexpr quint32 kCentralFileHeader = 0x02014b50; constexpr quint32 kLocalFileHeader = 0x04034b50; // Marker of the ZIP64 extension: sizes and offsets of 0xffffffff are only valid // in the ZIP64 records, which are not read here. constexpr quint32 kZip64Marker = 0xffffffffu; constexpr quint16 kMethodStored = 0; constexpr quint16 kMethodDeflated = 8; // The largest comment a spec-compliant EOCD can carry. The record is searched // backwards from the end of the file over that window, which is how an archive // with trailing data is still found. constexpr int kMaxCommentLength = 0xffff; // Reads a little-endian value out of a buffer. Every field of the format is // little-endian, on every platform, so this is byte order, not memcpy. quint16 readU16(const QByteArray& data, int offset) { return static_cast(static_cast(data[offset])) | (static_cast(static_cast(data[offset + 1])) << 8); } quint32 readU32(const QByteArray& data, int offset) { return static_cast(static_cast(data[offset])) | (static_cast(static_cast(data[offset + 1])) << 8) | (static_cast(static_cast(data[offset + 2])) << 16) | (static_cast(static_cast(data[offset + 3])) << 24); } // Inflates a raw deflate stream (no zlib header, hence the negative window // bits). The output size is known from the directory, so the buffer is sized // once and grown only if the stream turns out to be longer. bool inflateRaw(const QByteArray& input, quint32 expectedSize, QByteArray* out, QString* error) { if (expectedSize > ZipArchive::kMaxEntrySize) { if (error) *error = QStringLiteral("Entrée trop volumineuse."); return false; } QByteArray result(static_cast(expectedSize), Qt::Uninitialized); z_stream stream{}; // -MAX_WBITS selects the raw deflate that ZIP entries use, as opposed to // the zlib-wrapped stream inflateInit2() defaults to. if (inflateInit2(&stream, -MAX_WBITS) != Z_OK) { if (error) *error = QStringLiteral("Initialisation de la décompression impossible."); return false; } stream.next_in = reinterpret_cast(const_cast(input.constData())); stream.avail_in = static_cast(input.size()); stream.next_out = reinterpret_cast(result.data()); stream.avail_out = static_cast(result.size()); int status = Z_OK; if (expectedSize > 0) status = inflate(&stream, Z_FINISH); // A stream that produced nothing because the buffer was already the right // size returns Z_STREAM_END here; an empty entry is legitimate. if (expectedSize == 0) status = inflate(&stream, Z_FINISH); const uLong produced = stream.total_out; inflateEnd(&stream); if (status != Z_STREAM_END) { if (error) { *error = QStringLiteral("Entrée compressée illisible (%1).") .arg(QString::fromLatin1(zError(status))); } return false; } if (produced != expectedSize) { if (error) { *error = QStringLiteral("Taille d'entrée incohérente (%1 octets lus, %2 annoncés).") .arg(static_cast(produced)) .arg(static_cast(expectedSize)); } return false; } result.resize(static_cast(produced)); *out = result; return true; } } // namespace bool ZipArchive::open(const QString& path, QString* error) { QFile file(path); if (!file.open(QIODevice::ReadOnly)) { if (error) *error = QStringLiteral("Impossible de lire %1.").arg(path); return false; } // Refused above rather than allocated: the declared size is a lie until the // central directory is parsed, and this file comes from the desktop. if (file.size() > static_cast(kMaxEntrySize)) { if (error) *error = QStringLiteral("Archive trop volumineuse."); return false; } return openData(file.readAll(), error); } bool ZipArchive::openData(const QByteArray& data, QString* error) { m_data = data; m_entries.clear(); return parse(error); } bool ZipArchive::parse(QString* error) { auto fail = [error](const QString& message) { if (error) *error = message; return false; }; if (m_data.size() < 22) return fail(QStringLiteral("Archive trop courte.")); // The end-of-central-directory record sits at the very end, after a // comment of up to 64 KiB, so it is searched backwards. int eocd = -1; const int searchStart = qMax(0, m_data.size() - 22 - kMaxCommentLength); for (int i = m_data.size() - 22; i >= searchStart; --i) { if (readU32(m_data, i) == kEndOfCentralDir) { eocd = i; break; } } if (eocd < 0) return fail(QStringLiteral("Archive ZIP illisible (répertoire introuvable).")); const quint16 entryCount = readU16(m_data, eocd + 10); const quint32 directorySize = readU32(m_data, eocd + 12); const quint32 directoryOffset = readU32(m_data, eocd + 16); if (directoryOffset == kZip64Marker || directorySize == kZip64Marker || entryCount == 0xffff) { // Nothing in a plugin package needs ZIP64, and guessing its record // layout would be guesswork: refusing says so instead. return fail(QStringLiteral("Archive ZIP64 non prise en charge.")); } const qint64 directoryEnd = static_cast(directoryOffset) + directorySize; if (directoryOffset > static_cast(m_data.size()) || directoryEnd > m_data.size()) { return fail(QStringLiteral("Répertoire de l'archive hors limites.")); } int cursor = static_cast(directoryOffset); for (quint16 i = 0; i < entryCount; ++i) { if (cursor + 46 > m_data.size()) { return fail(QStringLiteral("Répertoire de l'archive tronqué.")); } if (readU32(m_data, cursor) != kCentralFileHeader) { return fail(QStringLiteral("Entrée d'archive illisible.")); } const quint16 method = readU16(m_data, cursor + 10); const quint32 compressedSize = readU32(m_data, cursor + 20); const quint32 uncompressedSize = readU32(m_data, cursor + 24); const quint16 nameLength = readU16(m_data, cursor + 28); const quint16 extraLength = readU16(m_data, cursor + 30); const quint16 commentLength = readU16(m_data, cursor + 32); const quint32 localOffset = readU32(m_data, cursor + 42); if (cursor + 46 + nameLength > m_data.size()) { return fail(QStringLiteral("Nom d'entrée tronqué.")); } const QString name = QString::fromUtf8(m_data.constData() + cursor + 46, nameLength); if (compressedSize == kZip64Marker || uncompressedSize == kZip64Marker || localOffset == kZip64Marker) { return fail(QStringLiteral("Archive ZIP64 non prise en charge.")); } if (uncompressedSize > kMaxEntrySize) { return fail(QStringLiteral("Entrée trop volumineuse : %1.").arg(name)); } Entry entry; entry.name = name; entry.compressedSize = compressedSize; entry.uncompressedSize = uncompressedSize; entry.localHeaderOffset = localOffset; entry.method = method; m_entries.push_back(entry); cursor += 46 + nameLength + extraLength + commentLength; } if (error) error->clear(); return true; } QStringList ZipArchive::fileNames() const { QStringList names; names.reserve(static_cast(m_entries.size())); for (const Entry& entry : m_entries) { // A trailing '/' is the ZIP way of marking a directory. if (entry.name.endsWith(QLatin1Char('/'))) continue; names << entry.name; } return names; } int ZipArchive::indexOf(const QString& name) const { for (int i = 0; i < static_cast(m_entries.size()); ++i) { if (m_entries[i].name.compare(name, Qt::CaseInsensitive) == 0) return i; } return -1; } bool ZipArchive::contains(const QString& name) const { return indexOf(name) >= 0; } const ZipArchive::Entry* ZipArchive::find(const QString& name) const { const int index = indexOf(name); return index < 0 ? nullptr : &m_entries[static_cast(index)]; } bool ZipArchive::isSafeEntryName(const QString& name) { if (name.isEmpty()) return false; // A path is a path even on the other platform: both separators are refused // as a leading character, so the check does not depend on who reads it. if (name.startsWith(QLatin1Char('/')) || name.startsWith(QLatin1Char('\\'))) return false; if (name.size() > 1 && name.at(1) == QLatin1Char(':')) return false; // drive letter if (name.contains(QLatin1String(".."))) return false; return true; } QByteArray ZipArchive::read(const QString& name, QString* error) const { const Entry* entry = find(name); if (!entry) { if (error) *error = QStringLiteral("Entrée absente de l'archive : %1.").arg(name); return {}; } if (entry->name.endsWith(QLatin1Char('/'))) { if (error) *error = QStringLiteral("%1 est un dossier, pas un fichier.").arg(name); return {}; } if (entry->uncompressedSize > kMaxEntrySize) { if (error) *error = QStringLiteral("Entrée trop volumineuse : %1.").arg(name); return {}; } // The local header repeats the name and the extra field, both of which can // differ in length from the central directory's copy: the payload starts // after the local header's own name and extra, never at a fixed offset. const int header = static_cast(entry->localHeaderOffset); if (header < 0 || header + 30 > m_data.size() || readU32(m_data, header) != kLocalFileHeader) { if (error) *error = QStringLiteral("En-tête local illisible pour %1.").arg(name); return {}; } const int dataStart = header + 30 + readU16(m_data, header + 26) + readU16(m_data, header + 28); const qint64 dataEnd = static_cast(dataStart) + entry->compressedSize; if (dataStart < 0 || dataEnd > m_data.size()) { if (error) *error = QStringLiteral("Données tronquées pour %1.").arg(name); return {}; } const QByteArray payload = m_data.mid(dataStart, static_cast(entry->compressedSize)); if (entry->method == kMethodStored) { if (payload.size() != static_cast(entry->uncompressedSize)) { if (error) { *error = QStringLiteral("Taille d'entrée incohérente pour %1.").arg(name); } return {}; } if (error) error->clear(); return payload; } if (entry->method != kMethodDeflated) { if (error) { *error = QStringLiteral("Méthode de compression non prise en charge (%1) pour %2.") .arg(entry->method) .arg(name); } return {}; } QByteArray result; if (!inflateRaw(payload, entry->uncompressedSize, &result, error)) return {}; if (error) error->clear(); return result; }