summaryrefslogtreecommitdiff
path: root/archived/projt-launcher/launcher/MMCZip.cpp
blob: 9c5c09509263b55b297a359d98cc30288469341b (plain)
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
// SPDX-License-Identifier: GPL-3.0-only
// SPDX-FileCopyrightText: 2026 Project Tick
// SPDX-FileContributor: Project Tick Team
/*
 *  ProjT Launcher - Minecraft Launcher
 *  Copyright (C) 2026 Project Tick
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, version 3.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, write to the Free Software Foundation,
 *  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * === Upstream License Block (Do Not Modify) ==============================
 *
 *
 *
 *  Prism Launcher - Minecraft Launcher
 *  Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
 *  Copyright (c) 2023-2024 Trial97 <alexandru.tripon97@gmail.com>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, version 3.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, write to the Free Software Foundation,
 *  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * This file incorporates work covered by the following copyright and
 * permission notice:
 *
 *      Copyright 2013-2021 MultiMC Contributors
 *
 *      Licensed under the Apache License, Version 2.0 (the "License");
 *      you may not use this file except in compliance with the License.
 *      You may obtain a copy of the License at
 *
 *          http://www.apache.org/licenses/LICENSE-2.0
 *
 *      Unless required by applicable law or agreed to in writing, software
 *      distributed under the License is distributed on an "AS IS" BASIS,
 *      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *      See the License for the specific language governing permissions and
 *      limitations under the License.
 *
 * ======================================================================== */

#include "MMCZip.h"
#include <quazip/quazip.h>
#include <quazip/quazipdir.h>
#include <quazip/quazipfile.h>
#include <quazip/quazipfileinfo.h>
#include "FileSystem.h"

#include <QCoreApplication>
#include <QDebug>
#include <QFileInfo>
#include <QUrl>

#if defined(LAUNCHER_APPLICATION)
#include <QtConcurrentRun>
#endif

namespace
{
	bool isWithinExtractionRoot(const QDir& root, const QString& path)
	{
		const auto cleanRoot = QDir::cleanPath(root.absolutePath());
		const auto cleanPath = QDir::cleanPath(path);
		return cleanPath == cleanRoot || cleanPath.startsWith(cleanRoot + '/');
	}

	bool symlinkEscapesExtractionRoot(QuaZip* zip, const QString& outputPath, const QDir& root)
	{
		QuaZipFileInfo64 info;
		if (!zip->getCurrentFileInfo(&info) || !info.isSymbolicLink())
		{
			return false;
		}

		QuaZipFile linkFile(zip);
		if (!linkFile.open(QIODevice::ReadOnly))
		{
			return true;
		}

		const auto linkTarget = QFile::decodeName(linkFile.readAll());
		linkFile.close();

		QString resolvedTarget;
		if (QDir::isAbsolutePath(linkTarget))
		{
			resolvedTarget = QDir::cleanPath(linkTarget);
		}
		else
		{
			const auto outputDir = QFileInfo(outputPath).dir();
			resolvedTarget	   = QDir::cleanPath(outputDir.absoluteFilePath(linkTarget));
		}

		return !isWithinExtractionRoot(root, resolvedTarget);
	}
} // namespace

namespace MMCZip
{
	// ours
	bool mergeZipFiles(QuaZip* into, QFileInfo from, QSet<QString>& contained, const Filter& filter)
	{
		QuaZip modZip(from.filePath());
		modZip.open(QuaZip::mdUnzip);

		QuaZipFile fileInsideMod(&modZip);
		QuaZipFile zipOutFile(into);
		for (bool more = modZip.goToFirstFile(); more; more = modZip.goToNextFile())
		{
			QString filename = modZip.getCurrentFileName();
			if (filter && !filter(filename))
			{
				qDebug() << "Skipping file " << filename << " from " << from.fileName() << " - filtered";
				continue;
			}
			if (contained.contains(filename))
			{
				qDebug() << "Skipping already contained file " << filename << " from " << from.fileName();
				continue;
			}
			contained.insert(filename);

			if (!fileInsideMod.open(QIODevice::ReadOnly))
			{
				qCritical() << "Failed to open " << filename << " from " << from.fileName();
				return false;
			}

			QuaZipNewInfo info_out(fileInsideMod.getActualFileName());

			if (!zipOutFile.open(QIODevice::WriteOnly, info_out))
			{
				qCritical() << "Failed to open " << filename << " in the jar";
				fileInsideMod.close();
				return false;
			}
			if (!JlCompress::copyData(fileInsideMod, zipOutFile))
			{
				zipOutFile.close();
				fileInsideMod.close();
				qCritical() << "Failed to copy data of " << filename << " into the jar";
				return false;
			}
			zipOutFile.close();
			fileInsideMod.close();
		}
		return true;
	}

