-
Notifications
You must be signed in to change notification settings - Fork 406
Expand file tree
/
Copy pathimagewriter.cpp
More file actions
4407 lines (3855 loc) · 168 KB
/
imagewriter.cpp
File metadata and controls
4407 lines (3855 loc) · 168 KB
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
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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
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
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* SPDX-License-Identifier: Apache-2.0
* Copyright (C) 2020-2025 Raspberry Pi Ltd
*/
#include "downloadextractthread.h"
#include "imagewriter.h"
#include "writeprogresswatchdog.h"
#include "embedded_config.h"
#include "config.h"
#include "file_operations.h"
#include "drivelistitem.h"
#include "customization_generator.h"
#include "drivelist/drivelist.h"
#include "dependencies/sha256crypt/sha256crypt.h"
#include "dependencies/yescrypt/yescrypt_wrapper.h"
#include "driveformatthread.h"
#include "localfileextractthread.h"
#include "systemmemorymanager.h"
#include "downloadstatstelemetry.h"
#include "wlancredentials.h"
#include "device_info.h"
#include "platformquirks.h"
#ifndef CLI_ONLY_BUILD
#include "iconimageprovider.h"
#include "iconmultifetcher.h"
#include "nativefiledialog.h"
#include <QQmlApplicationEngine>
#include <QQuickWindow>
#endif
#include <archive.h>
#include <archive_entry.h>
#include <lzma.h>
#include <qjsondocument.h>
#include <QJsonArray>
#include <random>
#include <QFile>
#include <QFileInfo>
#include <QTextStream>
#include <QProcess>
#include <QRegularExpression>
#include <QStandardPaths>
#include <QStorageInfo>
#include <QTimeZone>
#include <QNetworkInterface>
#include <QCoreApplication>
#ifndef CLI_ONLY_BUILD
#include <QQmlContext>
#include <QWindow>
#include <QGuiApplication>
#include <QClipboard>
#endif
#include <QUrl>
#include <QUrlQuery>
#include <QString>
#include <QStringList>
#include <QHostAddress>
#include <QDateTime>
#include "curlfetcher.h"
#include "curlnetworkconfig.h"
#include <QDebug>
#include <QJsonObject>
#include <QTranslator>
#include <QPasswordDigestor>
#include <QVersionNumber>
#include <QCryptographicHash>
#include <QRandomGenerator>
#ifndef CLI_ONLY_BUILD
#include <QDesktopServices>
#include <QAccessible>
#endif
#include <stdlib.h>
#include <new>
#include <QLocale>
#include <QMetaType>
#include "imageadvancedoptions.h"
#ifdef Q_OS_WIN
#include <windows.h>
#include <QProcessEnvironment>
#endif
#ifdef Q_OS_LINUX
#include "linux/stpanalyzer.h"
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
#endif
using namespace ImageOptions;
namespace {
constexpr uint MAX_SUBITEMS_DEPTH = 16;
} // namespace anonymous
// Initialize static member for secure boot CLI override
bool ImageWriter::_forceSecureBootEnabled = false;
ImageWriter::ImageWriter(QObject *parent)
: QObject(parent),
_cacheManager(nullptr),
_waitingForCacheVerification(false),
_src(), _repo(QUrl(QString(OSLIST_URL))),
_dst(), _parentCategory(), _osName(), _osReleaseDate(), _currentLang(), _currentLangcode(), _currentKeyboard(),
_expectedHash(), _cmdline(), _config(), _firstrun(), _cloudinit(), _cloudinitNetwork(), _initFormat(),
_downloadLen(0), _extrLen(0), _devLen(0), _dlnow(0), _verifynow(0),
_drivelist(DriveListModel(this)), // explicitly parented, so QML doesn't delete it
_selectedDeviceValid(false),
_writeState(WriteState::Idle),
_cancelledDueToDeviceRemoval(false),
_hwlist(HWListModel(*this)),
_oslist(OSListModel(*this)),
_engine(nullptr),
_networkchecktimer(),
_osListRefreshTimer(),
_suspendInhibitor(nullptr),
_thread(nullptr),
_verifyEnabled(true), _multipleFilesInZip(false), _online(false), _extractSizeKnown(true), _needsDecompressScan(false),
_settings(),
_translations(),
_trans(nullptr),
_refreshIntervalOverrideMinutes(-1),
_refreshJitterOverrideMinutes(-1),
#ifndef CLI_ONLY_BUILD
_piConnectToken(),
_mainWindow(nullptr),
#else
_piConnectToken(),
#endif
_progressWatchdog(nullptr),
_forceSyncMode(false)
{
// Initialise CacheManager
_cacheManager = new CacheManager(this);
// Initialise PerformanceStats
_performanceStats = new PerformanceStats(this);
// Initialize debug options with defaults
// Direct I/O is enabled by default (matches current behavior)
// Periodic sync is enabled by default but skipped when direct I/O is active
_debugDirectIO = true;
_debugPeriodicSync = true;
_debugVerboseLogging = false;
_debugAsyncIO = true; // Async I/O enabled by default for performance
_debugIPv4Only = false; // Use both IPv4 and IPv6 by default
_debugSkipEndOfDevice = false; // Normal behavior; enable for counterfeit cards
// Calculate optimal async queue depth based on system memory
_debugAsyncQueueDepth = SystemMemoryManager::instance().getOptimalAsyncQueueDepth();
// Set up file operations logging to use Qt's debug output
rpi_imager::SetFileOperationsLogCallback([](const std::string& msg) {
qDebug() << "[FileOps]" << msg.c_str();
});
qDebug() << "FileOperations log callback installed";
QString platform;
#ifndef CLI_ONLY_BUILD
if (qobject_cast<QGuiApplication*>(QCoreApplication::instance()) )
{
platform = QGuiApplication::platformName();
}
else
#endif
{
platform = "cli";
}
_device_info = std::make_unique<DeviceInfo>();
if (::isEmbeddedMode())
{
connect(&_networkchecktimer, SIGNAL(timeout()), SLOT(pollNetwork()));
_networkchecktimer.start(100);
changeKeyboard(detectPiKeyboard());
if (_currentKeyboard.isEmpty())
_currentKeyboard = "us";
_currentLang = "English";
{
QString nvmem_blconfig_path = {};
QFile f("/sys/firmware/devicetree/base/aliases/blconfig");
if (f.exists() && f.open(QIODevice::ReadOnly)) {
QByteArray fileContent = f.readAll();
nvmem_blconfig_path = QString::fromLatin1(fileContent.constData());
f.close();
}
QString blconfig_link = {};
if (!nvmem_blconfig_path.isEmpty()) {
QString findCommand = "/usr/bin/find";
QStringList findArguments = {
"-L",
"/sys/bus/nvmem",
"-maxdepth",
"3",
"-samefile",
"/sys/firmware/devicetree/base" + nvmem_blconfig_path
};
QProcess *findProcess = new QProcess(this);
connect(findProcess, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
[&blconfig_link, &findProcess](int exitCode, QProcess::ExitStatus exitStatus) { // clazy:exclude=lambda-in-connect
blconfig_link = findProcess->readAllStandardOutput();
});
findProcess->start(findCommand, findArguments);
findProcess->waitForFinished(); //Default timeout: 30s
delete findProcess;
}
if (!blconfig_link.isEmpty()) {
QDir blconfig_of_dir = QDir(blconfig_link);
if (blconfig_of_dir.cdUp()) {
QFile blconfig_file = QFile(blconfig_of_dir.path() + QDir::separator() + "nvmem");
if (blconfig_file.exists() && blconfig_file.open(blconfig_file.ReadOnly)) {
const QByteArrayList eepromSettings = blconfig_file.readAll().split('\n');
blconfig_file.close();
for (const QByteArray &setting : eepromSettings)
{
if (setting.startsWith("IMAGER_REPO_URL="))
{
_repo = setting.mid(16).trimmed();
qDebug() << "Repository from EEPROM:" << _repo;
}
}
}
}
}
}
// The STP analyzer is only built for embedded mode, so
// unlike the block above that can be selected at runtime,
// this must be selected at build time.
#ifdef BUILD_EMBEDDED
StpAnalyzer *stpAnalyzer = new StpAnalyzer(5, this);
connect(stpAnalyzer, SIGNAL(detected()), SLOT(onSTPdetected()));
stpAnalyzer->startListening("eth0");
#endif
}
if (!_settings.isWritable() && !_settings.fileName().isEmpty())
{
/* Settings file is not writable, probably run by root previously */
QString settingsFile = _settings.fileName();
qDebug() << "Settings file" << settingsFile << "not writable. Recreating it";
QFile f(_settings.fileName());
QByteArray oldsettings;
if (f.open(f.ReadOnly))
{
oldsettings = f.readAll();
f.close();
}
f.remove();
if (f.open(f.WriteOnly))
{
f.write(oldsettings);
f.close();
_settings.sync();
}
else
{
qDebug() << "Error deleting and recreating settings file. Please remove manually.";
}
}
// Cache management is now handled entirely by CacheManager
QDir dir(":/i18n", "rpi-imager_*.qm");
const QStringList transFiles = dir.entryList();
QLocale currentLocale;
QStringList localeComponents = currentLocale.name().split('_');
QString currentlangcode;
if (!localeComponents.isEmpty())
currentlangcode = localeComponents.first();
for (const QString &tf : transFiles)
{
QString langcode = tf.mid(11, tf.length()-14);
QLocale loc(langcode);
/* Use "English" for "en" and not "American English" */
QString langname = (langcode == "en" ? "English" : loc.nativeLanguageName() );
_translations.insert(langname, langcode);
if (langcode == currentlangcode)
{
_currentLang = langname;
_currentLangcode = currentlangcode;
}
}
// Connect to CacheManager signals
connect(_cacheManager, &CacheManager::cacheFileUpdated,
this, [this](const QByteArray& hash) {
qDebug() << "Received cacheFileUpdated signal - refreshing UI for hash:" << hash;
emit cacheStatusChanged();
});
connect(_cacheManager, &CacheManager::cacheVerificationComplete,
this, [this](bool isValid) {
if (isValid) {
// Emit cache status changed signal for QML to react to
emit cacheStatusChanged();
}
});
connect(_cacheManager, &CacheManager::cacheInvalidated,
this, [this]() {
// Emit cache status changed signal when cache is invalidated
emit cacheStatusChanged();
});
// Connect to specific device removal events
connect(&_drivelist, &DriveListModel::deviceRemoved,
this, &ImageWriter::onSelectedDeviceRemoved);
// Connect drive list poll timing events for performance tracking
// Only record polls that take longer than 200ms to avoid noise from normal fast polls
connect(&_drivelist, &DriveListModel::eventDriveListPoll,
this, [this](quint32 durationMs){
if (durationMs >= 200) {
_performanceStats->recordEvent(PerformanceStats::EventType::DriveListPoll, durationMs, true);
}
});
// Connect OS list parse timing events for performance tracking
connect(&_oslist, &OSListModel::eventOsListParse,
this, [this](quint32 durationMs, bool success){
_performanceStats->recordEvent(PerformanceStats::EventType::OsListParse, durationMs, success);
});
// Start background cache operations early
_cacheManager->startBackgroundOperations();
// Start background drive list polling
qDebug() << "Starting background drive list polling";
_drivelist.startPolling();
// Configure OS list refresh timer (single-shot; we reschedule after each fetch)
_osListRefreshTimer.setSingleShot(true);
connect(&_osListRefreshTimer, &QTimer::timeout, this, &ImageWriter::onOsListRefreshTimeout);
// Belt-and-braces: ensure potentially dangerous flags are not persisted between runs
// If found in settings, remove them immediately
if (_settings.contains("disable_warnings")) {
_settings.remove("disable_warnings");
_settings.sync();
qDebug() << "Removed persisted disable_warnings flag from settings";
}
}
void ImageWriter::setMainWindow(QObject *window)
{
#ifndef CLI_ONLY_BUILD
// Convert QObject to QWindow
_mainWindow = qobject_cast<QWindow*>(window);
if (!_mainWindow) {
// If it's not a QWindow directly, try to get the window from a QQuickWindow
QQuickWindow *quickWindow = qobject_cast<QQuickWindow*>(window);
if (quickWindow) {
_mainWindow = quickWindow;
}
}
#else
Q_UNUSED(window);
#endif
}
void ImageWriter::bringWindowToForeground()
{
#ifndef CLI_ONLY_BUILD
if (!_mainWindow) {
return;
}
// Get the native window handle and pass it to the platform-specific implementation
void* windowHandle = reinterpret_cast<void*>(_mainWindow->winId());
if (windowHandle) {
PlatformQuirks::bringWindowToForeground(windowHandle);
qDebug() << "Requested window to be brought to foreground for rpi-connect token";
}
#endif
}
QString ImageWriter::getNativeOpenFileName(const QString &title,
const QString &initialDir,
const QString &filter)
{
#ifndef CLI_ONLY_BUILD
if (!NativeFileDialog::areNativeDialogsAvailable()) {
return QString();
}
return NativeFileDialog::getOpenFileName(title, initialDir, filter, _mainWindow);
#else
Q_UNUSED(title);
Q_UNUSED(initialDir);
Q_UNUSED(filter);
return QString();
#endif
}
QString ImageWriter::readFileContents(const QString &filePath)
{
if (filePath.isEmpty()) {
return QString();
}
QFile file(filePath);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug() << "Failed to open file:" << filePath << "Error:" << file.errorString();
return QString();
}
QTextStream in(&file);
QString content = in.readAll();
file.close();
return content.trimmed();
}
ImageWriter::~ImageWriter()
{
// Stop network monitoring first - the callback captures 'this' pointer
// Must be done before any other cleanup to prevent use-after-free
qDebug() << "Stopping network monitoring";
PlatformQuirks::stopNetworkMonitoring();
// Stop background drive list polling
qDebug() << "Stopping background drive list polling";
_drivelist.stopPolling();
// Stop and cleanup CacheManager background thread before Qt's automatic cleanup
// This ensures the background thread is properly terminated before ImageWriter is destroyed
if (_cacheManager) {
qDebug() << "Cleaning up CacheManager";
delete _cacheManager;
_cacheManager = nullptr;
}
// Ensure any running thread is properly cleaned up
if (_thread) {
if (_thread->isRunning()) {
qDebug() << "Cancelling running thread in ImageWriter destructor";
_thread->cancelDownload();
if (!_thread->wait(10000)) {
qDebug() << "Thread did not finish within 10 seconds, terminating it";
_thread->terminate();
_thread->wait(2000);
}
}
delete _thread;
_thread = nullptr;
}
// Cleanup suspend inhibitor if it's still active
if (_suspendInhibitor) {
delete _suspendInhibitor;
_suspendInhibitor = nullptr;
}
if (_trans)
{
QCoreApplication::removeTranslator(_trans);
delete _trans;
}
}
void ImageWriter::setEngine(QQmlApplicationEngine *engine)
{
#ifndef CLI_ONLY_BUILD
_engine = engine;
if (_engine) {
// Register icon provider for image://icons/<url>
_engine->addImageProvider(QStringLiteral("icons"), new IconImageProvider());
}
#else
Q_UNUSED(engine);
#endif
}
/* Set URL to download from */
void ImageWriter::setSrc(const QUrl &url, quint64 downloadLen, quint64 extrLen, QByteArray expectedHash, bool multifilesinzip, QString parentcategory, QString osname, QByteArray initFormat, QString releaseDate)
{
_src = url;
_downloadLen = downloadLen;
_extrLen = extrLen;
_expectedHash = expectedHash;
_multipleFilesInZip = multifilesinzip;
_parentCategory = parentcategory;
_osName = osname;
_initFormat = (initFormat == "none") ? "" : initFormat;
_osReleaseDate = releaseDate;
// If extract size is provided from manifest, we can trust it; otherwise assume known until proven otherwise
_extractSizeKnown = true;
_needsDecompressScan = false;
qDebug() << "setSrc: initFormat parameter:" << initFormat << "-> _initFormat set to:" << _initFormat;
if (!_downloadLen && url.isLocalFile())
{
QFileInfo fi(url.toLocalFile());
_downloadLen = fi.size();
}
}
/* Set device to write to */
void ImageWriter::setDst(const QString &device, quint64 deviceSize)
{
_dst = device;
_devLen = deviceSize;
_selectedDeviceValid = !device.isEmpty();
// Reset write completion state when device selection changes
if (device.isEmpty()) {
setWriteState(WriteState::Idle);
}
qDebug() << "Device selection changed to:" << device;
}
/* Returns true if src and dst are set and destination device is still valid */
bool ImageWriter::readyToWrite()
{
return !_src.isEmpty() && !_dst.isEmpty() && _selectedDeviceValid;
}
/* Returns true if running on Raspberry Pi */
bool ImageWriter::isRaspberryPiDevice()
{
return _device_info->isRaspberryPi();
}
bool ImageWriter::createHardwareTags()
{
QJsonDocument doc = getFilteredOSlistDocument();
QJsonObject root = doc.object();
if (root.isEmpty() || !doc.isObject()) {
qWarning() << Q_FUNC_INFO << "Invalid root";
return false;
}
QJsonValue imager = root.value("imager");
if (!imager.isObject()) {
qWarning() << Q_FUNC_INFO << "missing imager";
return false;
}
QJsonValue devices = imager.toObject().value("devices");
const QJsonArray deviceArray = devices.toArray();
_device_info->setHardwareTags(deviceArray);
return true;
}
QString ImageWriter::getHardwareName()
{
return _device_info->hardwareName();
}
/* Start writing */
void ImageWriter::startWrite()
{
// Refuse re-entry while a write is already in progress. The deferred-watchdog
// fix (#1511) prevents false stall timeouts during macOS auth, so users should
// no longer reach this path. The guard remains as defence-in-depth. (#1511)
if (_writeState == WriteState::Preparing || _writeState == WriteState::Writing ||
_writeState == WriteState::Verifying || _writeState == WriteState::Finalizing) {
qDebug() << "startWrite: ignoring — write already in progress, state:" << _writeState;
return;
}
// Clean up a finished-but-not-yet-collected thread (deleteLater timing gap).
// A *running* thread here is a bug — our exit paths (onError, onCancelled,
// QThread::finished handler) should have cleaned up already.
if (_thread) {
Q_ASSERT(!_thread->isRunning());
_thread->deleteLater();
_thread = nullptr;
}
if (!readyToWrite())
{
// Provide a user-visible error rather than silently returning, so the UI can recover
// Check all conditions and provide comprehensive error messages
QStringList missingItems;
if (_src.isEmpty())
missingItems.append(tr("image"));
if (_dst.isEmpty())
missingItems.append(tr("storage device"));
else if (!_selectedDeviceValid)
missingItems.append(tr("valid storage device (device no longer available)"));
QString reason;
if (!missingItems.isEmpty())
{
if (missingItems.size() == 1)
reason = tr("No %1 selected.").arg(missingItems.first());
else
reason = tr("No %1 selected.").arg(missingItems.join(tr(" or ")));
}
else
{
reason = tr("Unknown precondition failure.");
}
emit error(tr("Cannot start write. %1").arg(reason));
return;
}
setWriteState(WriteState::Preparing);
if (_src.toString() == "internal://format")
{
// For formatting operations, skip all cache operations since we don't need cached files
qDebug() << "Starting format operation - skipping cache operations";
DriveFormatThread *dft = new DriveFormatThread(_dst.toLatin1(), this);
connect(dft, SIGNAL(success()), SLOT(onSuccess()));
connect(dft, SIGNAL(error(QString)), SLOT(onError(QString)));
connect(dft, SIGNAL(preparationStatusUpdate(QString)), SLOT(onPreparationStatusUpdate(QString)));
connect(dft, &DriveFormatThread::eventDriveFormat,
this, [this](quint32 durationMs, bool success){
_performanceStats->recordEvent(PerformanceStats::EventType::DriveFormat, durationMs, success);
});
dft->start();
return;
}
QByteArray urlstr = _src.toString(_src.FullyEncoded).toLatin1();
QString lowercaseurl = urlstr.toLower();
const bool compressed = lowercaseurl.endsWith(".zip") ||
lowercaseurl.endsWith(".xz") ||
lowercaseurl.endsWith(".bz2") ||
lowercaseurl.endsWith(".gz") ||
lowercaseurl.endsWith(".7z") ||
lowercaseurl.endsWith(".zst") ||
lowercaseurl.endsWith(".cache");
// Proactive validation for local sources before spawning threads
if (_src.isLocalFile())
{
const QString localPath = _src.toLocalFile();
QFileInfo localFi(localPath);
if (!localFi.exists())
{
onError(tr("Source file not found: %1").arg(localPath));
return;
}
if (!localFi.isFile())
{
onError(tr("Source is not a regular file: %1").arg(localPath));
return;
}
if (!localFi.isReadable())
{
onError(tr("Source file is not readable: %1").arg(localPath));
return;
}
}
if (!_extrLen && _src.isLocalFile())
{
if (!compressed)
_extrLen = _downloadLen;
else if (lowercaseurl.endsWith(".xz"))
_parseXZFile();
else if (lowercaseurl.endsWith(".gz"))
_parseGzFile();
else
_parseCompressedFile();
}
if (_devLen && _extrLen > _devLen)
{
emit error(tr("Storage capacity is not large enough.\n\n"
"The image requires at least %1 of storage.")
.arg(formatSize(_extrLen)));
return;
}
if (_extrLen && !_multipleFilesInZip && _extrLen % 512 != 0)
{
emit error(tr("Input file is not a valid disk image.\n\n"
"File size %1 bytes is not a multiple of 512 bytes.")
.arg(_extrLen));
return;
}
// Start performance stats session early so cache lookup is captured
// Use platform-specific write device path (e.g., rdisk on macOS for direct I/O)
QString writeDevicePath = PlatformQuirks::getWriteDevicePath(_dst);
_performanceStats->startSession(_osName.isEmpty() ? _src.fileName() : _osName,
_extrLen > 0 ? _extrLen : _downloadLen,
writeDevicePath);
// Populate system info for performance analysis
{
PerformanceStats::SystemInfo sysInfo;
auto &memMgr = SystemMemoryManager::instance();
// Memory info
sysInfo.totalMemoryBytes = static_cast<quint64>(memMgr.getTotalMemoryMB()) * 1024 * 1024;
sysInfo.availableMemoryBytes = static_cast<quint64>(memMgr.getAvailableMemoryMB()) * 1024 * 1024;
// Device info - use platform-specific write device path
sysInfo.devicePath = writeDevicePath;
sysInfo.deviceSizeBytes = _devLen;
sysInfo.deviceDescription = ""; // Would need DriveListItem lookup
sysInfo.deviceIsUsb = true; // Assume USB for now
sysInfo.deviceIsRemovable = true;
// Platform info
#ifdef Q_OS_MACOS
sysInfo.osName = "macOS";
#elif defined(Q_OS_LINUX)
sysInfo.osName = "Linux";
#elif defined(Q_OS_WIN)
sysInfo.osName = "Windows";
#else
sysInfo.osName = "Unknown";
#endif
sysInfo.osVersion = QSysInfo::productVersion();
sysInfo.cpuArchitecture = QSysInfo::currentCpuArchitecture();
sysInfo.cpuCoreCount = QThread::idealThreadCount();
// Imager version
sysInfo.imagerVersion = IMAGER_VERSION_STR;
#ifdef QT_DEBUG
sysInfo.imagerBuildType = "Debug";
#else
sysInfo.imagerBuildType = "Release";
#endif
sysInfo.qtVersion = qVersion();
sysInfo.qtBuildVersion = QT_VERSION_STR;
// Write configuration - not known yet, will be set later when file is opened
// These will be set via the DirectIOAttempt event metadata
sysInfo.directIOEnabled = false; // Default, actual value set when file opens
sysInfo.periodicSyncEnabled = true; // Default
auto syncConfig = memMgr.calculateSyncConfiguration();
sysInfo.syncIntervalBytes = syncConfig.syncIntervalBytes;
sysInfo.syncIntervalMs = syncConfig.syncIntervalMs;
sysInfo.memoryTier = syncConfig.memoryTier;
// Buffer configuration
sysInfo.writeBufferSize = memMgr.getOptimalWriteBufferSize();
sysInfo.inputBufferSize = memMgr.getOptimalInputBufferSize();
sysInfo.inputRingBufferSlots = memMgr.getOptimalRingBufferSlots(sysInfo.inputBufferSize);
// Write ring buffer is dynamically sized based on optimal queue depth
// Report the max configurable depth (512) + headroom for logging purposes
// Actual allocation may be smaller based on available memory
sysInfo.writeRingBufferSlots = 512 + 4;
_performanceStats->setSystemInfo(sysInfo);
}
// Time cache lookup for performance tracking
// Use hasPotentialCache() which doesn't require verification to be complete
// This allows us to start verification for cached files that haven't been verified yet
QElapsedTimer cacheLookupTimer;
cacheLookupTimer.start();
bool potentialCacheHit = !_expectedHash.isEmpty() && _cacheManager->hasPotentialCache(_expectedHash);
_performanceStats->recordEvent(PerformanceStats::EventType::CacheLookup,
static_cast<quint32>(cacheLookupTimer.elapsed()), true,
potentialCacheHit ? "potential_hit" : (_expectedHash.isEmpty() ? "no_hash" : "miss"));
if (potentialCacheHit)
{
// Use background cache manager to check cache file integrity
CacheManager::CacheStatus cacheStatus = _cacheManager->getCacheStatus();
qDebug() << "Cache status: verificationComplete=" << cacheStatus.verificationComplete
<< "isValid=" << cacheStatus.isValid
<< "file=" << cacheStatus.cacheFileName;
if (cacheStatus.verificationComplete && cacheStatus.isValid)
{
qDebug() << "Using verified cache file (background verified):" << cacheStatus.cacheFileName;
// Use cached file
urlstr = QUrl::fromLocalFile(cacheStatus.cacheFileName).toString(_src.FullyEncoded).toLatin1();
}
else if (cacheStatus.verificationComplete && !cacheStatus.isValid)
{
qDebug() << "Cache file failed background integrity check, invalidating and proceeding with download";
_cacheManager->invalidateCache();
// Continue with original URL - cache will be recreated during download
}
else
{
// Background verification not yet complete
qDebug() << "Cache verification needed - waiting for completion";
// Connect to cache verification progress and completion signals
connect(_cacheManager, &CacheManager::cacheVerificationProgress,
this, &ImageWriter::onCacheVerificationProgress);
connect(_cacheManager, &CacheManager::cacheVerificationComplete,
this, &ImageWriter::onCacheVerificationComplete);
// Start timing cache verification
_cacheVerificationTimer.start();
if (!cacheStatus.verificationComplete)
{
qDebug() << "Starting cache verification";
_cacheManager->startVerification(_expectedHash);
}
else
{
qDebug() << "Verification is already in progress. Waiting for it to complete.";
}
// Set flag to indicate we're waiting for cache verification
_waitingForCacheVerification = true;
// Emit signal to update UI for cache verification
emit cacheVerificationStarted();
// Don't proceed with write yet - wait for cache verification to complete
return;
}
}
try {
if (QUrl(urlstr).isLocalFile())
{
auto *localThread = new LocalFileExtractThread(urlstr, writeDevicePath.toLatin1(), _expectedHash, this);
localThread->setNeedsDecompressScan(_needsDecompressScan);
_thread = localThread;
}
else
{
_thread = new DownloadExtractThread(urlstr, writeDevicePath.toLatin1(), _expectedHash, this);
if (_repo.toString() == OSLIST_URL)
{
DownloadStatsTelemetry *tele = new DownloadStatsTelemetry(urlstr, _parentCategory.toLatin1(), _osName.toLatin1(), isEmbeddedMode(), _currentLangcode, this);
connect(tele, SIGNAL(finished()), tele, SLOT(deleteLater()));
tele->start();
}
}
} catch (const std::bad_alloc& e) {
// Memory allocation failed during thread/buffer creation
qDebug() << "Memory allocation failed during write setup:" << e.what();
// Log the failure to performance stats
_performanceStats->recordEvent(
PerformanceStats::EventType::MemoryAllocationFailure,
0, // No duration - immediate failure
false,
QString("Failed to allocate memory for write operation: %1").arg(e.what())
);
// Provide a clear, actionable error message to the user
QString errorMsg = tr("Failed to start write operation: insufficient memory.\n\n"
"The system does not have enough available memory to perform this operation. "
"Try closing other applications to free up memory, then try again.\n\n"
"Technical details: %1").arg(e.what());
setWriteState(WriteState::Failed);
_performanceStats->endSession(false, "Memory allocation failure");
emit error(errorMsg);
return;
} catch (const std::exception& e) {
// Other exception during thread creation
qDebug() << "Exception during write setup:" << e.what();
_performanceStats->recordEvent(
PerformanceStats::EventType::MemoryAllocationFailure,
0,
false,
QString("Exception during write setup: %1").arg(e.what())
);
setWriteState(WriteState::Failed);
_performanceStats->endSession(false, QString("Setup exception: %1").arg(e.what()));
emit error(tr("Failed to start write operation: %1").arg(e.what()));
return;
}
// Set the extract size for accurate write progress (compressed images have larger extracted size)
_thread->setExtractTotal(_extrLen > 0 ? _extrLen : _downloadLen);
connect(_thread, SIGNAL(success()), SLOT(onSuccess()));
connect(_thread, SIGNAL(error(QString)), SLOT(onError(QString)));
connect(_thread, SIGNAL(finalizing()), SLOT(onFinalizing()));
connect(_thread, SIGNAL(preparationStatusUpdate(QString)), SLOT(onPreparationStatusUpdate(QString)));
// Ensure cleanup of thread pointer on finish in all paths
connect(_thread, &QThread::finished, this, [this]() {
if (_thread)
{
_thread->deleteLater();
_thread = nullptr;
}
});
// Connect to progress signals if this is a DownloadExtractThread
DownloadExtractThread *downloadThread = qobject_cast<DownloadExtractThread*>(_thread);
if (downloadThread) {
connect(downloadThread, &DownloadExtractThread::downloadProgressChanged,
this, &ImageWriter::downloadProgress);
connect(downloadThread, &DownloadExtractThread::writeProgressChanged,
this, &ImageWriter::writeProgress);
connect(downloadThread, &DownloadExtractThread::verifyProgressChanged,
this, &ImageWriter::verifyProgress);
// Connect async write progress signal for event-driven UI updates during WaitForPendingWrites
// This signal is emitted from IOCP completion callbacks, providing real-time progress
connect(downloadThread, &DownloadThread::asyncWriteProgress,
this, &ImageWriter::writeProgress, Qt::QueuedConnection);
// Capture progress for performance stats (lightweight - just stores raw samples)
connect(downloadThread, &DownloadExtractThread::downloadProgressChanged,
this, [this](quint64 now, quint64 total){
_performanceStats->recordDownloadProgress(now, total);
});
connect(downloadThread, &DownloadExtractThread::decompressProgressChanged,
this, [this](quint64 now, quint64 total){
_performanceStats->recordDecompressProgress(now, total);
});
connect(downloadThread, &DownloadExtractThread::writeProgressChanged,
this, [this](quint64 now, quint64 total){
_performanceStats->recordWriteProgress(now, total);
});
connect(downloadThread, &DownloadThread::asyncWriteProgress,
this, [this](quint64 now, quint64 total){
_performanceStats->recordWriteProgress(now, total);
}, Qt::QueuedConnection);
connect(downloadThread, &DownloadExtractThread::verifyProgressChanged,
this, [this](quint64 now, quint64 total){
_performanceStats->recordVerifyProgress(now, total);
});
// Also transition state to Verifying when verify progress first arrives
connect(downloadThread, &DownloadExtractThread::verifyProgressChanged,
this, [this](quint64 /*now*/, quint64 /*total*/){
if (_writeState != WriteState::Verifying && _writeState != WriteState::Finalizing && _writeState != WriteState::Succeeded)
setWriteState(WriteState::Verifying);
});
// Capture ring buffer stall events for time-series correlation
connect(downloadThread, &DownloadExtractThread::eventRingBufferStats,
this, [this](qint64 timestampMs, quint32 durationMs, QString metadata){
// Record as an event with explicit startMs from the stall timestamp
PerformanceStats::TimedEvent event;
event.type = PerformanceStats::EventType::RingBufferStarvation;
event.startMs = static_cast<uint32_t>(timestampMs);
event.durationMs = durationMs;
event.metadata = metadata;
event.success = true;
event.bytesTransferred = 0;
_performanceStats->addEvent(event);
});
// Pipeline timing summary events (emitted at end of extraction)
connect(downloadThread, &DownloadExtractThread::eventPipelineDecompressionTime,
this, [this](quint32 totalMs, quint64 bytesDecompressed){
_performanceStats->recordTransferEvent(
PerformanceStats::EventType::PipelineDecompressionTime,
totalMs, bytesDecompressed, true,
QString("bytes: %1 MB").arg(bytesDecompressed / (1024*1024)));
});
connect(downloadThread, &DownloadExtractThread::eventPipelineRingBufferWaitTime,
this, [this](quint32 totalMs, quint64 bytesRead){
_performanceStats->recordTransferEvent(
PerformanceStats::EventType::PipelineRingBufferWaitTime,
totalMs, bytesRead, true,
QString("bytes: %1 MB").arg(bytesRead / (1024*1024)));
});
connect(downloadThread, &DownloadExtractThread::eventWriteRingBufferStats,
this, [this](quint64 producerStalls, quint64 consumerStalls,
quint64 producerWaitMs, quint64 consumerWaitMs){
QString metadata = QString("producer_stalls: %1 (%2 ms); consumer_stalls: %3 (%4 ms)")
.arg(producerStalls).arg(producerWaitMs)
.arg(consumerStalls).arg(consumerWaitMs);
// Use combined wait time as duration for the event
quint32 totalWaitMs = static_cast<quint32>(producerWaitMs + consumerWaitMs);
_performanceStats->recordEvent(
PerformanceStats::EventType::WriteRingBufferStats,
totalWaitMs, true, metadata);
});
}
// Connect performance event signals from DownloadThread
connect(_thread, &DownloadThread::eventDriveUnmount,
this, [this](quint32 durationMs, bool success){
_performanceStats->recordEvent(PerformanceStats::EventType::DriveUnmount, durationMs, success);
});
connect(_thread, &DownloadThread::eventDriveUnmountVolumes,
this, [this](quint32 durationMs, bool success){
_performanceStats->recordEvent(PerformanceStats::EventType::DriveUnmountVolumes, durationMs, success);
});
connect(_thread, &DownloadThread::eventDriveDiskClean,
this, [this](quint32 durationMs, bool success){
_performanceStats->recordEvent(PerformanceStats::EventType::DriveDiskClean, durationMs, success);
});
connect(_thread, &DownloadThread::eventDriveRescan,
this, [this](quint32 durationMs, bool success){
_performanceStats->recordEvent(PerformanceStats::EventType::DriveRescan, durationMs, success);
});