-
Notifications
You must be signed in to change notification settings - Fork 919
Expand file tree
/
Copy pathowncloudpropagator.cpp
More file actions
1791 lines (1564 loc) · 69.3 KB
/
owncloudpropagator.cpp
File metadata and controls
1791 lines (1564 loc) · 69.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) by Olivier Goffart <ogoffart@owncloud.com>
* Copyright (C) by Klaas Freitag <freitag@owncloud.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 "owncloudpropagator.h"
#include "common/syncjournaldb.h"
#include "common/syncjournalfilerecord.h"
#include "propagatedownload.h"
#include "propagateupload.h"
#include "propagateremotedelete.h"
#include "propagateremotemove.h"
#include "propagateremotemkdir.h"
#include "bulkpropagatorjob.h"
#include "updatee2eefoldermetadatajob.h"
#include "updatemigratede2eemetadatajob.h"
#include "propagatorjobs.h"
#include "filesystem.h"
#include "common/utility.h"
#include "account.h"
#include "common/asserts.h"
#include "discoveryphase.h"
#include "syncfileitem.h"
#include "foldermetadata.h"
#ifdef Q_OS_WIN
#include <windef.h>
#include <winbase.h>
#endif
#include <QStack>
#include <QFileInfo>
#include <QDir>
#include <QLoggingCategory>
#include <QTimer>
#include <QObject>
#include <QTimerEvent>
#include <QRegularExpression>
#include <qmath.h>
namespace OCC {
Q_LOGGING_CATEGORY(lcPropagator, "nextcloud.sync.propagator", QtInfoMsg)
Q_LOGGING_CATEGORY(lcDirectory, "nextcloud.sync.propagator.directory", QtInfoMsg)
Q_LOGGING_CATEGORY(lcRootDirectory, "nextcloud.sync.propagator.root.directory", QtInfoMsg)
Q_LOGGING_CATEGORY(lcCleanupPolls, "nextcloud.sync.propagator.cleanuppolls", QtInfoMsg)
qint64 criticalFreeSpaceLimit()
{
qint64 value = 512 * 1000 * 1000LL;
static bool hasEnv = false;
static qint64 env = qgetenv("OWNCLOUD_CRITICAL_FREE_SPACE_BYTES").toLongLong(&hasEnv);
if (hasEnv) {
value = env;
}
return qBound(0LL, value, freeSpaceLimit());
}
qint64 freeSpaceLimit()
{
qint64 value = 1000 * 1000 * 1000LL;
static bool hasEnv = false;
static qint64 env = qgetenv("OWNCLOUD_FREE_SPACE_BYTES").toLongLong(&hasEnv);
if (hasEnv) {
value = env;
}
return value;
}
OwncloudPropagator::~OwncloudPropagator() = default;
int OwncloudPropagator::maximumActiveTransferJob()
{
if (_downloadLimit != 0
|| _uploadLimit != 0
|| !_syncOptions._parallelNetworkJobs) {
// disable parallelism when there is a network limit.
return 1;
}
return qMin(3, qCeil(_syncOptions._parallelNetworkJobs / 2.));
}
/* The maximum number of active jobs in parallel */
int OwncloudPropagator::hardMaximumActiveJob()
{
if (!_syncOptions._parallelNetworkJobs)
return 1;
return _syncOptions._parallelNetworkJobs;
}
PropagateItemJob::~PropagateItemJob()
{
if (auto p = propagator()) {
// Normally, every job should clean itself from the _activeJobList. So this should not be
// needed. But if a job has a bug or is deleted before the network jobs signal get received,
// we might risk end up with dangling pointer in the list which may cause crashes.
p->_activeJobList.removeAll(this);
}
}
static qint64 getMinBlacklistTime()
{
return qMax(qEnvironmentVariableIntValue("OWNCLOUD_BLACKLIST_TIME_MIN"),
25); // 25 seconds
}
static qint64 getMaxBlacklistTime()
{
int v = qEnvironmentVariableIntValue("OWNCLOUD_BLACKLIST_TIME_MAX");
if (v > 0)
return v;
return 24 * 60 * 60; // 1 day
}
/** Creates a blacklist entry, possibly taking into account an old one.
*
* The old entry may be invalid, then a fresh entry is created.
*/
static SyncJournalErrorBlacklistRecord createBlacklistEntry(
const SyncJournalErrorBlacklistRecord &old, const SyncFileItem &item)
{
SyncJournalErrorBlacklistRecord entry;
entry._file = item._file;
entry._errorString = item._errorString;
entry._lastTryModtime = item._modtime;
entry._lastTryEtag = item._etag;
entry._lastTryTime = Utility::qDateTimeToTime_t(QDateTime::currentDateTimeUtc());
entry._renameTarget = item._renameTarget;
entry._retryCount = old._retryCount + 1;
entry._requestId = item._requestId;
static qint64 minBlacklistTime(getMinBlacklistTime());
static qint64 maxBlacklistTime(qMax(getMaxBlacklistTime(), minBlacklistTime));
// The factor of 5 feels natural: 25s, 2 min, 10 min, ~1h, ~5h, ~24h
entry._ignoreDuration = old._ignoreDuration * 5;
if (item._httpErrorCode == 403) {
qCWarning(lcPropagator) << "Probably firewall error: " << item._httpErrorCode << ", blacklisting up to 1h only";
entry._ignoreDuration = qMin(entry._ignoreDuration, qint64(60 * 60));
} else if (item._httpErrorCode == 413 || item._httpErrorCode == 415) {
qCWarning(lcPropagator) << "Fatal Error condition" << item._httpErrorCode << ", maximum blacklist ignore time!";
entry._ignoreDuration = maxBlacklistTime;
}
entry._ignoreDuration = qBound(minBlacklistTime, entry._ignoreDuration, maxBlacklistTime);
if (item._status == SyncFileItem::SoftError) {
// Track these errors, but don't actively suppress them.
entry._ignoreDuration = 0;
}
if (item._httpErrorCode == 507) {
entry._errorCategory = SyncJournalErrorBlacklistRecord::InsufficientRemoteStorage;
}
return entry;
}
/** Updates, creates or removes a blacklist entry for the given item.
*
* May adjust the status or item._errorString.
*/
void blacklistUpdate(SyncJournalDb *journal, SyncFileItem &item)
{
SyncJournalErrorBlacklistRecord oldEntry = journal->errorBlacklistEntry(item._file);
bool mayBlacklist =
item._errorMayBeBlacklisted // explicitly flagged for blacklisting
|| ((item._status == SyncFileItem::NormalError
|| item._status == SyncFileItem::SoftError
|| item._status == SyncFileItem::DetailError)
&& item._httpErrorCode != 0 // or non-local error
);
// No new entry? Possibly remove the old one, then done.
if (!mayBlacklist) {
if (oldEntry.isValid()) {
journal->wipeErrorBlacklistEntry(item._file);
}
return;
}
auto newEntry = createBlacklistEntry(oldEntry, item);
journal->setErrorBlacklistEntry(newEntry);
// Suppress the error if it was and continues to be blacklisted.
// An ignoreDuration of 0 mean we're tracking the error, but not actively
// suppressing it.
if (item._hasBlacklistEntry && newEntry._ignoreDuration > 0) {
item._status = SyncFileItem::BlacklistedError;
qCInfo(lcPropagator) << "blacklisting " << item._file
<< " for " << newEntry._ignoreDuration
<< ", retry count " << newEntry._retryCount;
return;
}
// Some soft errors might become louder on repeat occurrence
if (item._status == SyncFileItem::SoftError
&& newEntry._retryCount > 1) {
qCWarning(lcPropagator) << "escalating soft error on " << item._file
<< " to normal error, " << item._httpErrorCode;
item._status = SyncFileItem::NormalError;
return;
}
}
void PropagateItemJob::done(const SyncFileItem::Status statusArg, const QString &errorString, const ErrorCategory category)
{
// Duplicate calls to done() are a logic error
ENFORCE(_state != Finished);
_state = Finished;
_item->_status = statusArg;
reportClientStatuses();
if (_item->_isRestoration) {
if (_item->_status == SyncFileItem::Success
|| _item->_status == SyncFileItem::Conflict) {
_item->_status = SyncFileItem::Restoration;
} else {
_item->_errorString += tr("; Restoration Failed: %1").arg(errorString);
}
} else {
if (_item->_errorString.isEmpty()) {
_item->_errorString = errorString;
}
}
if (propagator()->_abortRequested && (_item->_status == SyncFileItem::NormalError
|| _item->_status == SyncFileItem::FatalError)) {
// an abort request is ongoing. Change the status to Soft-Error
_item->_status = SyncFileItem::SoftError;
}
// Blacklist handling
switch (_item->_status) {
case SyncFileItem::SoftError:
case SyncFileItem::FatalError:
case SyncFileItem::NormalError:
case SyncFileItem::DetailError:
// Check the blacklist, possibly adjusting the item (including its status)
blacklistUpdate(propagator()->_journal, *_item);
break;
case SyncFileItem::Success:
case SyncFileItem::Restoration:
if (_item->_hasBlacklistEntry) {
// wipe blacklist entry.
propagator()->_journal->wipeErrorBlacklistEntry(_item->_file);
// remove a blacklist entry in case the file was moved.
if (_item->_originalFile != _item->_file) {
propagator()->_journal->wipeErrorBlacklistEntry(_item->_originalFile);
}
}
break;
case SyncFileItem::Conflict:
case SyncFileItem::FileIgnored:
case SyncFileItem::NoStatus:
case SyncFileItem::BlacklistedError:
case SyncFileItem::FileLocked:
case SyncFileItem::FileNameInvalid:
case SyncFileItem::FileNameInvalidOnServer:
case SyncFileItem::FileNameClash:
// nothing
break;
}
if (_item->hasErrorStatus())
qCWarning(lcPropagator) << "Could not complete propagation of" << _item->destination() << "by" << this << "with status" << _item->_status << "and error:" << _item->_errorString;
else
qCInfo(lcPropagator) << "Completed propagation of" << _item->destination() << "by" << this << "with status" << _item->_status;
emit propagator()->itemCompleted(_item, category);
emit finished(_item->_status);
if (_item->_status == SyncFileItem::FatalError) {
// Abort all remaining jobs.
propagator()->abort();
}
}
void PropagateItemJob::slotRestoreJobFinished(SyncFileItem::Status status)
{
QString msg;
if (_restoreJob) {
msg = _restoreJob->restoreJobMsg();
_restoreJob->setRestoreJobMsg();
}
if (status == SyncFileItem::Success || status == SyncFileItem::Conflict
|| status == SyncFileItem::Restoration) {
done(SyncFileItem::SoftError, msg, ErrorCategory::GenericError);
} else {
done(status, tr("A file or folder was removed from a read only share, but restoring failed: %1").arg(msg), ErrorCategory::GenericError);
}
}
bool PropagateItemJob::hasEncryptedAncestor() const
{
SyncJournalFileRecord rec;
return propagator()->_journal->findEncryptedAncestorForRecord(_item->_file, &rec)
&& rec.isValid() && rec.isE2eEncrypted();
}
void PropagateItemJob::reportClientStatuses()
{
if (_item->_status == SyncFileItem::Status::FileNameClash) {
if (_item->_direction != SyncFileItem::Direction::Up) {
propagator()->account()->reportClientStatus(ClientStatusReportingStatus::DownloadError_ConflictInvalidCharacters);
}
} else if (_item->_status == SyncFileItem::Status::FileNameInvalid) {
propagator()->account()->reportClientStatus(ClientStatusReportingStatus::DownloadError_ConflictInvalidCharacters);
} else if (_item->_httpErrorCode != HttpErrorCodeNone && _item->_httpErrorCode != HttpErrorCodeSuccess
&& _item->_httpErrorCode != HttpErrorCodeSuccessCreated && _item->_httpErrorCode != HttpErrorCodeSuccessNoContent) {
if (_item->_direction == SyncFileItem::Up) {
const auto isCodeBadReqOrUnsupportedMediaType =
(_item->_httpErrorCode == HttpErrorCodeBadRequest || _item->_httpErrorCode == HttpErrorCodeUnsupportedMediaType);
const auto isExceptionInfoPresent = !_item->_errorExceptionName.isEmpty() && !_item->_errorExceptionMessage.isEmpty();
if (isCodeBadReqOrUnsupportedMediaType && isExceptionInfoPresent && _item->_errorExceptionName.contains(QStringLiteral("UnsupportedMediaType"))
&& _item->_errorExceptionMessage.contains(QStringLiteral("virus"), Qt::CaseInsensitive)) {
propagator()->account()->reportClientStatus(ClientStatusReportingStatus::UploadError_Virus_Detected);
} else {
propagator()->account()->reportClientStatus(ClientStatusReportingStatus::UploadError_ServerError);
}
} else {
propagator()->account()->reportClientStatus(ClientStatusReportingStatus::DownloadError_ServerError);
}
}
}
// ================================================================================
PropagateItemJob *OwncloudPropagator::createJob(const SyncFileItemPtr &item)
{
bool deleteExisting = item->_instruction == CSYNC_INSTRUCTION_TYPE_CHANGE;
switch (item->_instruction) {
case CSYNC_INSTRUCTION_REMOVE:
if (item->_direction == SyncFileItem::Down)
return new PropagateLocalRemove(this, item);
else
return new PropagateRemoteDelete(this, item);
case CSYNC_INSTRUCTION_NEW:
case CSYNC_INSTRUCTION_TYPE_CHANGE:
case CSYNC_INSTRUCTION_CONFLICT:
if (item->isDirectory()) {
// CONFLICT has _direction == None
if (item->_direction != SyncFileItem::Up) {
auto job = new PropagateLocalMkdir(this, item);
job->setDeleteExistingFile(deleteExisting);
return job;
} else {
auto job = new PropagateRemoteMkdir(this, item);
job->setDeleteExisting(deleteExisting);
return job;
}
} //fall through
case CSYNC_INSTRUCTION_SYNC:
if (item->_direction != SyncFileItem::Up) {
auto job = new PropagateDownloadFile(this, item);
job->setDeleteExistingFolder(deleteExisting);
return job;
} else {
if (deleteExisting || !isDelayedUploadItem(item)) {
auto job = createUploadJob(item, deleteExisting);
return job.release();
} else {
pushDelayedUploadTask(item);
return nullptr;
}
}
case CSYNC_INSTRUCTION_RENAME:
if (item->_direction == SyncFileItem::Up) {
return new PropagateRemoteMove(this, item);
} else {
return new PropagateLocalRename(this, item);
}
case CSYNC_INSTRUCTION_UPDATE_VFS_METADATA:
return new PropagateVfsUpdateMetadataJob(this, item);
case CSYNC_INSTRUCTION_UPDATE_ENCRYPTION_METADATA:
{
const auto rootE2eeFolderPath = item->_file.split('/').first();
const auto rootE2eeFolderPathFullRemotePath = fullRemotePath(rootE2eeFolderPath);
return new UpdateMigratedE2eeMetadataJob(this, item, rootE2eeFolderPathFullRemotePath, remotePath());
}
case CSYNC_INSTRUCTION_IGNORE:
case CSYNC_INSTRUCTION_ERROR:
return new PropagateIgnoreJob(this, item);
case CSYNC_INSTRUCTION_NONE:
case CSYNC_INSTRUCTION_EVAL:
case CSYNC_INSTRUCTION_EVAL_RENAME:
case CSYNC_INSTRUCTION_STAT_ERROR:
case CSYNC_INSTRUCTION_UPDATE_METADATA:
case CSYNC_INSTRUCTION_CASE_CLASH_CONFLICT:
return nullptr;
}
return nullptr;
}
std::unique_ptr<PropagateUploadFileCommon> OwncloudPropagator::createUploadJob(SyncFileItemPtr item, bool deleteExisting)
{
auto job = std::unique_ptr<PropagateUploadFileCommon>{};
if (item->_size > syncOptions()._initialChunkSize && account()->capabilities().chunkingNg()) {
// Item is above _initialChunkSize, thus will be classified as to be chunked
job = std::make_unique<PropagateUploadFileNG>(this, item);
} else {
job = std::make_unique<PropagateUploadFileV1>(this, item);
}
job->setDeleteExisting(deleteExisting);
return job;
}
void OwncloudPropagator::pushDelayedUploadTask(SyncFileItemPtr item)
{
_delayedTasks.push_back(item);
}
void OwncloudPropagator::resetDelayedUploadTasks()
{
_scheduleDelayedTasks = false;
_delayedTasks.clear();
}
void OwncloudPropagator::adjustDeletedFoldersWithNewChildren(SyncFileItemVector &items)
{
/*
process each item that is new and is a directory and make sure every parent in its tree has the instruction CSYNC_INSTRUCTION_NEW
instead of CSYNC_INSTRUCTION_REMOVE
NOTE: We are iterating backwards to take advantage of optimization later, when searching for the parent of current it
*/
for (auto it = std::crbegin(items); it != std::crend(items); ++it) {
if ((*it)->_instruction != CSYNC_INSTRUCTION_NEW || (*it)->_direction != SyncFileItem::Up || !(*it)->isDirectory() || (*it)->_file == QStringLiteral("/")) {
continue;
}
// #1 get root folder name for the current item that we need to reupload
const auto folderPathSplit = (*it)->_file.split(QLatin1Char('/'), Qt::SkipEmptyParts);
if (folderPathSplit.isEmpty()) {
continue;
}
const auto itemRootFolderName = folderPathSplit.first();
if (itemRootFolderName.isEmpty()) {
continue;
}
// #2 iterate backwards (for optimization) and find the root folder by name
const auto itemRootFolderReverseIt = std::find_if(it, std::crend(items), [&itemRootFolderName](const auto ¤tItem) {
return currentItem->_file == itemRootFolderName;
});
if (itemRootFolderReverseIt == std::rend(items)) {
continue;
}
// #3 convert reverse iterator to normal iterator
const auto itemFolderIt = (itemRootFolderReverseIt + 1).base();
// #4 if the root folder is set to be removed, then we will need to fix this by reuploading every folder in
// the tree, including the root
if (itemFolderIt == std::end(items)) {
continue;
}
auto nextFolderInTreeIt = itemFolderIt;
do {
// #5 Iterate forward from the CSYNC_INSTRUCTION_NEW folder's root, and make sure every folder in it's tree is set to CSYNC_INSTRUCTION_NEW
if ((*nextFolderInTreeIt)->isDirectory()
&& (*nextFolderInTreeIt)->_instruction == CSYNC_INSTRUCTION_REMOVE
&& (*nextFolderInTreeIt)->_direction == SyncFileItem::Down
&& (*it)->_file.startsWith(QString((*nextFolderInTreeIt)->_file) + QLatin1Char('/'))) {
qCWarning(lcPropagator) << "WARNING: New directory to upload " << (*it)->_file
<< "is in the removed directories tree " << (*nextFolderInTreeIt)->_file
<< " This should not happen! But, we are going to reupload the entire folder structure.";
(*nextFolderInTreeIt)->_instruction = CSYNC_INSTRUCTION_NEW;
(*nextFolderInTreeIt)->_direction = SyncFileItem::Up;
}
++nextFolderInTreeIt;
} while (nextFolderInTreeIt != std::end(items) && (*nextFolderInTreeIt)->_file != (*it)->_file);
}
}
qint64 OwncloudPropagator::smallFileSize()
{
const qint64 smallFileSize = 100 * 1024; //default to 1 MB. Not dynamic right now.
return smallFileSize;
}
void OwncloudPropagator::start(SyncFileItemVector &&items)
{
Q_ASSERT(std::is_sorted(items.begin(), items.end()));
_abortRequested = false;
/* This builds all the jobs needed for the propagation.
* Each directory is a PropagateDirectory job, which contains the files in it.
* In order to do that we loop over the items. (which are sorted by destination)
* When we enter a directory, we can create the directory job and push it on the stack. */
const auto regex = syncOptions().fileRegex();
if (regex.isValid()) {
QSet<QStringView> names;
for (auto &i : items) {
if (regex.match(i->_file).hasMatch()) {
int index = -1;
QStringView ref;
do {
ref = i->_file.mid(0, index);
names.insert(ref);
index = ref.lastIndexOf(QLatin1Char('/'));
} while (index > 0);
}
}
items.erase(std::remove_if(items.begin(), items.end(), [&names](auto i) {
return !names.contains(QStringView { i->_file });
}),
items.end());
}
QStringList files;
for (const auto &item : items) {
files.push_back(item->_file);
}
// process each item that is new and is a directory and make sure every parent in its tree has the instruction NEW instead of REMOVE
adjustDeletedFoldersWithNewChildren(items);
resetDelayedUploadTasks();
_rootJob.reset(new PropagateRootDirectory(this));
QStack<QPair<QString /* directory name */, PropagateDirectory * /* job */>> directories;
directories.push(qMakePair(QString(), _rootJob.data()));
QVector<PropagatorJob *> directoriesToRemove;
QString removedDirectory;
QString maybeConflictDirectory;
for (const SyncFileItemPtr &item : std::as_const(items)) {
if (!removedDirectory.isEmpty() && item->_file.startsWith(removedDirectory)) {
// this is an item in a directory which is going to be removed.
auto *delDirJob = qobject_cast<PropagateDirectory *>(directoriesToRemove.first());
const auto isNewDirectory = item->isDirectory() &&
(item->_instruction == CSYNC_INSTRUCTION_NEW || item->_instruction == CSYNC_INSTRUCTION_TYPE_CHANGE);
if (item->_instruction == CSYNC_INSTRUCTION_REMOVE || isNewDirectory) {
// If it is a remove it is already taken care of by the removal of the parent directory
// If it is a new directory then it is inside a deleted directory... That can happen if
// the directory etag was not fetched properly on the previous sync because the sync was
// aborted while uploading this directory (which is now removed). We can ignore it.
// increase the number of subjobs that would be there.
if (delDirJob) {
delDirJob->increaseAffectedCount();
}
continue;
} else if (item->_instruction == CSYNC_INSTRUCTION_IGNORE) {
continue;
} else if (item->_instruction == CSYNC_INSTRUCTION_RENAME) {
// all is good, the rename will be executed before the directory deletion
} else {
qCWarning(lcPropagator) << "WARNING: Job within a removed directory? This should not happen!"
<< item->_file << item->_instruction;
}
}
// If a CONFLICT item contains files these can't be processed because
// the conflict handling is likely to rename the directory. This can happen
// when there's a new local directory at the same time as a remote file.
if (!maybeConflictDirectory.isEmpty()) {
if (item->destination().startsWith(maybeConflictDirectory)) {
qCInfo(lcPropagator) << "Skipping job inside CONFLICT directory"
<< item->_file << item->_instruction;
item->_instruction = CSYNC_INSTRUCTION_NONE;
continue;
} else {
maybeConflictDirectory.clear();
}
}
while (!item->destination().startsWith(directories.top().first)) {
directories.pop();
}
if (item->isDirectory()) {
startDirectoryPropagation(item,
directories,
directoriesToRemove,
removedDirectory,
items);
} else if (!directories.top().second->_item->_isFileDropDetected) {
startFilePropagation(item,
directories,
directoriesToRemove,
removedDirectory,
maybeConflictDirectory);
}
}
for (const auto it : std::as_const(directoriesToRemove)) {
_rootJob->appendDirDeletionJob(it);
}
connect(_rootJob.data(), &PropagatorJob::finished, this, &OwncloudPropagator::emitFinished);
_jobScheduled = false;
scheduleNextJob();
}
void OwncloudPropagator::startDirectoryPropagation(const SyncFileItemPtr &item,
QStack<QPair<QString, PropagateDirectory *>> &directories,
QVector<PropagatorJob *> &directoriesToRemove,
QString &removedDirectory,
const SyncFileItemVector &items)
{
auto directoryPropagationJob = std::make_unique<PropagateDirectory>(this, item);
if (item->_instruction == CSYNC_INSTRUCTION_TYPE_CHANGE
&& item->_direction == SyncFileItem::Up) {
// Skip all potential uploads to the new folder.
// Processing them now leads to problems with permissions:
// checkForPermissions() has already run and used the permissions
// of the file we're about to delete to decide whether uploading
// to the new dir is ok...
for (const auto &dirItem : items) {
if (dirItem->destination().startsWith(item->destination() + "/")) {
dirItem->_instruction = CSYNC_INSTRUCTION_NONE;
_anotherSyncNeeded = true;
}
}
}
if (item->_instruction == CSYNC_INSTRUCTION_REMOVE) {
// We do the removal of directories at the end, because there might be moves from
// these directories that will happen later.
directoriesToRemove.prepend(directoryPropagationJob.get());
removedDirectory = item->_file + "/";
// We should not update the etag of parent directories of the removed directory
// since it would be done before the actual remove (issue #1845)
// NOTE: Currently this means that we don't update those etag at all in this sync,
// but it should not be a problem, they will be updated in the next sync.
for (int i = 0; i < directories.size(); ++i) {
if (directories[i].second->_item->_instruction == CSYNC_INSTRUCTION_UPDATE_METADATA) {
directories[i].second->_item->_instruction = CSYNC_INSTRUCTION_NONE;
}
}
} else {
const auto currentDirJob = directories.top().second;
currentDirJob->appendJob(directoryPropagationJob.get());
}
directories.push(qMakePair(item->destination() + "/", directoryPropagationJob.release()));
if (item->_isFileDropDetected) {
const auto currentDirJob = directories.top().second;
currentDirJob->appendJob(new UpdateE2eeFolderMetadataJob(this, item, item->_file));
item->_instruction = CSYNC_INSTRUCTION_UPDATE_METADATA;
_anotherSyncNeeded = true;
} else if (item->_isEncryptedMetadataNeedUpdate) {
processE2eeMetadataMigration(item, directories);
}
}
void OwncloudPropagator::startFilePropagation(const SyncFileItemPtr &item,
QStack<QPair<QString, PropagateDirectory *> > &directories,
QVector<PropagatorJob *> &directoriesToRemove,
QString &removedDirectory,
QString &maybeConflictDirectory)
{
if (item->_instruction == CSYNC_INSTRUCTION_TYPE_CHANGE) {
// will delete directories, so defer execution
auto job = createJob(item);
if (job) {
directoriesToRemove.prepend(job);
}
removedDirectory = item->_file + "/";
} else {
directories.top().second->appendTask(item);
}
if (item->_instruction == CSYNC_INSTRUCTION_CONFLICT) {
// This might be a file or a directory on the local side. If it's a
// directory we want to skip processing items inside it.
maybeConflictDirectory = item->_file + "/";
}
}
void OwncloudPropagator::processE2eeMetadataMigration(const SyncFileItemPtr &item, QStack<QPair<QString, PropagateDirectory *>> &directories)
{
if (item->_e2eEncryptionServerCapability >= EncryptionStatusEnums::ItemEncryptionStatus::EncryptedMigratedV2_0) {
// migrating to v2.0+
const auto rootE2eeFolderPath = item->_file.split('/').first();
const auto rootE2eeFolderPathWithSlash = QString(rootE2eeFolderPath + "/");
QPair<QString, PropagateDirectory *> foundDirectory = {QString{}, nullptr};
for (auto it = std::rbegin(directories); it != std::rend(directories); ++it) {
if (it->first == rootE2eeFolderPathWithSlash) {
foundDirectory = *it;
break;
}
}
UpdateMigratedE2eeMetadataJob *existingUpdateJob = nullptr;
SyncFileItemPtr topLevelitem = item;
if (foundDirectory.second) {
topLevelitem = foundDirectory.second->_item;
if (!foundDirectory.second->_subJobs._jobsToDo.isEmpty()) {
for (const auto jobToDo : foundDirectory.second->_subJobs._jobsToDo) {
if (const auto foundExistingUpdateMigratedE2eeMetadataJob = qobject_cast<UpdateMigratedE2eeMetadataJob *>(jobToDo)) {
existingUpdateJob = foundExistingUpdateMigratedE2eeMetadataJob;
break;
}
}
}
}
if (!existingUpdateJob) {
// we will need to update topLevelitem encryption status so it gets written to database
const auto currentDirJob = directories.top().second;
const auto rootE2eeFolderPathFullRemotePath = fullRemotePath(rootE2eeFolderPath);
const auto updateMetadataJob = new UpdateMigratedE2eeMetadataJob(this, topLevelitem, rootE2eeFolderPathFullRemotePath, remotePath());
if (item != topLevelitem) {
updateMetadataJob->addSubJobItem(item->_encryptedFileName, item);
}
currentDirJob->appendJob(updateMetadataJob);
} else {
if (item != topLevelitem) {
// simply append subJob item so we can set its encryption status when corresponging subjob finishes
existingUpdateJob->addSubJobItem(item->_encryptedFileName, item);
}
}
} else {
// migrating to v1.2
const auto remoteFilename = item->_encryptedFileName.isEmpty() ? item->_file : item->_encryptedFileName;
const auto currentDirJob = directories.top().second;
currentDirJob->appendJob(new UpdateE2eeFolderMetadataJob(this, item, remoteFilename));
}
item->_instruction = CSYNC_INSTRUCTION_UPDATE_METADATA;
}
const SyncOptions &OwncloudPropagator::syncOptions() const
{
return _syncOptions;
}
void OwncloudPropagator::setSyncOptions(const SyncOptions &syncOptions)
{
_syncOptions = syncOptions;
_chunkSize = syncOptions._initialChunkSize;
}
bool OwncloudPropagator::localFileNameClash(const QString &relFile)
{
const QString file(_localDir + relFile);
Q_ASSERT(!file.isEmpty());
if (!file.isEmpty() && Utility::fsCasePreserving()) {
#ifdef Q_OS_MAC
const QFileInfo fileInfo(file);
if (!fileInfo.exists()) {
return false;
} else {
// Need to normalize to composited form because of QTBUG-39622/QTBUG-55896
const QString cName = fileInfo.canonicalFilePath().normalized(QString::NormalizationForm_C);
if (file != cName && !cName.endsWith(relFile, Qt::CaseSensitive)) {
qCWarning(lcPropagator) << "Detected case clash between" << file << "and" << cName;
return true;
}
}
#elif defined(Q_OS_WIN)
WIN32_FIND_DATA FindFileData;
HANDLE hFind = nullptr;
hFind = FindFirstFileW(reinterpret_cast<const wchar_t *>(FileSystem::longWinPath(file).utf16()), &FindFileData);
if (hFind == INVALID_HANDLE_VALUE) {
// returns false.
} else {
const QString realFileName = QString::fromWCharArray(FindFileData.cFileName);
FindClose(hFind);
if (!file.endsWith(realFileName, Qt::CaseSensitive)) {
qCWarning(lcPropagator) << "Detected case clash between" << file << "and" << realFileName;
return true;
}
}
#else
// On Linux, the file system is case sensitive, but this code is useful for testing.
// Just check that there is no other file with the same name and different casing.
QFileInfo fileInfo(file);
const QString fn = fileInfo.fileName();
const QStringList list = fileInfo.dir().entryList({ fn });
if (list.count() > 1 || (list.count() == 1 && list[0] != fn)) {
qCWarning(lcPropagator) << "Detected case clash between" << file << "and" << list.constFirst();
return true;
}
#endif
}
return false;
}
bool OwncloudPropagator::hasCaseClashAccessibilityProblem(const QString &relfile)
{
#ifdef Q_OS_WIN
bool result = false;
const QString file(_localDir + relfile);
WIN32_FIND_DATA FindFileData;
HANDLE hFind = nullptr;
hFind = FindFirstFileW(reinterpret_cast<const wchar_t *>(FileSystem::longWinPath(file).utf16()), &FindFileData);
if (hFind != INVALID_HANDLE_VALUE) {
QString firstFile = QString::fromWCharArray(FindFileData.cFileName);
if (FindNextFile(hFind, &FindFileData)) {
QString secondFile = QString::fromWCharArray(FindFileData.cFileName);
// This extra check shouldn't be necessary, but ensures that there
// are two different filenames that are identical when case is ignored.
if (firstFile != secondFile
&& QString::compare(firstFile, secondFile, Qt::CaseInsensitive) == 0) {
result = true;
qCWarning(lcPropagator) << "Found two filepaths that only differ in case: " << firstFile << secondFile;
}
}
FindClose(hFind);
}
return result;
#else
Q_UNUSED(relfile);
return false;
#endif
}
QString OwncloudPropagator::fullLocalPath(const QString &tmp_file_name) const
{
return _localDir + tmp_file_name;
}
QString OwncloudPropagator::localPath() const
{
return _localDir;
}
void OwncloudPropagator::scheduleNextJob()
{
if (_jobScheduled) return; // don't schedule more than 1
_jobScheduled = true;
QTimer::singleShot(3, this, &OwncloudPropagator::scheduleNextJobImpl);
}
void OwncloudPropagator::scheduleNextJobImpl()
{
// TODO: If we see that the automatic up-scaling has a bad impact we
// need to check how to avoid this.
// Down-scaling on slow networks? https://github.com/owncloud/client/issues/3382
// Making sure we do up/down at same time? https://github.com/owncloud/client/issues/1633
_jobScheduled = false;
if (_activeJobList.count() < maximumActiveTransferJob()) {
if (_rootJob->scheduleSelfOrChild()) {
scheduleNextJob();
}
} else if (_activeJobList.count() < hardMaximumActiveJob()) {
int likelyFinishedQuicklyCount = 0;
// NOTE: Only counts the first 3 jobs! Then for each
// one that is likely finished quickly, we can launch another one.
// When a job finishes another one will "move up" to be one of the first 3 and then
// be counted too.
for (int i = 0; i < maximumActiveTransferJob() && i < _activeJobList.count(); i++) {
if (_activeJobList.at(i)->isLikelyFinishedQuickly()) {
likelyFinishedQuicklyCount++;
}
}
if (_activeJobList.count() < maximumActiveTransferJob() + likelyFinishedQuicklyCount) {
qCDebug(lcPropagator) << "Can pump in another request! activeJobs =" << _activeJobList.count();
if (_rootJob->scheduleSelfOrChild()) {
scheduleNextJob();
}
}
}
}
void OwncloudPropagator::reportProgress(const SyncFileItem &item, qint64 bytes)
{
emit progress(item, bytes);
}
AccountPtr OwncloudPropagator::account() const
{
return _account;
}
OwncloudPropagator::DiskSpaceResult OwncloudPropagator::diskSpaceCheck() const
{
const qint64 freeBytes = Utility::freeDiskSpace(_localDir);
if (freeBytes < 0) {
return DiskSpaceOk;
}
if (freeBytes < criticalFreeSpaceLimit()) {
return DiskSpaceCritical;
}
if (freeBytes - _rootJob->committedDiskSpace() < freeSpaceLimit()) {
return DiskSpaceFailure;
}
return DiskSpaceOk;
}
bool OwncloudPropagator::createConflict(const SyncFileItemPtr &item,
PropagatorCompositeJob *composite, QString *error)
{
QString fn = fullLocalPath(item->_file);
QString renameError;
auto conflictModTime = FileSystem::getModTime(fn);
if (conflictModTime <= 0) {
*error = tr("Impossible to get modification time for file in conflict %1").arg(fn);
return false;
}
QString conflictUserName;
if (account()->capabilities().uploadConflictFiles())
conflictUserName = account()->davDisplayName();
QString conflictFileName = Utility::makeConflictFileName(
item->_file, Utility::qDateTimeFromTime_t(conflictModTime), conflictUserName);
QString conflictFilePath = fullLocalPath(conflictFileName);
emit touchedFile(fn);
emit touchedFile(conflictFilePath);
if (!FileSystem::rename(fn, conflictFilePath, &renameError)) {
// If the rename fails, don't replace it.
// If the file is locked, we want to retry this sync when it
// becomes available again.
if (FileSystem::isFileLocked(fn)) {
emit seenLockedFile(fn);
}
if (error)
*error = renameError;
return false;
}
qCInfo(lcPropagator) << "Created conflict file" << fn << "->" << conflictFileName;
// Create a new conflict record. To get the base etag, we need to read it from the db.
ConflictRecord conflictRecord;
conflictRecord.path = conflictFileName.toUtf8();
conflictRecord.baseModtime = item->_previousModtime;
conflictRecord.initialBasePath = item->_file.toUtf8();
SyncJournalFileRecord baseRecord;
if (_journal->getFileRecord(item->_originalFile, &baseRecord) && baseRecord.isValid()) {
conflictRecord.baseEtag = baseRecord._etag;
conflictRecord.baseFileId = baseRecord._fileId;
} else {
// We might very well end up with no fileid/etag for new/new conflicts
}
_journal->setConflictRecord(conflictRecord);
// Create a new upload job if the new conflict file should be uploaded
if (account()->capabilities().uploadConflictFiles()) {
if (composite && !QFileInfo(conflictFilePath).isDir()) {
SyncFileItemPtr conflictItem = SyncFileItemPtr(new SyncFileItem);
conflictItem->_file = conflictFileName;
conflictItem->_type = ItemTypeFile;
conflictItem->_direction = SyncFileItem::Up;
conflictItem->_instruction = CSYNC_INSTRUCTION_NEW;
conflictItem->_modtime = conflictModTime;
conflictItem->_size = item->_previousSize;
emit newItem(conflictItem);
composite->appendTask(conflictItem);
}
}
// Need a new sync to detect the created copy of the conflicting file
_anotherSyncNeeded = true;
return true;
}