	bool compressDirFiles(QuaZip* zip, QString dir, QFileInfoList files, bool followSymlinks)
	{
		QDir directory(dir);
		if (!directory.exists())
			return false;

		for (auto e : files)
		{
			auto filePath = directory.relativeFilePath(e.absoluteFilePath());
			auto srcPath  = e.absoluteFilePath();
			if (followSymlinks)
			{
				if (e.isSymLink())
				{
					srcPath = e.symLinkTarget();
				}
				else
				{
					srcPath = e.canonicalFilePath();
				}
			}
			if (!JlCompress::compressFile(zip, srcPath, filePath))
				return false;
		}

		return true;
	}

	bool compressDirFiles(QString fileCompressed, QString dir, QFileInfoList files, bool followSymlinks)
	{
		QuaZip zip(fileCompressed);
		zip.setUtf8Enabled(true);
		QDir().mkpath(QFileInfo(fileCompressed).absolutePath());
		if (!zip.open(QuaZip::mdCreate))
		{
			FS::deletePath(fileCompressed);
			return false;
		}

		auto result = compressDirFiles(&zip, dir, files, followSymlinks);

		zip.close();
		if (zip.getZipError() != 0)
		{
			FS::deletePath(fileCompressed);
			return false;
		}

		return result;
	}

#if defined(LAUNCHER_APPLICATION)
	// ours
	bool createModdedJar(QString sourceJarPath, QString targetJarPath, const QList<Mod*>& mods)
	{
		QuaZip zipOut(targetJarPath);
		zipOut.setUtf8Enabled(true);
		if (!zipOut.open(QuaZip::mdCreate))
		{
			FS::deletePath(targetJarPath);
			qCritical() << "Failed to open the minecraft.jar for modding";
			return false;
		}
		// Files already added to the jar.
		// These files will be skipped.
		QSet<QString> addedFiles;

		// Modify the jar
		// This needs to be done in reverse-order to ensure we respect the loading order of components
		for (auto i = mods.crbegin(); i != mods.crend(); i++)
		{
			const auto* mod = *i;
			// do not merge disabled mods.
			if (!mod->enabled())
				continue;
			if (mod->type() == ResourceType::ZIPFILE)
			{
				if (!mergeZipFiles(&zipOut, mod->fileinfo(), addedFiles))
				{
					zipOut.close();
					FS::deletePath(targetJarPath);
					qCritical() << "Failed to add" << mod->fileinfo().fileName() << "to the jar.";
					return false;
				}
			}
			else if (mod->type() == ResourceType::SINGLEFILE)
			{
				auto filename = mod->fileinfo();
				// Check if file already added to avoid duplicates
				if (addedFiles.contains(filename.fileName()))
				{
					qDebug() << "Skipping duplicate file" << filename.fileName();
					continue;
				}
				if (!JlCompress::compressFile(&zipOut, filename.absoluteFilePath(), filename.fileName()))
				{
					zipOut.close();
					FS::deletePath(targetJarPath);
					qCritical() << "Failed to add" << mod->fileinfo().fileName() << "to the jar.";
					return false;
				}
				addedFiles.insert(filename.fileName());
			}
			else if (mod->type() == ResourceType::FOLDER)
			{
				// untested, but seems to be unused / not possible to reach
				auto filename		= mod->fileinfo();
				QString what_to_zip = filename.absoluteFilePath();
				QDir dir(what_to_zip);
				dir.cdUp();
				QString parent_dir = dir.absolutePath();
				auto files		   = QFileInfoList();
				collectFileListRecursively(what_to_zip, nullptr, &files, nullptr);

				// Remove files that have already been added to avoid duplicates
				for (auto e : files)
				{
					if (addedFiles.contains(e.filePath()))
						files.removeAll(e);
				}

				if (!compressDirFiles(&zipOut, parent_dir, files))
				{
					zipOut.close();
					FS::deletePath(targetJarPath);
					qCritical() << "Failed to add" << mod->fileinfo().fileName() << "to the jar.";
					return false;
				}
				qDebug() << "Adding folder " << filename.fileName() << " from " << filename.absoluteFilePath();
			}
			else
			{
				// Make sure we do not continue launching when something is missing or undefined...
				zipOut.close();
				FS::deletePath(targetJarPath);
				qCritical() << "Failed to add unknown mod type" << mod->fileinfo().fileName() << "to the jar.";
				return false;
			}
		}

		if (!mergeZipFiles(&zipOut,
						   QFileInfo(sourceJarPath),
						   addedFiles,
						   [](const QString key) { return !key.contains("META-INF"); }))
		{
			zipOut.close();
			FS::deletePath(targetJarPath);
			qCritical() << "Failed to insert minecraft.jar contents.";
			return false;
		}

		// Recompress the jar
		zipOut.close();
		if (zipOut.getZipError() != 0)
		{
			FS::deletePath(targetJarPath);
			qCritical() << "Failed to finalize minecraft.jar!";
			return false;
		}
		return true;
	}
#endif

