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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
|
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
* Copyright (C) 2022 TheKodeToad <TheKodeToad@proton.me>
* Copyright (C) 2022 Rachel Powers <508861+Ryex@users.noreply.github.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, see <https://www.gnu.org/licenses/>.
*
* 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 "FileSystem.h"
#include <QPair>
#include "BuildConfig.h"
#include <QDebug>
#include <QDir>
#include <QDirIterator>
#include <QFile>
#include <QFileInfo>
#include <QSaveFile>
#include <QStandardPaths>
#include <QStorageInfo>
#include <QTextStream>
#include <QUrl>
#include <QtNetwork>
#include <system_error>
#include "DesktopServices.h"
#include "StringUtils.h"
#if defined Q_OS_WIN32
#define NOMINMAX
#define WIN32_LEAN_AND_MEAN
#include <objbase.h>
#include <objidl.h>
#include <shlguid.h>
#include <shlobj.h>
#include <shobjidl.h>
#include <sys/utime.h>
#include <versionhelpers.h>
#include <windows.h>
#include <winnls.h>
#include <string>
// for ShellExecute
#include <Shellapi.h>
#include <objbase.h>
#include <shlobj.h>
#else
#include <utime.h>
#endif
// Snippet from https://github.com/gulrak/filesystem#using-it-as-single-file-header
#ifdef __APPLE__
#include <Availability.h> // for deployment target to support pre-catalina targets without std::fs
#endif // __APPLE__
#if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || (defined(__cplusplus) && __cplusplus >= 201703L)) && defined(__has_include)
#if __has_include(<filesystem>) && (!defined(__MAC_OS_X_VERSION_MIN_REQUIRED) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 101500)
#define GHC_USE_STD_FS
#include <filesystem>
namespace fs = std::filesystem;
#endif // MacOS min version check
#endif // Other OSes version check
#ifndef GHC_USE_STD_FS
#include <ghc/filesystem.hpp>
namespace fs = ghc::filesystem;
#endif
// clone
#if defined(Q_OS_LINUX)
#include <errno.h>
#include <fcntl.h> /* Definition of FICLONE* constants */
#include <linux/fs.h>
#include <sys/ioctl.h>
#include <unistd.h>
#elif defined(Q_OS_MACOS)
#include <sys/attr.h>
#include <sys/clonefile.h>
#elif defined(Q_OS_WIN)
// winbtrfs clone vs rundll32 shellbtrfs.dll,ReflinkCopy
#include <fileapi.h>
#include <stdio.h>
#include <tchar.h>
#include <windows.h>
// refs
#include <winioctl.h>
#if defined(__MINGW32__)
#include <crtdbg.h>
#endif
#endif
#if defined(Q_OS_WIN)
#if defined(__MINGW32__)
typedef struct _DUPLICATE_EXTENTS_DATA {
HANDLE FileHandle;
LARGE_INTEGER SourceFileOffset;
LARGE_INTEGER TargetFileOffset;
LARGE_INTEGER ByteCount;
} DUPLICATE_EXTENTS_DATA, *PDUPLICATE_EXTENTS_DATA;
typedef struct _FSCTL_GET_INTEGRITY_INFORMATION_BUFFER {
WORD ChecksumAlgorithm; // Checksum algorithm. e.g. CHECKSUM_TYPE_UNCHANGED, CHECKSUM_TYPE_NONE, CHECKSUM_TYPE_CRC32
WORD Reserved; // Must be 0
DWORD Flags; // FSCTL_INTEGRITY_FLAG_xxx
DWORD ChecksumChunkSizeInBytes;
DWORD ClusterSizeInBytes;
} FSCTL_GET_INTEGRITY_INFORMATION_BUFFER, *PFSCTL_GET_INTEGRITY_INFORMATION_BUFFER;
typedef struct _FSCTL_SET_INTEGRITY_INFORMATION_BUFFER {
WORD ChecksumAlgorithm; // Checksum algorithm. e.g. CHECKSUM_TYPE_UNCHANGED, CHECKSUM_TYPE_NONE, CHECKSUM_TYPE_CRC32
WORD Reserved; // Must be 0
DWORD Flags; // FSCTL_INTEGRITY_FLAG_xxx
} FSCTL_SET_INTEGRITY_INFORMATION_BUFFER, *PFSCTL_SET_INTEGRITY_INFORMATION_BUFFER;
#endif
#ifndef FSCTL_DUPLICATE_EXTENTS_TO_FILE
#define FSCTL_DUPLICATE_EXTENTS_TO_FILE CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 209, METHOD_BUFFERED, FILE_WRITE_DATA)
#endif
#ifndef FSCTL_GET_INTEGRITY_INFORMATION
#define FSCTL_GET_INTEGRITY_INFORMATION \
CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 159, METHOD_BUFFERED, FILE_ANY_ACCESS) // FSCTL_GET_INTEGRITY_INFORMATION_BUFFER
#endif
#ifndef FSCTL_SET_INTEGRITY_INFORMATION
#define FSCTL_SET_INTEGRITY_INFORMATION \
CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 160, METHOD_BUFFERED, FILE_READ_DATA | FILE_WRITE_DATA) // FSCTL_SET_INTEGRITY_INFORMATION_BUFFER
#endif
#ifndef ERROR_NOT_CAPABLE
#define ERROR_NOT_CAPABLE 775L
#endif
#ifndef ERROR_BLOCK_TOO_MANY_REFERENCES
#define ERROR_BLOCK_TOO_MANY_REFERENCES 347L
#endif
#endif
namespace FS {
void ensureExists(const QDir& dir)
{
if (!QDir().mkpath(dir.absolutePath())) {
throw FileSystemException("Unable to create folder " + dir.dirName() + " (" + dir.absolutePath() + ")");
}
}
void write(const QString& filename, const QByteArray& data)
{
ensureExists(QFileInfo(filename).dir());
QSaveFile file(filename);
if (!file.open(QSaveFile::WriteOnly)) {
throw FileSystemException("Couldn't open " + filename + " for writing: " + file.errorString());
}
if (data.size() != file.write(data)) {
throw FileSystemException("Error writing data to " + filename + ": " + file.errorString());
}
if (!file.commit()) {
throw FileSystemException("Error while committing data to " + filename + ": " + file.errorString());
}
}
QByteArray read(const QString& filename)
{
QFile file(filename);
if (!file.open(QFile::ReadOnly)) {
throw FileSystemException("Unable to open " + filename + " for reading: " + file.errorString());
}
const qint64 size = file.size();
QByteArray data(int(size), 0);
const qint64 ret = file.read(data.data(), size);
if (ret == -1 || ret != size) {
throw FileSystemException("Error reading data from " + filename + ": " + file.errorString());
}
return data;
}
bool updateTimestamp(const QString& filename)
{
#ifdef Q_OS_WIN32
std::wstring filename_utf_16 = filename.toStdWString();
return (_wutime64(filename_utf_16.c_str(), nullptr) == 0);
#else
QByteArray filenameBA = QFile::encodeName(filename);
return (utime(filenameBA.data(), nullptr) == 0);
#endif
}
bool ensureFilePathExists(QString filenamepath)
{
QFileInfo a(filenamepath);
QDir dir;
QString ensuredPath = a.path();
bool success = dir.mkpath(ensuredPath);
return success;
}
bool ensureFolderPathExists(QString foldernamepath)
{
QFileInfo a(foldernamepath);
QDir dir;
QString ensuredPath = a.filePath();
bool success = dir.mkpath(ensuredPath);
return success;
}
/**
* @brief Copies a directory and it's contents from src to dest
* @param offset subdirectory form src to copy to dest
* @return if there was an error during the filecopy
*/
bool copy::operator()(const QString& offset, bool dryRun)
{
using copy_opts = fs::copy_options;
m_copied = 0; // reset counter
m_failedPaths.clear();
// NOTE always deep copy on windows. the alternatives are too messy.
#if defined Q_OS_WIN32
m_followSymlinks = true;
#endif
auto src = PathCombine(m_src.absolutePath(), offset);
auto dst = PathCombine(m_dst.absolutePath(), offset);
std::error_code err;
fs::copy_options opt = copy_opts::none;
// The default behavior is to follow symlinks
if (!m_followSymlinks)
opt |= copy_opts::copy_symlinks;
// Function that'll do the actual copying
auto copy_file = [&](QString src_path, QString relative_dst_path) {
if (m_matcher && (m_matcher->matches(relative_dst_path) != m_whitelist))
return;
auto dst_path = PathCombine(dst, relative_dst_path);
if (!dryRun) {
ensureFilePathExists(dst_path);
fs::copy(StringUtils::toStdString(src_path), StringUtils::toStdString(dst_path), opt, err);
}
if (err) {
qWarning() << "Failed to copy files:" << QString::fromStdString(err.message());
qDebug() << "Source file:" << src_path;
qDebug() << "Destination file:" << dst_path;
m_failedPaths.append(dst_path);
emit copyFailed(relative_dst_path);
return;
}
m_copied++;
emit fileCopied(relative_dst_path);
};
// We can't use copy_opts::recursive because we need to take into account the
// blacklisted paths, so we iterate over the source directory, and if there's no blacklist
// match, we copy the file.
QDir src_dir(src);
QDirIterator source_it(src, QDir::Filter::Files | QDir::Filter::Hidden, QDirIterator::Subdirectories);
while (source_it.hasNext()) {
auto src_path = source_it.next();
auto relative_path = src_dir.relativeFilePath(src_path);
copy_file(src_path, relative_path);
}
// If the root src is not a directory, the previous iterator won't run.
if (!fs::is_directory(StringUtils::toStdString(src)))
copy_file(src, "");
return err.value() == 0;
}
/// qDebug print support for the LinkPair struct
QDebug operator<<(QDebug debug, const LinkPair& lp)
{
QDebugStateSaver saver(debug);
debug.nospace() << "LinkPair{ src: " << lp.src << " , dst: " << lp.dst << " }";
return debug;
}
bool create_link::operator()(const QString& offset, bool dryRun)
{
m_linked = 0; // reset counter
m_path_results.clear();
m_links_to_make.clear();
m_path_results.clear();
make_link_list(offset);
if (!dryRun)
return make_links();
return true;
}
/**
* @brief Make a list of all the links to make
* @param offset subdirectory of src to link to dest
*/
void create_link::make_link_list(const QString& offset)
{
for (auto pair : m_path_pairs) {
const QString& srcPath = pair.src;
const QString& dstPath = pair.dst;
auto src = PathCombine(QDir(srcPath).absolutePath(), offset);
auto dst = PathCombine(QDir(dstPath).absolutePath(), offset);
// you can't hard link a directory so make sure if we deal with a directory we do so recursively
if (m_useHardLinks)
m_recursive = true;
// Function that'll do the actual linking
auto link_file = [&](QString src_path, QString relative_dst_path) {
if (m_matcher && (m_matcher->matches(relative_dst_path) != m_whitelist)) {
qDebug() << "path" << relative_dst_path << "in black list or not in whitelist";
return;
}
auto dst_path = PathCombine(dst, relative_dst_path);
LinkPair link = { src_path, dst_path };
m_links_to_make.append(link);
};
if ((!m_recursive) || !fs::is_directory(StringUtils::toStdString(src))) {
if (m_debug)
qDebug() << "linking single file or dir:" << src << "to" << dst;
link_file(src, "");
} else {
if (m_debug)
qDebug() << "linking recursively:" << src << "to" << dst << ", max_depth:" << m_max_depth;
QDir src_dir(src);
QDirIterator source_it(src, QDir::Filter::Files | QDir::Filter::Hidden, QDirIterator::Subdirectories);
QStringList linkedPaths;
while (source_it.hasNext()) {
auto src_path = source_it.next();
auto relative_path = src_dir.relativeFilePath(src_path);
if (m_max_depth >= 0 && pathDepth(relative_path) > m_max_depth) {
relative_path = pathTruncate(relative_path, m_max_depth);
src_path = src_dir.filePath(relative_path);
if (linkedPaths.contains(src_path)) {
continue;
}
}
linkedPaths.append(src_path);
link_file(src_path, relative_path);
}
}
}
}
bool create_link::make_links()
{
for (auto link : m_links_to_make) {
QString src_path = link.src;
QString dst_path = link.dst;
auto src_path_std = StringUtils::toStdString(link.src);
auto dst_path_std = StringUtils::toStdString(link.dst);
ensureFilePathExists(dst_path);
if (m_useHardLinks) {
if (m_debug)
qDebug() << "making hard link:" << src_path << "to" << dst_path;
fs::create_hard_link(src_path_std, dst_path_std, m_os_err);
} else if (fs::is_directory(src_path_std)) {
if (m_debug)
qDebug() << "making directory_symlink:" << src_path << "to" << dst_path;
fs::create_directory_symlink(src_path_std, dst_path_std, m_os_err);
} else {
if (m_debug)
qDebug() << "making symlink:" << src_path << "to" << dst_path;
fs::create_symlink(src_path_std, dst_path_std, m_os_err);
}
if (m_os_err) {
qWarning() << "Failed to link files:" << QString::fromStdString(m_os_err.message());
qDebug() << "Source file:" << src_path;
qDebug() << "Destination file:" << dst_path;
qDebug() << "Error category:" << m_os_err.category().name();
qDebug() << "Error code:" << m_os_err.value();
emit linkFailed(src_path, dst_path, QString::fromStdString(m_os_err.message()), m_os_err.value());
} else {
m_linked++;
emit fileLinked(src_path, dst_path);
}
if (m_os_err)
return false;
}
return true;
}
void create_link::runPrivileged(const QString& offset)
{
m_linked = 0; // reset counter
m_path_results.clear();
m_links_to_make.clear();
bool gotResults = false;
make_link_list(offset);
QString serverName = BuildConfig.LAUNCHER_APP_BINARY_NAME + "_filelink_server" + StringUtils::getRandomAlphaNumeric();
connect(&m_linkServer, &QLocalServer::newConnection, this, [&]() {
qDebug() << "Client connected, sending out pairs";
// construct block of data to send
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
qint32 blocksize = quint32(sizeof(quint32));
for (auto link : m_links_to_make) {
blocksize += quint32(link.src.size());
blocksize += quint32(link.dst.size());
}
qDebug() << "About to write block of size:" << blocksize;
out << blocksize;
out << quint32(m_links_to_make.length());
for (auto link : m_links_to_make) {
out << link.src;
out << link.dst;
}
QLocalSocket* clientConnection = m_linkServer.nextPendingConnection();
connect(clientConnection, &QLocalSocket::disconnected, clientConnection, &QLocalSocket::deleteLater);
connect(clientConnection, &QLocalSocket::readyRead, this, [&, clientConnection]() {
QDataStream in;
quint32 blockSize = 0;
in.setDevice(clientConnection);
qDebug() << "Reading path results from client";
qDebug() << "bytes available" << clientConnection->bytesAvailable();
// Relies on the fact that QDataStream serializes a quint32 into
// sizeof(quint32) bytes
if (clientConnection->bytesAvailable() < (int)sizeof(quint32))
return;
qDebug() << "reading block size";
in >> blockSize;
qDebug() << "blocksize is" << blockSize;
qDebug() << "bytes available" << clientConnection->bytesAvailable();
if (clientConnection->bytesAvailable() < blockSize || in.atEnd())
return;
quint32 numResults;
in >> numResults;
qDebug() << "numResults" << numResults;
for (quint32 i = 0; i < numResults; i++) {
FS::LinkResult result;
in >> result.src;
in >> result.dst;
in >> result.err_msg;
qint32 err_value;
in >> err_value;
result.err_value = err_value;
if (result.err_value) {
qDebug() << "privileged link fail" << result.src << "to" << result.dst << "code" << result.err_value << result.err_msg;
emit linkFailed(result.src, result.dst, result.err_msg, result.err_value);
} else {
qDebug() << "privileged link success" << result.src << "to" << result.dst;
m_linked++;
emit fileLinked(result.src, result.dst);
}
m_path_results.append(result);
}
gotResults = true;
qDebug() << "results received, closing connection";
clientConnection->close();
});
qint64 byteswritten = clientConnection->write(block);
bool bytesflushed = clientConnection->flush();
qDebug() << "block flushed" << byteswritten << bytesflushed;
});
qDebug() << "Listening on pipe" << serverName;
if (!m_linkServer.listen(serverName)) {
qDebug() << "Unable to start local pipe server on" << serverName << ":" << m_linkServer.errorString();
return;
}
ExternalLinkFileProcess* linkFileProcess = new ExternalLinkFileProcess(serverName, m_useHardLinks, this);
connect(linkFileProcess, &ExternalLinkFileProcess::processExited, this, [&]() { emit finishedPrivileged(gotResults); });
connect(linkFileProcess, &ExternalLinkFileProcess::finished, linkFileProcess, &QObject::deleteLater);
linkFileProcess->start();
}
void ExternalLinkFileProcess::runLinkFile()
{
QString fileLinkExe =
PathCombine(QCoreApplication::instance()->applicationDirPath(), BuildConfig.LAUNCHER_APP_BINARY_NAME + "_filelink");
QString params = "-s " + m_server;
params += " -H " + QVariant(m_useHardLinks).toString();
#if defined Q_OS_WIN32
SHELLEXECUTEINFO ShExecInfo;
fileLinkExe = fileLinkExe + ".exe";
qDebug() << "Running: runas" << fileLinkExe << params;
LPCWSTR programNameWin = (const wchar_t*)fileLinkExe.utf16();
LPCWSTR paramsWin = (const wchar_t*)params.utf16();
// https://learn.microsoft.com/en-us/windows/win32/api/shellapi/ns-shellapi-shellexecuteinfoa
ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
ShExecInfo.hwnd = NULL; // Optional. A handle to the owner window, used to display and position any UI that the system might produce
// while executing this function.
ShExecInfo.lpVerb = L"runas"; // elevate to admin, show UAC
ShExecInfo.lpFile = programNameWin;
ShExecInfo.lpParameters = paramsWin;
ShExecInfo.lpDirectory = NULL;
ShExecInfo.nShow = SW_HIDE;
ShExecInfo.hInstApp = NULL;
ShellExecuteEx(&ShExecInfo);
WaitForSingleObject(ShExecInfo.hProcess, INFINITE);
CloseHandle(ShExecInfo.hProcess);
#endif
qDebug() << "Process exited";
}
bool move(const QString& source, const QString& dest)
{
std::error_code err;
ensureFilePathExists(dest);
fs::rename(StringUtils::toStdString(source), StringUtils::toStdString(dest), err);
if (err) {
qWarning() << "Failed to move file:" << QString::fromStdString(err.message());
qDebug() << "Source file:" << source;
qDebug() << "Destination file:" << dest;
}
return err.value() == 0;
}
bool deletePath(QString path)
{
std::error_code err;
fs::remove_all(StringUtils::toStdString(path), err);
if (err) {
qWarning() << "Failed to remove files:" << QString::fromStdString(err.message());
}
return err.value() == 0;
}
bool trash(QString path, QString* pathInTrash)
{
#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
return false;
#else
// FIXME: Figure out trash in Flatpak. Qt seemingly doesn't use the Trash portal
if (DesktopServices::isFlatpak())
return false;
#if defined Q_OS_WIN32
if (IsWindowsServer())
return false;
#endif
return QFile::moveToTrash(path, pathInTrash);
#endif
}
QString PathCombine(const QString& path1, const QString& path2)
{
if (!path1.size())
return path2;
if (!path2.size())
return path1;
return QDir::cleanPath(path1 + QDir::separator() + path2);
}
QString PathCombine(const QString& path1, const QString& path2, const QString& path3)
{
return PathCombine(PathCombine(path1, path2), path3);
}
QString PathCombine(const QString& path1, const QString& path2, const QString& path3, const QString& path4)
{
return PathCombine(PathCombine(path1, path2, path3), path4);
}
QString AbsolutePath(const QString& path)
{
return QFileInfo(path).absolutePath();
}
int pathDepth(const QString& path)
{
if (path.isEmpty())
return 0;
QFileInfo info(path);
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
auto parts = QDir::toNativeSeparators(info.path()).split(QDir::separator(), QString::SkipEmptyParts);
#else
auto parts = QDir::toNativeSeparators(info.path()).split(QDir::separator(), Qt::SkipEmptyParts);
#endif
int numParts = parts.length();
numParts -= parts.count(".");
numParts -= parts.count("..") * 2;
return numParts;
}
QString pathTruncate(const QString& path, int depth)
{
if (path.isEmpty() || (depth < 0))
return "";
QString trunc = QFileInfo(path).path();
if (pathDepth(trunc) > depth) {
return pathTruncate(trunc, depth);
}
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
auto parts = QDir::toNativeSeparators(trunc).split(QDir::separator(), QString::SkipEmptyParts);
#else
auto parts = QDir::toNativeSeparators(trunc).split(QDir::separator(), Qt::SkipEmptyParts);
#endif
if (parts.startsWith(".") && !path.startsWith(".")) {
parts.removeFirst();
}
if (QDir::toNativeSeparators(path).startsWith(QDir::separator())) {
parts.prepend("");
}
trunc = parts.join(QDir::separator());
return trunc;
}
QString ResolveExecutable(QString path)
{
if (path.isEmpty()) {
return QString();
}
if (!path.contains('/')) {
path = QStandardPaths::findExecutable(path);
}
QFileInfo pathInfo(path);
if (!pathInfo.exists() || !pathInfo.isExecutable()) {
return QString();
}
return pathInfo.absoluteFilePath();
}
/**
* Normalize path
*
* Any paths inside the current folder will be normalized to relative paths (to current)
* Other paths will be made absolute
*/
QString NormalizePath(QString path)
{
QDir a = QDir::currentPath();
QString currentAbsolute = a.absolutePath();
QDir b(path);
QString newAbsolute = b.absolutePath();
if (newAbsolute.startsWith(currentAbsolute)) {
return a.relativeFilePath(newAbsolute);
} else {
return newAbsolute;
}
}
QString badFilenameChars = "\"\\/?<>:;*|!+\r\n";
QString RemoveInvalidFilenameChars(QString string, QChar replaceWith)
{
for (int i = 0; i < string.length(); i++) {
if (badFilenameChars.contains(string[i])) {
string[i] = replaceWith;
}
}
return string;
}
QString DirNameFromString(QString string, QString inDir)
{
int num = 0;
QString baseName = RemoveInvalidFilenameChars(string, '-');
QString dirName;
do {
if (num == 0) {
dirName = baseName;
} else {
dirName = baseName + "(" + QString::number(num) + ")";
}
// If it's over 9000
if (num > 9000)
return "";
num++;
} while (QFileInfo(PathCombine(inDir, dirName)).exists());
return dirName;
}
// Does the folder path contain any '!'? If yes, return true, otherwise false.
// (This is a problem for Java)
bool checkProblemticPathJava(QDir folder)
{
QString pathfoldername = folder.absolutePath();
return pathfoldername.contains("!", Qt::CaseInsensitive);
}
QString getDesktopDir()
{
return QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
}
// Cross-platform Shortcut creation
bool createShortcut(QString destination, QString target, QStringList args, QString name, QString icon)
{
if (destination.isEmpty()) {
destination = PathCombine(getDesktopDir(), RemoveInvalidFilenameChars(name));
}
#if defined(Q_OS_MACOS)
// Create the Application
QDir applicationDirectory =
QStandardPaths::writableLocation(QStandardPaths::ApplicationsLocation) + "/" + BuildConfig.LAUNCHER_NAME + " Instances/";
if (!applicationDirectory.mkpath(".")) {
qWarning() << "Couldn't create application directory";
return false;
}
QDir application = applicationDirectory.path() + "/" + name + ".app/";
if (application.exists()) {
qWarning() << "Application already exists!";
return false;
}
if (!application.mkpath(".")) {
qWarning() << "Couldn't create application";
return false;
}
QDir content = application.path() + "/Contents/";
QDir resources = content.path() + "/Resources/";
QDir binaryDir = content.path() + "/MacOS/";
QFile info = content.path() + "/Info.plist";
if (!(content.mkpath(".") && resources.mkpath(".") && binaryDir.mkpath("."))) {
qWarning() << "Couldn't create directories within application";
return false;
}
info.open(QIODevice::WriteOnly | QIODevice::Text);
QFile(icon).rename(resources.path() + "/Icon.icns");
// Create the Command file
QString exec = binaryDir.path() + "/Run.command";
QFile f(exec);
f.open(QIODevice::WriteOnly | QIODevice::Text);
QTextStream stream(&f);
QString argstring;
if (!args.empty())
argstring = " \"" + args.join("\" \"") + "\"";
stream << "#!/bin/bash"
<< "\n";
stream << "\"" << target << "\" " << argstring << "\n";
stream.flush();
f.close();
f.setPermissions(f.permissions() | QFileDevice::ExeOwner | QFileDevice::ExeGroup | QFileDevice::ExeOther);
// Generate the Info.plist
QTextStream infoStream(&info);
infoStream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n"
"<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" "
"\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">"
"<plist version=\"1.0\">\n"
"<dict>\n"
" <key>CFBundleExecutable</key>\n"
" <string>Run.command</string>\n" // The path to the executable
" <key>CFBundleIconFile</key>\n"
" <string>Icon.icns</string>\n"
" <key>CFBundleName</key>\n"
" <string>"
<< name
<< "</string>\n" // Name of the application
" <key>CFBundlePackageType</key>\n"
" <string>APPL</string>\n"
" <key>CFBundleShortVersionString</key>\n"
" <string>1.0</string>\n"
" <key>CFBundleVersion</key>\n"
" <string>1.0</string>\n"
"</dict>\n"
"</plist>";
return true;
#elif defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD)
if (!destination.endsWith(".desktop")) // in case of isFlatpak destination is already populated
destination += ".desktop";
QFile f(destination);
f.open(QIODevice::WriteOnly | QIODevice::Text);
QTextStream stream(&f);
QString argstring;
if (!args.empty())
argstring = " '" + args.join("' '") + "'";
stream << "[Desktop Entry]"
<< "\n";
stream << "Type=Application"
<< "\n";
stream << "Exec=\"" << target.toLocal8Bit() << "\"" << argstring.toLocal8Bit() << "\n";
stream << "Name=" << name.toLocal8Bit() << "\n";
if (!icon.isEmpty()) {
stream << "Icon=" << icon.toLocal8Bit() << "\n";
}
stream.flush();
f.close();
f.setPermissions(f.permissions() | QFileDevice::ExeOwner | QFileDevice::ExeGroup | QFileDevice::ExeOther);
return true;
#elif defined(Q_OS_WIN)
QFileInfo targetInfo(target);
if (!targetInfo.exists()) {
qWarning() << "Target file does not exist!";
return false;
}
target = targetInfo.absoluteFilePath();
if (target.length() >= MAX_PATH) {
qWarning() << "Target file path is too long!";
return false;
}
if (!icon.isEmpty() && icon.length() >= MAX_PATH) {
qWarning() << "Icon path is too long!";
return false;
}
destination += ".lnk";
if (destination.length() >= MAX_PATH) {
qWarning() << "Destination path is too long!";
return false;
}
QString argStr;
int argCount = args.count();
for (int i = 0; i < argCount; i++) {
if (args[i].contains(' ')) {
argStr.append('"').append(args[i]).append('"');
} else {
argStr.append(args[i]);
}
if (i < argCount - 1) {
argStr.append(" ");
}
}
if (argStr.length() >= MAX_PATH) {
qWarning() << "Arguments string is too long!";
return false;
}
HRESULT hres;
// ...yes, you need to initialize the entire COM stack just to make a shortcut
hres = CoInitialize(nullptr);
if (FAILED(hres)) {
qWarning() << "Failed to initialize COM!";
return false;
}
WCHAR wsz[MAX_PATH];
IShellLink* psl;
// create an IShellLink instance - this stores the shortcut's attributes
hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&psl);
if (SUCCEEDED(hres)) {
wmemset(wsz, 0, MAX_PATH);
target.toWCharArray(wsz);
psl->SetPath(wsz);
wmemset(wsz, 0, MAX_PATH);
argStr.toWCharArray(wsz);
psl->SetArguments(wsz);
wmemset(wsz, 0, MAX_PATH);
targetInfo.absolutePath().toWCharArray(wsz);
psl->SetWorkingDirectory(wsz); // "Starts in" attribute
if (!icon.isEmpty()) {
wmemset(wsz, 0, MAX_PATH);
icon.toWCharArray(wsz);
psl->SetIconLocation(wsz, 0);
}
// query an IPersistFile interface from our IShellLink instance
// this is the interface that will actually let us save the shortcut to disk!
IPersistFile* ppf;
hres = psl->QueryInterface(IID_IPersistFile, (LPVOID*)&ppf);
if (SUCCEEDED(hres)) {
wmemset(wsz, 0, MAX_PATH);
destination.toWCharArray(wsz);
hres = ppf->Save(wsz, TRUE);
if (FAILED(hres)) {
qWarning() << "IPresistFile->Save() failed";
qWarning() << "hres = " << hres;
}
ppf->Release();
} else {
qWarning() << "Failed to query IPersistFile interface from IShellLink instance";
qWarning() << "hres = " << hres;
}
psl->Release();
} else {
qWarning() << "Failed to create IShellLink instance";
qWarning() << "hres = " << hres;
}
// go away COM, nobody likes you
CoUninitialize();
return SUCCEEDED(hres);
#else
qWarning("Desktop Shortcuts not supported on your platform!");
return false;
#endif
}
bool overrideFolder(QString overwritten_path, QString override_path)
{
using copy_opts = fs::copy_options;
if (!FS::ensureFolderPathExists(overwritten_path))
return false;
std::error_code err;
fs::copy_options opt = copy_opts::recursive | copy_opts::overwrite_existing;
// FIXME: hello traveller! Apparently std::copy does NOT overwrite existing files on GNU libstdc++ on Windows?
fs::copy(StringUtils::toStdString(override_path), StringUtils::toStdString(overwritten_path), opt, err);
if (err) {
qCritical() << QString("Failed to apply override from %1 to %2").arg(override_path, overwritten_path);
qCritical() << "Reason:" << QString::fromStdString(err.message());
}
return err.value() == 0;
}
QString getFilesystemTypeName(FilesystemType type)
{
auto iter = s_filesystem_type_names.constFind(type);
if (iter != s_filesystem_type_names.constEnd()) {
return iter.value().constFirst();
}
return getFilesystemTypeName(FilesystemType::UNKNOWN);
}
FilesystemType getFilesystemTypeFuzzy(const QString& name)
{
for (auto iter = s_filesystem_type_names.constBegin(); iter != s_filesystem_type_names.constEnd(); ++iter) {
auto fs_names = iter.value();
for (auto fs_name : fs_names) {
if (name.toUpper().contains(fs_name.toUpper()))
return iter.key();
}
}
return FilesystemType::UNKNOWN;
}
FilesystemType getFilesystemType(const QString& name)
{
for (auto iter = s_filesystem_type_names.constBegin(); iter != s_filesystem_type_names.constEnd(); ++iter) {
auto fs_names = iter.value();
if (fs_names.contains(name.toUpper()))
return iter.key();
}
return FilesystemType::UNKNOWN;
}
/**
* @brief path to the near ancestor that exists
*
*/
QString nearestExistentAncestor(const QString& path)
{
if (QFileInfo::exists(path))
return path;
QDir dir(path);
if (!dir.makeAbsolute())
return {};
do {
dir.setPath(QDir::cleanPath(dir.filePath(QStringLiteral(".."))));
} while (!dir.exists() && !dir.isRoot());
return dir.exists() ? dir.path() : QString();
}
/**
* @brief colect information about the filesystem under a file
*
*/
FilesystemInfo statFS(const QString& path)
{
FilesystemInfo info;
QStorageInfo storage_info(nearestExistentAncestor(path));
info.fsTypeName = storage_info.fileSystemType();
info.fsType = getFilesystemTypeFuzzy(info.fsTypeName);
info.blockSize = storage_info.blockSize();
info.bytesAvailable = storage_info.bytesAvailable();
info.bytesFree = storage_info.bytesFree();
info.bytesTotal = storage_info.bytesTotal();
info.name = storage_info.name();
info.rootPath = storage_info.rootPath();
return info;
}
/**
* @brief if the Filesystem is reflink/clone capable
*
*/
bool canCloneOnFS(const QString& path)
{
FilesystemInfo info = statFS(path);
return canCloneOnFS(info);
}
bool canCloneOnFS(const FilesystemInfo& info)
{
return canCloneOnFS(info.fsType);
}
bool canCloneOnFS(FilesystemType type)
{
return s_clone_filesystems.contains(type);
}
/**
* @brief if the Filesystem is reflink/clone capable and both paths are on the same device
*
*/
bool canClone(const QString& src, const QString& dst)
{
auto srcVInfo = statFS(src);
auto dstVInfo = statFS(dst);
bool sameDevice = srcVInfo.rootPath == dstVInfo.rootPath;
return sameDevice && canCloneOnFS(srcVInfo) && canCloneOnFS(dstVInfo);
}
/**
* @brief reflink/clones a directory and it's contents from src to dest
* @param offset subdirectory form src to copy to dest
* @return if there was an error during the filecopy
*/
bool clone::operator()(const QString& offset, bool dryRun)
{
if (!canClone(m_src.absolutePath(), m_dst.absolutePath())) {
qWarning() << "Can not clone: not same device or not clone/reflink filesystem";
qDebug() << "Source path:" << m_src.absolutePath();
qDebug() << "Destination path:" << m_dst.absolutePath();
emit cloneFailed(m_src.absolutePath(), m_dst.absolutePath());
return false;
}
m_cloned = 0; // reset counter
m_failedClones.clear();
auto src = PathCombine(m_src.absolutePath(), offset);
auto dst = PathCombine(m_dst.absolutePath(), offset);
std::error_code err;
// Function that'll do the actual cloneing
auto cloneFile = [&](QString src_path, QString relative_dst_path) {
if (m_matcher && (m_matcher->matches(relative_dst_path) != m_whitelist))
return;
auto dst_path = PathCombine(dst, relative_dst_path);
if (!dryRun) {
ensureFilePathExists(dst_path);
clone_file(src_path, dst_path, err);
}
if (err) {
qDebug() << "Failed to clone files: error" << err.value() << "message" << QString::fromStdString(err.message());
qDebug() << "Source file:" << src_path;
qDebug() << "Destination file:" << dst_path;
m_failedClones.append(qMakePair(src_path, dst_path));
emit cloneFailed(src_path, dst_path);
return;
}
m_cloned++;
emit fileCloned(src_path, dst_path);
};
// We can't use copy_opts::recursive because we need to take into account the
// blacklisted paths, so we iterate over the source directory, and if there's no blacklist
// match, we copy the file.
QDir src_dir(src);
QDirIterator source_it(src, QDir::Filter::Files | QDir::Filter::Hidden, QDirIterator::Subdirectories);
while (source_it.hasNext()) {
auto src_path = source_it.next();
auto relative_path = src_dir.relativeFilePath(src_path);
cloneFile(src_path, relative_path);
}
// If the root src is not a directory, the previous iterator won't run.
if (!fs::is_directory(StringUtils::toStdString(src)))
cloneFile(src, "");
return err.value() == 0;
}
/**
* @brief clone/reflink file from src to dst
*
*/
bool clone_file(const QString& src, const QString& dst, std::error_code& ec)
{
auto src_path = StringUtils::toStdString(QDir::toNativeSeparators(QFileInfo(src).absoluteFilePath()));
auto dst_path = StringUtils::toStdString(QDir::toNativeSeparators(QFileInfo(dst).absoluteFilePath()));
FilesystemInfo srcinfo = statFS(src);
FilesystemInfo dstinfo = statFS(dst);
if ((srcinfo.rootPath != dstinfo.rootPath) || (srcinfo.fsType != dstinfo.fsType)) {
ec = std::make_error_code(std::errc::not_supported);
qWarning() << "reflink/clone must be to the same device and filesystem! src and dst root filesystems do not match.";
return false;
}
#if defined(Q_OS_WIN)
if (!win_ioctl_clone(src_path, dst_path, ec)) {
qDebug() << "failed win_ioctl_clone";
qWarning() << "clone/reflink not supported on windows outside of btrfs or ReFS!";
qWarning() << "check out https://github.com/maharmstone/btrfs for btrfs support!";
return false;
}
#elif defined(Q_OS_LINUX)
if (!linux_ficlone(src_path, dst_path, ec)) {
qDebug() << "failed linux_ficlone:";
return false;
}
#elif defined(Q_OS_MACOS)
if (!macos_bsd_clonefile(src_path, dst_path, ec)) {
qDebug() << "failed macos_bsd_clonefile:";
return false;
}
#else
qWarning() << "clone/reflink not supported! unknown OS";
ec = std::make_error_code(std::errc::not_supported);
return false;
#endif
return true;
}
#if defined(Q_OS_WIN)
static long RoundUpToPowerOf2(long originalValue, long roundingMultiplePowerOf2)
{
long mask = roundingMultiplePowerOf2 - 1;
return (originalValue + mask) & ~mask;
}
bool win_ioctl_clone(const std::wstring& src_path, const std::wstring& dst_path, std::error_code& ec)
{
/**
* This algorithm inspired from https://github.com/0xbadfca11/reflink
* LICENSE MIT
*
* Additional references
* https://learn.microsoft.com/en-us/windows/win32/api/winioctl/ni-winioctl-fsctl_duplicate_extents_to_file
* https://github.com/microsoft/CopyOnWrite/blob/main/lib/Windows/WindowsCopyOnWriteFilesystem.cs#L94
*/
HANDLE hSourceFile = CreateFileW(src_path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
if (hSourceFile == INVALID_HANDLE_VALUE) {
ec = std::error_code(GetLastError(), std::system_category());
qDebug() << "Failed to open source file" << src_path.c_str();
return false;
}
ULONG fs_flags;
if (!GetVolumeInformationByHandleW(hSourceFile, nullptr, 0, nullptr, nullptr, &fs_flags, nullptr, 0)) {
ec = std::error_code(GetLastError(), std::system_category());
qDebug() << "Failed to get Filesystem information for " << src_path.c_str();
CloseHandle(hSourceFile);
return false;
}
if (!(fs_flags & FILE_SUPPORTS_BLOCK_REFCOUNTING)) {
SetLastError(ERROR_NOT_CAPABLE);
ec = std::error_code(GetLastError(), std::system_category());
qWarning() << "Filesystem at " << src_path.c_str() << " does not support reflink";
CloseHandle(hSourceFile);
return false;
}
FILE_END_OF_FILE_INFO sourceFileLength;
if (!GetFileSizeEx(hSourceFile, &sourceFileLength.EndOfFile)) {
ec = std::error_code(GetLastError(), std::system_category());
qDebug() << "Failed to size of source file" << src_path.c_str();
CloseHandle(hSourceFile);
return false;
}
FILE_BASIC_INFO sourceFileBasicInfo;
if (!GetFileInformationByHandleEx(hSourceFile, FileBasicInfo, &sourceFileBasicInfo, sizeof(sourceFileBasicInfo))) {
ec = std::error_code(GetLastError(), std::system_category());
qDebug() << "Failed to source file info" << src_path.c_str();
CloseHandle(hSourceFile);
return false;
}
ULONG junk;
FSCTL_GET_INTEGRITY_INFORMATION_BUFFER sourceFileIntegrity;
if (!DeviceIoControl(hSourceFile, FSCTL_GET_INTEGRITY_INFORMATION, nullptr, 0, &sourceFileIntegrity, sizeof(sourceFileIntegrity), &junk,
nullptr)) {
ec = std::error_code(GetLastError(), std::system_category());
qDebug() << "Failed to source file integrity info" << src_path.c_str();
CloseHandle(hSourceFile);
return false;
}
HANDLE hDestFile = CreateFileW(dst_path.c_str(), GENERIC_READ | GENERIC_WRITE | DELETE, 0, nullptr, CREATE_NEW, 0, hSourceFile);
if (hDestFile == INVALID_HANDLE_VALUE) {
ec = std::error_code(GetLastError(), std::system_category());
qDebug() << "Failed to open dest file" << dst_path.c_str();
CloseHandle(hSourceFile);
return false;
}
FILE_DISPOSITION_INFO destFileDispose = { TRUE };
if (!SetFileInformationByHandle(hDestFile, FileDispositionInfo, &destFileDispose, sizeof(destFileDispose))) {
ec = std::error_code(GetLastError(), std::system_category());
qDebug() << "Failed to set dest file info" << dst_path.c_str();
CloseHandle(hSourceFile);
CloseHandle(hDestFile);
return false;
}
if (!DeviceIoControl(hDestFile, FSCTL_SET_SPARSE, nullptr, 0, nullptr, 0, &junk, nullptr)) {
ec = std::error_code(GetLastError(), std::system_category());
qDebug() << "Failed to set dest sparseness" << dst_path.c_str();
CloseHandle(hSourceFile);
CloseHandle(hDestFile);
return false;
}
FSCTL_SET_INTEGRITY_INFORMATION_BUFFER setDestFileintegrity = { sourceFileIntegrity.ChecksumAlgorithm, sourceFileIntegrity.Reserved,
sourceFileIntegrity.Flags };
if (!DeviceIoControl(hDestFile, FSCTL_SET_INTEGRITY_INFORMATION, &setDestFileintegrity, sizeof(setDestFileintegrity), nullptr, 0,
nullptr, nullptr)) {
ec = std::error_code(GetLastError(), std::system_category());
qDebug() << "Failed to set dest file integrity info" << dst_path.c_str();
CloseHandle(hSourceFile);
CloseHandle(hDestFile);
return false;
}
if (!SetFileInformationByHandle(hDestFile, FileEndOfFileInfo, &sourceFileLength, sizeof(sourceFileLength))) {
ec = std::error_code(GetLastError(), std::system_category());
qDebug() << "Failed to set dest file size" << dst_path.c_str();
CloseHandle(hSourceFile);
CloseHandle(hDestFile);
return false;
}
const LONG64 splitThreshold = (1LL << 32) - sourceFileIntegrity.ClusterSizeInBytes;
DUPLICATE_EXTENTS_DATA dupExtent;
dupExtent.FileHandle = hSourceFile;
for (LONG64 offset = 0, remain = RoundUpToPowerOf2(sourceFileLength.EndOfFile.QuadPart, sourceFileIntegrity.ClusterSizeInBytes);
remain > 0; offset += splitThreshold, remain -= splitThreshold) {
dupExtent.SourceFileOffset.QuadPart = dupExtent.TargetFileOffset.QuadPart = offset;
dupExtent.ByteCount.QuadPart = std::min(splitThreshold, remain);
if (!DeviceIoControl(hDestFile, FSCTL_DUPLICATE_EXTENTS_TO_FILE, &dupExtent, sizeof(dupExtent), nullptr, 0, &junk, nullptr)) {
DWORD err = GetLastError();
QString additionalMessage;
if (err == ERROR_BLOCK_TOO_MANY_REFERENCES) {
static const int MaxClonesPerFile = 8175;
additionalMessage =
QString(
" This is ERROR_BLOCK_TOO_MANY_REFERENCES and may mean you have surpassed the maximum "
"allowed %1 references for a single file. "
"See "
"https://docs.microsoft.com/en-us/windows-server/storage/refs/block-cloning#functionality-restrictions-and-remarks")
.arg(MaxClonesPerFile);
}
ec = std::error_code(err, std::system_category());
qDebug() << "Failed copy-on-write cloning of" << src_path.c_str() << "to" << dst_path.c_str() << "with error" << err
<< additionalMessage;
CloseHandle(hSourceFile);
CloseHandle(hDestFile);
return false;
}
}
if (!(sourceFileBasicInfo.FileAttributes & FILE_ATTRIBUTE_SPARSE_FILE)) {
FILE_SET_SPARSE_BUFFER setDestSparse = { FALSE };
if (!DeviceIoControl(hDestFile, FSCTL_SET_SPARSE, &setDestSparse, sizeof(setDestSparse), nullptr, 0, &junk, nullptr)) {
qDebug() << "Failed to set dest file sparseness" << dst_path.c_str();
CloseHandle(hSourceFile);
CloseHandle(hDestFile);
return false;
}
}
sourceFileBasicInfo.CreationTime.QuadPart = 0;
if (!SetFileInformationByHandle(hDestFile, FileBasicInfo, &sourceFileBasicInfo, sizeof(sourceFileBasicInfo))) {
qDebug() << "Failed to set dest file creation time" << dst_path.c_str();
CloseHandle(hSourceFile);
CloseHandle(hDestFile);
return false;
}
if (!FlushFileBuffers(hDestFile)) {
qDebug() << "Failed to flush dest file buffer" << dst_path.c_str();
CloseHandle(hSourceFile);
CloseHandle(hDestFile);
return false;
}
destFileDispose = { FALSE };
bool result = !!SetFileInformationByHandle(hDestFile, FileDispositionInfo, &destFileDispose, sizeof(destFileDispose));
CloseHandle(hSourceFile);
CloseHandle(hDestFile);
return result;
}
#elif defined(Q_OS_LINUX)
bool linux_ficlone(const std::string& src_path, const std::string& dst_path, std::error_code& ec)
{
// https://man7.org/linux/man-pages/man2/ioctl_ficlone.2.html
int src_fd = open(src_path.c_str(), O_RDONLY);
if (src_fd == -1) {
qDebug() << "Failed to open file:" << src_path.c_str();
qDebug() << "Error:" << strerror(errno);
ec = std::make_error_code(static_cast<std::errc>(errno));
return false;
}
int dst_fd = open(dst_path.c_str(), O_CREAT | O_WRONLY | O_TRUNC, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
if (dst_fd == -1) {
qDebug() << "Failed to open file:" << dst_path.c_str();
qDebug() << "Error:" << strerror(errno);
ec = std::make_error_code(static_cast<std::errc>(errno));
close(src_fd);
return false;
}
// attempt to clone
if (ioctl(dst_fd, FICLONE, src_fd) == -1) {
qDebug() << "Failed to clone file:" << src_path.c_str() << "to" << dst_path.c_str();
qDebug() << "Error:" << strerror(errno);
ec = std::make_error_code(static_cast<std::errc>(errno));
close(src_fd);
close(dst_fd);
return false;
}
if (close(src_fd)) {
qDebug() << "Failed to close file:" << src_path.c_str();
qDebug() << "Error:" << strerror(errno);
}
if (close(dst_fd)) {
qDebug() << "Failed to close file:" << dst_path.c_str();
qDebug() << "Error:" << strerror(errno);
}
return true;
}
#elif defined(Q_OS_MACOS)
bool macos_bsd_clonefile(const std::string& src_path, const std::string& dst_path, std::error_code& ec)
{
// clonefile(const char * src, const char * dst, int flags);
// https://www.manpagez.com/man/2/clonefile/
qDebug() << "attempting file clone via clonefile" << src_path.c_str() << "to" << dst_path.c_str();
if (clonefile(src_path.c_str(), dst_path.c_str(), 0) == -1) {
qDebug() << "Failed to clone file:" << src_path.c_str() << "to" << dst_path.c_str();
qDebug() << "Error:" << strerror(errno);
ec = std::make_error_code(static_cast<std::errc>(errno));
return false;
}
return true;
}
#endif
/**
* @brief if the Filesystem is symlink capable
*
*/
bool canLinkOnFS(const QString& path)
{
FilesystemInfo info = statFS(path);
return canLinkOnFS(info);
}
bool canLinkOnFS(const FilesystemInfo& info)
{
return canLinkOnFS(info.fsType);
}
bool canLinkOnFS(FilesystemType type)
{
return !s_non_link_filesystems.contains(type);
}
/**
* @brief if the Filesystem is symlink capable on both ends
*
*/
bool canLink(const QString& src, const QString& dst)
{
return canLinkOnFS(src) && canLinkOnFS(dst);
}
uintmax_t hardLinkCount(const QString& path)
{
std::error_code err;
int count = fs::hard_link_count(StringUtils::toStdString(path), err);
if (err) {
qWarning() << "Failed to count hard links for" << path << ":" << QString::fromStdString(err.message());
count = 0;
}
return count;
}
} // namespace FS
|