libzipplugin.cpp 34.8 KB
Newer Older
Ragnar Thomsen's avatar
Ragnar Thomsen committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
/*
 * Copyright (c) 2017 Ragnar Thomsen <rthomsen6@gmail.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ( INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "libzipplugin.h"
#include "ark_debug.h"
#include "queries.h"

30
#include <KIO/Global>
Ragnar Thomsen's avatar
Ragnar Thomsen committed
31 32 33 34 35 36 37 38
#include <KLocalizedString>
#include <KPluginFactory>

#include <QDataStream>
#include <QDateTime>
#include <QDir>
#include <QDirIterator>
#include <QFile>
39
#include <qplatformdefs.h>
Ragnar Thomsen's avatar
Ragnar Thomsen committed
40 41
#include <QThread>

42
#include <utime.h>
43
#include <zlib.h>
44
#include <memory>
45

46
K_PLUGIN_CLASS_WITH_JSON(LibzipPlugin, "kerfuffle_libzip.json")
Ragnar Thomsen's avatar
Ragnar Thomsen committed
47

48 49
void LibzipPlugin::progressCallback(zip_t *, double progress, void *that)
{
50
    static_cast<LibzipPlugin *>(that)->emitProgress(progress);
51
}
Ragnar Thomsen's avatar
Ragnar Thomsen committed
52 53 54 55 56 57 58 59 60 61 62 63

LibzipPlugin::LibzipPlugin(QObject *parent, const QVariantList & args)
    : ReadWriteArchiveInterface(parent, args)
    , m_overwriteAll(false)
    , m_skipAll(false)
    , m_listAfterAdd(false)
{
    qCDebug(ARK) << "Initializing libzip plugin";
}

LibzipPlugin::~LibzipPlugin()
{
64
    for (const auto e : qAsConst(m_emittedEntries)) {
Ragnar Thomsen's avatar
Ragnar Thomsen committed
65 66 67 68 69 70 71 72 73 74
        // Entries might be passed to pending slots, so we just schedule their deletion.
        e->deleteLater();
    }
}

bool LibzipPlugin::list()
{
    qCDebug(ARK) << "Listing archive contents for:" << QFile::encodeName(filename());
    m_numberOfEntries = 0;

75
    int errcode = 0;
Ragnar Thomsen's avatar
Ragnar Thomsen committed
76 77 78
    zip_error_t err;

    // Open archive.
79
    zip_t *archive = zip_open(QFile::encodeName(filename()).constData(), ZIP_RDONLY, &errcode);
Ragnar Thomsen's avatar
Ragnar Thomsen committed
80 81 82 83 84 85 86 87
    zip_error_init_with_code(&err, errcode);
    if (!archive) {
        qCCritical(ARK) << "Failed to open archive. Code:" << errcode;
        emit error(xi18n("Failed to open archive: %1", QString::fromUtf8(zip_error_strerror(&err))));
        return false;
    }

    // Fetch archive comment.
88
    m_comment = QString::fromLocal8Bit(zip_get_archive_comment(archive, nullptr, ZIP_FL_ENC_RAW));
Ragnar Thomsen's avatar
Ragnar Thomsen committed
89 90

    // Get number of archive entries.
Elvis Angelaccio's avatar
Elvis Angelaccio committed
91
    const auto nofEntries = zip_get_num_entries(archive, 0);
Ragnar Thomsen's avatar
Ragnar Thomsen committed
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
    qCDebug(ARK) << "Found entries:" << nofEntries;

    // Loop through all archive entries.
    for (int i = 0; i < nofEntries; i++) {

        if (QThread::currentThread()->isInterruptionRequested()) {
            break;
        }

        emitEntryForIndex(archive, i);
        if (m_listAfterAdd) {
            // Start at 50%.
            emit progress(0.5 + (0.5 * float(i + 1) / nofEntries));
        } else {
            emit progress(float(i + 1) / nofEntries);
        }
    }

    zip_close(archive);
    m_listAfterAdd = false;
    return true;
}

bool LibzipPlugin::addFiles(const QVector<Archive::Entry*> &files, const Archive::Entry *destination, const CompressionOptions& options, uint numberOfEntriesToAdd)
{
    Q_UNUSED(numberOfEntriesToAdd)
118
    int errcode = 0;
Ragnar Thomsen's avatar
Ragnar Thomsen committed
119 120 121
    zip_error_t err;

    // Open archive.
122
    zip_t *archive = zip_open(QFile::encodeName(filename()).constData(), ZIP_CREATE, &errcode);
Ragnar Thomsen's avatar
Ragnar Thomsen committed
123 124 125 126 127 128 129 130
    zip_error_init_with_code(&err, errcode);
    if (!archive) {
        qCCritical(ARK) << "Failed to open archive. Code:" << errcode;
        emit error(xi18n("Failed to open archive: %1", QString::fromUtf8(zip_error_strerror(&err))));
        return false;
    }

    uint i = 0;
131
    for (const Archive::Entry* e : files) {
Ragnar Thomsen's avatar
Ragnar Thomsen committed
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149

        if (QThread::currentThread()->isInterruptionRequested()) {
            break;
        }

        // If entry is a directory, traverse and add all its files and subfolders.
        if (QFileInfo(e->fullPath()).isDir()) {

            if (!writeEntry(archive, e->fullPath(), destination, options, true)) {
                return false;
            }

            QDirIterator it(e->fullPath(),
                            QDir::AllEntries | QDir::Readable |
                            QDir::Hidden | QDir::NoDotAndDotDot,
                            QDirIterator::Subdirectories);

            while (!QThread::currentThread()->isInterruptionRequested() && it.hasNext()) {
Elvis Angelaccio's avatar
Elvis Angelaccio committed
150
                const QString path = it.next();
Ragnar Thomsen's avatar
Ragnar Thomsen committed
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172

                if (QFileInfo(path).isDir()) {
                    if (!writeEntry(archive, path, destination, options, true)) {
                        return false;
                    }
                } else {
                    if (!writeEntry(archive, path, destination, options)) {
                        return false;
                    }
                }
                i++;
            }
        } else {
            if (!writeEntry(archive, e->fullPath(), destination, options)) {
                return false;
            }
        }
        i++;
    }
    qCDebug(ARK) << "Added" << i << "entries";

    // Register the callback function to get progress feedback.
173
    zip_register_progress_callback_with_state(archive, 0.001, progressCallback, nullptr, this);
Ragnar Thomsen's avatar
Ragnar Thomsen committed
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189

    qCDebug(ARK) << "Writing entries to disk...";
    if (zip_close(archive)) {
        qCCritical(ARK) << "Failed to write archive";
        emit error(xi18n("Failed to write archive."));
        return false;
    }

    // We list the entire archive after adding files to ensure entry
    // properties are up-to-date.
    m_listAfterAdd = true;
    list();

    return true;
}

190
void LibzipPlugin::emitProgress(double percentage)
Ragnar Thomsen's avatar
Ragnar Thomsen committed
191 192
{
    // Go from 0 to 50%. The second half is the subsequent listing.
193
    emit progress(0.5 * percentage);
Ragnar Thomsen's avatar
Ragnar Thomsen committed
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
}

bool LibzipPlugin::writeEntry(zip_t *archive, const QString &file, const Archive::Entry* destination, const CompressionOptions& options, bool isDir)
{
    Q_ASSERT(archive);

    QByteArray destFile;
    if (destination) {
        destFile = QString(destination->fullPath() + file).toUtf8();
    } else {
        destFile = file.toUtf8();
    }

    qlonglong index;
    if (isDir) {
209
        index = zip_dir_add(archive, destFile.constData(), ZIP_FL_ENC_GUESS);
Ragnar Thomsen's avatar
Ragnar Thomsen committed
210 211 212 213 214 215 216 217 218
        if (index == -1) {
            // If directory already exists in archive, we get an error.
            qCWarning(ARK) << "Failed to add dir " << file << ":" << zip_strerror(archive);
            return true;
        }
    } else {
        zip_source_t *src = zip_source_file(archive, QFile::encodeName(file).constData(), 0, -1);
        Q_ASSERT(src);

219
        index = zip_file_add(archive, destFile.constData(), src, ZIP_FL_ENC_GUESS | ZIP_FL_OVERWRITE);
Ragnar Thomsen's avatar
Ragnar Thomsen committed
220 221 222 223 224 225 226
        if (index == -1) {
            zip_source_free(src);
            qCCritical(ARK) << "Could not add entry" << file << ":" << zip_strerror(archive);
            emit error(xi18n("Failed to add entry: %1", QString::fromUtf8(zip_strerror(archive))));
            return false;
        }
    }
227 228 229 230

#ifndef Q_OS_WIN
    // Set permissions.
    QT_STATBUF result;
231
    if (QT_STAT(QFile::encodeName(file).constData(), &result) != 0) {
232 233 234 235 236 237 238 239 240
        qCWarning(ARK) << "Failed to read permissions for:" << file;
    } else {
        zip_uint32_t attributes = result.st_mode << 16;
        if (zip_file_set_external_attributes(archive, index, ZIP_FL_UNCHANGED, ZIP_OPSYS_UNIX, attributes) != 0) {
            qCWarning(ARK) << "Failed to set external attributes for:" << file;
        }
    }
#endif

Ragnar Thomsen's avatar
Ragnar Thomsen committed
241 242 243
    if (!password().isEmpty()) {
        Q_ASSERT(!options.encryptionMethod().isEmpty());
        if (options.encryptionMethod() == QLatin1String("AES128")) {
244
            zip_file_set_encryption(archive, index, ZIP_EM_AES_128, password().toUtf8().constData());
Ragnar Thomsen's avatar
Ragnar Thomsen committed
245
        } else if (options.encryptionMethod() == QLatin1String("AES192")) {
246
            zip_file_set_encryption(archive, index, ZIP_EM_AES_192, password().toUtf8().constData());
Ragnar Thomsen's avatar
Ragnar Thomsen committed
247
        } else if (options.encryptionMethod() == QLatin1String("AES256")) {
248
            zip_file_set_encryption(archive, index, ZIP_EM_AES_256, password().toUtf8().constData());
Ragnar Thomsen's avatar
Ragnar Thomsen committed
249 250 251
        }
    }

252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
    // Set compression level and method.
    zip_int32_t compMethod = ZIP_CM_DEFAULT;
    if (!options.compressionMethod().isEmpty()) {
        if (options.compressionMethod() == QLatin1String("Deflate")) {
            compMethod = ZIP_CM_DEFLATE;
        } else if (options.compressionMethod() == QLatin1String("BZip2")) {
            compMethod = ZIP_CM_BZIP2;
        } else if (options.compressionMethod() == QLatin1String("Store")) {
            compMethod = ZIP_CM_STORE;
        }
    }
    const int compLevel = options.isCompressionLevelSet() ? options.compressionLevel() : 6;
    if (zip_set_file_compression(archive, index, compMethod, compLevel) != 0) {
        qCCritical(ARK) << "Could not set compression options for" << file << ":" << zip_strerror(archive);
        emit error(xi18n("Failed to set compression options for entry: %1", QString::fromUtf8(zip_strerror(archive))));
        return false;
    }

Ragnar Thomsen's avatar
Ragnar Thomsen committed
270 271 272 273 274 275 276
    return true;
}

bool LibzipPlugin::emitEntryForIndex(zip_t *archive, qlonglong index)
{
    Q_ASSERT(archive);

277 278
    zip_stat_t statBuffer;
    if (zip_stat_index(archive, index, ZIP_FL_ENC_GUESS, &statBuffer)) {
Ragnar Thomsen's avatar
Ragnar Thomsen committed
279 280 281 282 283 284
        qCCritical(ARK) << "Failed to read stat for index" << index;
        return false;
    }

    auto e = new Archive::Entry();

285 286
    if (statBuffer.valid & ZIP_STAT_NAME) {
        e->setFullPath(QString::fromUtf8(statBuffer.name));
Ragnar Thomsen's avatar
Ragnar Thomsen committed
287 288 289 290 291 292
    }

    if (e->fullPath(PathFormat::WithTrailingSlash).endsWith(QDir::separator())) {
        e->setProperty("isDirectory", true);
    }

293
    if (statBuffer.valid & ZIP_STAT_MTIME) {
294
        e->setProperty("timestamp", QDateTime::fromSecsSinceEpoch(statBuffer.mtime));
Ragnar Thomsen's avatar
Ragnar Thomsen committed
295
    }
296 297
    if (statBuffer.valid & ZIP_STAT_SIZE) {
        e->setProperty("size", (qulonglong)statBuffer.size);
Ragnar Thomsen's avatar
Ragnar Thomsen committed
298
    }
299 300
    if (statBuffer.valid & ZIP_STAT_COMP_SIZE) {
        e->setProperty("compressedSize", (qlonglong)statBuffer.comp_size);
Ragnar Thomsen's avatar
Ragnar Thomsen committed
301
    }
302
    if (statBuffer.valid & ZIP_STAT_CRC) {
Ragnar Thomsen's avatar
Ragnar Thomsen committed
303
        if (!e->isDir()) {
304
            e->setProperty("CRC", QString::number((qulonglong)statBuffer.crc, 16).toUpper());
Ragnar Thomsen's avatar
Ragnar Thomsen committed
305 306
        }
    }
307 308
    if (statBuffer.valid & ZIP_STAT_COMP_METHOD) {
        switch(statBuffer.comp_method) {
Ragnar Thomsen's avatar
Ragnar Thomsen committed
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
            case ZIP_CM_STORE:
                e->setProperty("method", QStringLiteral("Store"));
                emit compressionMethodFound(QStringLiteral("Store"));
                break;
            case ZIP_CM_DEFLATE:
                e->setProperty("method", QStringLiteral("Deflate"));
                emit compressionMethodFound(QStringLiteral("Deflate"));
                break;
            case ZIP_CM_DEFLATE64:
                e->setProperty("method", QStringLiteral("Deflate64"));
                emit compressionMethodFound(QStringLiteral("Deflate64"));
                break;
            case ZIP_CM_BZIP2:
                e->setProperty("method", QStringLiteral("BZip2"));
                emit compressionMethodFound(QStringLiteral("BZip2"));
                break;
            case ZIP_CM_LZMA:
                e->setProperty("method", QStringLiteral("LZMA"));
                emit compressionMethodFound(QStringLiteral("LZMA"));
                break;
            case ZIP_CM_XZ:
                e->setProperty("method", QStringLiteral("XZ"));
                emit compressionMethodFound(QStringLiteral("XZ"));
                break;
        }
    }
335 336
    if (statBuffer.valid & ZIP_STAT_ENCRYPTION_METHOD) {
        if (statBuffer.encryption_method != ZIP_EM_NONE) {
Ragnar Thomsen's avatar
Ragnar Thomsen committed
337
            e->setProperty("isPasswordProtected", true);
338
            switch(statBuffer.encryption_method) {
Ragnar Thomsen's avatar
Ragnar Thomsen committed
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
                case ZIP_EM_TRAD_PKWARE:
                    emit encryptionMethodFound(QStringLiteral("ZipCrypto"));
                    break;
                case ZIP_EM_AES_128:
                    emit encryptionMethodFound(QStringLiteral("AES128"));
                    break;
                case ZIP_EM_AES_192:
                    emit encryptionMethodFound(QStringLiteral("AES192"));
                    break;
                case ZIP_EM_AES_256:
                    emit encryptionMethodFound(QStringLiteral("AES256"));
                    break;
            }
        }
    }

355 356 357 358
    // Read external attributes, which contains the file permissions.
    zip_uint8_t opsys;
    zip_uint32_t attributes;
    if (zip_file_get_external_attributes(archive, index, ZIP_FL_UNCHANGED, &opsys, &attributes) == -1) {
359 360
        qCCritical(ARK) << "Could not read external attributes for entry:" << QString::fromUtf8(statBuffer.name);
        emit error(xi18n("Failed to read metadata for entry: %1", QString::fromUtf8(statBuffer.name)));
361 362 363 364 365 366 367 368 369 370 371 372 373
        return false;
    }

    // Set permissions.
    switch (opsys) {
    case ZIP_OPSYS_UNIX:
        // Unix permissions are stored in the leftmost 16 bits of the external file attribute.
        e->setProperty("permissions", permissionsToString(attributes >> 16));
        break;
    default:    // TODO: non-UNIX.
        break;
    }

Ragnar Thomsen's avatar
Ragnar Thomsen committed
374 375 376 377 378 379 380 381
    emit entry(e);
    m_emittedEntries << e;

    return true;
}

bool LibzipPlugin::deleteFiles(const QVector<Archive::Entry*> &files)
{
382
    int errcode = 0;
Ragnar Thomsen's avatar
Ragnar Thomsen committed
383 384 385
    zip_error_t err;

    // Open archive.
386
    zip_t *archive = zip_open(QFile::encodeName(filename()).constData(), 0, &errcode);
Ragnar Thomsen's avatar
Ragnar Thomsen committed
387 388 389 390 391 392 393 394
    zip_error_init_with_code(&err, errcode);
    if (archive == nullptr) {
        qCCritical(ARK) << "Failed to open archive. Code:" << errcode;
        emit error(xi18n("Failed to open archive: %1", QString::fromUtf8(zip_error_strerror(&err))));
        return false;
    }

    qulonglong i = 0;
395
    for (const Archive::Entry* e : files) {
Ragnar Thomsen's avatar
Ragnar Thomsen committed
396 397 398 399 400

        if (QThread::currentThread()->isInterruptionRequested()) {
            break;
        }

401
        const qlonglong index = zip_name_locate(archive, e->fullPath().toUtf8().constData(), ZIP_FL_ENC_GUESS);
Ragnar Thomsen's avatar
Ragnar Thomsen committed
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
        if (index == -1) {
            qCCritical(ARK) << "Could not find entry to delete:" << e->fullPath();
            emit error(xi18n("Failed to delete entry: %1", e->fullPath()));
            return false;
        }
        if (zip_delete(archive, index) == -1) {
            qCCritical(ARK) << "Could not delete entry" << e->fullPath() << ":" << zip_strerror(archive);
            emit error(xi18n("Failed to delete entry: %1", QString::fromUtf8(zip_strerror(archive))));
            return false;
        }
        emit entryRemoved(e->fullPath());
        emit progress(float(++i) / files.size());
    }
    qCDebug(ARK) << "Deleted" << i << "entries";

    if (zip_close(archive)) {
        qCCritical(ARK) << "Failed to write archive";
        emit error(xi18n("Failed to write archive."));
        return false;
    }
    return true;
}

bool LibzipPlugin::addComment(const QString& comment)
{
427
    int errcode = 0;
Ragnar Thomsen's avatar
Ragnar Thomsen committed
428 429 430
    zip_error_t err;

    // Open archive.
431
    zip_t *archive = zip_open(QFile::encodeName(filename()).constData(), 0, &errcode);
Ragnar Thomsen's avatar
Ragnar Thomsen committed
432 433 434 435 436 437 438 439
    zip_error_init_with_code(&err, errcode);
    if (archive == nullptr) {
        qCCritical(ARK) << "Failed to open archive. Code:" << errcode;
        emit error(xi18n("Failed to open archive: %1", QString::fromUtf8(zip_error_strerror(&err))));
        return false;
    }

    // Set archive comment.
440
    if (zip_set_archive_comment(archive, comment.toUtf8().constData(), comment.length())) {
Ragnar Thomsen's avatar
Ragnar Thomsen committed
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
        qCCritical(ARK) << "Failed to set comment:" << zip_strerror(archive);
        return false;
    }

    if (zip_close(archive)) {
        qCCritical(ARK) << "Failed to write archive";
        emit error(xi18n("Failed to write archive."));
        return false;
    }
    return true;
}

bool LibzipPlugin::testArchive()
{
    qCDebug(ARK) << "Testing archive";
456
    int errcode = 0;
Ragnar Thomsen's avatar
Ragnar Thomsen committed
457 458 459
    zip_error_t err;

    // Open archive performing extra consistency checks.
460
    zip_t *archive = zip_open(QFile::encodeName(filename()).constData(), ZIP_CHECKCONS, &errcode);
Ragnar Thomsen's avatar
Ragnar Thomsen committed
461 462 463 464 465
    zip_error_init_with_code(&err, errcode);
    if (archive == nullptr) {
        qCCritical(ARK) << "Failed to open archive:" << zip_error_strerror(&err);
        return false;
    }
466 467 468 469 470

    // Check CRC-32 for each archive entry.
    const int nofEntries = zip_get_num_entries(archive, 0);
    for (int i = 0; i < nofEntries; i++) {

471 472 473 474
        if (QThread::currentThread()->isInterruptionRequested()) {
            return false;
        }

475
        // Get statistic for entry. Used to get entry size.
476 477 478
        zip_stat_t statBuffer;
        if (zip_stat_index(archive, i, 0, &statBuffer) != 0) {
            qCCritical(ARK) << "Failed to read stat for" << statBuffer.name;
479 480 481
            return false;
        }

482
        std::unique_ptr<zip_file, decltype(&zip_fclose)> zipFile { zip_fopen_index(archive, i, 0), &zip_fclose };
483
        std::unique_ptr<uchar[]> buf(new uchar[statBuffer.size]);
484
        const int len = zip_fread(zipFile.get(), buf.get(), statBuffer.size);
485 486
        if (len == -1 || uint(len) != statBuffer.size) {
            qCCritical(ARK) << "Failed to read data for" << statBuffer.name;
487 488
            return false;
        }
489
        if (statBuffer.crc != crc32(0, &buf.get()[0], len)) {
490
            qCCritical(ARK) << "CRC check failed for" << statBuffer.name;
491 492 493 494 495 496
            return false;
        }

        emit progress(float(i) / nofEntries);
    }

Ragnar Thomsen's avatar
Ragnar Thomsen committed
497 498 499 500 501 502 503 504
    zip_close(archive);

    emit testSuccess();
    return true;
}

bool LibzipPlugin::doKill()
{
Elvis Angelaccio's avatar
Elvis Angelaccio committed
505
    return false;
Ragnar Thomsen's avatar
Ragnar Thomsen committed
506 507 508 509 510 511 512 513
}

bool LibzipPlugin::extractFiles(const QVector<Archive::Entry*> &files, const QString& destinationDirectory, const ExtractionOptions& options)
{
    qCDebug(ARK) << "Extracting files to:" << destinationDirectory;
    const bool extractAll = files.isEmpty();
    const bool removeRootNode = options.isDragAndDropEnabled();

514
    int errcode = 0;
Ragnar Thomsen's avatar
Ragnar Thomsen committed
515 516 517
    zip_error_t err;

    // Open archive.
518
    zip_t *archive = zip_open(QFile::encodeName(filename()).constData(), ZIP_RDONLY, &errcode);
Ragnar Thomsen's avatar
Ragnar Thomsen committed
519 520 521 522 523 524 525 526 527 528
    zip_error_init_with_code(&err, errcode);
    if (archive == nullptr) {
        qCCritical(ARK) << "Failed to open archive. Code:" << errcode;
        emit error(xi18n("Failed to open archive: %1", QString::fromUtf8(zip_error_strerror(&err))));
        return false;
    }

    // Set password if known.
    if (!password().isEmpty()) {
        qCDebug(ARK) << "Password already known. Setting...";
529
        zip_set_default_password(archive, password().toUtf8().constData());
Ragnar Thomsen's avatar
Ragnar Thomsen committed
530 531 532
    }

    // Get number of archive entries.
Elvis Angelaccio's avatar
Elvis Angelaccio committed
533
    const qlonglong nofEntries = extractAll ? zip_get_num_entries(archive, 0) : files.size();
Ragnar Thomsen's avatar
Ragnar Thomsen committed
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557

    // Extract entries.
    m_overwriteAll = false; // Whether to overwrite all files
    m_skipAll = false; // Whether to skip all files
    if (extractAll) {
        // We extract all entries.
        for (qlonglong i = 0; i < nofEntries; i++) {
            if (QThread::currentThread()->isInterruptionRequested()) {
                break;
            }
            if (!extractEntry(archive,
                              QDir::fromNativeSeparators(QString::fromUtf8(zip_get_name(archive, i, ZIP_FL_ENC_GUESS))),
                              QString(),
                              destinationDirectory,
                              options.preservePaths(),
                              removeRootNode)) {
                qCDebug(ARK) << "Extraction failed";
                return false;
            }
            emit progress(float(i + 1) / nofEntries);
        }
    } else {
        // We extract only the entries in files.
        qulonglong i = 0;
558
        for (const Archive::Entry* e : files) {
Ragnar Thomsen's avatar
Ragnar Thomsen committed
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
            if (QThread::currentThread()->isInterruptionRequested()) {
                break;
            }
            if (!extractEntry(archive,
                              e->fullPath(),
                              e->rootNode,
                              destinationDirectory,
                              options.preservePaths(),
                              removeRootNode)) {
                qCDebug(ARK) << "Extraction failed";
                return false;
            }
            emit progress(float(++i) / nofEntries);
        }
    }

    zip_close(archive);
    return true;
}

bool LibzipPlugin::extractEntry(zip_t *archive, const QString &entry, const QString &rootNode, const QString &destDir, bool preservePaths, bool removeRootNode)
{
    const bool isDirectory = entry.endsWith(QDir::separator());

    // Add trailing slash to destDir if not present.
    QString destDirCorrected(destDir);
    if (!destDir.endsWith(QDir::separator())) {
        destDirCorrected.append(QDir::separator());
    }

    // Remove rootnode if supplied and set destination path.
    QString destination;
    if (preservePaths) {
        if (!removeRootNode || rootNode.isEmpty()) {
            destination = destDirCorrected + entry;
        } else {
            QString truncatedEntry = entry;
            truncatedEntry.remove(0, rootNode.size());
            destination = destDirCorrected + truncatedEntry;
        }
    } else {
        if (isDirectory) {
            qCDebug(ARK) << "Skipping directory:" << entry;
            return true;
        }
        destination = destDirCorrected + QFileInfo(entry).fileName();
    }

607 608 609 610 611 612 613 614 615
    // Store parent mtime.
    QString parentDir;
    if (isDirectory) {
        QDir pDir = QFileInfo(destination).dir();
        pDir.cdUp();
        parentDir = pDir.path();
    } else {
        parentDir = QFileInfo(destination).path();
    }
616
    // For top-level items, don't restore parent dir mtime.
Elvis Angelaccio's avatar
Elvis Angelaccio committed
617
    const bool restoreParentMtime = (parentDir + QDir::separator() != destDirCorrected);
618 619 620

    time_t parent_mtime;
    if (restoreParentMtime) {
621
        parent_mtime = QFileInfo(parentDir).lastModified().toMSecsSinceEpoch() / 1000;
622 623
    }

Ragnar Thomsen's avatar
Ragnar Thomsen committed
624 625 626 627 628 629 630
    // Create parent directories for files. For directories create them.
    if (!QDir().mkpath(QFileInfo(destination).path())) {
        qCDebug(ARK) << "Failed to create directory:" << QFileInfo(destination).path();
        emit error(xi18n("Failed to create directory: %1", QFileInfo(destination).path()));
        return false;
    }

631
    // Get statistic for entry. Used to get entry size and mtime.
632
    zip_stat_t statBuffer;
633
    if (zip_stat(archive, entry.toUtf8().constData(), 0, &statBuffer) != 0) {
634 635 636 637
        if (isDirectory && zip_error_code_zip(zip_get_error(archive)) == ZIP_ER_NOENT) {
            qCWarning(ARK) << "Skipping folder without entry:" << entry;
            return true;
        }
638 639
        qCCritical(ARK) << "Failed to read stat for entry" << entry;
        return false;
Ragnar Thomsen's avatar
Ragnar Thomsen committed
640 641
    }

642
    if (!isDirectory) {
Ragnar Thomsen's avatar
Ragnar Thomsen committed
643

644 645 646 647
        // Handle existing destination files.
        QString renamedEntry = entry;
        while (!m_overwriteAll && QFileInfo::exists(destination)) {
            if (m_skipAll) {
Ragnar Thomsen's avatar
Ragnar Thomsen committed
648
                return true;
649 650 651 652 653 654
            } else {
                Kerfuffle::OverwriteQuery query(renamedEntry);
                emit userQuery(&query);
                query.waitForResponse();

                if (query.responseCancelled()) {
655
                    emit cancelled();
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
                    return false;
                } else if (query.responseSkip()) {
                    return true;
                } else if (query.responseAutoSkip()) {
                    m_skipAll = true;
                    return true;
                } else if (query.responseRename()) {
                    const QString newName(query.newFilename());
                    destination = QFileInfo(destination).path() + QDir::separator() + QFileInfo(newName).fileName();
                    renamedEntry = QFileInfo(entry).path() + QDir::separator() + QFileInfo(newName).fileName();
                } else if (query.responseOverwriteAll()) {
                    m_overwriteAll = true;
                    break;
                } else if (query.responseOverwrite()) {
                    break;
                }
Ragnar Thomsen's avatar
Ragnar Thomsen committed
672 673 674
            }
        }

675
        // Handle password-protected files.
Alexey Ivanov's avatar
Alexey Ivanov committed
676
        std::unique_ptr<zip_file, decltype(&zip_fclose)> zipFile { nullptr, &zip_fclose };
677
        bool firstTry = true;
678
        while (!zipFile) {
679
            zipFile.reset(zip_fopen(archive, entry.toUtf8().constData(), 0));
680
            if (zipFile) {
681 682 683 684 685 686 687 688 689 690 691 692 693
                break;
            } else if (zip_error_code_zip(zip_get_error(archive)) == ZIP_ER_NOPASSWD ||
                       zip_error_code_zip(zip_get_error(archive)) == ZIP_ER_WRONGPASSWD) {
                Kerfuffle::PasswordNeededQuery query(filename(), !firstTry);
                emit userQuery(&query);
                query.waitForResponse();

                if (query.responseCancelled()) {
                    emit cancelled();
                    return false;
                }
                setPassword(query.password());

694
                if (zip_set_default_password(archive, password().toUtf8().constData())) {
695 696 697 698 699 700
                    qCDebug(ARK) << "Failed to set password for:" << entry;
                }
                firstTry = false;
            } else {
                qCCritical(ARK) << "Failed to open file:" << zip_strerror(archive);
                emit error(xi18n("Failed to open '%1':<nl/>%2", entry, QString::fromUtf8(zip_strerror(archive))));
Ragnar Thomsen's avatar
Ragnar Thomsen committed
701 702
                return false;
            }
703
        }
Ragnar Thomsen's avatar
Ragnar Thomsen committed
704

705 706 707 708
        QFile file(destination);
        if (!file.open(QIODevice::WriteOnly)) {
            qCCritical(ARK) << "Failed to open file for writing";
            emit error(xi18n("Failed to open file for writing: %1", destination));
Ragnar Thomsen's avatar
Ragnar Thomsen committed
709 710 711
            return false;
        }

712 713 714 715 716
        QDataStream out(&file);

        // Write archive entry to file. We use a read/write buffer of 1000 chars.
        qulonglong sum = 0;
        char buf[1000];
717
        while (sum != statBuffer.size) {
718
            const auto readBytes = zip_fread(zipFile.get(), buf, 1000);
719
            if (readBytes < 0) {
720 721 722 723
                qCCritical(ARK) << "Failed to read data";
                emit error(xi18n("Failed to read data for entry: %1", entry));
                return false;
            }
724
            if (out.writeRawData(buf, readBytes) != readBytes) {
725 726 727 728
                qCCritical(ARK) << "Failed to write data";
                emit error(xi18n("Failed to write data for entry: %1", entry));
                return false;
            }
Ragnar Thomsen's avatar
Ragnar Thomsen committed
729

730
            sum += readBytes;
731
        }
Ragnar Thomsen's avatar
Ragnar Thomsen committed
732

733
        const auto index = zip_name_locate(archive, entry.toUtf8().constData(), ZIP_FL_ENC_GUESS);
734 735 736
        if (index == -1) {
            qCCritical(ARK) << "Could not locate entry:" << entry;
            emit error(xi18n("Failed to locate entry: %1", entry));
Ragnar Thomsen's avatar
Ragnar Thomsen committed
737 738
            return false;
        }
739 740 741 742 743 744

        zip_uint8_t opsys;
        zip_uint32_t attributes;
        if (zip_file_get_external_attributes(archive, index, ZIP_FL_UNCHANGED, &opsys, &attributes) == -1) {
            qCCritical(ARK) << "Could not read external attributes for entry:" << entry;
            emit error(xi18n("Failed to read metadata for entry: %1", entry));
Ragnar Thomsen's avatar
Ragnar Thomsen committed
745 746 747
            return false;
        }

748 749 750 751 752 753 754 755 756
        // Inspired by fuse-zip source code: fuse-zip/lib/fileNode.cpp
        switch (opsys) {
        case ZIP_OPSYS_UNIX:
            // Unix permissions are stored in the leftmost 16 bits of the external file attribute.
            file.setPermissions(KIO::convertPermissions(attributes >> 16));
            break;
        default:    // TODO: non-UNIX.
            break;
        }
757

758
        file.close();
759 760
    }

761 762
    // Set mtime for entry.
    utimbuf times;
763
    times.modtime = statBuffer.mtime;
764
    if (utime(destination.toUtf8().constData(), &times) != 0) {
765
        qCWarning(ARK) << "Failed to restore mtime:" << destination;
766 767
    }

768 769 770
    if (restoreParentMtime) {
        // Restore mtime for parent dir.
        times.modtime = parent_mtime;
771
        if (utime(parentDir.toUtf8().constData(), &times) != 0) {
772 773
            qCWarning(ARK) << "Failed to restore mtime for parent dir of:" << destination;
        }
774 775
    }

Ragnar Thomsen's avatar
Ragnar Thomsen committed
776 777 778 779 780 781
    return true;
}

bool LibzipPlugin::moveFiles(const QVector<Archive::Entry*> &files, Archive::Entry *destination, const CompressionOptions &options)
{
    Q_UNUSED(options)
782
    int errcode = 0;
Ragnar Thomsen's avatar
Ragnar Thomsen committed
783 784 785
    zip_error_t err;

    // Open archive.
786
    zip_t *archive = zip_open(QFile::encodeName(filename()).constData(), 0, &errcode);
Ragnar Thomsen's avatar
Ragnar Thomsen committed
787 788 789 790 791 792 793 794 795 796 797 798 799 800
    zip_error_init_with_code(&err, errcode);
    if (archive == nullptr) {
        qCCritical(ARK) << "Failed to open archive. Code:" << errcode;
        emit error(xi18n("Failed to open archive: %1", QString::fromUtf8(zip_error_strerror(&err))));
        return false;
    }

    QStringList filePaths = entryFullPaths(files);
    filePaths.sort();
    const QStringList destPaths = entryPathsFromDestination(filePaths, destination, entriesWithoutChildren(files).count());

    int i;
    for (i = 0; i < filePaths.size(); ++i) {

801
        const int index = zip_name_locate(archive, filePaths.at(i).toUtf8().constData(), ZIP_FL_ENC_GUESS);
Ragnar Thomsen's avatar
Ragnar Thomsen committed
802 803 804 805 806 807
        if (index == -1) {
            qCCritical(ARK) << "Could not find entry to move:" << filePaths.at(i);
            emit error(xi18n("Failed to move entry: %1", filePaths.at(i)));
            return false;
        }

808
        if (zip_file_rename(archive, index, destPaths.at(i).toUtf8().constData(), ZIP_FL_ENC_GUESS) == -1) {
Ragnar Thomsen's avatar
Ragnar Thomsen committed
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
            qCCritical(ARK) << "Could not move entry:" << filePaths.at(i);
            emit error(xi18n("Failed to move entry: %1", filePaths.at(i)));
            return false;
        }

        emit entryRemoved(filePaths.at(i));
        emitEntryForIndex(archive, index);
        emit progress(i/filePaths.count());
    }
    if (zip_close(archive)) {
        qCCritical(ARK) << "Failed to write archive";
        emit error(xi18n("Failed to write archive."));
        return false;
    }
    qCDebug(ARK) << "Moved" << i << "entries";

    return true;
}

bool LibzipPlugin::copyFiles(const QVector<Archive::Entry*> &files, Archive::Entry *destination, const CompressionOptions &options)
{
    Q_UNUSED(options)
831
    int errcode = 0;
Ragnar Thomsen's avatar
Ragnar Thomsen committed
832 833 834
    zip_error_t err;

    // Open archive.
835
    zip_t *archive = zip_open(QFile::encodeName(filename()).constData(), 0, &errcode);
Ragnar Thomsen's avatar
Ragnar Thomsen committed
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
    zip_error_init_with_code(&err, errcode);
    if (archive == nullptr) {
        qCCritical(ARK) << "Failed to open archive. Code:" << errcode;
        emit error(xi18n("Failed to open archive: %1", QString::fromUtf8(zip_error_strerror(&err))));
        return false;
    }

    const QStringList filePaths = entryFullPaths(files);
    const QStringList destPaths = entryPathsFromDestination(filePaths, destination, 0);

    int i;
    for (i = 0; i < filePaths.size(); ++i) {

        QString dest = destPaths.at(i);

        if (dest.endsWith(QDir::separator())) {
852
            if (zip_dir_add(archive, dest.toUtf8().constData(), ZIP_FL_ENC_GUESS) == -1) {
Ragnar Thomsen's avatar
Ragnar Thomsen committed
853 854 855 856 857 858
                // If directory already exists in archive, we get an error.
                qCWarning(ARK) << "Failed to add dir " << dest << ":" << zip_strerror(archive);
                continue;
            }
        }

859
        const int srcIndex = zip_name_locate(archive, filePaths.at(i).toUtf8().constData(), ZIP_FL_ENC_GUESS);
Ragnar Thomsen's avatar
Ragnar Thomsen committed
860 861 862 863 864 865 866 867 868 869 870 871
        if (srcIndex == -1) {
            qCCritical(ARK) << "Could not find entry to copy:" << filePaths.at(i);
            emit error(xi18n("Failed to copy entry: %1", filePaths.at(i)));
            return false;
        }

        zip_source_t *src = zip_source_zip(archive, archive, srcIndex, 0, 0, -1);
        if (!src) {
            qCCritical(ARK) << "Failed to create source for:" << filePaths.at(i);
            return false;
        }

872
        const int destIndex = zip_file_add(archive, dest.toUtf8().constData(), src, ZIP_FL_ENC_GUESS | ZIP_FL_OVERWRITE);
Ragnar Thomsen's avatar
Ragnar Thomsen committed
873 874 875 876 877 878 879
        if (destIndex == -1) {
            zip_source_free(src);
            qCCritical(ARK) << "Could not add entry" << dest << ":" << zip_strerror(archive);
            emit error(xi18n("Failed to add entry: %1", QString::fromUtf8(zip_strerror(archive))));
            return false;
        }

880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
        // Get permissions from source entry.
        zip_uint8_t opsys;
        zip_uint32_t attributes;
        if (zip_file_get_external_attributes(archive, srcIndex, ZIP_FL_UNCHANGED, &opsys, &attributes) == -1) {
            qCCritical(ARK) << "Failed to read external attributes for source:" << filePaths.at(i);
            emit error(xi18n("Failed to read metadata for entry: %1", filePaths.at(i)));
            return false;
        }

        // Set permissions on dest entry.
        if (zip_file_set_external_attributes(archive, destIndex, ZIP_FL_UNCHANGED, opsys, attributes) != 0) {
            qCCritical(ARK) << "Failed to set external attributes for destination:" << dest;
            emit error(xi18n("Failed to set metadata for entry: %1", dest));
            return false;
        }
Ragnar Thomsen's avatar
Ragnar Thomsen committed
895
    }
896 897

    // Register the callback function to get progress feedback.
898
    zip_register_progress_callback_with_state(archive, 0.001, progressCallback, nullptr, this);
899

Ragnar Thomsen's avatar
Ragnar Thomsen committed
900 901 902 903 904
    if (zip_close(archive)) {
        qCCritical(ARK) << "Failed to write archive";
        emit error(xi18n("Failed to write archive."));
        return false;
    }
905 906 907 908 909

    // List the archive to update the model.
    m_listAfterAdd = true;
    list();

Ragnar Thomsen's avatar
Ragnar Thomsen committed
910 911 912 913 914
    qCDebug(ARK) << "Copied" << i << "entries";

    return true;
}

Laurent Montel's avatar
Laurent Montel committed
915
QString LibzipPlugin::permissionsToString(mode_t perm)
916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
{
    QString modeval;
    if ((perm & S_IFMT) == S_IFDIR) {
        modeval.append(QLatin1Char('d'));
    } else if ((perm & S_IFMT) == S_IFLNK) {
        modeval.append(QLatin1Char('l'));
    } else {
        modeval.append(QLatin1Char('-'));
    }
    modeval.append((perm & S_IRUSR) ? QLatin1Char('r') : QLatin1Char('-'));
    modeval.append((perm & S_IWUSR) ? QLatin1Char('w') : QLatin1Char('-'));
    if ((perm & S_ISUID) && (perm & S_IXUSR)) {
        modeval.append(QLatin1Char('s'));
    } else if ((perm & S_ISUID)) {
        modeval.append(QLatin1Char('S'));
    } else if ((perm & S_IXUSR)) {
        modeval.append(QLatin1Char('x'));
    } else {
        modeval.append(QLatin1Char('-'));
    }
    modeval.append((perm & S_IRGRP) ? QLatin1Char('r') : QLatin1Char('-'));
    modeval.append((perm & S_IWGRP) ? QLatin1Char('w') : QLatin1Char('-'));
    if ((perm & S_ISGID) && (perm & S_IXGRP)) {
        modeval.append(QLatin1Char('s'));
    } else if ((perm & S_ISGID)) {
        modeval.append(QLatin1Char('S'));
    } else if ((perm & S_IXGRP)) {
        modeval.append(QLatin1Char('x'));
    } else {
        modeval.append(QLatin1Char('-'));
    }
    modeval.append((perm & S_IROTH) ? QLatin1Char('r') : QLatin1Char('-'));
    modeval.append((perm & S_IWOTH) ? QLatin1Char('w') : QLatin1Char('-'));
    if ((perm & S_ISVTX) && (perm & S_IXOTH)) {
        modeval.append(QLatin1Char('t'));
    } else if ((perm & S_ISVTX)) {
        modeval.append(QLatin1Char('T'));
    } else if ((perm & S_IXOTH)) {
        modeval.append(QLatin1Char('x'));
    } else {
        modeval.append(QLatin1Char('-'));
    }
    return modeval;
}

961 962 963 964 965 966

bool LibzipPlugin::hasBatchExtractionProgress() const
{
    return true;
}

Ragnar Thomsen's avatar
Ragnar Thomsen committed
967
#include "libzipplugin.moc"