	// ours
	QString findFolderOfFileInZip(QuaZip* zip,
								  const QString& what,
								  const QStringList& ignore_paths,
								  const QString& root)
	{
		QuaZipDir rootDir(zip, root);
		for (auto&& fileName : rootDir.entryList(QDir::Files))
		{
			if (fileName == what)
				return root;

			QCoreApplication::processEvents();
		}

		// Recurse the search to non-ignored subfolders
		for (auto&& fileName : rootDir.entryList(QDir::Dirs))
		{
			if (ignore_paths.contains(fileName))
				continue;

			QString result = findFolderOfFileInZip(zip, what, ignore_paths, root + fileName);
			if (!result.isEmpty())
				return result;
		}

		return {};
	}

	// ours
	bool findFilesInZip(QuaZip* zip, const QString& what, QStringList& result, const QString& root)
	{
		QuaZipDir rootDir(zip, root);
		for (auto fileName : rootDir.entryList(QDir::Files))
		{
			if (fileName == what)
			{
				result.append(root);
				return true;
			}
		}
		for (auto fileName : rootDir.entryList(QDir::Dirs))
		{
			findFilesInZip(zip, what, result, root + fileName);
		}
		return !result.isEmpty();
	}

	// ours
	std::optional<QStringList> extractSubDir(QuaZip* zip, const QString& subdir, const QString& target)
	{
		auto target_top_dir = QUrl::fromLocalFile(target);

		QStringList extracted;

		qDebug() << "Extracting subdir" << subdir << "from" << zip->getZipName() << "to" << target;
		auto numEntries = zip->getEntriesCount();
		if (numEntries < 0)
		{
			qWarning() << "Failed to enumerate files in archive";
			return std::nullopt;
		}
		else if (numEntries == 0)
		{
			qDebug() << "Extracting empty archives seems odd...";
			return extracted;
		}
		else if (!zip->goToFirstFile())
		{
			qWarning() << "Failed to seek to first file in zip";
			return std::nullopt;
		}

		do
		{
			QString file_name = zip->getCurrentFileName();
			file_name		  = FS::RemoveInvalidPathChars(file_name);
			if (!file_name.startsWith(subdir))
				continue;

			auto relative_file_name = QDir::fromNativeSeparators(file_name.mid(subdir.size()));
			auto original_name		= relative_file_name;

			// Fix subdirs/files ending with a / getting transformed into absolute paths
			if (relative_file_name.startsWith('/'))
				relative_file_name = relative_file_name.mid(1);

			// Fix weird "folders with a single file get squashed" thing
			QString sub_path;
			if (relative_file_name.contains('/') && !relative_file_name.endsWith('/'))
			{
				sub_path = relative_file_name.section('/', 0, -2) + '/';
				FS::ensureFolderPathExists(FS::PathCombine(target, sub_path));

				relative_file_name = relative_file_name.split('/').last();
			}

			QString target_file_path;
			if (relative_file_name.isEmpty())
			{
				target_file_path = target + '/';
			}
			else
			{
				target_file_path = FS::PathCombine(target_top_dir.toLocalFile(), sub_path, relative_file_name);
				if (relative_file_name.endsWith('/') && !target_file_path.endsWith('/'))
					target_file_path += '/';
			}

			if (!target_top_dir.isParentOf(QUrl::fromLocalFile(target_file_path)))
			{
				qWarning() << "Extracting" << relative_file_name
						   << "was cancelled, because it was effectively outside of the target path" << target;
				return std::nullopt;
			}

			if (!JlCompress::extractFile(zip, "", target_file_path))
			{
				qWarning() << "Failed to extract file" << original_name << "to" << target_file_path;
				JlCompress::removeFile(extracted);
				return std::nullopt;
			}

			extracted.append(target_file_path);
			auto fileInfo = QFileInfo(target_file_path);
			if (fileInfo.isFile())
			{
				auto permissions   = fileInfo.permissions();
				auto maxPermisions = QFileDevice::Permission::ReadUser | QFileDevice::Permission::WriteUser
								   | QFileDevice::Permission::ExeUser | QFileDevice::Permission::ReadGroup
								   | QFileDevice::Permission::ReadOther;
				auto minPermisions = QFileDevice::Permission::ReadUser | QFileDevice::Permission::WriteUser;

				auto newPermisions = (permissions & maxPermisions) | minPermisions;
				if (newPermisions != permissions)
				{
					if (!QFile::setPermissions(target_file_path, newPermisions))
					{
						qWarning() << (QObject::tr("Could not fix permissions for %1").arg(target_file_path));
					}
				}
			}
			else if (fileInfo.isDir())
			{
				// Ensure the folder has the minimal required permissions
				QFile::Permissions minimalPermissions = QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner
													  | QFile::ReadGroup | QFile::ExeGroup | QFile::ReadOther
													  | QFile::ExeOther;

				QFile::Permissions currentPermissions = fileInfo.permissions();
				if ((currentPermissions & minimalPermissions) != minimalPermissions)
				{
					if (!QFile::setPermissions(target_file_path, minimalPermissions))
					{
						qWarning() << (QObject::tr("Could not fix permissions for %1").arg(target_file_path));
					}
				}
			}
			qDebug() << "Extracted file" << relative_file_name << "to" << target_file_path;
		}
		while (zip->goToNextFile());

		return extracted;
	}

