Repository navigation
Expand file tree
/
Copy pathgameiso.cpp
More file actions
1307 lines (1075 loc) · 39.3 KB
/
Copy pathgameiso.cpp
File metadata and controls
1307 lines (1075 loc) · 39.3 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
// ============================================================
// gameiso.cpp
// PlayStation 2 (ISO 9660), PlayStation 3 (UDF), and
// GameCube (GCM/FST) disc image support.
// ============================================================
#include "gameiso.h"
#include <QByteArray>
#include <QCoreApplication>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QLibrary>
#include <QSet>
#include <QStringList>
#include <QVector>
#include <QDebug>
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
#include <QTextCodec>
#endif
#include <archive.h>
#include <archive_entry.h>
#include <algorithm>
#include <cstring>
#include <functional>
#include <vector>
#include <sys/types.h>
namespace {
constexpr qint64 kSectorSize = 2048;
constexpr qint64 kMaxDescriptorSector = 32;
constexpr quint32 kGameCubeMagic = 0xC2339F3D;
constexpr int kMaxDirectoryDepth = 64;
constexpr int kMaxDirectoryEntries = 2000000;
const QString ERROR_FILE_NOT_FOUND = QStringLiteral("File not found: ");
const QString ERROR_OPEN_ISO = QStringLiteral("Failed to open ISO file: ");
const QString ERROR_CREATE_DIR = QStringLiteral("Failed to create the destination folder: ");
const QString ERROR_ISO9660_OPEN = QStringLiteral("Failed to open ISO 9660 image: ");
const QString ERROR_ISO9660_READ = QStringLiteral("Failed to read ISO 9660 image: ");
const QString ERROR_UDF_OPEN = QStringLiteral("Failed to open UDF image: ");
const QString ERROR_UDF_READ = QStringLiteral("Failed to read UDF image: ");
const QString ERROR_GAMECUBE_OPEN = QStringLiteral("Failed to open GameCube image: ");
const QString ERROR_GAMECUBE_READ = QStringLiteral("Failed to read GameCube image: ");
const QString ERROR_NO_FILES = QStringLiteral("No files were found in the disc image.");
// ============================================================
// Small helpers
// ============================================================
bool fileExists(const QString &filePath, QString &errorMessage)
{
if (!QFileInfo(filePath).exists()) {
errorMessage = ERROR_FILE_NOT_FOUND + filePath;
return false;
}
return true;
}
bool createOutputDir(const QString &outputPath, QString &errorMessage)
{
if (!QDir().mkpath(outputPath)) {
errorMessage = ERROR_CREATE_DIR + outputPath;
return false;
}
return true;
}
QByteArray readAt(QFile &file, qint64 offset, qint64 length)
{
if (offset < 0 || length <= 0) return QByteArray();
if (!file.seek(offset)) return QByteArray();
return file.read(length);
}
quint32 readBe32(const QByteArray &data, int offset)
{
if (offset < 0 || offset + 4 > data.size()) return 0;
const uchar *p = reinterpret_cast<const uchar *>(data.constData() + offset);
return (quint32(p[0]) << 24)
| (quint32(p[1]) << 16)
| (quint32(p[2]) << 8)
| quint32(p[3]);
}
QString sanitizeRelativePath(const QString &rawPath, bool &ok)
{
ok = false;
QString path = rawPath;
path.replace(QLatin1Char('\\'), QLatin1Char('/'));
// ISO image paths may be absolute or prefixed with "./".
while (path.startsWith(QLatin1String("./"))) {
path.remove(0, 2);
}
while (path.startsWith(QLatin1Char('/'))) {
path.remove(0, 1);
}
if (path.isEmpty()) return QString();
const QStringList parts = path.split(QLatin1Char('/'), Qt::SkipEmptyParts);
QStringList safeParts;
for (const QString &part : parts) {
if (part.isEmpty() || part == QLatin1String(".") || part == QLatin1String("..")) {
return QString();
}
if (part.contains(QChar('\0'))) {
return QString();
}
safeParts << part;
}
if (safeParts.isEmpty()) return QString();
const QString result = safeParts.join(QLatin1Char('/'));
if (result.size() > 4096) return QString();
ok = true;
return result;
}
QString archiveError(archive *reader)
{
const char *message = archive_error_string(reader);
return message ? QString::fromLocal8Bit(message) : QStringLiteral("Unknown archive error.");
}
bool isRootIsoPath(const QString &path)
{
return path.isEmpty()
|| path == QLatin1String(".")
|| path == QLatin1String("./")
|| path == QLatin1String("/");
}
} // namespace
// ============================================================
// Format detection
// ============================================================
static bool hasXdvdfsSignature(QFile &file, qint64 fileSize, qint64 baseOffset)
{
static const char magic[] = "MICROSOFT*XBOX*MEDIA";
const qint64 offset = baseOffset + 32 * kSectorSize;
if (offset < 0 || offset + static_cast<qint64>(sizeof(magic)) - 1 > fileSize) {
return false;
}
const QByteArray data = readAt(file, offset, static_cast<qint64>(sizeof(magic)) - 1);
return data == QByteArray(magic, static_cast<int>(sizeof(magic)) - 1);
}
static bool hasIso9660DescriptorAt(QFile &file, qint64 fileSize, qint64 sector)
{
const qint64 offset = sector * kSectorSize;
if (offset + 7 > fileSize) return false;
// Volume descriptor: type byte followed by "CD001".
const QByteArray data = readAt(file, offset, 7);
if (data.size() < 7) return false;
if (data.at(0) != 1 && data.at(0) != 2) return false;
return data.mid(1, 5) == QByteArrayLiteral("CD001");
}
static bool hasUdfVolumeRecognitionSequence(QFile &file, qint64 fileSize)
{
bool foundBea = false;
bool foundNsr = false;
for (qint64 sector = 16; sector < kMaxDescriptorSector; ++sector) {
const qint64 offset = sector * kSectorSize;
if (offset + 6 > fileSize) break;
const QByteArray data = readAt(file, offset, 6);
if (data.size() < 6) break;
const QByteArray identifier = data.mid(1, 5);
if (identifier == QByteArrayLiteral("BEA01")) {
foundBea = true;
} else if (identifier == QByteArrayLiteral("NSR02")
|| identifier == QByteArrayLiteral("NSR03")) {
foundNsr = true;
}
}
return foundBea && foundNsr;
}
IsoImageFormat detectIsoImageFormat(const QString &isoPath)
{
QFile file(isoPath);
if (!file.open(QIODevice::ReadOnly)) {
return IsoImageFormat::Unknown;
}
const qint64 fileSize = file.size();
if (fileSize < 0x20) {
return IsoImageFormat::Unknown;
}
// XDVDFS can start at the beginning of the image or after an offset.
static const qint64 xdvdfsBases[] = {
0,
0x0FD90000LL,
0x02080000LL
};
for (qint64 base : xdvdfsBases) {
if (hasXdvdfsSignature(file, fileSize, base)) {
return IsoImageFormat::XboxXdvdfs;
}
}
// GameCube GCM/FST boot magic.
if (fileSize >= 0x440) {
const QByteArray header = readAt(file, 0x1C, 4);
if (header.size() == 4 && readBe32(header, 0) == kGameCubeMagic) {
return IsoImageFormat::GameCube;
}
}
// Prefer UDF when both UDF and ISO 9660 descriptors exist (UDF bridge).
if (hasUdfVolumeRecognitionSequence(file, fileSize)) {
return IsoImageFormat::Udf;
}
for (qint64 sector = 16; sector < kMaxDescriptorSector; ++sector) {
if (hasIso9660DescriptorAt(file, fileSize, sector)) {
return IsoImageFormat::Iso9660;
}
}
return IsoImageFormat::Unknown;
}
QString isoImageFormatName(IsoImageFormat format)
{
switch (format) {
case IsoImageFormat::XboxXdvdfs:
return QStringLiteral("Xbox XDVDFS");
case IsoImageFormat::GameCube:
return QStringLiteral("GameCube");
case IsoImageFormat::Iso9660:
return QStringLiteral("ISO 9660");
case IsoImageFormat::Udf:
return QStringLiteral("UDF");
case IsoImageFormat::Unknown:
break;
}
return QStringLiteral("Unknown");
}
bool hasIso9660FileSystem(const QString &isoPath)
{
QFile file(isoPath);
if (!file.open(QIODevice::ReadOnly)) return false;
const qint64 fileSize = file.size();
for (qint64 sector = 16; sector < kMaxDescriptorSector; ++sector) {
if (hasIso9660DescriptorAt(file, fileSize, sector)) {
return true;
}
}
return false;
}
// ============================================================
// ISO 9660 (PlayStation 2)
// ============================================================
archive *openIso9660Archive(const QString &isoPath, QString &errorMessage)
{
archive *reader = archive_read_new();
if (!reader) {
errorMessage = ERROR_ISO9660_OPEN + QStringLiteral("failed to allocate archive reader.");
return nullptr;
}
archive_read_support_filter_all(reader);
archive_read_support_format_iso9660(reader);
const QByteArray nativePath = QFile::encodeName(isoPath);
if (archive_read_open_filename(reader, nativePath.constData(), 65536) != ARCHIVE_OK) {
errorMessage = ERROR_ISO9660_OPEN + archiveError(reader);
archive_read_free(reader);
return nullptr;
}
return reader;
}
int countIso9660Files(const QString &isoPath, QString &errorMessage)
{
archive *reader = openIso9660Archive(isoPath, errorMessage);
if (!reader) return -1;
int count = 0;
archive_entry *entry = nullptr;
int result = ARCHIVE_OK;
while ((result = archive_read_next_header(reader, &entry)) == ARCHIVE_OK
|| result == ARCHIVE_WARN) {
if (archive_entry_filetype(entry) == AE_IFREG) {
++count;
}
archive_read_data_skip(reader);
}
if (result != ARCHIVE_EOF) {
errorMessage = ERROR_ISO9660_READ + archiveError(reader);
archive_read_free(reader);
return -1;
}
archive_read_free(reader);
return count;
}
QStringList listIso9660Contents(const QString &isoPath, QString &errorMessage)
{
errorMessage.clear();
QStringList files;
if (!fileExists(isoPath, errorMessage)) return files;
archive *reader = openIso9660Archive(isoPath, errorMessage);
if (!reader) return files;
QSet<QString> seen;
archive_entry *entry = nullptr;
int result = ARCHIVE_OK;
while ((result = archive_read_next_header(reader, &entry)) == ARCHIVE_OK
|| result == ARCHIVE_WARN) {
const char *pathname = archive_entry_pathname(entry);
if (!pathname) {
archive_read_data_skip(reader);
continue;
}
const mode_t entryType = archive_entry_filetype(entry);
if (entryType != AE_IFREG && entryType != AE_IFDIR) {
archive_read_data_skip(reader);
continue;
}
const QString rawPath = QString::fromUtf8(pathname);
if (isRootIsoPath(rawPath)) {
archive_read_data_skip(reader);
continue;
}
bool validPath = false;
const QString relativePath = sanitizeRelativePath(rawPath, validPath);
if (validPath && !seen.contains(relativePath)) {
seen.insert(relativePath);
files << relativePath;
} else if (!validPath) {
qWarning() << "Skipping unsafe ISO 9660 path:" << rawPath;
}
archive_read_data_skip(reader);
}
if (result != ARCHIVE_EOF) {
errorMessage = ERROR_ISO9660_READ + archiveError(reader);
files.clear();
}
archive_read_free(reader);
files.sort(Qt::CaseInsensitive);
return files;
}
bool extractIso9660Image(const QString &isoPath, const QString &outputPath,
QString &errorMessage,
ExtractProgressCallback progressCallback)
{
errorMessage.clear();
if (!fileExists(isoPath, errorMessage)) return false;
if (outputPath.isEmpty()) {
errorMessage = QStringLiteral("No output folder was selected.");
return false;
}
if (!createOutputDir(outputPath, errorMessage)) return false;
const QString rootPath = QDir(outputPath).absolutePath();
const int totalFiles = countIso9660Files(isoPath, errorMessage);
if (totalFiles < 0) return false;
archive *reader = openIso9660Archive(isoPath, errorMessage);
if (!reader) return false;
int currentFile = 0;
int extractedFiles = 0;
int failedFiles = 0;
archive_entry *entry = nullptr;
int result = ARCHIVE_OK;
std::vector<char> buffer(1024 * 1024);
while ((result = archive_read_next_header(reader, &entry)) == ARCHIVE_OK
|| result == ARCHIVE_WARN) {
const char *pathname = archive_entry_pathname(entry);
if (!pathname) {
archive_read_data_skip(reader);
continue;
}
const mode_t entryType = archive_entry_filetype(entry);
const QString rawPath = QString::fromUtf8(pathname);
if (isRootIsoPath(rawPath)) {
archive_read_data_skip(reader);
continue;
}
bool validPath = false;
const QString relativePath = sanitizeRelativePath(rawPath, validPath);
if (entryType == AE_IFDIR) {
if (validPath) {
QDir().mkpath(QDir(rootPath).filePath(relativePath));
}
archive_read_data_skip(reader);
continue;
}
if (entryType != AE_IFREG) {
archive_read_data_skip(reader);
continue;
}
if (!validPath) {
qWarning() << "Skipping unsafe ISO 9660 path:" << rawPath;
++currentFile;
if (progressCallback) {
progressCallback(currentFile, totalFiles, rawPath);
}
archive_read_data_skip(reader);
continue;
}
const QString outputFilePath = QDir(rootPath).filePath(relativePath);
const QFileInfo outputInfo(outputFilePath);
if (!QDir().mkpath(outputInfo.absolutePath())) {
++failedFiles;
++currentFile;
qWarning() << "Failed to create parent directory for:" << outputFilePath;
if (progressCallback) {
progressCallback(currentFile, totalFiles, relativePath);
}
archive_read_data_skip(reader);
continue;
}
QFile outputFile(outputFilePath);
bool extracted = outputFile.open(QIODevice::WriteOnly | QIODevice::Truncate);
qint64 written = 0;
if (extracted) {
while (true) {
const la_ssize_t bytesRead =
archive_read_data(reader, buffer.data(), buffer.size());
if (bytesRead < 0) {
qWarning() << "ISO 9660 read error for:" << relativePath
<< archiveError(reader);
extracted = false;
break;
}
if (bytesRead == 0) break;
if (outputFile.write(buffer.data(), bytesRead) != bytesRead) {
qWarning() << "Failed to write extracted file:" << outputFilePath;
extracted = false;
break;
}
written += bytesRead;
}
const la_int64_t expectedSize = archive_entry_size(entry);
if (extracted && archive_entry_size_is_set(entry)
&& expectedSize >= 0 && written != expectedSize) {
qWarning() << "Short read for ISO 9660 file:" << relativePath
<< "expected" << expectedSize << "got" << written;
extracted = false;
}
outputFile.close();
}
if (!extracted) {
++failedFiles;
outputFile.remove();
} else {
++extractedFiles;
}
++currentFile;
if (progressCallback) {
progressCallback(currentFile, totalFiles, relativePath);
}
}
if (result != ARCHIVE_EOF) {
errorMessage = ERROR_ISO9660_READ + archiveError(reader);
archive_read_free(reader);
return false;
}
archive_read_free(reader);
if (extractedFiles == 0) {
errorMessage = QStringLiteral("Failed to extract any file from the ISO 9660 image.");
return false;
}
if (failedFiles > 0) {
qWarning() << failedFiles << "ISO 9660 file(s) failed to extract.";
}
return true;
}
// ============================================================
// UDF (PlayStation 3)
// ============================================================
namespace {
struct UdfDirent
{
unsigned int d_type;
const char *d_name;
};
struct UdfEntry
{
QString path;
bool isDirectory = false;
};
class UdfApi
{
public:
~UdfApi()
{
if (lib.isLoaded()) {
lib.unload();
}
}
bool load(QString &errorMessage)
{
const QString appDir = QCoreApplication::applicationDirPath();
QStringList candidates;
if (!appDir.isEmpty()) {
candidates << appDir + QStringLiteral("/libudfread.so.0")
<< appDir + QStringLiteral("/lib/libudfread.so.0")
<< appDir + QStringLiteral("/../lib/libudfread.so.0");
}
candidates << QStringLiteral("libudfread.so.0")
<< QStringLiteral("libudfread.so")
<< QStringLiteral("udfread");
for (const QString &candidate : candidates) {
lib.setFileName(candidate);
if (lib.load()) {
break;
}
}
if (!lib.isLoaded()) {
errorMessage = QStringLiteral(
"libudfread is not available. Install the libudfread0 package "
"to extract PlayStation 3 UDF images. (%1)")
.arg(lib.errorString());
return false;
}
bool resolved = true;
resolved &= resolve(init, "udfread_init");
resolved &= resolve(open, "udfread_open");
resolved &= resolve(close, "udfread_close");
resolved &= resolve(opendir, "udfread_opendir");
resolved &= resolve(readdir, "udfread_readdir");
resolved &= resolve(closedir, "udfread_closedir");
resolved &= resolve(fileOpen, "udfread_file_open");
resolved &= resolve(fileClose, "udfread_file_close");
resolved &= resolve(fileSize, "udfread_file_size");
resolved &= resolve(fileRead, "udfread_file_read");
if (!resolved) {
errorMessage = QStringLiteral(
"The installed libudfread library is missing required functions.");
lib.unload();
return false;
}
return true;
}
template <typename T>
bool resolve(T &target, const char *name)
{
target = reinterpret_cast<T>(lib.resolve(name));
return target != nullptr;
}
QLibrary lib;
void *(*init)() = nullptr;
int (*open)(void *, const char *) = nullptr;
void (*close)(void *) = nullptr;
void *(*opendir)(void *, const char *) = nullptr;
UdfDirent *(*readdir)(void *, UdfDirent *) = nullptr;
void (*closedir)(void *) = nullptr;
void *(*fileOpen)(void *, const char *) = nullptr;
void (*fileClose)(void *) = nullptr;
int64_t (*fileSize)(void *) = nullptr;
ssize_t (*fileRead)(void *, void *, size_t) = nullptr;
};
class UdfVolumeGuard
{
public:
UdfVolumeGuard(UdfApi &api, void *volume)
: m_api(api)
, m_volume(volume)
{
}
~UdfVolumeGuard()
{
if (m_volume) m_api.close(m_volume);
}
UdfVolumeGuard(const UdfVolumeGuard &) = delete;
UdfVolumeGuard &operator=(const UdfVolumeGuard &) = delete;
private:
UdfApi &m_api;
void *m_volume;
};
void *openUdfVolume(UdfApi &api, const QString &isoPath, QString &errorMessage)
{
QString loadError;
if (!api.load(loadError)) {
errorMessage = loadError;
return nullptr;
}
void *volume = api.init();
if (!volume) {
errorMessage = QStringLiteral("Failed to initialize the UDF reader.");
return nullptr;
}
const QByteArray nativePath = QFile::encodeName(isoPath);
if (api.open(volume, nativePath.constData()) < 0) {
errorMessage = ERROR_UDF_OPEN + isoPath;
api.close(volume);
return nullptr;
}
return volume;
}
bool walkUdfDirectory(UdfApi &api, void *volume, const QString &relativeDirectory,
QVector<UdfEntry> &entries, QSet<QString> &visitedDirectories,
QString &errorMessage, int depth, int &entryCount)
{
if (depth > kMaxDirectoryDepth) {
errorMessage = QStringLiteral("UDF directory nesting is too deep.");
return false;
}
if (visitedDirectories.contains(relativeDirectory)) {
return true;
}
visitedDirectories.insert(relativeDirectory);
const QString udfPath = relativeDirectory.isEmpty()
? QStringLiteral("/")
: QLatin1Char('/') + relativeDirectory;
const QByteArray nativePath = udfPath.toUtf8();
void *directory = api.opendir(volume, nativePath.constData());
if (!directory) {
errorMessage = QStringLiteral("Failed to open UDF directory: ") + udfPath;
return false;
}
bool ok = true;
UdfDirent dirent{};
while (api.readdir(directory, &dirent)) {
if (!dirent.d_name) continue;
const QString name = QString::fromUtf8(dirent.d_name);
if (name.isEmpty() || name == QLatin1String(".") || name == QLatin1String("..")) {
continue;
}
if (name.contains(QLatin1Char('/')) || name.contains(QLatin1Char('\\'))) {
qWarning() << "Skipping unsafe UDF path component:" << name;
continue;
}
if (++entryCount > kMaxDirectoryEntries) {
errorMessage = QStringLiteral("UDF image contains too many entries.");
ok = false;
break;
}
const QString childPath = relativeDirectory.isEmpty()
? name
: relativeDirectory + QLatin1Char('/') + name;
if (dirent.d_type == 1) {
UdfEntry entry;
entry.path = childPath;
entry.isDirectory = true;
entries << entry;
if (!walkUdfDirectory(api, volume, childPath, entries,
visitedDirectories, errorMessage, depth + 1,
entryCount)) {
ok = false;
break;
}
} else if (dirent.d_type == 2) {
UdfEntry entry;
entry.path = childPath;
entry.isDirectory = false;
entries << entry;
} else {
qWarning() << "Skipping UDF entry with unknown type:" << childPath;
}
}
api.closedir(directory);
return ok;
}
bool collectUdfEntries(const QString &isoPath, QVector<UdfEntry> &entries,
QString &errorMessage)
{
errorMessage.clear();
entries.clear();
if (!fileExists(isoPath, errorMessage)) return false;
UdfApi api;
void *volume = openUdfVolume(api, isoPath, errorMessage);
if (!volume) return false;
UdfVolumeGuard volumeGuard(api, volume);
QSet<QString> visitedDirectories;
int entryCount = 0;
if (!walkUdfDirectory(api, volume, QString(), entries, visitedDirectories,
errorMessage, 0, entryCount)) {
return false;
}
return true;
}
} // namespace
QStringList listUdfContents(const QString &isoPath, QString &errorMessage)
{
QVector<UdfEntry> entries;
if (!collectUdfEntries(isoPath, entries, errorMessage)) {
return QStringList();
}
QStringList files;
files.reserve(entries.size());
for (const UdfEntry &entry : entries) {
files << entry.path;
}
files.sort(Qt::CaseInsensitive);
return files;
}
bool extractUdfImage(const QString &isoPath, const QString &outputPath,
QString &errorMessage,
ExtractProgressCallback progressCallback)
{
errorMessage.clear();
if (outputPath.isEmpty()) {
errorMessage = QStringLiteral("No output folder was selected.");
return false;
}
QVector<UdfEntry> entries;
if (!collectUdfEntries(isoPath, entries, errorMessage)) {
return false;
}
int totalFiles = 0;
for (const UdfEntry &entry : entries) {
if (!entry.isDirectory) ++totalFiles;
}
if (totalFiles == 0) {
errorMessage = ERROR_NO_FILES;
return false;
}
if (!createOutputDir(outputPath, errorMessage)) return false;
UdfApi api;
void *volume = openUdfVolume(api, isoPath, errorMessage);
if (!volume) return false;
UdfVolumeGuard volumeGuard(api, volume);
const QString rootPath = QDir(outputPath).absolutePath();
std::vector<char> buffer(1024 * 1024);
int currentFile = 0;
int extractedFiles = 0;
int failedFiles = 0;
for (const UdfEntry &entry : entries) {
bool validPath = false;
const QString relativePath = sanitizeRelativePath(entry.path, validPath);
if (!validPath) {
qWarning() << "Skipping unsafe UDF path:" << entry.path;
if (!entry.isDirectory) {
++currentFile;
if (progressCallback) {
progressCallback(currentFile, totalFiles, entry.path);
}
}
continue;
}
const QString outputFilePath = QDir(rootPath).filePath(relativePath);
if (entry.isDirectory) {
QDir().mkpath(outputFilePath);
continue;
}
const QFileInfo outputInfo(outputFilePath);
if (!QDir().mkpath(outputInfo.absolutePath())) {
++failedFiles;
++currentFile;
qWarning() << "Failed to create parent directory for:" << outputFilePath;
if (progressCallback) {
progressCallback(currentFile, totalFiles, relativePath);
}
continue;
}
const QString udfPath = QLatin1Char('/') + relativePath;
const QByteArray nativeUdfPath = udfPath.toUtf8();
void *udfFile = api.fileOpen(volume, nativeUdfPath.constData());
bool extracted = udfFile != nullptr;
if (extracted) {
const int64_t fileSize = api.fileSize(udfFile);
if (fileSize < 0) {
qWarning() << "Failed to get UDF file size:" << relativePath;
extracted = false;
}
QFile outputFile(outputFilePath);
if (extracted && !outputFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
qWarning() << "Failed to create output file:" << outputFilePath;
extracted = false;
}
qint64 written = 0;
if (extracted) {
while (true) {
const ssize_t bytesRead =
api.fileRead(udfFile, buffer.data(), buffer.size());
if (bytesRead < 0) {
qWarning() << "UDF read error for:" << relativePath;
extracted = false;
break;
}
if (bytesRead == 0) break;
if (outputFile.write(buffer.data(), bytesRead) != bytesRead) {
qWarning() << "Failed to write extracted file:" << outputFilePath;
extracted = false;
break;
}
written += bytesRead;
}
if (extracted && fileSize >= 0 && written != fileSize) {
qWarning() << "Short read for UDF file:" << relativePath
<< "expected" << fileSize << "got" << written;
extracted = false;
}
outputFile.close();
if (!extracted) outputFile.remove();
}
api.fileClose(udfFile);
} else {
qWarning() << "Failed to open UDF file:" << relativePath;
}
if (extracted) {
++extractedFiles;
} else {
++failedFiles;
}
++currentFile;
if (progressCallback) {
progressCallback(currentFile, totalFiles, relativePath);
}
}
if (extractedFiles == 0) {
errorMessage = QStringLiteral("Failed to extract any file from the UDF image.");
return false;
}
if (failedFiles > 0) {
qWarning() << failedFiles << "UDF file(s) failed to extract.";
}
return true;
}
// ============================================================
// GameCube GCM/FST
// ============================================================
namespace {
struct GameCubeEntry
{
QString path;
bool isDirectory = false;
quint64 offset = 0;
quint64 size = 0;
};
QString decodeGameCubeName(const QByteArray &rawName)
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
if (QTextCodec *codec = QTextCodec::codecForName("Shift-JIS")) {
return codec->toUnicode(rawName);
}
#endif
return QString::fromLatin1(rawName);
}
bool isValidGameCubeName(const QString &name)
{
return !name.isEmpty()
&& name != QLatin1String(".")
&& name != QLatin1String("..")
&& !name.contains(QLatin1Char('/'))
&& !name.contains(QLatin1Char('\\'))
&& !name.contains(QChar('\0'));
}
bool parseGameCubeEntries(const QString &isoPath, QVector<GameCubeEntry> &entries,
QString &errorMessage)
{
errorMessage.clear();
entries.clear();
QFile file(isoPath);
if (!file.open(QIODevice::ReadOnly)) {
errorMessage = ERROR_GAMECUBE_OPEN + isoPath;
return false;
}
const qint64 fileSize = file.size();
if (fileSize < 0x440) {