jobs.cpp 14.9 KB
Newer Older
1 2
/*
 * Copyright (c) 2007 Henrique Pinto <henrique.pinto@kdemail.net>
3
 * Copyright (c) 2008-2009 Harald Hvaal <haraldhv@stud.ntnu.no>
4
 * Copyright (c) 2009-2012 Raphael Kubo da Costa <rakuco@FreeBSD.org>
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
 *
 * 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.
 */
27

28
#include "jobs.h"
29
#include "ark_debug.h"
30

31
#include <QDir>
32
#include <QDirIterator>
33
#include <QFileInfo>
34
#include <QRegularExpression>
35
#include <QThread>
36
#include <QTimer>
37

38
#include <KLocalizedString>
39

40 41
//#define DEBUG_RACECONDITION

42 43
namespace Kerfuffle
{
44

45 46 47
class Job::Private : public QThread
{
public:
48 49 50 51
    Private(Job *job, QObject *parent = 0)
        : QThread(parent)
        , q(job)
    {
Laurent Montel's avatar
Laurent Montel committed
52
        connect(q, &KJob::result, this, &QThread::quit);
53 54
    }

55
    virtual void run() Q_DECL_OVERRIDE;
56

57
private:
58 59 60 61 62
    Job *q;
};

void Job::Private::run()
{
63
    q->doWork();
64

65 66 67
    if (q->isRunning()) {
        exec();
    }
68 69 70 71 72 73

#ifdef DEBUG_RACECONDITION
    QThread::sleep(2);
#endif
}

Elvis Angelaccio's avatar
Elvis Angelaccio committed
74 75
Job::Job(ReadOnlyArchiveInterface *interface)
    : KJob()
76
    , m_archiveInterface(interface)
77 78
    , m_isRunning(false)
    , d(new Private(this))
79 80 81 82 83 84 85 86 87 88 89 90
{
    static bool onlyOnce = false;
    if (!onlyOnce) {
        qRegisterMetaType<QPair<QString, QString> >("QPair<QString,QString>");
        onlyOnce = true;
    }

    setCapabilities(KJob::Killable);
}

Job::~Job()
{
91 92
    if (d->isRunning()) {
        d->wait();
93 94
    }

95
    delete d;
96
}
97

98 99 100 101 102
ReadOnlyArchiveInterface *Job::archiveInterface()
{
    return m_archiveInterface;
}

103 104 105 106 107
bool Job::isRunning() const
{
    return m_isRunning;
}

108 109
void Job::start()
{
110
    jobTimer.start();
111
    m_isRunning = true;
112

113
    if (archiveInterface()->waitForFinishedSignal()) {
114 115 116 117 118 119
        // CLI-based interfaces run a QProcess, no need to use threads.
        QTimer::singleShot(0, this, &Job::doWork);
    } else {
        // Run the job in another thread.
        d->start();
    }
120 121
}

122 123 124 125 126 127
void Job::emitResult()
{
    m_isRunning = false;
    KJob::emitResult();
}

128 129
void Job::connectToArchiveInterfaceSignals()
{
Laurent Montel's avatar
Laurent Montel committed
130 131 132 133 134 135
    connect(archiveInterface(), &ReadOnlyArchiveInterface::cancelled, this, &Job::onCancelled);
    connect(archiveInterface(), &ReadOnlyArchiveInterface::error, this, &Job::onError);
    connect(archiveInterface(), &ReadOnlyArchiveInterface::entry, this, &Job::onEntry);
    connect(archiveInterface(), &ReadOnlyArchiveInterface::entryRemoved, this, &Job::onEntryRemoved);
    connect(archiveInterface(), &ReadOnlyArchiveInterface::progress, this, &Job::onProgress);
    connect(archiveInterface(), &ReadOnlyArchiveInterface::info, this, &Job::onInfo);
136
    connect(archiveInterface(), &ReadOnlyArchiveInterface::finished, this, &Job::onFinished);
Laurent Montel's avatar
Laurent Montel committed
137
    connect(archiveInterface(), &ReadOnlyArchiveInterface::userQuery, this, &Job::onUserQuery);
138 139
}

140 141
void Job::onCancelled()
{
142
    qCDebug(ARK) << "Cancelled emitted";
143 144 145
    setError(KJob::KilledJobError);
}

146 147
void Job::onError(const QString & message, const QString & details)
{
148
    Q_UNUSED(details)
149

150
    qCDebug(ARK) << "Error emitted:" << message;
151
    setError(KJob::UserDefinedError);
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
    setErrorText(message);
}

void Job::onEntry(const ArchiveEntry & archiveEntry)
{
    emit newEntry(archiveEntry);
}

void Job::onProgress(double value)
{
    setPercent(static_cast<unsigned long>(100.0*value));
}

void Job::onInfo(const QString& info)
{
    emit infoMessage(this, info);
}

void Job::onEntryRemoved(const QString & path)
{
    emit entryRemoved(path);
}

void Job::onFinished(bool result)
{
177
    qCDebug(ARK) << "Job finished, result:" << result << ", time:" << jobTimer.elapsed() << "ms";
178 179 180 181 182 183 184 185 186 187 188

    emitResult();
}

void Job::onUserQuery(Query *query)
{
    emit userQuery(query);
}

bool Job::doKill()
{
189
    bool ret = archiveInterface()->doKill();
190
    if (!ret) {
191
        qCWarning(ARK) << "Killing does not seem to be supported here.";
192
    }
193 194 195
    return ret;
}

Elvis Angelaccio's avatar
Elvis Angelaccio committed
196 197
ListJob::ListJob(ReadOnlyArchiveInterface *interface)
    : Job(interface)
198 199 200
    , m_isSingleFolderArchive(true)
    , m_isPasswordProtected(false)
    , m_extractedFilesSize(0)
201 202
    , m_dirCount(0)
    , m_filesCount(0)
203
{
204
    qCDebug(ARK) << "ListJob started";
Laurent Montel's avatar
Laurent Montel committed
205
    connect(this, &ListJob::newEntry, this, &ListJob::onNewEntry);
206 207 208 209 210
}

void ListJob::doWork()
{
    emit description(this, i18n("Loading archive..."));
211
    connectToArchiveInterfaceSignals();
212
    bool ret = archiveInterface()->list();
213

214
    if (!archiveInterface()->waitForFinishedSignal()) {
215
        onFinished(ret);
216
    }
217 218
}

219
qlonglong ListJob::extractedFilesSize() const
220 221 222 223
{
    return m_extractedFilesSize;
}

224
bool ListJob::isPasswordProtected() const
225 226 227 228
{
    return m_isPasswordProtected;
}

229
bool ListJob::isSingleFolderArchive() const
230
{
231 232 233 234
    if (m_filesCount == 1 && m_dirCount == 0) {
        return false;
    }

235 236 237
    return m_isSingleFolderArchive;
}

238 239 240 241 242
void ListJob::onNewEntry(const ArchiveEntry& entry)
{
    m_extractedFilesSize += entry[ Size ].toLongLong();
    m_isPasswordProtected |= entry [ IsPasswordProtected ].toBool();

243 244 245 246 247 248
    if (entry[IsDirectory].toBool()) {
        m_dirCount++;
    } else {
        m_filesCount++;
    }

249
    if (m_isSingleFolderArchive) {
250 251 252
        // RPM filenames have the ./ prefix, and "." would be detected as the subfolder name, so we remove it.
        const QString fileName = entry[FileName].toString().replace(QRegularExpression(QStringLiteral("^\\./")), QString());
        const QString basePath = fileName.split(QLatin1Char('/')).at(0);
253

254 255 256
        if (m_basePath.isEmpty()) {
            m_basePath = basePath;
            m_subfolderName = basePath;
257
        } else {
258 259 260 261
            if (m_basePath != basePath) {
                m_isSingleFolderArchive = false;
                m_subfolderName.clear();
            }
262 263 264 265
        }
    }
}

266
QString ListJob::subfolderName() const
267
{
268 269 270 271
    if (!isSingleFolderArchive()) {
        return QString();
    }

272 273 274
    return m_subfolderName;
}

Elvis Angelaccio's avatar
Elvis Angelaccio committed
275 276
ExtractJob::ExtractJob(const QVariantList& files, const QString& destinationDir, const ExtractionOptions& options, ReadOnlyArchiveInterface *interface)
    : Job(interface)
277 278 279
    , m_files(files)
    , m_destinationDir(destinationDir)
    , m_options(options)
280
{
281
    qCDebug(ARK) << "ExtractJob created";
282
    setDefaultOptions();
283 284 285 286 287 288 289 290 291 292 293 294
}

void ExtractJob::doWork()
{
    QString desc;
    if (m_files.count() == 0) {
        desc = i18n("Extracting all files");
    } else {
        desc = i18np("Extracting one file", "Extracting %1 files", m_files.count());
    }
    emit description(this, desc);

295 296 297 298 299 300 301
    QFileInfo destDirInfo(m_destinationDir);
    if (destDirInfo.isDir() && (!destDirInfo.isWritable() || !destDirInfo.isExecutable())) {
        onError(xi18n("Could not write to destination <filename>%1</filename>.<nl/>Check whether you have sufficient permissions.", m_destinationDir), QString());
        onFinished(false);
        return;
    }

302
    connectToArchiveInterfaceSignals();
303

304
    qCDebug(ARK) << "Starting extraction with" << m_files.count() << "selected files."
305 306
             << "Destination dir:" << m_destinationDir
             << "Options:" << m_options;
307

308
    bool ret = archiveInterface()->copyFiles(m_files, m_destinationDir, m_options);
309

310
    if (!archiveInterface()->waitForFinishedSignal()) {
311
        onFinished(ret);
312
    }
313 314
}

315
void ExtractJob::setDefaultOptions()
316
{
317 318
    ExtractionOptions defaultOptions;

319
    defaultOptions[QStringLiteral("PreservePaths")] = false;
320 321 322 323 324 325

    ExtractionOptions::const_iterator it = defaultOptions.constBegin();
    for (; it != defaultOptions.constEnd(); ++it) {
        if (!m_options.contains(it.key())) {
            m_options[it.key()] = it.value();
        }
326 327 328
    }
}

329 330 331 332 333
QString ExtractJob::destinationDirectory() const
{
    return m_destinationDir;
}

334 335 336 337 338
ExtractionOptions ExtractJob::extractionOptions() const
{
    return m_options;
}

339 340 341 342 343
TempExtractJob::TempExtractJob(const QString &file, bool passwordProtectedHint, ReadOnlyArchiveInterface *interface)
    : Job(interface)
    , m_file(file)
    , m_passwordProtectedHint(passwordProtectedHint)
{
344
    m_tmpExtractDir = new QTemporaryDir();
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
}

QString TempExtractJob::validatedFilePath() const
{
    QString path = extractionDir() + QLatin1Char('/') + m_file;

    // Make sure a maliciously crafted archive with parent folders named ".." do
    // not cause the previewed file path to be located outside the temporary
    // directory, resulting in a directory traversal issue.
    path.remove(QStringLiteral("../"));

    return path;
}

ExtractionOptions TempExtractJob::extractionOptions() const
{
    ExtractionOptions options;
    options[QStringLiteral("PreservePaths")] = true;

    if (m_passwordProtectedHint) {
        options[QStringLiteral("PasswordProtectedHint")] = true;
    }

    return options;
}

371 372 373 374 375
QTemporaryDir *TempExtractJob::tempDir() const
{
    return m_tmpExtractDir;
}

376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
void TempExtractJob::doWork()
{
    emit description(this, i18n("Extracting one file"));

    connectToArchiveInterfaceSignals();

    qCDebug(ARK) << "Extracting:" << m_file;

    bool ret = archiveInterface()->copyFiles({ QVariant::fromValue(fileRootNodePair(m_file)) }, extractionDir(), extractionOptions());

    if (!archiveInterface()->waitForFinishedSignal()) {
        onFinished(ret);
    }
}

391
QString TempExtractJob::extractionDir() const
392
{
393
    return m_tmpExtractDir->path();
394 395
}

396 397
PreviewJob::PreviewJob(const QString& file, bool passwordProtectedHint, ReadOnlyArchiveInterface *interface)
    : TempExtractJob(file, passwordProtectedHint, interface)
398
{
399
    qCDebug(ARK) << "PreviewJob started";
400 401 402 403 404 405 406 407 408 409 410 411 412 413
}

OpenJob::OpenJob(const QString& file, bool passwordProtectedHint, ReadOnlyArchiveInterface *interface)
    : TempExtractJob(file, passwordProtectedHint, interface)
{
    qCDebug(ARK) << "OpenJob started";
}

OpenWithJob::OpenWithJob(const QString& file, bool passwordProtectedHint, ReadOnlyArchiveInterface *interface)
    : OpenJob(file, passwordProtectedHint, interface)
{
    qCDebug(ARK) << "OpenWithJob started";
}

Elvis Angelaccio's avatar
Elvis Angelaccio committed
414 415
AddJob::AddJob(const QStringList& files, const CompressionOptions& options , ReadWriteArchiveInterface *interface)
    : Job(interface)
416 417
    , m_files(files)
    , m_options(options)
418
{
419
    qCDebug(ARK) << "AddJob started";
420 421 422 423
}

void AddJob::doWork()
{
424
    // Set current dir.
425 426 427 428 429 430 431 432
    const QString globalWorkDir = m_options.value(QStringLiteral("GlobalWorkDir")).toString();
    const QDir workDir = globalWorkDir.isEmpty() ? QDir::current() : QDir(globalWorkDir);
    if (!globalWorkDir.isEmpty()) {
        qCDebug(ARK) << "GlobalWorkDir is set, changing dir to " << globalWorkDir;
        m_oldWorkingDir = QDir::currentPath();
        QDir::setCurrent(globalWorkDir);
    }

433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
    // Count total number of entries to be added.
    qulonglong totalCount = 0;
    QElapsedTimer timer;
    timer.start();
    foreach (const QString &f, m_files) {
        totalCount++;
        if (QFileInfo(f).isDir()) {
            QDirIterator it(f, QDir::AllEntries | QDir::Readable | QDir::Hidden |
                            QDir::NoDotAndDotDot, QDirIterator::Subdirectories);
            while (it.hasNext()) {
                it.next();
                totalCount++;
            }
        }
    }
    qCDebug(ARK) << "Counted" << totalCount << "entries in" << timer.elapsed() << "ms";

    m_options[QStringLiteral("NumberOfEntries")] = totalCount;

    qCDebug(ARK) << "AddJob: going to add" << totalCount << "entries";
    emit description(this, i18np("Adding a file", "Adding %1 files", totalCount));

    ReadWriteArchiveInterface *m_writeInterface =
        qobject_cast<ReadWriteArchiveInterface*>(archiveInterface());

    Q_ASSERT(m_writeInterface);

460 461 462 463 464 465 466 467 468 469 470 471 472 473
    // The file paths must be relative to GlobalWorkDir.
    QStringList relativeFiles;
    foreach (const QString& file, m_files) {
        // #191821: workDir must be used instead of QDir::current()
        //          so that symlinks aren't resolved automatically
        QString relativePath = workDir.relativeFilePath(file);

        if (file.endsWith(QLatin1Char('/'))) {
            relativePath += QLatin1Char('/');
        }

        relativeFiles << relativePath;
    }

474
    connectToArchiveInterfaceSignals();
475
    bool ret = m_writeInterface->addFiles(relativeFiles, m_options);
476

477
    if (!archiveInterface()->waitForFinishedSignal()) {
478
        onFinished(ret);
479
    }
480 481
}

482 483 484 485 486 487 488 489 490
void AddJob::onFinished(bool result)
{
    if (!m_oldWorkingDir.isEmpty()) {
        QDir::setCurrent(m_oldWorkingDir);
    }

    Job::onFinished(result);
}

Elvis Angelaccio's avatar
Elvis Angelaccio committed
491 492
DeleteJob::DeleteJob(const QVariantList& files, ReadWriteArchiveInterface *interface)
    : Job(interface)
493
    , m_files(files)
494 495 496 497 498 499 500 501
{
}

void DeleteJob::doWork()
{
    emit description(this, i18np("Deleting a file from the archive", "Deleting %1 files", m_files.count()));

    ReadWriteArchiveInterface *m_writeInterface =
502
        qobject_cast<ReadWriteArchiveInterface*>(archiveInterface());
503 504 505

    Q_ASSERT(m_writeInterface);

506
    connectToArchiveInterfaceSignals();
507
    bool ret = m_writeInterface->deleteFiles(m_files);
508

509
    if (!archiveInterface()->waitForFinishedSignal()) {
510
        onFinished(ret);
511
    }
512
}
513

Elvis Angelaccio's avatar
Elvis Angelaccio committed
514 515
CommentJob::CommentJob(const QString& comment, ReadWriteArchiveInterface *interface)
    : Job(interface)
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
    , m_comment(comment)
{
}

void CommentJob::doWork()
{
    emit description(this, i18n("Adding comment"));

    ReadWriteArchiveInterface *m_writeInterface =
        qobject_cast<ReadWriteArchiveInterface*>(archiveInterface());

    Q_ASSERT(m_writeInterface);

    connectToArchiveInterfaceSignals();
    bool ret = m_writeInterface->addComment(m_comment);

    if (!archiveInterface()->waitForFinishedSignal()) {
        onFinished(ret);
    }
}

Elvis Angelaccio's avatar
Elvis Angelaccio committed
537 538
TestJob::TestJob(ReadOnlyArchiveInterface *interface)
    : Job(interface)
Ragnar Thomsen's avatar
Ragnar Thomsen committed
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
{
    m_testSuccess = false;
}

void TestJob::doWork()
{
    qCDebug(ARK) << "TestJob started";

    emit description(this, i18n("Testing archive"));
    connectToArchiveInterfaceSignals();
    connect(archiveInterface(), &ReadOnlyArchiveInterface::testSuccess, this, &TestJob::onTestSuccess);

    bool ret = archiveInterface()->testArchive();

    if (!archiveInterface()->waitForFinishedSignal()) {
        onFinished(ret);
    }
}

void TestJob::onTestSuccess()
{
    m_testSuccess = true;
}

bool TestJob::testSucceeded()
{
    return m_testSuccess;
}

568
} // namespace Kerfuffle
569

570