	// ours
	bool extractRelFile(QuaZip* zip, const QString& file, const QString& target)
	{
		return JlCompress::extractFile(zip, file, target);
	}

	// ours
	std::optional<QStringList> extractDir(QString fileCompressed, QString dir)
	{
		QuaZip zip(fileCompressed);
		if (!zip.open(QuaZip::mdUnzip))
		{
			// check if this is a minimum size empty zip file...
			QFileInfo fileInfo(fileCompressed);
			if (fileInfo.size() == 22)
			{
				return QStringList();
			}
			qWarning() << "Could not open archive for unpacking:" << fileCompressed << "Error:" << zip.getZipError();
			;
			return std::nullopt;
		}
		return extractSubDir(&zip, "", dir);
	}

	// ours
	std::optional<QStringList> extractDir(QString fileCompressed, QString subdir, QString dir)
	{
		QuaZip zip(fileCompressed);
		if (!zip.open(QuaZip::mdUnzip))
		{
			// check if this is a minimum size empty zip file...
			QFileInfo fileInfo(fileCompressed);
			if (fileInfo.size() == 22)
			{
				return QStringList();
			}
			qWarning() << "Could not open archive for unpacking:" << fileCompressed << "Error:" << zip.getZipError();
			;
			return std::nullopt;
		}
		return extractSubDir(&zip, subdir, dir);
	}

	// ours
	bool extractFile(QString fileCompressed, QString file, QString target)
	{
		QuaZip zip(fileCompressed);
		if (!zip.open(QuaZip::mdUnzip))
		{
			// check if this is a minimum size empty zip file...
			QFileInfo fileInfo(fileCompressed);
			if (fileInfo.size() == 22)
			{
				return true;
			}
			qWarning() << "Could not open archive for unpacking:" << fileCompressed << "Error:" << zip.getZipError();
			return false;
		}
		return extractRelFile(&zip, file, target);
	}

