-
Notifications
You must be signed in to change notification settings - Fork 668
/
discovery.cpp
1548 lines (1399 loc) · 69.6 KB
/
discovery.cpp
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
/*
* Copyright (C) by Olivier Goffart <ogoffart@woboq.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; either version 2 of the License, or
* (at your option) any later version.
*
* 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.
*/
#include "discovery.h"
#include "csync.h"
#include "owncloudpropagator.h"
#include "syncfileitem.h"
#include "csync/csync_exclude.h"
#include "csync/vio/csync_vio_local.h"
#include "common/checksums.h"
#include "common/syncjournaldb.h"
#include "libsync/theme.h"
#include <algorithm>
#include <QFile>
#include <QFileInfo>
#include <QThreadPool>
namespace OCC {
Q_LOGGING_CATEGORY(lcDisco, "sync.discovery", QtInfoMsg)
void ProcessDirectoryJob::start()
{
qCInfo(lcDisco) << "STARTING" << _currentFolder._server << _queryServer << _currentFolder._local << _queryLocal;
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))) {
_queryLocal = ParentNotChanged;
}
}
if (_queryLocal == NormalQuery) {
startAsyncLocalQuery();
} else {
_localQueryDone = true;
}
if (_localQueryDone && _serverQueryDone) {
process();
}
}
void ProcessDirectoryJob::process()
{
OC_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.
struct Entries {
QString nameOverride;
SyncJournalFileRecord dbEntry;
RemoteInfo serverEntry;
LocalInfo localEntry;
};
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() ? QString::fromUtf8(rec._path) : QString::fromUtf8(rec._path.constData() + (pathU8.size() + 1));
if (rec.isVirtualFile() && isVfsWithSuffix()) {
name = 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 = chopVirtualFileSuffix(e.name);
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 (const auto &f : entries) {
const auto &e = f.second;
PathTuple path;
path = _currentFolder.addName(e.nameOverride.isEmpty() ? f.first : e.nameOverride);
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 = QString::fromUtf8(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);
}
}
// 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 bool isHidden = [&] {
if (Q_UNLIKELY(Theme::instance()->enableCernBranding())) {
return e.localEntry.isHidden || (f.first[0] == QLatin1Char('.') && f.first != QLatin1String(".sys.admin#recall#"));
} else {
return e.localEntry.isHidden || f.first[0] == QLatin1Char('.');
}
}();
if (handleExcluded(path._target,
e.localEntry.name,
e.localEntry.isDirectory || e.serverEntry.isDirectory,
isHidden,
e.localEntry.isSymLink)) {
// the file only exists in the db
if (!e.localEntry.isValid() && e.dbEntry.isValid()) {
qCWarning(lcDisco) << "Removing db entry for non exisitng ignored file:" << path._original;
_discoveryData->_statedb->deleteFileRecord(path._original, true);
}
continue;
}
if (_queryServer == InBlackList || _discoveryData->isInSelectiveSyncBlackList(path._original)) {
processBlacklisted(path, e.localEntry, e.dbEntry);
continue;
}
processFile(std::move(path), e.localEntry, e.serverEntry, e.dbEntry);
}
QTimer::singleShot(0, _discoveryData, &DiscoveryPhase::scheduleMoreJobs);
}
bool ProcessDirectoryJob::handleExcluded(const QString &path, const QString &localName, bool isDirectory, bool isHidden, bool isSymlink)
{
auto excluded = _discoveryData->_excludes->traversalPatternMatch(path, isDirectory ? ItemTypeDirectory : ItemTypeFile);
// FIXME: move to ExcludedFiles 's regexp ?
bool isInvalidPattern = false;
if (excluded == CSYNC_NOT_EXCLUDED && !_discoveryData->_invalidFilenameRx.pattern().isEmpty()) {
if (path.contains(_discoveryData->_invalidFilenameRx)) {
excluded = CSYNC_FILE_EXCLUDE_INVALID_CHAR;
isInvalidPattern = true;
}
}
if (excluded == CSYNC_NOT_EXCLUDED && _discoveryData->_ignoreHiddenFiles && isHidden) {
excluded = CSYNC_FILE_EXCLUDE_HIDDEN;
}
if (excluded == CSYNC_NOT_EXCLUDED && !localName.isEmpty()
&& _discoveryData->_serverBlacklistedFiles.contains(localName)) {
excluded = CSYNC_FILE_EXCLUDE_SERVER_BLACKLISTED;
isInvalidPattern = true;
}
if (excluded == CSYNC_NOT_EXCLUDED && !isSymlink) {
return false;
} else if (excluded == CSYNC_FILE_SILENTLY_EXCLUDED || excluded == CSYNC_FILE_EXCLUDE_AND_REMOVE) {
Q_EMIT _discoveryData->silentlyExcluded(path);
return true;
} else if (excluded == CSYNC_FILE_EXCLUDE_RESERVED) {
Q_EMIT _discoveryData->excluded(path);
return true;
}
auto item = SyncFileItemPtr::create();
item->_file = path;
item->_originalFile = path;
item->setInstruction(CSYNC_INSTRUCTION_IGNORE);
if (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:
case CSYNC_FILE_EXCLUDE_RESERVED:
qFatal("These were handled earlier");
case CSYNC_FILE_EXCLUDE_LIST:
item->_errorString = tr("File is listed on the ignore list.");
item->_status = SyncFileItem::Excluded;
break;
case CSYNC_FILE_EXCLUDE_INVALID_CHAR:
if (item->_file.endsWith(QLatin1Char('.'))) {
item->_errorString = tr("File names ending with a period are not supported on this file system.");
} else {
const auto unsupportedCharacter = [](const QString &fName) {
const auto unsupportedCharacter = QStringLiteral("\\:?*\"<>|");
for (const auto &x : unsupportedCharacter) {
if (fName.contains(x)) {
return x;
}
}
return QChar();
}(item->_file);
if (!unsupportedCharacter.isNull()) {
item->_errorString = tr("File names containing the character '%1' are not supported on this file system.")
.arg(unsupportedCharacter);
} else if (isInvalidPattern) {
item->_errorString = tr("File name contains at least one invalid character");
} else {
item->_errorString = tr("The file name is a reserved name on this file system.");
if (!localName.isEmpty()) {
// The file is indeed a system file and that we don't upload it is no problem
item->_status = SyncFileItem::Excluded;
}
}
}
break;
case CSYNC_FILE_EXCLUDE_TRAILING_SPACE:
item->_errorString = tr("Filename contains trailing spaces.");
break;
case CSYNC_FILE_EXCLUDE_LONG_FILENAME:
item->_errorString = tr("Filename is too long.");
break;
case CSYNC_FILE_EXCLUDE_HIDDEN:
item->_errorString = tr("File/Folder is ignored because it's hidden.");
item->_status = SyncFileItem::Excluded;
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_CANNOT_ENCODE:
item->_errorString = tr("The filename cannot be encoded on your file system.");
break;
case CSYNC_FILE_EXCLUDE_SERVER_BLACKLISTED:
item->_errorString = tr("The filename is blacklisted on the server.");
break;
}
}
_childIgnored = true;
Q_EMIT _discoveryData->itemDiscovered(item);
return true;
}
void ProcessDirectoryJob::processFile(const PathTuple &path,
const LocalInfo &localEntry, const RemoteInfo &serverEntry,
const SyncJournalFileRecord &dbEntry)
{
// The percent-encoded file name as it would be passed in an HTTP request. This can be used to
// debug Unicode encoding/normalization issues.
auto encodedFileName = QUrl::fromLocalFile(path._original).toEncoded().sliced(std::string_view("file:").length());
const char *hasServer = serverEntry.isValid() ? "true" : _queryServer == ParentNotChanged ? "db" : "false";
const char *hasLocal = localEntry.isValid() ? "true" : _queryLocal == ParentNotChanged ? "db" : "false";
// The code below is formatted like this ON PURPOSE: each field is db/local/server, one field
// per (source code) line, so it's easy to understand.
// clang-format off
qCInfo(lcDisco).nospace() << "Processing " << path._original
<< " | 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)
<< " (" << encodedFileName << ")";
// clang-format on
if (_discoveryData->isRenamed(path._original)) {
qCDebug(lcDisco) << "Ignoring renamed";
return; // Ignore this.
}
auto item = SyncFileItem::fromSyncJournalFileRecord(dbEntry);
item->_file = path._target;
item->_originalFile = path._original;
item->_previousSize = dbEntry._fileSize;
item->_previousModtime = dbEntry._modtime;
if (item->_type == ItemTypeVirtualFileDownload) {
// 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.
item->_type = ItemTypeVirtualFile;
} else if (item->_type == ItemTypeVirtualFileDehydration) {
// Similarly db entries with a dehydration request denote a regular file
// until the request is processed.
item->_type = ItemTypeFile;
}
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->setInstruction(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)
{
const auto checksumHeader = ChecksumHeader::parseChecksumHeader(header);
if (checksumHeader.isValid()) {
// TODO: compute async?
QByteArray checksum = ComputeChecksum::computeNowOnFile(path, checksumHeader.type());
if (!checksum.isEmpty()) {
item->_checksumHeader = ChecksumHeader(checksumHeader.type(), checksum).makeChecksumHeader();
return true;
}
}
return false;
}
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->_type = serverEntry.isDirectory ? ItemTypeDirectory : ItemTypeFile;
item->_etag = serverEntry.etag;
item->_directDownloadUrl = serverEntry.directDownloadUrl;
item->_directDownloadCookies = serverEntry.directDownloadCookies;
// Check for missing server data
{
QStringList missingData;
if (serverEntry.size == -1) {
missingData.append(QStringLiteral("size"));
}
if (serverEntry.remotePerm.isNull()) {
missingData.append(QStringLiteral("permissions"));
}
if (serverEntry.etag.isEmpty()) {
missingData.append(QStringLiteral("etag"));
}
if (serverEntry.fileId.isEmpty()) {
missingData.append(QStringLiteral("id"));
}
if (!missingData.isEmpty()) {
item->setInstruction(CSYNC_INSTRUCTION_ERROR);
_childIgnored = true;
item->_errorString = tr("server reported no %1").arg(missingData.join(QLatin1String(", ")));
qCWarning(lcDisco) << item->_errorString;
Q_EMIT _discoveryData->itemDiscovered(item);
return;
}
}
// The file is known in the db already
if (dbEntry.isValid()) {
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->setInstruction(CSYNC_INSTRUCTION_TYPE_CHANGE);
item->_direction = SyncFileItem::Down;
item->_modtime = serverEntry.modtime;
item->_size = serverEntry.size;
if (dbEntry.isDirectory()) {
// TODO: move the decision to the backend
if (_discoveryData->_syncOptions._vfs->mode() != Vfs::Off && _pinState != PinState::AlwaysLocal) {
item->_type = ItemTypeVirtualFile;
}
}
} 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->setInstruction(CSYNC_INSTRUCTION_SYNC);
item->_type = ItemTypeVirtualFileDownload;
item->_size = serverEntry.size;
} else if (dbEntry._etag != serverEntry.etag.toUtf8()) {
item->_direction = SyncFileItem::Down;
item->_modtime = serverEntry.modtime;
item->_size = serverEntry.size;
if (serverEntry.isDirectory) {
OC_ENFORCE(dbEntry.isDirectory());
item->setInstruction(CSYNC_INSTRUCTION_UPDATE_METADATA);
} else if (!localEntry.isValid() && _queryLocal != ParentNotChanged) {
// Deleted locally, changed on server
item->setInstruction(CSYNC_INSTRUCTION_NEW);
} else {
item->setInstruction(CSYNC_INSTRUCTION_SYNC);
}
} else if (dbEntry._remotePerm != serverEntry.remotePerm || dbEntry._fileId != serverEntry.fileId) {
item->setInstruction(CSYNC_INSTRUCTION_UPDATE_METADATA);
item->_direction = SyncFileItem::Down;
} else {
processFileAnalyzeLocalInfo(item, path, localEntry, serverEntry, dbEntry, ParentNotChanged);
return;
}
processFileAnalyzeLocalInfo(item, path, localEntry, serverEntry, dbEntry, _queryServer);
return;
}
// Unknown in db: new file on the server
Q_ASSERT(!dbEntry.isValid());
item->setInstruction(CSYNC_INSTRUCTION_NEW);
item->_direction = SyncFileItem::Down;
item->_modtime = serverEntry.modtime;
item->_size = serverEntry.size;
auto postProcessServerNew = [=]() mutable {
// Turn new remote files into virtual files if the option is enabled.
// TODO: move the decision to the backend
const auto &opts = _discoveryData->_syncOptions;
if (!localEntry.isValid()
&& item->_type == ItemTypeFile
&& opts._vfs->mode() != Vfs::Off
&& _pinState != PinState::AlwaysLocal) {
item->_type = ItemTypeVirtualFile;
if (isVfsWithSuffix()) {
addVirtualFileSuffix(path._original);
}
}
processFileAnalyzeLocalInfo(item, path, localEntry, serverEntry, dbEntry, _queryServer);
};
// Potential NEW/NEW conflict is handled in AnalyzeLocal
if (localEntry.isValid()) {
postProcessServerNew();
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");
done = true;
return;
}
if (!serverEntry.isDirectory && base._etag != serverEntry.etag.toUtf8()) {
/* File with different etag, don't do a rename, but download the file again */
qCInfo(lcDisco, "file etag different, not a rename");
done = true;
return;
}
// Now we know there is a sane rename candidate.
QString originalPath = QString::fromUtf8(base._path);
if (_discoveryData->isRenamed(originalPath)) {
qCInfo(lcDisco, "folder already has a rename entry, skipping");
return;
}
QString originalPathAdjusted = _discoveryData->adjustRenamedPath(originalPath, SyncFileItem::Up);
if (!base.isDirectory()) {
csync_file_stat_t buf;
if (csync_vio_local_stat(_discoveryData->_localDir + originalPathAdjusted, &buf)) {
qCInfo(lcDisco) << "Local file does not exist anymore." << originalPathAdjusted;
return;
}
// NOTE: This prohibits some VFS renames from being detected since
// suffix-file size is different from the db size. That's ok, they'll DELETE+NEW.
if (buf.modtime != base._modtime || buf.size != base._fileSize || buf.type == ItemTypeDirectory) {
qCInfo(lcDisco) << "File has changed locally, not a rename." << originalPath;
return;
}
} else {
if (!QFileInfo(_discoveryData->_localDir + originalPathAdjusted).isDir()) {
qCInfo(lcDisco) << "Local directory does not exist anymore." << originalPathAdjusted;
return;
}
}
// Renames of virtuals are possible
if (base.isVirtualFile()) {
item->_type = ItemTypeVirtualFile;
}
bool wasDeletedOnServer = _discoveryData->findAndCancelDeletedJob(originalPath).first;
auto postProcessRename = [this, item, base, originalPath](PathTuple &path) {
auto adjustedOriginalPath = _discoveryData->adjustRenamedPath(originalPath, SyncFileItem::Up);
_discoveryData->_renamedItemsRemote.insert(originalPath, path._target);
item->_modtime = base._modtime;
item->_inode = base._inode;
item->setInstruction(CSYNC_INSTRUCTION_RENAME);
item->_direction = SyncFileItem::Down;
item->_renameTarget = path._target;
item->_file = adjustedOriginalPath;
item->_originalFile = originalPath;
path._original = originalPath;
path._local = adjustedOriginalPath;
qCInfo(lcDisco) << "Rename detected (down) " << item->_file << " -> " << item->_renameTarget;
};
if (wasDeletedOnServer) {
postProcessRename(path);
done = true;
} else {
// we need to make a request to the server to know that the original file is deleted on the server
_pendingAsyncJobs++;
auto job = new RequestEtagJob(_discoveryData->_account, _discoveryData->_baseUrl, _discoveryData->_remoteFolder + originalPath, this);
connect(job, &RequestEtagJob::finishedSignal, this, [=]() mutable {
_pendingAsyncJobs--;
QTimer::singleShot(0, _discoveryData, &DiscoveryPhase::scheduleMoreJobs);
if (job->httpStatusCode() == 207 ||
// Somehow another item claimed this original path, consider as if it existed
_discoveryData->isRenamed(originalPath)) {
// If the file exist or if there is another error, consider it is a new file.
postProcessServerNew();
return;
} else if (OC_ENSURE(job->httpStatusCode() == 404)) {
// The file do not exist, it is a rename
// In case the deleted item was discovered in parallel
_discoveryData->findAndCancelDeletedJob(originalPath);
postProcessRename(path);
processFileFinalize(
item, path, item->isDirectory(), item->instruction() == CSYNC_INSTRUCTION_RENAME ? NormalQuery : ParentDontExist, _queryServer);
return;
}
Q_EMIT _discoveryData->fatalError(tr("Error while doing a rename, unhandled status code: %1").arg(job->httpStatusCode()));
});
job->start();
done = true; // Ideally, if the origin still exist on the server, we should continue searching... but that'd be difficult
async = true;
}
};
if (!_discoveryData->_statedb->getFileRecordsByFileId(serverEntry.fileId, renameCandidateProcessing)) {
dbError();
return;
}
if (async) {
return; // We went async
}
if (item->instruction() == CSYNC_INSTRUCTION_NEW) {
postProcessServerNew();
return;
}
processFileAnalyzeLocalInfo(item, path, localEntry, serverEntry, dbEntry, _queryServer);
}
void ProcessDirectoryJob::processFileAnalyzeLocalInfo(
const SyncFileItemPtr &item, const PathTuple &path, const LocalInfo &localEntry,
const RemoteInfo &serverEntry, const SyncJournalFileRecord &dbEntry, QueryMode recurseQueryServer)
{
const bool noServerEntry = (_queryServer != ParentNotChanged && !serverEntry.isValid()) || (_queryServer == ParentNotChanged && !dbEntry.isValid());
if (noServerEntry) {
recurseQueryServer = ParentDontExist;
}
const bool serverModified = [&] {
bool modifiedOnServer =
(item->instruction() & (CSYNC_INSTRUCTION_NEW | CSYNC_INSTRUCTION_SYNC | CSYNC_INSTRUCTION_RENAME | CSYNC_INSTRUCTION_TYPE_CHANGE));
// Decay server modifications to UPDATE_METADATA if the local virtual exists
const bool hasLocalVirtual = localEntry.isVirtualFile || (_queryLocal == ParentNotChanged && dbEntry.isVirtualFile());
const bool virtualFileDownload = item->_type == ItemTypeVirtualFileDownload || item->instruction() == CSYNC_INSTRUCTION_TYPE_CHANGE;
if (modifiedOnServer && !virtualFileDownload && hasLocalVirtual) {
item->setInstruction(CSYNC_INSTRUCTION_UPDATE_METADATA);
modifiedOnServer = false;
item->_type = ItemTypeVirtualFile;
}
if (dbEntry.isVirtualFile() && !virtualFileDownload) {
item->_type = ItemTypeVirtualFile;
}
return modifiedOnServer;
}();
_childModified |= serverModified;
auto finalize = [item, localEntry, serverEntry, this](const PathTuple &path, QueryMode recurseQueryServer) {
bool recurse = item->isDirectory() || localEntry.isDirectory || serverEntry.isDirectory;
// Even if we have a local directory: If the remote is a file that's propagated as a
// conflict we don't need to recurse into it. (local c1.owncloud, c1/ ; remote: c1)
if (item->instruction() == CSYNC_INSTRUCTION_CONFLICT && !item->isDirectory())
recurse = false;
if (_queryLocal != NormalQuery && _queryServer != NormalQuery)
recurse = false;
auto recurseQueryLocal = _queryLocal == ParentNotChanged ? ParentNotChanged
: localEntry.isDirectory || item->instruction() == CSYNC_INSTRUCTION_RENAME ? NormalQuery
: ParentDontExist;
processFileFinalize(item, path, recurse, recurseQueryLocal, recurseQueryServer);
};
if (!localEntry.isValid()) {
if (_queryLocal == ParentNotChanged && dbEntry.isValid()) {
// Not modified locally (ParentNotChanged)
if (noServerEntry) {
// not on the server: Removed on the server, delete locally
item->setInstruction(CSYNC_INSTRUCTION_REMOVE);
item->_direction = SyncFileItem::Down;
} else if (dbEntry._type == ItemTypeVirtualFileDehydration) {
// dehydration requested
item->_direction = SyncFileItem::Down;
item->setInstruction(CSYNC_INSTRUCTION_SYNC);
item->_type = ItemTypeVirtualFileDehydration;
}
} else if (noServerEntry) {
// Not locally, not on the server. The entry is stale!
qCInfo(lcDisco) << "Stale DB entry";
_discoveryData->_statedb->deleteFileRecord(path._original, true);
return;
} else if (dbEntry._type == ItemTypeVirtualFile && isVfsWithSuffix()) {
// If the virtual file is removed, recreate it.
// This is a precaution since the suffix files don't look like the real ones
// and we don't want users to accidentally delete server data because they
// might not expect that deleting the placeholder will have a remote effect.
item->setInstruction(CSYNC_INSTRUCTION_NEW);
item->_direction = SyncFileItem::Down;
item->_type = ItemTypeVirtualFile;
} else if (!serverModified) {
// Removed locally: also remove on the server.
if (!dbEntry._serverHasIgnoredFiles) {
item->setInstruction(CSYNC_INSTRUCTION_REMOVE);
item->_direction = SyncFileItem::Up;
}
}
finalize(path, recurseQueryServer);
return;
}
Q_ASSERT(localEntry.isValid());
item->_inode = localEntry.inode;
if (dbEntry.isValid()) {
const bool typeChange = localEntry.isDirectory != dbEntry.isDirectory();
if (!typeChange && localEntry.isVirtualFile) {
if (noServerEntry) {
item->setInstruction(CSYNC_INSTRUCTION_REMOVE);
item->_direction = SyncFileItem::Down;
} else if (!dbEntry.isVirtualFile() && isVfsWithSuffix()) {
// If we find what looks to be a spurious "abc.owncloud" the base file "abc"
// might have been renamed to that. Make sure that the base file is not
// deleted from the server.
if (dbEntry._modtime == localEntry.modtime && dbEntry._fileSize == localEntry.size) {
qCInfo(lcDisco) << "Base file was renamed to virtual file:" << item->_file;
item->_direction = SyncFileItem::Down;
item->setInstruction(CSYNC_INSTRUCTION_SYNC);
item->_type = ItemTypeVirtualFileDehydration;
addVirtualFileSuffix(item->_file);
item->_renameTarget = item->_file;
} else {
qCInfo(lcDisco) << "Virtual file with non-virtual db entry, ignoring:" << item->_file;
item->setInstruction(CSYNC_INSTRUCTION_IGNORE);
}
}
} else if (!typeChange && ((dbEntry._modtime == localEntry.modtime && dbEntry._fileSize == localEntry.size) || localEntry.isDirectory)) {
// Local file unchanged.
if (noServerEntry) {
item->setInstruction(CSYNC_INSTRUCTION_REMOVE);
item->_direction = SyncFileItem::Down;
} else if (dbEntry._type == ItemTypeVirtualFileDehydration || localEntry.type == ItemTypeVirtualFileDehydration) {
item->_direction = SyncFileItem::Down;
item->setInstruction(CSYNC_INSTRUCTION_SYNC);
item->_type = ItemTypeVirtualFileDehydration;
} else if (!serverModified
&& (dbEntry._inode != localEntry.inode
|| _discoveryData->_syncOptions._vfs->needsMetadataUpdate(*item))) {
item->setInstruction(CSYNC_INSTRUCTION_UPDATE_METADATA);
item->_direction = SyncFileItem::Down;
}
} else if (!typeChange && isVfsWithSuffix()
&& dbEntry.isVirtualFile() && !localEntry.isVirtualFile
&& dbEntry._inode == localEntry.inode
&& dbEntry._modtime == localEntry.modtime
&& localEntry.size == 1) {
// A suffix vfs file can be downloaded by renaming it to remove the suffix.
// This check leaks some details of VfsSuffix, particularly the size of placeholders.
item->_direction = SyncFileItem::Down;
if (noServerEntry) {
item->setInstruction(CSYNC_INSTRUCTION_REMOVE);
item->_type = ItemTypeFile;
} else {
item->setInstruction(CSYNC_INSTRUCTION_SYNC);
item->_type = ItemTypeVirtualFileDownload;
item->_previousSize = 1;
}
} else if (serverModified
|| (isVfsWithSuffix() && dbEntry.isVirtualFile())) {
// There's a local change and a server change: Conflict!
// Alternatively, this might be a suffix-file that's virtual in the db but
// not locally. These also become conflicts. For in-place placeholders that's
// not necessary: they could be replaced by real files and should then trigger
// a regular SYNC upwards when there's no server change.
processFileConflict(item, path, localEntry, serverEntry, dbEntry);
} else if (typeChange) {
item->setInstruction(CSYNC_INSTRUCTION_TYPE_CHANGE);
item->_direction = SyncFileItem::Up;
item->_checksumHeader.clear();
item->_size = localEntry.size;
item->_modtime = localEntry.modtime;
item->_type = localEntry.isDirectory ? ItemTypeDirectory : ItemTypeFile;
_childModified = true;
} else {
// Local file was changed
item->setInstruction(CSYNC_INSTRUCTION_SYNC);
if (noServerEntry) {
// Special case! deleted on server, modified on client, the instruction is then NEW
item->setInstruction(CSYNC_INSTRUCTION_NEW);
}
item->_direction = SyncFileItem::Up;
item->_checksumHeader.clear();
item->_size = localEntry.size;
item->_modtime = localEntry.modtime;
_childModified = true;
// Checksum comparison at this stage is only enabled for .eml files,
// check #4754 #4755
bool isEmlFile = path._original.endsWith(QLatin1String(".eml"), Qt::CaseInsensitive);
if (isEmlFile && dbEntry._fileSize == localEntry.size && !dbEntry._checksumHeader.isEmpty()) {
if (computeLocalChecksum(dbEntry._checksumHeader, _discoveryData->_localDir + path._local, item)
&& item->_checksumHeader == dbEntry._checksumHeader) {
qCInfo(lcDisco) << "NOTE: Checksums are identical, file did not actually change: " << path._local;
item->setInstruction(CSYNC_INSTRUCTION_UPDATE_METADATA);
}
}
}
finalize(path, recurseQueryServer);
return;
}
Q_ASSERT(!dbEntry.isValid());
if (localEntry.isVirtualFile && !noServerEntry) {
// Somehow there is a missing DB entry while the virtual file already exists.
// The instruction should already be set correctly.
OC_ASSERT(item->instruction() == CSYNC_INSTRUCTION_UPDATE_METADATA);
OC_ASSERT(item->_type == ItemTypeVirtualFile);
finalize(path, recurseQueryServer);
return;
} else if (serverModified) {
processFileConflict(item, path, localEntry, serverEntry, dbEntry);
finalize(path, recurseQueryServer);
return;
}
// New local file or rename
item->setInstruction(CSYNC_INSTRUCTION_NEW);
item->_direction = SyncFileItem::Up;
item->_checksumHeader.clear();
item->_size = localEntry.size;
item->_modtime = localEntry.modtime;
item->_type = localEntry.isDirectory ? ItemTypeDirectory : localEntry.isVirtualFile ? ItemTypeVirtualFile : ItemTypeFile;
_childModified = true;
auto postProcessLocalNew = [item, localEntry, this](const PathTuple &path) {
if (localEntry.isVirtualFile) {
const bool isPlaceHolder = _discoveryData->_syncOptions._vfs->isDehydratedPlaceholder(_discoveryData->_localDir + path._local);
if (isPlaceHolder) {
qCWarning(lcDisco) << "Wiping virtual file without db entry for" << path._local;
item->setInstruction(CSYNC_INSTRUCTION_REMOVE);
item->_direction = SyncFileItem::Down;
} else {
qCWarning(lcDisco) << "Virtual file without db entry for" << path._local
<< "but looks odd, keeping";
item->setInstruction(CSYNC_INSTRUCTION_IGNORE);
}
}
};
// Check if it is a move
OCC::SyncJournalFileRecord base;
if (!_discoveryData->_statedb->getFileRecordByInode(localEntry.inode, &base)) {
dbError();
return;
}
const auto originalPath = QString::fromUtf8(base._path);
// Function to gradually check conditions for accepting a move-candidate
auto moveCheck = [&]() {
if (!base.isValid()) {
qCInfo(lcDisco) << "Not a move, no item in db with inode" << localEntry.inode;
return false;
}
if (base.isDirectory() != item->isDirectory()) {
qCInfo(lcDisco) << "Not a move, types don't match" << base._type << item->_type << localEntry.type;
return false;
}
// Directories and virtual files don't need size/mtime equality
if (!localEntry.isDirectory && !base.isVirtualFile()
&& (base._modtime != localEntry.modtime || base._fileSize != localEntry.size)) {
qCInfo(lcDisco) << "Not a move, mtime or size differs, "
<< "modtime:" << base._modtime << localEntry.modtime << ", "
<< "size:" << base._fileSize << localEntry.size;
return false;
}
// The old file must have been deleted.
if (QFile::exists(_discoveryData->_localDir + originalPath)
// Exception: If the rename changes case only (like "foo" -> "Foo") the
// old filename might still point to the same file.
&& !(Utility::fsCasePreserving()
&& originalPath.compare(path._local, Qt::CaseInsensitive) == 0
&& originalPath != path._local)) {
qCInfo(lcDisco) << "Not a move, base file still exists at" << originalPath;
return false;
}
// Verify the checksum where possible
if (!base._checksumHeader.isEmpty() && item->_type == ItemTypeFile && base._type == ItemTypeFile) {
if (computeLocalChecksum(base._checksumHeader, _discoveryData->_localDir + path._original, item)) {
qCInfo(lcDisco) << "checking checksum of potential rename " << path._original << item->_checksumHeader << base._checksumHeader;
if (item->_checksumHeader != base._checksumHeader) {
qCInfo(lcDisco) << "Not a move, checksums differ";
return false;
}
}
}
if (_discoveryData->isRenamed(originalPath)) {
qCInfo(lcDisco) << "Not a move, base path already renamed";
return false;
}
return true;
};
// If it's not a move it's just a local-NEW
if (!moveCheck()) {
postProcessLocalNew(path);
finalize(path, recurseQueryServer);
return;
}
// Check local permission if we are allowed to put move the file here
// Technically we should use the permissions from the server, but we'll assume it is the same
auto movePerms = checkMovePermissions(base._remotePerm, originalPath, item->isDirectory());
if (!movePerms.sourceOk || !movePerms.destinationOk) {
qCInfo(lcDisco) << "Move without permission to rename base file, "
<< "source:" << movePerms.sourceOk
<< ", target:" << movePerms.destinationOk
<< ", targetNew:" << movePerms.destinationNewOk;
// If we can create the destination, do that.
// Permission errors on the destination will be handled by checkPermissions later.
postProcessLocalNew(path);
finalize(path, recurseQueryServer);
// If the destination upload will work, we're fine with the source deletion.
// If the source deletion can't work, checkPermissions will error.
if (movePerms.destinationNewOk)
return;
// Here we know the new location can't be uploaded: must prevent the source delete.
// Two cases: either the source item was already processed or not.
auto wasDeletedOnClient = _discoveryData->findAndCancelDeletedJob(originalPath);
if (wasDeletedOnClient.first) {
// More complicated. The REMOVE is canceled. Restore will happen next sync.
qCInfo(lcDisco) << "Undid remove instruction on source" << originalPath;
_discoveryData->_statedb->deleteFileRecord(originalPath, true);
_discoveryData->_statedb->schedulePathForRemoteDiscovery(originalPath);
_discoveryData->_anotherSyncNeeded = true;
} else {
// Signal to future checkPermissions() to forbid the REMOVE and set to restore instead
qCInfo(lcDisco) << "Preventing future remove on source" << originalPath;
_discoveryData->_forbiddenDeletes.insert(originalPath + QLatin1Char('/'));
}
return;
}
auto wasDeletedOnClient = _discoveryData->findAndCancelDeletedJob(originalPath);
auto processRename = [item, originalPath, base, this](PathTuple path) {
auto adjustedOriginalPath = _discoveryData->adjustRenamedPath(originalPath, SyncFileItem::Down);
_discoveryData->_renamedItemsLocal.insert(originalPath, path._target);
// TODO: move to SyncFileItem so its easier to refactor if item changes in any way...
item->_renameTarget = path._target;
path._server = adjustedOriginalPath;
item->_file = path._server;
path._original = originalPath;
item->_originalFile = path._original;
item->_modtime = base._modtime;
item->_inode = base._inode;
item->setInstruction(CSYNC_INSTRUCTION_RENAME);
item->_direction = SyncFileItem::Up;
item->_fileId = base._fileId;
item->_remotePerm = base._remotePerm;
item->_etag = QString::fromUtf8(base._etag);
item->_type = base._type;
// Discard any download/dehydrate tags on the base file.
// They could be preserved and honored in a follow-up sync,
// but it complicates handling a lot and will happen rarely.
if (item->_type == ItemTypeVirtualFileDownload) {
item->_type = ItemTypeVirtualFile;