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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 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 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 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 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 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 335 336 337 338 339 340 341 342 343 344 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 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 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 427 428 429 430 431 432 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 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
|
/*
SPDX-FileCopyrightText: 2005 Shie Erlich <erlich@users.sourceforge.net>
SPDX-FileCopyrightText: 2007-2008 Csaba Karai <cskarai@freemail.hu>
SPDX-FileCopyrightText: 2008 Jonas Bähr <jonas.baehr@web.de>
SPDX-FileCopyrightText: 2005-2022 Krusader Krew <https://krusader.org>
SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "checksumdlg.h"
#include "../GUI/krlistwidget.h"
#include "../GUI/krtreewidget.h"
#include "../icon.h"
#include "../krglobal.h"
#include "../krservices.h"
#include "../krusader.h"
// QtCore
#include <QDirIterator>
#include <QFile>
#include <QFileInfo>
#include <QList>
#include <QMap>
#include <QTextStream>
// QtWidgets
#include <QDialogButtonBox>
#include <QFileDialog>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QProgressBar>
#include <QtConcurrent/QtConcurrentRun> // krazy:exclude=includes
#include <KLocalizedString>
#include <KMessageBox>
#include <KUrlRequester>
void Checksum::startCreationWizard(const QString &path, const QStringList &files)
{
if (files.isEmpty())
return;
QDialog *dialog = new CHECKSUM_::CreateWizard(path, files);
dialog->show();
}
void Checksum::startVerifyWizard(const QString &path, const QString &checksumFile)
{
QDialog *dialog = new CHECKSUM_::VerifyWizard(path, checksumFile);
dialog->show();
}
namespace CHECKSUM_
{
bool stopListFiles;
// async operation invoked by QtConcurrent::run in creation wizard
QStringList listFiles(const QString &path, const QStringList &fileNames)
{
const QDir baseDir(path);
QStringList allFiles;
for (const QString &fileName : fileNames) {
if (stopListFiles)
return QStringList();
QDir subDir = QDir(baseDir.filePath(fileName));
if (subDir.exists()) {
subDir.setFilter(QDir::Files);
QDirIterator it(subDir, QDirIterator::Subdirectories | QDirIterator::FollowSymlinks);
while (it.hasNext()) {
if (stopListFiles)
return QStringList();
allFiles << baseDir.relativeFilePath(it.next());
}
} else {
// assume this is a file
allFiles << fileName;
}
}
return allFiles;
}
// ------------- Checksum Process
ChecksumProcess::ChecksumProcess(QObject *parent, const QString &path)
: KProcess(parent)
, m_tmpOutFile(QDir::tempPath() + QLatin1String("/krusader_XXXXXX.stdout"))
, m_tmpErrFile(QDir::tempPath() + QLatin1String("/krusader_XXXXXX.stderr"))
{
m_tmpOutFile.open(); // necessary to create the filename
m_tmpErrFile.open(); // necessary to create the filename
setOutputChannelMode(KProcess::SeparateChannels); // without this the next 2 lines have no effect!
setStandardOutputFile(m_tmpOutFile.fileName());
setStandardErrorFile(m_tmpErrFile.fileName());
setWorkingDirectory(path);
connect(this, &ChecksumProcess::errorOccurred, this, &ChecksumProcess::slotError);
connect(this, static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished), this, &ChecksumProcess::slotFinished);
}
ChecksumProcess::~ChecksumProcess()
{
disconnect(this, nullptr, this, nullptr); // QProcess emits finished() on destruction
close();
}
void ChecksumProcess::slotError(QProcess::ProcessError error)
{
if (error == QProcess::FailedToStart) {
KMessageBox::error(nullptr, i18n("<qt>Could not start <b>%1</b>.</qt>", program().join(" ")));
}
}
void ChecksumProcess::slotFinished(int, QProcess::ExitStatus exitStatus)
{
if (exitStatus != QProcess::NormalExit) {
KMessageBox::error(nullptr, i18n("<qt>There was an error while running <b>%1</b>.</qt>", program().join(" ")));
return;
}
// parse result files
if (!KrServices::fileToStringList(&m_tmpOutFile, m_outputLines) || !KrServices::fileToStringList(&m_tmpErrFile, m_errorLines)) {
KMessageBox::error(nullptr, i18n("Error reading stdout or stderr"));
return;
}
emit resultReady();
}
// ------------- Generic Checksum Wizard
ChecksumWizard::ChecksumWizard(const QString &path)
: QWizard(krApp)
, m_path(path)
, m_process(nullptr)
{
setAttribute(Qt::WA_DeleteOnClose);
// init the dictionary - pity it has to be manually
m_checksumTools.insert("md5", "md5sum");
m_checksumTools.insert("sha1", "sha1sum");
m_checksumTools.insert("sha256", "sha256sum");
m_checksumTools.insert("sha224", "sha224sum");
m_checksumTools.insert("sha384", "sha384sum");
m_checksumTools.insert("sha512", "sha512sum");
connect(this, &QWizard::currentIdChanged, this, &ChecksumWizard::slotCurrentIdChanged);
}
ChecksumWizard::~ChecksumWizard()
{
if (m_process) {
delete m_process;
}
}
void ChecksumWizard::slotCurrentIdChanged(int id)
{
if (id == m_introId) {
onIntroPage();
} else if (id == m_progressId) {
if (m_process) {
// we are coming from the result page;
delete m_process;
m_process = nullptr;
restart();
} else {
button(QWizard::BackButton)->hide();
button(QWizard::NextButton)->hide();
onProgressPage();
}
} else if (id == m_resultId) {
onResultPage();
}
}
QWizardPage *ChecksumWizard::createProgressPage(const QString &title)
{
auto *page = new QWizardPage;
page->setTitle(title);
page->setPixmap(QWizard::LogoPixmap, Icon("process-working").pixmap(32));
page->setSubTitle(i18n("Please wait..."));
auto *mainLayout = new QVBoxLayout;
page->setLayout(mainLayout);
// "busy" indicator
auto *bar = new QProgressBar();
bar->setRange(0, 0);
mainLayout->addWidget(bar);
return page;
}
bool ChecksumWizard::checkExists(const QString &type)
{
if (!KrServices::cmdExist(m_checksumTools[type])) {
KMessageBox::error(this,
i18n("<qt>Krusader cannot find a checksum tool that handles %1 on your system. "
"Please check the <b>Dependencies</b> page in Krusader's settings.</qt>",
type));
return false;
}
return true;
}
void ChecksumWizard::runProcess(const QString &type, const QStringList &args)
{
Q_ASSERT(m_process == nullptr);
m_process = new ChecksumProcess(this, m_path);
m_process->setProgram(KrServices::fullPathName(m_checksumTools[type]), args);
// show next page (with results) (only) when process is done
connect(m_process, &ChecksumProcess::resultReady, this, &QWizard::next);
// run the process
m_process->start();
}
void ChecksumWizard::addChecksumLine(KrTreeWidget *tree, const QString &line)
{
auto *item = new QTreeWidgetItem(tree);
const qsizetype hashLength = line.indexOf(' '); // delimiter is either " " or " *"
item->setText(0, line.left(hashLength));
QString fileName = line.mid(hashLength + 2);
if (fileName.endsWith('\n'))
fileName.chop(1);
item->setText(1, fileName);
}
// ------------- Create Wizard
CreateWizard::CreateWizard(const QString &path, const QStringList &_files)
: ChecksumWizard(path)
, m_fileNames(_files)
{
m_introId = addPage(createIntroPage());
m_progressId = addPage(createProgressPage(i18n("Creating Checksums")));
m_resultId = addPage(createResultPage());
setButton(QWizard::FinishButton, QDialogButtonBox(QDialogButtonBox::Save).button(QDialogButtonBox::Save));
connect(&m_listFilesWatcher, &QFutureWatcher<QStringList>::resultReadyAt, this, &CreateWizard::createChecksums);
}
QWizardPage *CreateWizard::createIntroPage()
{
auto *page = new QWizardPage;
page->setTitle(i18n("Create Checksums"));
page->setPixmap(QWizard::LogoPixmap, Icon("document-edit-sign").pixmap(32));
page->setSubTitle(i18n("About to calculate checksum for the following files or folders:"));
auto *mainLayout = new QVBoxLayout;
page->setLayout(mainLayout);
// file list
auto *listWidget = new KrListWidget;
listWidget->addItems(m_fileNames);
mainLayout->addWidget(listWidget);
// checksum method
auto *hLayout = new QHBoxLayout;
QLabel *methodLabel = new QLabel(i18n("Select the checksum method:"));
hLayout->addWidget(methodLabel);
m_methodBox = new KComboBox;
// -- fill the combo with available methods
for (const QString &type : m_checksumTools.keys())
m_methodBox->addItem(type);
m_methodBox->setFocus();
hLayout->addWidget(m_methodBox);
mainLayout->addLayout(hLayout);
return page;
}
QWizardPage *CreateWizard::createResultPage()
{
auto *page = new QWizardPage;
page->setTitle(i18n("Checksum Results"));
auto *mainLayout = new QVBoxLayout;
page->setLayout(mainLayout);
m_hashesTreeWidget = new KrTreeWidget(this);
m_hashesTreeWidget->setAllColumnsShowFocus(true);
m_hashesTreeWidget->setHeaderLabels(QStringList() << i18n("Hash") << i18n("File"));
mainLayout->addWidget(m_hashesTreeWidget);
m_errorLabel = new QLabel(i18n("Errors received:"));
mainLayout->addWidget(m_errorLabel);
m_errorListWidget = new KrListWidget;
mainLayout->addWidget(m_errorListWidget);
m_onePerFileBox = new QCheckBox(i18n("Save one checksum file for each source file"));
m_onePerFileBox->setChecked(false);
mainLayout->addWidget(m_onePerFileBox);
return page;
}
void CreateWizard::onIntroPage()
{
button(QWizard::NextButton)->show();
}
void CreateWizard::onProgressPage()
{
// first, get all files (recurse in directories) - async
stopListFiles = false; // QFuture cannot cancel QtConcurrent::run
connect(this, &CreateWizard::finished, this, [=]() {
stopListFiles = true;
});
QFuture<QStringList> listFuture = QtConcurrent::run(listFiles, m_path, m_fileNames);
m_listFilesWatcher.setFuture(listFuture);
}
void CreateWizard::createChecksums()
{
const QString type = m_methodBox->currentText();
if (!checkExists(type)) {
button(QWizard::BackButton)->show();
return;
}
const QStringList &allFiles = m_listFilesWatcher.result();
if (allFiles.isEmpty()) {
KMessageBox::error(this, i18n("No files found"));
button(QWizard::BackButton)->show();
return;
}
runProcess(type, allFiles);
// set suggested filename
m_suggestedFilePath = QDir(m_path).filePath((m_fileNames.count() > 1 ? QString("checksum.") : (m_fileNames[0] + '.')) + type);
}
void CreateWizard::onResultPage()
{
// hash tools display errors into stderr, so we'll use that to determine the result of the job
const QStringList outputLines = m_process->stdOutput();
const QStringList errorLines = m_process->errOutput();
bool errors = !errorLines.isEmpty();
bool successes = !outputLines.isEmpty();
QWizardPage *page = currentPage();
page->setPixmap(QWizard::LogoPixmap, Icon(errors || !successes ? "dialog-error" : "dialog-information").pixmap(32));
page->setSubTitle(errors || !successes ? i18n("Errors were detected while creating the checksums") : i18n("Checksums were created successfully"));
m_hashesTreeWidget->clear();
m_hashesTreeWidget->setVisible(successes);
if (successes) {
for (const QString &line : outputLines)
addChecksumLine(m_hashesTreeWidget, line);
// m_hashesTreeWidget->sortItems(1, Qt::AscendingOrder);
}
m_errorLabel->setVisible(errors);
m_errorListWidget->setVisible(errors);
m_errorListWidget->clear();
m_errorListWidget->addItems(errorLines);
m_onePerFileBox->setEnabled(outputLines.size() > 1);
button(QWizard::FinishButton)->setEnabled(successes);
}
bool CreateWizard::savePerFile()
{
const QString type = m_suggestedFilePath.mid(m_suggestedFilePath.lastIndexOf('.'));
krApp->startWaiting(i18n("Saving checksum files..."), 0);
for (const QString &line : m_process->stdOutput()) {
const QString filename = line.mid(line.indexOf(' ') + 2) + type;
if (!saveChecksumFile(QStringList() << line, filename)) {
KMessageBox::error(this, i18n("Errors occurred while saving multiple checksums. Stopping"));
krApp->stopWait();
return false;
}
}
krApp->stopWait();
return true;
}
bool CreateWizard::saveChecksumFile(const QStringList &data, const QString &filename)
{
QString filePath = filename.isEmpty() ? m_suggestedFilePath : filename;
if (filename.isEmpty() || QFile::exists(filePath)) {
filePath = QFileDialog::getSaveFileName(this, QString(), filePath);
if (filePath.isEmpty())
return false; // user pressed cancel
}
QFile file(filePath);
if (file.open(QIODevice::WriteOnly)) {
QTextStream stream(&file);
for (const QString &line : data)
stream << line << "\n";
file.close();
}
if (file.error() != QFile::NoError) {
KMessageBox::detailedError(this, i18n("Error saving file %1", filePath), file.errorString());
return false;
}
return true;
}
void CreateWizard::accept()
{
const bool saved = m_onePerFileBox->isChecked() ? savePerFile() : saveChecksumFile(m_process->stdOutput());
if (saved)
QWizard::accept();
}
// ------------- Verify Wizard
VerifyWizard::VerifyWizard(const QString &path, const QString &inputFile)
: ChecksumWizard(path)
{
m_checksumFile = isSupported(inputFile) ? inputFile : path;
m_introId = addPage(createIntroPage()); // m_checksumFile must already be set
m_progressId = addPage(createProgressPage(i18n("Verifying Checksums")));
m_resultId = addPage(createResultPage());
}
void VerifyWizard::slotChecksumPathChanged(const QString &path)
{
m_hashesTreeWidget->clear();
button(QWizard::NextButton)->setEnabled(false);
if (!isSupported(path))
return;
m_checksumFile = path;
// parse and display checksum file content; only for the user, parsed values are not used
m_hashesTreeWidget->clear();
QFile file(m_checksumFile);
if (file.open(QFile::ReadOnly)) {
QTextStream inStream(&file);
while (!inStream.atEnd()) {
addChecksumLine(m_hashesTreeWidget, file.readLine());
}
}
file.close();
button(QWizard::NextButton)->setEnabled(true);
}
QWizardPage *VerifyWizard::createIntroPage()
{
auto *page = new QWizardPage;
page->setTitle(i18n("Verify Checksum File"));
page->setPixmap(QWizard::LogoPixmap, Icon("document-edit-verify").pixmap(32));
page->setSubTitle(i18n("About to verify the following checksum file"));
auto *mainLayout = new QVBoxLayout;
page->setLayout(mainLayout);
// checksum file
auto *hLayout = new QHBoxLayout;
QLabel *checksumFileLabel = new QLabel(i18n("Checksum file:"));
hLayout->addWidget(checksumFileLabel);
auto *checksumFileReq = new KUrlRequester;
QString typesFilter;
for (const QString &ext : m_checksumTools.keys())
typesFilter += ("*." + ext + ' ');
checksumFileReq->setNameFilter(typesFilter);
checksumFileReq->setText(m_checksumFile);
checksumFileReq->setFocus();
connect(checksumFileReq, &KUrlRequester::textChanged, this, &VerifyWizard::slotChecksumPathChanged);
hLayout->addWidget(checksumFileReq);
mainLayout->addLayout(hLayout);
// content of checksum file
m_hashesTreeWidget = new KrTreeWidget(page);
m_hashesTreeWidget->setAllColumnsShowFocus(true);
m_hashesTreeWidget->setHeaderLabels(QStringList() << i18n("Hash") << i18n("File"));
mainLayout->addWidget(m_hashesTreeWidget);
return page;
}
QWizardPage *VerifyWizard::createResultPage()
{
auto *page = new QWizardPage;
page->setTitle(i18n("Verify Result"));
auto *mainLayout = new QVBoxLayout;
page->setLayout(mainLayout);
m_outputLabel = new QLabel(i18n("Result output:"));
mainLayout->addWidget(m_outputLabel);
m_outputListWidget = new KrListWidget;
mainLayout->addWidget(m_outputListWidget);
return page;
}
void VerifyWizard::onIntroPage()
{
// cannot do this in constructor: NextButton->hide() is overridden
slotChecksumPathChanged(m_checksumFile);
}
void VerifyWizard::onProgressPage()
{
// verify checksum file...
const QString extension = QFileInfo(m_checksumFile).suffix();
if (!checkExists(extension)) {
button(QWizard::BackButton)->show();
return;
}
runProcess(extension,
QStringList() << "--strict"
<< "-c" << m_checksumFile);
}
void VerifyWizard::onResultPage()
{
// better not only trust error output
const bool errors = m_process->exitCode() != 0 || !m_process->errOutput().isEmpty();
QWizardPage *page = currentPage();
page->setPixmap(QWizard::LogoPixmap, Icon(errors ? "dialog-error" : "dialog-information").pixmap(32));
page->setSubTitle(errors ? i18n("Errors were detected while verifying the checksums") : i18n("Checksums were verified successfully"));
// print everything, errors first
m_outputListWidget->clear();
m_outputListWidget->addItems(m_process->errOutput() + m_process->stdOutput());
button(QWizard::FinishButton)->setEnabled(!errors);
}
bool VerifyWizard::isSupported(const QString &path)
{
const QFileInfo fileInfo(path);
return fileInfo.isFile() && m_checksumTools.contains(fileInfo.suffix());
}
} // NAMESPACE CHECKSUM_
|