	bool collectFileListRecursively(const QString& rootDir,
									const QString& subDir,
									QFileInfoList* files,
									FilterFileFunction excludeFilter)
	{
		QDir rootDirectory(rootDir);
		if (!rootDirectory.exists())
			return false;

		QDir directory;
		if (subDir == nullptr)
			directory = rootDirectory;
		else
			directory = QDir(subDir);

		if (!directory.exists())
			return false; // shouldn't ever happen

		// recurse directories
		QFileInfoList entries = directory.entryInfoList(QDir::AllDirs | QDir::NoDotAndDotDot | QDir::Hidden);
		for (const auto& e : entries)
		{
			if (!collectFileListRecursively(rootDir, e.filePath(), files, excludeFilter))
				return false;
		}

		// collect files
		entries = directory.entryInfoList(QDir::Files);
		for (const auto& e : entries)
		{
			if (excludeFilter && excludeFilter(e))
			{
				QString relativeFilePath = rootDirectory.relativeFilePath(e.absoluteFilePath());
				qDebug() << "Skipping file " << relativeFilePath;
				continue;
			}

			files->append(e); // we want the original paths for compressDirFiles
		}
		return true;
	}

#if defined(LAUNCHER_APPLICATION)
	void ExportToZipTask::executeTask()
	{
		setStatus("Adding files...");
		setProgress(0, m_files.length());
		m_build_zip_future = QtConcurrent::run(QThreadPool::globalInstance(), [this]() { return exportZip(); });
		connect(&m_build_zip_watcher, &QFutureWatcher<ZipResult>::finished, this, &ExportToZipTask::finish);
		m_build_zip_watcher.setFuture(m_build_zip_future);
	}

	auto ExportToZipTask::exportZip() -> ZipResult
	{
		if (!m_dir.exists())
		{
			return ZipResult(tr("Folder doesn't exist"));
		}
		if (!m_output.isOpen() && !m_output.open(QuaZip::mdCreate))
		{
			return ZipResult(tr("Could not create file"));
		}

		for (auto fileName : m_extra_files.keys())
		{
			if (m_build_zip_future.isCanceled())
				return ZipResult();
			QuaZipFile indexFile(&m_output);
			if (!indexFile.open(QIODevice::WriteOnly, QuaZipNewInfo(fileName)))
			{
				return ZipResult(tr("Could not create:") + fileName);
			}
			indexFile.write(m_extra_files[fileName]);
		}

		for (const QFileInfo& file : m_files)
		{
			if (m_build_zip_future.isCanceled())
				return ZipResult();

			auto absolute = file.absoluteFilePath();
			auto relative = m_dir.relativeFilePath(absolute);
			setStatus("Compressing: " + relative);
			setProgress(m_progress + 1, m_progressTotal);
			if (m_follow_symlinks)
			{
				if (file.isSymLink())
					absolute = file.symLinkTarget();
				else
					absolute = file.canonicalFilePath();
			}

			if (!m_exclude_files.contains(relative)
				&& !JlCompress::compressFile(&m_output, absolute, m_destination_prefix + relative))
			{
				return ZipResult(tr("Could not read and compress %1").arg(relative));
			}
		}

		m_output.close();
		if (m_output.getZipError() != 0)
		{
			return ZipResult(tr("A zip error occurred"));
		}
		return ZipResult();
	}

	void ExportToZipTask::finish()
	{
		if (!isRunning())
		{
			FS::deletePath(m_output_path);
			return;
		}
		if (m_build_zip_future.isCanceled())
		{
			FS::deletePath(m_output_path);
			emitAborted();
		}
		else if (auto result = m_build_zip_future.result(); result.has_value())
		{
			FS::deletePath(m_output_path);
			emitFailed(result.value());
		}
		else
		{
			emitSucceeded();
		}
	}

	bool ExportToZipTask::abort()
	{
		if (m_build_zip_future.isRunning())
		{
			m_build_zip_future.cancel();
			emitAborted();
			return true;
		}
		return false;
	}

	void ExtractZipTask::executeTask()
	{
		if (!m_input->isOpen() && !m_input->open(QuaZip::mdUnzip))
		{
			emitFailed(tr("Unable to open supplied zip file."));
			return;
		}
		m_zip_future = QtConcurrent::run(QThreadPool::globalInstance(), [this]() { return extractZip(); });
		connect(&m_zip_watcher, &QFutureWatcher<ZipResult>::finished, this, &ExtractZipTask::finish);
		m_zip_watcher.setFuture(m_zip_future);
	}

