-
Notifications
You must be signed in to change notification settings - Fork 947
Expand file tree
/
Copy pathdiscovery.cpp
More file actions
2530 lines (2243 loc) · 124 KB
/
discovery.cpp
File metadata and controls
2530 lines (2243 loc) · 124 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* SPDX-FileCopyrightText: 2021 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2018 ownCloud GmbH
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "account.h"
#include "discovery.h"
#include "common/filesystembase.h"
#include "common/syncjournaldb.h"
#include "filesystem.h"
#include "syncfileitem.h"
#include "progressdispatcher.h"
#include <QDebug>
#include <algorithm>
#include <QEventLoop>
#include <QDir>
#include <set>
#include <QTextCodec>
#include "vio/csync_vio_local.h"
#include <QFileInfo>
#include <QFile>
#include <QThreadPool>
#include <common/checksums.h>
#include <common/constants.h>
#include "csync_exclude.h"
#include "csync.h"
namespace
{
constexpr const char *editorNamesForDelayedUpload[] = {"PowerPDF"};
constexpr const char *fileExtensionsToCheckIfOpenForSigning[] = {".pdf"};
constexpr auto delayIntervalForSyncRetryForOpenedForSigningFilesSeconds = 60;
constexpr auto delayIntervalForSyncRetryForFilesExceedQuotaSeconds = 60;
}
namespace OCC {
Q_LOGGING_CATEGORY(lcDisco, "nextcloud.sync.discovery", QtInfoMsg)
ProcessDirectoryJob::ProcessDirectoryJob(DiscoveryPhase *data, PinState basePinState, qint64 lastSyncTimestamp, QObject *parent)
: QObject(parent)
, _lastSyncTimestamp(lastSyncTimestamp)
, _discoveryData(data)
{
qCDebug(lcDisco) << data;
computePinState(basePinState);
}
ProcessDirectoryJob::ProcessDirectoryJob(const PathTuple &path, const SyncFileItemPtr &dirItem, QueryMode queryLocal, QueryMode queryServer, qint64 lastSyncTimestamp, ProcessDirectoryJob *parent)
: QObject(parent)
, _dirItem(dirItem)
, _dirParentItem(parent->_dirItem)
, _lastSyncTimestamp(lastSyncTimestamp)
, _queryServer(queryServer)
, _queryLocal(queryLocal)
, _discoveryData(parent->_discoveryData)
, _currentFolder(path)
{
qCDebug(lcDisco) << "PREPARING" << _currentFolder._server << _queryServer << _currentFolder._local << _queryLocal;
computePinState(parent->_pinState);
}
ProcessDirectoryJob::ProcessDirectoryJob(DiscoveryPhase *data, PinState basePinState, const PathTuple &path, const SyncFileItemPtr &dirItem, const SyncFileItemPtr &parentDirItem, QueryMode queryLocal, qint64 lastSyncTimestamp, QObject *parent)
: QObject(parent)
, _dirItem(dirItem)
, _dirParentItem(parentDirItem)
, _lastSyncTimestamp(lastSyncTimestamp)
, _queryLocal(queryLocal)
, _discoveryData(data)
, _currentFolder(path)
{
qCDebug(lcDisco) << "PREPARING" << _currentFolder._server << _queryServer << _currentFolder._local << _queryLocal;
computePinState(basePinState);
}
void ProcessDirectoryJob::start()
{
qCInfo(lcDisco) << "STARTING" << _currentFolder._server << _queryServer << _currentFolder._local << _queryLocal;
_discoveryData->_noCaseConflictRecordsInDb = _discoveryData->_statedb->caseClashConflictRecordPaths().isEmpty();
if (_queryServer == NormalQuery) {
_serverJob = startAsyncServerQuery();
} else {
_serverQueryDone = true;
}
// Check whether a normal local query is even necessary
if (_queryLocal == NormalQuery) {
if (!_discoveryData->_shouldDiscoverLocaly(_currentFolder._local)
&& (_currentFolder._local == _currentFolder._original || !_discoveryData->_shouldDiscoverLocaly(_currentFolder._original))
&& !_discoveryData->isInSelectiveSyncBlackList(_currentFolder._original)) {
_queryLocal = ParentNotChanged;
qCDebug(lcDisco) << "adjusted discovery policy" << _currentFolder._server << _queryServer << _currentFolder._local << _queryLocal;
}
}
if (_queryLocal == NormalQuery) {
startAsyncLocalQuery();
} else {
_localQueryDone = true;
}
if (_localQueryDone && _serverQueryDone) {
process();
}
}
void ProcessDirectoryJob::process()
{
ASSERT(_localQueryDone && _serverQueryDone);
// Build lookup tables for local, remote and db entries.
// For suffix-virtual files, the key will normally be the base file name
// without the suffix.
// However, if foo and foo.owncloud exists locally, there'll be "foo"
// with local, db, server entries and "foo.owncloud" with only a local
// entry.
std::map<QString, Entries> entries;
for (auto &e : _serverNormalQueryEntries) {
entries[e.name].serverEntry = std::move(e);
}
_serverNormalQueryEntries.clear();
// fetch all the name from the DB
auto pathU8 = _currentFolder._original.toUtf8();
if (!_discoveryData->_statedb->listFilesInPath(pathU8, [&](const SyncJournalFileRecord &rec) {
auto name = pathU8.isEmpty() ? rec._path : QString::fromUtf8(rec._path.constData() + (pathU8.size() + 1));
if (rec.isVirtualFile() && isVfsWithSuffix())
chopVirtualFileSuffix(name);
auto &dbEntry = entries[name].dbEntry;
dbEntry = rec;
setupDbPinStateActions(dbEntry);
})) {
dbError();
return;
}
for (auto &e : _localNormalQueryEntries) {
entries[e.name].localEntry = e;
}
if (isVfsWithSuffix()) {
// For vfs-suffix the local data for suffixed files should usually be associated
// with the non-suffixed name. Unless both names exist locally or there's
// other data about the suffixed file.
// This is done in a second path in order to not depend on the order of
// _localNormalQueryEntries.
for (auto &e : _localNormalQueryEntries) {
if (!e.isVirtualFile)
continue;
auto &suffixedEntry = entries[e.name];
bool hasOtherData = suffixedEntry.serverEntry.isValid() || suffixedEntry.dbEntry.isValid();
auto nonvirtualName = e.name;
chopVirtualFileSuffix(nonvirtualName);
auto &nonvirtualEntry = entries[nonvirtualName];
// If the non-suffixed entry has no data, move it
if (!nonvirtualEntry.localEntry.isValid()) {
std::swap(nonvirtualEntry.localEntry, suffixedEntry.localEntry);
if (!hasOtherData)
entries.erase(e.name);
} else if (!hasOtherData) {
// Normally a lone local suffixed file would be processed under the
// unsuffixed name. In this special case it's under the suffixed name.
// To avoid lots of special casing, make sure PathTuple::addName()
// will be called with the unsuffixed name anyway.
suffixedEntry.nameOverride = nonvirtualName;
}
}
}
_localNormalQueryEntries.clear();
//
// Iterate over entries and process them
//
for (auto &f : entries) {
auto &e = f.second;
PathTuple path;
path = _currentFolder.addName(e.nameOverride.isEmpty() ? f.first : e.nameOverride);
if (!_discoveryData->_listExclusiveFiles.isEmpty() && !_discoveryData->_listExclusiveFiles.contains(path._server)) {
qCInfo(lcDisco) << "Skipping a file:" << path._server << "as it is not listed in the _listExclusiveFiles";
continue;
}
if (isVfsWithSuffix()) {
// Without suffix vfs the paths would be good. But since the dbEntry and localEntry
// can have different names from f.first when suffix vfs is on, make sure the
// corresponding _original and _local paths are right.
if (e.dbEntry.isValid()) {
path._original = e.dbEntry._path;
} else if (e.localEntry.isVirtualFile) {
// We don't have a db entry - but it should be at this path
path._original = PathTuple::pathAppend(_currentFolder._original, e.localEntry.name);
}
if (e.localEntry.isValid()) {
path._local = PathTuple::pathAppend(_currentFolder._local, e.localEntry.name);
} else if (e.dbEntry.isVirtualFile()) {
// We don't have a local entry - but it should be at this path
addVirtualFileSuffix(path._local);
}
}
// On the server the path is mangled in case of E2EE
if (!e.serverEntry.e2eMangledName.isEmpty()) {
Q_ASSERT(_discoveryData->_remoteFolder.startsWith('/'));
Q_ASSERT(_discoveryData->_remoteFolder.endsWith('/'));
const auto rootPath = _discoveryData->_remoteFolder.mid(1);
Q_ASSERT(e.serverEntry.e2eMangledName.startsWith(rootPath));
path._server = e.serverEntry.e2eMangledName.mid(rootPath.length());
}
// If the filename starts with a . we consider it a hidden file
// For windows, the hidden state is also discovered within the vio
// local stat function.
// Recall file shall not be ignored (#4420)
const auto isHidden = e.localEntry.isHidden || (!f.first.isEmpty() && f.first[0] == '.' && f.first != QLatin1String(".sys.admin#recall#"));
const auto isEncryptedFolderButE2eIsNotSetup = e.serverEntry.isValid() && e.serverEntry.isE2eEncrypted() &&
_discoveryData->_account->e2e() && !_discoveryData->_account->e2e()->isInitialized();
if (isEncryptedFolderButE2eIsNotSetup) {
checkAndUpdateSelectiveSyncListsForE2eeFolders(path._server + "/");
}
const auto isBlacklisted = _queryServer == InBlackList || _discoveryData->isInSelectiveSyncBlackList(path._original) || isEncryptedFolderButE2eIsNotSetup;
const auto willBeExcluded = handleExcluded(path._target, e, entries, isHidden, isBlacklisted);
if (willBeExcluded) {
continue;
}
if (isBlacklisted) {
processBlacklisted(path, e.localEntry, e.dbEntry);
continue;
}
// HACK: Sometimes the serverEntry.etag does not correctly have its quotation marks amputated in the string.
// We are once again making sure they are chopped off here, but we should really find the root cause for why
// exactly they are not being lobbed off at any of the prior points of processing.
e.serverEntry.etag = Utility::normalizeEtag(e.serverEntry.etag);
processFile(std::move(path), e.localEntry, e.serverEntry, e.dbEntry);
}
_discoveryData->_listExclusiveFiles.clear();
QTimer::singleShot(0, _discoveryData, &DiscoveryPhase::scheduleMoreJobs);
}
bool ProcessDirectoryJob::handleExcluded(const QString &path, const Entries &entries, const std::map<QString, Entries> &allEntries, const bool isHidden, const bool isBlacklisted)
{
const auto isDirectory = entries.localEntry.isDirectory || entries.serverEntry.isDirectory;
auto excluded = _discoveryData->_excludes->traversalPatternMatch(path, isDirectory ? ItemTypeDirectory : ItemTypeFile);
const auto fileName = path.mid(path.lastIndexOf('/') + 1);
const auto isLocal = entries.localEntry.isValid();
if (excluded == CSYNC_NOT_EXCLUDED) {
const auto endsWithSpace = fileName.endsWith(QLatin1Char(' '));
if (endsWithSpace) {
excluded = CSYNC_FILE_EXCLUDE_TRAILING_SPACE;
}
}
// we don't need to trigger a warning if trailing/leading space file is already on the server or has already been synced down
// only if the OS supports trailing/leading spaces
const auto wasSyncedAlready = entries.serverEntry.isValid() || entries.dbEntry.isValid();
const auto hasLeadingOrTrailingSpaces = excluded == CSYNC_FILE_EXCLUDE_LEADING_SPACE
|| excluded == CSYNC_FILE_EXCLUDE_TRAILING_SPACE
|| excluded == CSYNC_FILE_EXCLUDE_LEADING_AND_TRAILING_SPACE;
const auto leadingAndTrailingSpacesFilesAllowed = !_discoveryData->_shouldEnforceWindowsFileNameCompatibility || _discoveryData->_leadingAndTrailingSpacesFilesAllowed.contains(_discoveryData->_localDir + path);
#if defined Q_OS_WINDOWS
if (hasLeadingOrTrailingSpaces && leadingAndTrailingSpacesFilesAllowed) {
#else
if (hasLeadingOrTrailingSpaces && (wasSyncedAlready || leadingAndTrailingSpacesFilesAllowed)) {
#endif
excluded = CSYNC_NOT_EXCLUDED;
}
// FIXME: move to ExcludedFiles 's regexp ?
bool isInvalidPattern = false;
if (excluded == CSYNC_NOT_EXCLUDED
&& !wasSyncedAlready
&& !_discoveryData->_invalidFilenameRx.pattern().isEmpty()
&& path.contains(_discoveryData->_invalidFilenameRx)) {
excluded = CSYNC_FILE_EXCLUDE_INVALID_CHAR;
isInvalidPattern = true;
}
if (excluded == CSYNC_NOT_EXCLUDED
&& !entries.dbEntry.isValid()
&& _discoveryData->_ignoreHiddenFiles && isHidden) {
excluded = CSYNC_FILE_EXCLUDE_HIDDEN;
}
const auto &localName = entries.localEntry.name;
const auto splitName = localName.split('.');
const auto &baseName = splitName.first();
const auto extension = splitName.size() > 1 ? splitName.last() : QString();
const auto accountCaps = _discoveryData->_account->capabilities();
const auto forbiddenFilenames = accountCaps.forbiddenFilenames();
const auto forbiddenBasenames = accountCaps.forbiddenFilenameBasenames();
const auto forbiddenExtensions = accountCaps.forbiddenFilenameExtensions();
const auto forbiddenChars = accountCaps.forbiddenFilenameCharacters();
const auto hasForbiddenFilename = forbiddenFilenames.contains(localName);
const auto hasForbiddenBasename = forbiddenBasenames.contains(baseName);
const auto hasForbiddenExtension = forbiddenExtensions.contains(extension);
auto forbiddenCharMatch = QString{};
const auto containsForbiddenCharacters =
std::any_of(forbiddenChars.cbegin(),
forbiddenChars.cend(),
[&localName, &forbiddenCharMatch](const QString &charPattern) {
if (localName.contains(charPattern)) {
forbiddenCharMatch = charPattern;
return true;
}
return false;
});
if (excluded == CSYNC_NOT_EXCLUDED && !localName.isEmpty()
&& !wasSyncedAlready
&&(_discoveryData->_serverBlacklistedFiles.contains(localName)
|| hasForbiddenFilename
|| hasForbiddenBasename
|| hasForbiddenExtension
|| containsForbiddenCharacters)) {
excluded = CSYNC_FILE_EXCLUDE_SERVER_BLACKLISTED;
isInvalidPattern = true;
}
auto localCodec = QTextCodec::codecForLocale();
if (!OCC::Utility::isWindows() && localCodec->mibEnum() != 106) {
// If the locale codec is not UTF-8, we must check that the filename from the server can
// be encoded in the local file system.
// (Note: on windows, the FS is always UTF-16, so we don't need to check) //
// We cannot use QTextCodec::canEncode() since that can incorrectly return true, see
// https://bugreports.qt.io/browse/QTBUG-6925.
QTextEncoder encoder(localCodec, QTextCodec::ConvertInvalidToNull);
if (encoder.fromUnicode(path).contains('\0')) {
qCWarning(lcDisco) << "Cannot encode " << path << " to local encoding " << localCodec->name();
excluded = CSYNC_FILE_EXCLUDE_CANNOT_ENCODE;
}
}
if (excluded == CSYNC_NOT_EXCLUDED && !entries.localEntry.isSymLink) {
return false;
} else if (excluded == CSYNC_FILE_SILENTLY_EXCLUDED || excluded == CSYNC_FILE_EXCLUDE_AND_REMOVE) {
emit _discoveryData->silentlyExcluded(path);
return true;
}
auto item = SyncFileItemPtr::create();
item->_file = path;
item->_originalFile = path;
item->_instruction = CSYNC_INSTRUCTION_IGNORE;
if (excluded == CSYNC_FILE_EXCLUDE_CASE_CLASH_CONFLICT && canRemoveCaseClashConflictedCopy(path, allEntries)) {
excluded = CSYNC_NOT_EXCLUDED;
item->_instruction = CSYNC_INSTRUCTION_REMOVE;
item->_direction = SyncFileItem::Down;
emit _discoveryData->itemDiscovered(item);
return true;
}
if (entries.localEntry.isSymLink) {
/* Symbolic links are ignored. */
item->_errorString = tr("Symbolic links are not supported in syncing.");
} else {
switch (excluded) {
case CSYNC_NOT_EXCLUDED:
case CSYNC_FILE_SILENTLY_EXCLUDED:
case CSYNC_FILE_EXCLUDE_AND_REMOVE:
qCFatal(lcDisco) << "These were handled earlier";
break;
case CSYNC_FILE_EXCLUDE_LIST:
item->_errorString = tr("File is listed on the ignore list.");
break;
case CSYNC_FILE_EXCLUDE_INVALID_CHAR:
if (item->_file.endsWith('.')) {
item->_errorString = tr("File names ending with a period are not supported on this file system.");
} else {
char invalid = '\0';
constexpr QByteArrayView invalidChars("\\:?*\"<>|");
for (const auto x : invalidChars) {
if (item->_file.contains(x)) {
invalid = x;
break;
}
}
if (invalid) {
item->_errorString = isDirectory
? tr("Folder names containing the character \"%1\" are not supported on this file system.", "%1: the invalid character").arg(QChar(invalid))
: tr("File names containing the character \"%1\" are not supported on this file system.", "%1: the invalid character").arg(QChar(invalid));
} else if (isInvalidPattern) {
item->_errorString = isDirectory
? tr("Folder name contains at least one invalid character")
: tr("File name contains at least one invalid character");
} else {
item->_errorString = isDirectory
? tr("Folder name is a reserved name on this file system.")
: tr("File name is a reserved name on this file system.");
}
}
item->_status = SyncFileItem::FileNameInvalid;
break;
case CSYNC_FILE_EXCLUDE_TRAILING_SPACE:
item->_errorString = tr("Filename contains trailing spaces.");
item->_status = SyncFileItem::FileNameInvalid;
if (isLocal && !maybeRenameForWindowsCompatibility(_discoveryData->_localDir + item->_file, excluded)) {
item->_errorString += QStringLiteral(" %1").arg(tr("Cannot be renamed or uploaded."));
}
break;
case CSYNC_FILE_EXCLUDE_LEADING_SPACE:
item->_errorString = tr("Filename contains leading spaces.");
item->_status = SyncFileItem::FileNameInvalid;
if (isLocal && !maybeRenameForWindowsCompatibility(_discoveryData->_localDir + item->_file, excluded)) {
item->_errorString += QStringLiteral(" %1").arg(tr("Cannot be renamed or uploaded."));
}
break;
case CSYNC_FILE_EXCLUDE_LEADING_AND_TRAILING_SPACE:
item->_errorString = tr("Filename contains leading and trailing spaces.");
item->_status = SyncFileItem::FileNameInvalid;
if (isLocal && !maybeRenameForWindowsCompatibility(_discoveryData->_localDir + item->_file, excluded)) {
item->_errorString += QStringLiteral(" %1").arg(tr("Cannot be renamed or uploaded."));
}
break;
case CSYNC_FILE_EXCLUDE_LONG_FILENAME:
item->_errorString = tr("Filename is too long.");
item->_status = SyncFileItem::FileNameInvalid;
break;
case CSYNC_FILE_EXCLUDE_HIDDEN:
item->_errorString = tr("File/Folder is ignored because it's hidden.");
break;
case CSYNC_FILE_EXCLUDE_STAT_FAILED:
item->_errorString = tr("Stat failed.");
break;
case CSYNC_FILE_EXCLUDE_CONFLICT:
item->_errorString = tr("Conflict: Server version downloaded, local copy renamed and not uploaded.");
item->_status = SyncFileItem::Conflict;
break;
case CSYNC_FILE_EXCLUDE_CASE_CLASH_CONFLICT:
item->_errorString = tr("Case Clash Conflict: Server file downloaded and renamed to avoid clash.");
item->_status = SyncFileItem::FileNameClash;
break;
case CSYNC_FILE_EXCLUDE_CANNOT_ENCODE:
item->_errorString = tr("The filename cannot be encoded on your file system.");
break;
case CSYNC_FILE_EXCLUDE_SERVER_BLACKLISTED:
const auto errorString = tr("The filename is blacklisted on the server.");
QString reasonString;
if (hasForbiddenFilename) {
reasonString = tr("Reason: the entire filename is forbidden.");
}
if (hasForbiddenBasename) {
reasonString = tr("Reason: the filename has a forbidden base name (filename start).");
}
if (hasForbiddenExtension) {
reasonString = tr("Reason: the file has a forbidden extension (.%1).").arg(extension);
}
if (containsForbiddenCharacters) {
reasonString = tr("Reason: the filename contains a forbidden character (%1).").arg(forbiddenCharMatch);
}
item->_errorString = reasonString.isEmpty() ? errorString : QStringLiteral("%1 %2").arg(errorString, reasonString);
item->_status = SyncFileItem::FileNameInvalidOnServer;
if (isLocal && !maybeRenameForWindowsCompatibility(_discoveryData->_localDir + item->_file, excluded)) {
item->_errorString += QStringLiteral(" %1").arg(tr("Cannot be renamed or uploaded."));
}
break;
}
}
if (_dirItem) {
_dirItem->_isAnyInvalidCharChild = _dirItem->_isAnyInvalidCharChild || item->_status == SyncFileItem::FileNameInvalid;
_dirItem->_isAnyCaseClashChild = _dirItem->_isAnyCaseClashChild || item->_status == SyncFileItem::FileNameClash;
}
_childIgnored = true;
if (isBlacklisted) {
emit _discoveryData->silentlyExcluded(path);
} else {
emit _discoveryData->itemDiscovered(item);
}
return true;
}
bool ProcessDirectoryJob::canRemoveCaseClashConflictedCopy(const QString &path, const std::map<QString, Entries> &allEntries)
{
const auto conflictRecord = _discoveryData->_statedb->caseConflictRecordByPath(path.toUtf8());
const auto originalBaseFileName = QFileInfo(QString(_discoveryData->_localDir + "/" + conflictRecord.initialBasePath)).fileName();
if (allEntries.find(originalBaseFileName) == allEntries.end()) {
// original entry is no longer on the server, remove conflicted copy
qCDebug(lcDisco) << "original entry:" << originalBaseFileName << "is no longer on the server, remove conflicted copy:" << path;
return true;
}
auto numMatchingEntries = 0;
for (auto it = allEntries.cbegin(); it != allEntries.cend(); ++it) {
if (it->first.compare(originalBaseFileName, Qt::CaseInsensitive) == 0 && it->second.serverEntry.isValid()) {
// only case-insensitive matching entries that are present on the server
++numMatchingEntries;
}
if (numMatchingEntries >= 2) {
break;
}
}
if (numMatchingEntries < 2) {
// original entry is present on the server but there is no case-clash conflict anymore, remove conflicted copy (only 1 matching file found during case-insensitive search)
qCDebug(lcDisco) << "original entry:" << originalBaseFileName << "is present on the server, but there is no case-clas conflict anymore, remove conflicted copy:" << path;
_discoveryData->_anotherSyncNeeded = true;
return true;
}
return false;
}
void ProcessDirectoryJob::checkAndUpdateSelectiveSyncListsForE2eeFolders(const QString &path)
{
bool ok = false;
const auto pathWithTrailingSlash = Utility::trailingSlashPath(path);
const auto blackListList = _discoveryData->_statedb->getSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, &ok);
auto blackListSet = QSet<QString>{blackListList.begin(), blackListList.end()};
blackListSet.insert(pathWithTrailingSlash);
auto blackList = blackListSet.values();
blackList.sort();
_discoveryData->_statedb->setSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, blackList);
const auto toRemoveFromBlacklistList = _discoveryData->_statedb->getSelectiveSyncList(SyncJournalDb::SelectiveSyncE2eFoldersToRemoveFromBlacklist, &ok);
auto toRemoveFromBlacklistSet = QSet<QString>{toRemoveFromBlacklistList.begin(), toRemoveFromBlacklistList.end()};
toRemoveFromBlacklistSet.insert(pathWithTrailingSlash);
// record it into a separate list to automatically remove from blacklist once the e2EE gets set up
auto toRemoveFromBlacklist = toRemoveFromBlacklistSet.values();
toRemoveFromBlacklist.sort();
_discoveryData->_statedb->setSelectiveSyncList(SyncJournalDb::SelectiveSyncE2eFoldersToRemoveFromBlacklist, toRemoveFromBlacklist);
}
void ProcessDirectoryJob::processFile(PathTuple path,
const LocalInfo &localEntry, const RemoteInfo &serverEntry,
const SyncJournalFileRecord &dbEntry)
{
const auto hasServer = serverEntry.isValid() ? "true" : _queryServer == ParentNotChanged ? "db" : "false";
const auto hasLocal = localEntry.isValid() ? "true" : _queryLocal == ParentNotChanged ? "db" : "false";
const auto serverFileIsLocked = (serverEntry.isValid() ? (serverEntry.locked == SyncFileItem::LockStatus::LockedItem ? "locked" : "not locked") : "");
const auto localFileIsLocked = dbEntry._lockstate._locked ? "locked" : "not locked";
const auto serverFileLockType = serverEntry.isValid() ? QString::number(static_cast<int>(serverEntry.lockOwnerType)) : QString{};
const auto localFileLockType = dbEntry._lockstate._locked ? QString::number(static_cast<int>(dbEntry._lockstate._lockOwnerType)) : QString{};
QString processingLog;
QDebug deleteLogger{&processingLog};
deleteLogger.nospace() << "Processing " << path._original
<< " | (db/local/remote)"
<< " | valid: " << dbEntry.isValid() << "/" << hasLocal << "/" << hasServer
<< " | mtime: " << dbEntry._modtime << "/" << localEntry.modtime << "/" << serverEntry.modtime
<< " | size: " << dbEntry._fileSize << "/" << localEntry.size << "/" << serverEntry.size
<< " | etag: " << dbEntry._etag << "//" << serverEntry.etag
<< " | checksum: " << dbEntry._checksumHeader << "//" << serverEntry.checksumHeader
<< " | perm: " << dbEntry._remotePerm << "//" << serverEntry.remotePerm
<< " | fileid: " << dbEntry._fileId << "//" << serverEntry.fileId
<< " | inode: " << dbEntry._inode << "/" << localEntry.inode << "/"
<< " | type: " << dbEntry._type << "/" << localEntry.type << "/" << (serverEntry.isDirectory ? ItemTypeDirectory : ItemTypeFile)
<< " | e2ee: " << dbEntry.isE2eEncrypted() << "/" << serverEntry.isE2eEncrypted()
<< " | e2eeMangledName: " << dbEntry.e2eMangledName() << "/" << serverEntry.e2eMangledName
<< " | file lock: " << localFileIsLocked << "//" << serverFileIsLocked
<< " | file lock type: " << localFileLockType << "//" << serverFileLockType
<< " | live photo: " << dbEntry._isLivePhoto << "//" << serverEntry.isLivePhoto
<< " | metadata missing: /" << localEntry.isMetadataMissing << '/';
if (_discoveryData->isRenamed(path._original)) {
qCDebug(lcDisco) << "Ignoring renamed";
return; // Ignore this.
}
const auto item = SyncFileItem::fromSyncJournalFileRecord(dbEntry);
item->_file = path._target;
item->_originalFile = path._original;
item->_previousSize = dbEntry._fileSize;
item->_previousModtime = dbEntry._modtime;
item->_discoveryResult = std::move(processingLog);
if (dbEntry._modtime == localEntry.modtime && dbEntry._type == ItemTypeVirtualFile && localEntry.type == ItemTypeFile) {
item->_type = ItemTypeFile;
qCInfo(lcDisco) << "Changing item type from virtual to normal file" << item->_file;
}
// The item shall only have this type if the db request for the virtual download
// was successful (like: no conflicting remote remove etc). This decision is done
// either in processFileAnalyzeRemoteInfo() or further down here.
if (item->_type == ItemTypeVirtualFileDownload)
item->_type = ItemTypeVirtualFile;
// Similarly db entries with a dehydration request denote a regular file
// until the request is processed.
if (item->_type == ItemTypeVirtualFileDehydration) {
item->_type = ItemTypeFile;
qCInfo(lcDisco) << "Changing item type from virtual to normal file" << item->_file;
}
// VFS suffixed files on the server are ignored
if (isVfsWithSuffix()) {
if (hasVirtualFileSuffix(serverEntry.name)
|| (localEntry.isVirtualFile && !dbEntry.isVirtualFile() && hasVirtualFileSuffix(dbEntry._path))) {
item->_instruction = CSYNC_INSTRUCTION_IGNORE;
item->_errorString = tr("File has extension reserved for virtual files.");
_childIgnored = true;
emit _discoveryData->itemDiscovered(item);
return;
}
}
if (serverEntry.isValid()) {
processFileAnalyzeRemoteInfo(item, path, localEntry, serverEntry, dbEntry);
return;
}
// Downloading a virtual file is like a server action and can happen even if
// server-side nothing has changed
// NOTE: Normally setting the VirtualFileDownload flag means that local and
// remote will be rediscovered. This is just a fallback for a similar check
// in processFileAnalyzeRemoteInfo().
if (_queryServer == ParentNotChanged
&& dbEntry.isValid()
&& (dbEntry._type == ItemTypeVirtualFileDownload
|| localEntry.type == ItemTypeVirtualFileDownload)
&& (localEntry.isValid() || _queryLocal == ParentNotChanged)) {
item->_direction = SyncFileItem::Down;
item->_instruction = CSYNC_INSTRUCTION_SYNC;
item->_type = ItemTypeVirtualFileDownload;
}
processFileAnalyzeLocalInfo(item, path, localEntry, serverEntry, dbEntry, _queryServer);
}
// Compute the checksum of the given file and assign the result in item->_checksumHeader
// Returns true if the checksum was successfully computed
static bool computeLocalChecksum(const QByteArray &header, const QString &path, const SyncFileItemPtr &item)
{
auto type = parseChecksumHeaderType(header);
if (!type.isEmpty()) {
// TODO: compute async?
QByteArray checksum = ComputeChecksum::computeNowOnFile(path, type);
if (!checksum.isEmpty()) {
item->_checksumHeader = makeChecksumHeader(type, checksum);
return true;
}
}
return false;
}
void ProcessDirectoryJob::postProcessServerNew(const SyncFileItemPtr &item,
PathTuple &path,
const LocalInfo &localEntry,
const RemoteInfo &serverEntry,
const SyncJournalFileRecord &dbEntry)
{
const auto opts = _discoveryData->_syncOptions;
if (item->isDirectory()) {
// Turn new remote folders into virtual folders if the option is enabled.
if (!localEntry.isValid() &&
opts._vfs->mode() == Vfs::WindowsCfApi &&
_pinState != PinState::AlwaysLocal &&
!FileSystem::isExcludeFile(item->_file)) {
item->_type = ItemTypeVirtualDirectory;
}
_pendingAsyncJobs++;
_discoveryData->checkSelectiveSyncNewFolder(path._server,
serverEntry.remotePerm,
[=, this](bool result) {
--_pendingAsyncJobs;
if (!result) {
processFileAnalyzeLocalInfo(item, path, localEntry, serverEntry, dbEntry, _queryServer);
}
QTimer::singleShot(0, _discoveryData, &DiscoveryPhase::scheduleMoreJobs);
});
return;
}
// Turn new remote files into virtual files if the option is enabled.
if (!localEntry.isValid() &&
opts._vfs->mode() != Vfs::Off &&
_pinState != PinState::AlwaysLocal &&
!FileSystem::isExcludeFile(item->_file)) {
if (item->_type == ItemTypeFile) {
item->_type = ItemTypeVirtualFile;
}
if (isVfsWithSuffix()) {
addVirtualFileSuffix(path._original);
}
}
if (opts._vfs->mode() != Vfs::Off && !item->_encryptedFileName.isEmpty()) {
// We are syncing a file for the first time (local entry is invalid) and it is encrypted file that will be virtual once synced
// to avoid having error of "file has changed during sync" when trying to hydrate it explicitly - we must remove Constants::e2EeTagSize bytes from the end
// as explicit hydration does not care if these bytes are present in the placeholder or not, but, the size must not change in the middle of the sync
// this way it works for both implicit and explicit hydration by making a placeholder size that does not includes encryption tag Constants::e2EeTagSize bytes
// another scenario - we are syncing a file which is on disk but not in the database (database was removed or file was not written there yet)
item->_size = serverEntry.size - Constants::e2EeTagSize;
}
processFileAnalyzeLocalInfo(item, path, localEntry, serverEntry, dbEntry, _queryServer);
}
void ProcessDirectoryJob::processFileAnalyzeRemoteInfo(const SyncFileItemPtr &item,
PathTuple path,
const LocalInfo &localEntry,
const RemoteInfo &serverEntry,
const SyncJournalFileRecord &dbEntry)
{
item->_checksumHeader = serverEntry.checksumHeader;
item->_fileId = serverEntry.fileId;
item->_remotePerm = serverEntry.remotePerm;
item->_isShared = serverEntry.remotePerm.hasPermission(RemotePermissions::IsShared) || serverEntry.sharedByMe;
item->_sharedByMe = serverEntry.sharedByMe;
item->_lastShareStateFetchedTimestamp = QDateTime::currentMSecsSinceEpoch();
item->_type = serverEntry.isDirectory ? ItemTypeDirectory : ItemTypeFile;
item->_etag = serverEntry.etag;
item->_directDownloadUrl = serverEntry.directDownloadUrl;
item->_directDownloadCookies = serverEntry.directDownloadCookies;
item->_e2eEncryptionStatus = serverEntry.isE2eEncrypted() ? SyncFileItem::EncryptionStatus::EncryptedMigratedV2_0 : SyncFileItem::EncryptionStatus::NotEncrypted;
if (serverEntry.isE2eEncrypted()) {
item->_e2eEncryptionServerCapability = EncryptionStatusEnums::fromEndToEndEncryptionApiVersion(_discoveryData->_account->capabilities().clientSideEncryptionVersion());
}
Q_ASSERT(item->_e2eEncryptionStatus != SyncFileItem::EncryptionStatus::Encrypted);
if (item->_e2eEncryptionStatusRemote != SyncFileItem::EncryptionStatus::NotEncrypted) {
Q_ASSERT(item->_e2eEncryptionStatus != SyncFileItem::EncryptionStatus::NotEncrypted);
}
item->_encryptedFileName = [=, this] {
if (serverEntry.e2eMangledName.isEmpty()) {
return QString();
}
Q_ASSERT(_discoveryData->_remoteFolder.startsWith('/'));
Q_ASSERT(_discoveryData->_remoteFolder.endsWith('/'));
const auto rootPath = _discoveryData->_remoteFolder.mid(1);
Q_ASSERT(serverEntry.e2eMangledName.startsWith(rootPath));
return serverEntry.e2eMangledName.mid(rootPath.length());
}();
item->_locked = serverEntry.locked;
item->_lockOwnerDisplayName = serverEntry.lockOwnerDisplayName;
item->_lockOwnerId = serverEntry.lockOwnerId;
item->_lockOwnerType = serverEntry.lockOwnerType;
item->_lockEditorApp = serverEntry.lockEditorApp;
item->_lockTime = serverEntry.lockTime;
item->_lockTimeout = serverEntry.lockTimeout;
item->_lockToken = serverEntry.lockToken;
item->_isLivePhoto = serverEntry.isLivePhoto;
item->_livePhotoFile = serverEntry.livePhotoFile;
item->_folderQuota.bytesUsed = serverEntry.folderQuota.bytesUsed;
item->_folderQuota.bytesAvailable = serverEntry.folderQuota.bytesAvailable;
// Check for missing server data
{
if (serverEntry.size == -1 || serverEntry.remotePerm.isNull() || serverEntry.etag.isEmpty() || serverEntry.fileId.isEmpty()) {
qCWarning(lcDisco) << "The response provided by the server is missing data:"
<< "- serverEntry.name:" << serverEntry.name
<< "- serverEntry.size:" << serverEntry.size
<< "- serverEntry.remotePerm:" << serverEntry.remotePerm
<< "- serverEntry.etag:" << serverEntry.etag
<< "- serverEntry.fileId:" << serverEntry.fileId;
item->_instruction = CSYNC_INSTRUCTION_ERROR;
_childIgnored = true;
item->_errorString = serverEntry.isDirectory ? tr("Folder is not accessible on the server.", "server error")
: tr("File is not accessible on the server.", "server error");
emit _discoveryData->itemDiscovered(item);
return;
}
}
// We want to check the lock state of this file after the lock time has expired
if(serverEntry.locked == SyncFileItem::LockStatus::LockedItem && serverEntry.lockTimeout > 0) {
const auto lockExpirationTime = serverEntry.lockTime + serverEntry.lockTimeout;
const auto timeRemaining = QDateTime::currentDateTime().secsTo(QDateTime::fromSecsSinceEpoch(lockExpirationTime));
// Add on a second as a precaution, sometimes we catch the server before it has had a chance to update
const auto lockExpirationTimeout = qMax(5LL, timeRemaining + 1);
_discoveryData->_anotherSyncNeeded = true;
_discoveryData->_filesNeedingScheduledSync.insert(path._original, lockExpirationTimeout);
} else if (serverEntry.locked == SyncFileItem::LockStatus::UnlockedItem && dbEntry._lockstate._locked) {
// We have received data that this file has been unlocked remotely, so let's notify the sync engine
// that we no longer need a scheduled sync run for this file
_discoveryData->_filesUnscheduleSync.append(path._original);
}
// The file is known in the db already
if (dbEntry.isValid()) {
const auto isDbEntryAnE2EePlaceholder = dbEntry.isVirtualFile() && !dbEntry.e2eMangledName().isEmpty();
Q_ASSERT(!isDbEntryAnE2EePlaceholder || serverEntry.size >= Constants::e2EeTagSize);
const auto isVirtualE2EePlaceholder = isDbEntryAnE2EePlaceholder && serverEntry.size >= Constants::e2EeTagSize;
const auto sizeOnServer = isVirtualE2EePlaceholder ? serverEntry.size - Constants::e2EeTagSize : serverEntry.size;
const auto metaDataSizeNeedsUpdateForE2EeFilePlaceholder = isVirtualE2EePlaceholder && dbEntry._fileSize == serverEntry.size;
if (serverEntry.isDirectory) {
// Even if over quota, continue syncing as normal for now
_discoveryData->checkSelectiveSyncExistingFolder(path._server);
}
if (serverEntry.isDirectory != dbEntry.isDirectory()) {
// If the type of the entity changed, it's like NEW, but
// needs to delete the other entity first.
item->_instruction = CSYNC_INSTRUCTION_TYPE_CHANGE;
item->_direction = SyncFileItem::Down;
item->_modtime = serverEntry.modtime;
item->_size = sizeOnServer;
} else if ((dbEntry._type == ItemTypeVirtualFileDownload || localEntry.type == ItemTypeVirtualFileDownload)
&& (localEntry.isValid() || _queryLocal == ParentNotChanged)) {
// The above check for the localEntry existing is important. Otherwise it breaks
// the case where a file is moved and simultaneously tagged for download in the db.
item->_direction = SyncFileItem::Down;
item->_instruction = CSYNC_INSTRUCTION_SYNC;
item->_type = ItemTypeVirtualFileDownload;
} else if (serverEntry.isValid() && !serverEntry.isDirectory && !serverEntry.remotePerm.isNull() && !serverEntry.remotePerm.hasPermission(RemotePermissions::CanRead)) {
item->_instruction = CSYNC_INSTRUCTION_REMOVE;
item->_direction = SyncFileItem::Down;
} else if (dbEntry._etag != serverEntry.etag) {
item->_direction = SyncFileItem::Down;
item->_modtime = serverEntry.modtime;
item->_size = sizeOnServer;
if (serverEntry.isDirectory) {
Q_ASSERT(dbEntry.isDirectory());
item->_instruction = CSYNC_INSTRUCTION_UPDATE_METADATA;
} else if (!localEntry.isValid() && _queryLocal != ParentNotChanged) {
// Deleted locally, changed on server
item->_instruction = CSYNC_INSTRUCTION_NEW;
} else {
item->_instruction = CSYNC_INSTRUCTION_SYNC;
qCDebug(lcDisco) << "CSYNC_INSTRUCTION_SYNC: File" << item->_file << "if (dbEntry._etag != serverEntry.etag)"
<< "dbEntry._etag:" << dbEntry._etag
<< "serverEntry.etag:" << serverEntry.etag
<< "serverEntry.isDirectory:" << serverEntry.isDirectory
<< "dbEntry.isDirectory:" << dbEntry.isDirectory();
}
} else if (dbEntry._modtime != serverEntry.modtime && localEntry.size == serverEntry.size && dbEntry._fileSize == serverEntry.size
&& dbEntry._etag == serverEntry.etag) {
item->_direction = SyncFileItem::Down;
item->_modtime = serverEntry.modtime;
item->_size = sizeOnServer;
item->_instruction = CSYNC_INSTRUCTION_UPDATE_METADATA;
} else if (dbEntry._remotePerm != serverEntry.remotePerm || dbEntry._fileId != serverEntry.fileId || metaDataSizeNeedsUpdateForE2EeFilePlaceholder) {
if (metaDataSizeNeedsUpdateForE2EeFilePlaceholder) {
// we are updating placeholder sizes after migrating from older versions with VFS + E2EE implicit hydration not supported
qCDebug(lcDisco) << "Migrating the E2EE VFS placeholder " << dbEntry.path() << " from older version. The old size is " << item->_size << ". The new size is " << sizeOnServer;
item->_size = sizeOnServer;
}
item->_instruction = CSYNC_INSTRUCTION_UPDATE_METADATA;
item->_direction = SyncFileItem::Down;
} else if (serverEntry.requestUpload && !serverEntry.isDirectory && (localEntry.isValid() || _queryLocal == ParentNotChanged)) {
// Server requested re-upload of this file. Check if we have a local copy and trigger upload.
qCInfo(lcDisco) << "Server requested re-upload for file:" << item->_file;
item->_instruction = CSYNC_INSTRUCTION_SYNC;
item->_direction = SyncFileItem::Up;
if (localEntry.isValid()) {
item->_size = localEntry.size;
item->_modtime = localEntry.modtime;
} else {
// If we're in ParentNotChanged mode and don't have localEntry, use db values
item->_size = dbEntry._fileSize;
item->_modtime = dbEntry._modtime;
}
_childModified = true;
} else {
// if (is virtual mode enabled and folder is encrypted - check if the size is the same as on the server and then - trigger server query
// to update a placeholder with corrected size (-16 Bytes)
// or, maybe, add a flag to the database - vfsE2eeSizeCorrected? if it is not set - subtract it from the placeholder's size and re-create/update a placeholder?
const QueryMode serverQueryMode = [this, &dbEntry, &serverEntry]() {
const auto isVfsModeOn = _discoveryData && _discoveryData->_syncOptions._vfs && _discoveryData->_syncOptions._vfs->mode() != Vfs::Off;
if (isVfsModeOn && dbEntry.isDirectory() && dbEntry.isE2eEncrypted()) {
qint64 localFolderSize = 0;
const auto listFilesCallback = [&localFolderSize](const OCC::SyncJournalFileRecord &record) {
if (record.isFile()) {
// add Constants::e2EeTagSize so we will know the size of E2EE file on the server
localFolderSize += record._fileSize + Constants::e2EeTagSize;
} else if (record.isVirtualFile()) {
// just a virtual file, so, the size must contain Constants::e2EeTagSize if it was not corrected already
localFolderSize += record._fileSize;
}
};
const auto listFilesSucceeded = _discoveryData->_statedb->listFilesInPath(dbEntry.path().toUtf8(), listFilesCallback);
if (listFilesSucceeded && localFolderSize != 0 && localFolderSize == serverEntry.sizeOfFolder) {
qCInfo(lcDisco) << "Migration of E2EE folder " << dbEntry.path() << " from older version to the one, supporting the implicit VFS hydration.";
return NormalQuery;
}
}
return ParentNotChanged;
}();
processFileAnalyzeLocalInfo(item, path, localEntry, serverEntry, dbEntry, serverQueryMode);
return;
}
processFileAnalyzeLocalInfo(item, path, localEntry, serverEntry, dbEntry, _queryServer);
return;
}
// Unknown in db: new file on the server
Q_ASSERT(!dbEntry.isValid());
if (checkNewDeleteConflict(item)) {
return;
}
item->_instruction = CSYNC_INSTRUCTION_NEW;
item->_direction = SyncFileItem::Down;
item->_modtime = serverEntry.modtime;
item->_size = serverEntry.size;
const auto conflictRecord = _discoveryData->_noCaseConflictRecordsInDb
? ConflictRecord{} :
_discoveryData->_statedb->caseConflictRecordByBasePath(item->_file);
if (conflictRecord.isValid() && QString::fromUtf8(conflictRecord.path).contains(QStringLiteral("(case clash from"))) {
qCInfo(lcDisco) << "should ignore" << item->_file << "has already a case clash conflict record" << conflictRecord.path;
item->_instruction = CSYNC_INSTRUCTION_IGNORE;
return;
}
if (serverEntry.isValid() && !serverEntry.isDirectory && !serverEntry.remotePerm.isNull() && !serverEntry.remotePerm.hasPermission(RemotePermissions::CanRead)) {
item->_instruction = CSYNC_INSTRUCTION_IGNORE;
emit _discoveryData->itemDiscovered(item);
return;
}
// Check if server requested re-upload and we have a local copy
if (serverEntry.requestUpload && !serverEntry.isDirectory && localEntry.isValid()) {
qCInfo(lcDisco) << "Server requested re-upload for new file:" << item->_file;
item->_instruction = CSYNC_INSTRUCTION_SYNC;
item->_direction = SyncFileItem::Up;
item->_size = localEntry.size;
item->_modtime = localEntry.modtime;
processFileAnalyzeLocalInfo(item, path, localEntry, serverEntry, dbEntry, _queryServer);
return;
}
// Potential NEW/NEW conflict is handled in AnalyzeLocal
if (localEntry.isValid()) {
postProcessServerNew(item, path, localEntry, serverEntry, dbEntry);
return;
}
// Not in db or locally: either new or a rename
Q_ASSERT(!dbEntry.isValid() && !localEntry.isValid());
// Check for renames (if there is a file with the same file id)
bool done = false;
bool async = false;
// This function will be executed for every candidate
auto renameCandidateProcessing = [&](const OCC::SyncJournalFileRecord &base) {
if (done)
return;
if (!base.isValid())
return;
// Remote rename of a virtual file we have locally scheduled for download.
if (base._type == ItemTypeVirtualFileDownload) {
// We just consider this NEW but mark it for download.
item->_type = ItemTypeVirtualFileDownload;
done = true;
return;
}
// Remote rename targets a file that shall be locally dehydrated.
if (base._type == ItemTypeVirtualFileDehydration) {
// Don't worry about the rename, just consider it DELETE + NEW(virtual)
done = true;
return;
}
// Some things prohibit rename detection entirely.
// Since we don't do the same checks again in reconcile, we can't
// just skip the candidate, but have to give up completely.
if (base.isDirectory() != item->isDirectory()) {
qCInfo(lcDisco, "file types different, not a rename");