	auto ExtractZipTask::extractZip() -> ZipResult
	{
		auto target			= m_output_dir.absolutePath();
		auto target_top_dir = QUrl::fromLocalFile(target);
		QDir target_dir(target);

		QStringList extracted;

		qDebug() << "Extracting subdir" << m_subdirectory << "from" << m_input->getZipName() << "to" << target;
		auto numEntries = m_input->getEntriesCount();
		if (numEntries < 0)
		{
			return ZipResult(tr("Failed to enumerate files in archive"));
		}
		if (numEntries == 0)
		{
			logWarning(tr("Extracting empty archives seems odd..."));
			return ZipResult();
		}
		if (!m_input->goToFirstFile())
		{
			return ZipResult(tr("Failed to seek to first file in zip"));
		}

		setStatus("Extracting files...");
		setProgress(0, numEntries);
		do
		{
			if (m_zip_future.isCanceled())
				return ZipResult();
			setProgress(m_progress + 1, m_progressTotal);
			QString file_name = m_input->getCurrentFileName();
			if (!file_name.startsWith(m_subdirectory))
				continue;

			auto relative_file_name = QDir::fromNativeSeparators(file_name.mid(m_subdirectory.size()));
			auto original_name		= relative_file_name;
			setStatus("Unpacking: " + relative_file_name);

			// Fix subdirs/files ending with a / getting transformed into absolute paths
			if (relative_file_name.startsWith('/'))
				relative_file_name = relative_file_name.mid(1);

			// Fix weird "folders with a single file get squashed" thing
			QString sub_path;
			if (relative_file_name.contains('/') && !relative_file_name.endsWith('/'))
			{
				sub_path = relative_file_name.section('/', 0, -2) + '/';
				FS::ensureFolderPathExists(FS::PathCombine(target, sub_path));

				relative_file_name = relative_file_name.split('/').last();
			}

			QString target_file_path;
			if (relative_file_name.isEmpty())
			{
				target_file_path = target + '/';
			}
			else
			{
				target_file_path = FS::PathCombine(target_top_dir.toLocalFile(), sub_path, relative_file_name);
				if (relative_file_name.endsWith('/') && !target_file_path.endsWith('/'))
					target_file_path += '/';
			}

			if (!target_top_dir.isParentOf(QUrl::fromLocalFile(target_file_path)))
			{
				return ZipResult(
					tr("Extracting %1 was cancelled, because it was effectively outside of the target path %2")
						.arg(relative_file_name, target));
			}
			if (symlinkEscapesExtractionRoot(m_input.get(), target_file_path, target_dir))
			{
				return ZipResult(
					tr("Extracting %1 was cancelled, because it links outside of the target path %2")
						.arg(relative_file_name, target));
			}

			if (!JlCompress::extractFile(m_input.get(), "", target_file_path))
			{
				JlCompress::removeFile(extracted);
				return ZipResult(tr("Failed to extract file %1 to %2").arg(original_name, target_file_path));
			}

			extracted.append(target_file_path);
			auto fileInfo = QFileInfo(target_file_path);
			if (fileInfo.isFile())
			{
				auto permissions   = fileInfo.permissions();
				auto maxPermisions = QFileDevice::Permission::ReadUser | QFileDevice::Permission::WriteUser
								   | QFileDevice::Permission::ExeUser | QFileDevice::Permission::ReadGroup
								   | QFileDevice::Permission::ReadOther;
				auto minPermisions = QFileDevice::Permission::ReadUser | QFileDevice::Permission::WriteUser;

				auto newPermisions = (permissions & maxPermisions) | minPermisions;
				if (newPermisions != permissions)
				{
					if (!QFile::setPermissions(target_file_path, newPermisions))
					{
						logWarning(tr("Could not fix permissions for %1").arg(target_file_path));
					}
				}
			}
			else if (fileInfo.isDir())
			{
				// Ensure the folder has the minimal required permissions
				QFile::Permissions minimalPermissions = QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner
													  | QFile::ReadGroup | QFile::ExeGroup | QFile::ReadOther
													  | QFile::ExeOther;

				QFile::Permissions currentPermissions = fileInfo.permissions();
				if ((currentPermissions & minimalPermissions) != minimalPermissions)
				{
					if (!QFile::setPermissions(target_file_path, minimalPermissions))
					{
						logWarning(tr("Could not fix permissions for %1").arg(target_file_path));
					}
				}
			}

			qDebug() << "Extracted file" << relative_file_name << "to" << target_file_path;
		}
		while (m_input->goToNextFile());

		return ZipResult();
	}

	void ExtractZipTask::finish()
	{
		if (!isRunning())
		{
			return;
		}
		if (m_zip_future.isCanceled())
		{
			emitAborted();
		}
		else if (auto result = m_zip_future.result(); result.has_value())
		{
			emitFailed(result.value());
		}
		else
		{
			emitSucceeded();
		}
	}

	bool ExtractZipTask::abort()
	{
		if (m_zip_future.isRunning())
		{
			m_zip_future.cancel();
			emitAborted();
			return true;
		}
		return false;
	}

#endif
} // namespace MMCZip