forked from meganz/sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync.cpp
More file actions
2008 lines (1750 loc) · 67.4 KB
/
sync.cpp
File metadata and controls
2008 lines (1750 loc) · 67.4 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
/**
* @file sync.cpp
* @brief Class for synchronizing local and remote trees
*
* (c) 2013-2014 by Mega Limited, Auckland, New Zealand
*
* This file is part of the MEGA SDK - Client Access Engine.
*
* Applications using the MEGA API must present a valid application key
* and comply with the the rules set forth in the Terms of Service.
*
* The MEGA SDK 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.
*
* @copyright Simplified (2-clause) BSD License.
*
* You should have received a copy of the license along with this
* program.
*/
#include <type_traits>
#include <unordered_set>
#include "mega.h"
#ifdef ENABLE_SYNC
#include "mega/sync.h"
#include "mega/megaapp.h"
#include "mega/transfer.h"
#include "mega/megaclient.h"
#include "mega/base64.h"
namespace mega {
const int Sync::SCANNING_DELAY_DS = 5;
const int Sync::EXTRA_SCANNING_DELAY_DS = 150;
const int Sync::FILE_UPDATE_DELAY_DS = 30;
const int Sync::FILE_UPDATE_MAX_DELAY_SECS = 60;
const dstime Sync::RECENT_VERSION_INTERVAL_SECS = 10800;
namespace {
// Need this to store `LightFileFingerprint` by-value in `FingerprintSet`
struct LightFileFingerprintComparator
{
bool operator()(const LightFileFingerprint& lhs, const LightFileFingerprint& rhs) const
{
return LightFileFingerprintCmp{}(&lhs, &rhs);
}
};
// Represents a file/folder for use in assigning fs IDs
struct FsFile
{
handle fsid;
LocalPath path;
};
// Caches fingerprints
class FingerprintCache
{
public:
using FingerprintSet = std::set<LightFileFingerprint, LightFileFingerprintComparator>;
// Adds a new fingerprint
template<typename T, typename = typename std::enable_if<std::is_same<LightFileFingerprint, typename std::decay<T>::type>::value>::type>
const LightFileFingerprint* add(T&& ffp)
{
const auto insertPair = mFingerprints.insert(std::forward<T>(ffp));
return &*insertPair.first;
}
// Returns the set of all fingerprints
const FingerprintSet& all() const
{
return mFingerprints;
}
private:
FingerprintSet mFingerprints;
};
using FingerprintLocalNodeMap = std::multimap<const LightFileFingerprint*, LocalNode*, LightFileFingerprintCmp>;
using FingerprintFileMap = std::multimap<const LightFileFingerprint*, FsFile, LightFileFingerprintCmp>;
// Collects all syncable filesystem paths in the given folder under `localpath`
set<LocalPath> collectAllPathsInFolder(Sync& sync, MegaApp& app, FileSystemAccess& fsaccess, LocalPath& localpath,
LocalPath& localdebris)
{
auto fa = fsaccess.newfileaccess(false);
if (!fa->fopen(localpath, true, false))
{
LOG_err << "Unable to open path: " << localpath.toPath(fsaccess);
return {};
}
if (fa->mIsSymLink)
{
LOG_debug << "Ignoring symlink: " << localpath.toPath(fsaccess);
return {};
}
assert(fa->type == FOLDERNODE);
auto da = std::unique_ptr<DirAccess>{fsaccess.newdiraccess()};
if (!da->dopen(&localpath, fa.get(), false))
{
LOG_err << "Unable to open directory: " << localpath.toPath(fsaccess);
return {};
}
set<LocalPath> paths; // has to be a std::set to enforce same sorting as `children` of `LocalNode`
LocalPath localname;
while (da->dnext(localpath, localname, false))
{
ScopedLengthRestore restoreLength(localpath);
localpath.appendWithSeparator(localname, false, fsaccess.localseparator);
// check if this record is to be ignored
if (app.sync_syncable(&sync, localname.toName(fsaccess).c_str(), localpath))
{
// skip the sync's debris folder
if (!localdebris.isContainingPathOf(localpath, fsaccess))
{
paths.insert(localpath);
}
}
}
return paths;
}
// Combines another fingerprint into `ffp`
void hashCombineFingerprint(LightFileFingerprint& ffp, const LightFileFingerprint& other)
{
hashCombine(ffp.size, other.size);
hashCombine(ffp.mtime, other.mtime);
}
// Combines the fingerprints of all file nodes in the given map
bool combinedFingerprint(LightFileFingerprint& ffp, const localnode_map& nodeMap)
{
bool success = false;
for (const auto& nodePair : nodeMap)
{
const LocalNode& l = *nodePair.second;
if (l.type == FILENODE)
{
LightFileFingerprint lFfp;
lFfp.genfingerprint(l.size, l.mtime);
hashCombineFingerprint(ffp, lFfp);
success = true;
}
}
return success;
}
// Combines the fingerprints of all files in the given paths
bool combinedFingerprint(LightFileFingerprint& ffp, FileSystemAccess& fsaccess, const set<LocalPath>& paths)
{
bool success = false;
for (auto& path : paths)
{
auto fa = fsaccess.newfileaccess(false);
auto pathArg = path; // todo: sort out const
if (!fa->fopen(pathArg, true, false))
{
LOG_err << "Unable to open path: " << path.toPath(fsaccess);
success = false;
break;
}
if (fa->mIsSymLink)
{
LOG_debug << "Ignoring symlink: " << path.toPath(fsaccess);
continue;
}
if (fa->type == FILENODE)
{
LightFileFingerprint faFfp;
faFfp.genfingerprint(fa->size, fa->mtime);
hashCombineFingerprint(ffp, faFfp);
success = true;
}
}
return success;
}
// Computes the fingerprint of the given `l` (file or folder) and stores it in `ffp`
bool computeFingerprint(LightFileFingerprint& ffp, const LocalNode& l)
{
if (l.type == FILENODE)
{
ffp.genfingerprint(l.size, l.mtime);
return true;
}
else if (l.type == FOLDERNODE)
{
return combinedFingerprint(ffp, l.children);
}
else
{
assert(false && "Invalid node type");
return false;
}
}
// Computes the fingerprint of the given `fa` (file or folder) and stores it in `ffp`
bool computeFingerprint(LightFileFingerprint& ffp, FileSystemAccess& fsaccess,
FileAccess& fa, LocalPath& path, const set<LocalPath>& paths)
{
if (fa.type == FILENODE)
{
assert(paths.empty());
ffp.genfingerprint(fa.size, fa.mtime);
return true;
}
else if (fa.type == FOLDERNODE)
{
return combinedFingerprint(ffp, fsaccess, paths);
}
else
{
assert(false && "Invalid node type");
return false;
}
}
// Collects all `LocalNode`s by storing them in `localnodes`, keyed by LightFileFingerprint.
// Invalidates the fs IDs of all local nodes.
// Stores all fingerprints in `fingerprints` for later reference.
void collectAllLocalNodes(FingerprintCache& fingerprints, FingerprintLocalNodeMap& localnodes,
LocalNode& l, handlelocalnode_map& fsidnodes)
{
// invalidate fsid of `l`
l.fsid = mega::UNDEF;
if (l.fsid_it != fsidnodes.end())
{
fsidnodes.erase(l.fsid_it);
l.fsid_it = fsidnodes.end();
}
// collect fingerprint
LightFileFingerprint ffp;
if (computeFingerprint(ffp, l))
{
const auto ffpPtr = fingerprints.add(std::move(ffp));
localnodes.insert(std::make_pair(ffpPtr, &l));
}
if (l.type == FILENODE)
{
return;
}
for (auto& childPair : l.children)
{
collectAllLocalNodes(fingerprints, localnodes, *childPair.second, fsidnodes);
}
}
// Collects all `File`s by storing them in `files`, keyed by FileFingerprint.
// Stores all fingerprints in `fingerprints` for later reference.
void collectAllFiles(bool& success, FingerprintCache& fingerprints, FingerprintFileMap& files,
Sync& sync, MegaApp& app, FileSystemAccess& fsaccess, LocalPath& localpath,
LocalPath& localdebris)
{
auto insertFingerprint = [&files, &fingerprints](FileSystemAccess& fsaccess, FileAccess& fa,
LocalPath& path, const set<LocalPath>& paths)
{
LightFileFingerprint ffp;
if (computeFingerprint(ffp, fsaccess, fa, path, paths))
{
const auto ffpPtr = fingerprints.add(std::move(ffp));
files.insert(std::make_pair(ffpPtr, FsFile{fa.fsid, path}));
}
};
auto fa = fsaccess.newfileaccess(false);
if (!fa->fopen(localpath, true, false))
{
LOG_err << "Unable to open path: " << localpath.toPath(fsaccess);
success = false;
return;
}
if (fa->mIsSymLink)
{
LOG_debug << "Ignoring symlink: " << localpath.toPath(fsaccess);
return;
}
if (!fa->fsidvalid)
{
LOG_err << "Invalid fs id for: " << localpath.toPath(fsaccess);
success = false;
return;
}
if (fa->type == FILENODE)
{
insertFingerprint(fsaccess, *fa, localpath, {});
}
else if (fa->type == FOLDERNODE)
{
const auto paths = collectAllPathsInFolder(sync, app, fsaccess, localpath, localdebris);
insertFingerprint(fsaccess, *fa, localpath, paths);
fa.reset();
for (const auto& path : paths)
{
LocalPath tmpPath = path;
collectAllFiles(success, fingerprints, files, sync, app, fsaccess, tmpPath, localdebris);
}
}
else
{
assert(false && "Invalid file type");
success = false;
return;
}
}
// Assigns fs IDs from `files` to those `localnodes` that match the fingerprints found in `files`.
// If there are multiple matches we apply a best-path heuristic.
size_t assignFilesystemIdsImpl(const FingerprintCache& fingerprints, FingerprintLocalNodeMap& localnodes,
FingerprintFileMap& files, handlelocalnode_map& fsidnodes, FileSystemAccess& fsaccess)
{
LocalPath nodePath;
string accumulated;
size_t assignmentCount = 0;
for (const auto& fp : fingerprints.all())
{
const auto nodeRange = localnodes.equal_range(&fp);
const auto nodeCount = std::distance(nodeRange.first, nodeRange.second);
if (nodeCount <= 0)
{
continue;
}
const auto fileRange = files.equal_range(&fp);
const auto fileCount = std::distance(fileRange.first, fileRange.second);
if (fileCount <= 0)
{
// without files we cannot assign fs IDs to these localnodes, so no need to keep them
localnodes.erase(nodeRange.first, nodeRange.second);
continue;
}
struct Element
{
int score;
handle fsid;
LocalNode* l;
};
std::vector<Element> elements;
elements.reserve(nodeCount * fileCount);
for (auto nodeIt = nodeRange.first; nodeIt != nodeRange.second; ++nodeIt)
{
auto l = nodeIt->second;
if (l != l->sync->localroot.get()) // never assign fs ID to the root localnode
{
nodePath = l->getLocalPath(false);
for (auto fileIt = fileRange.first; fileIt != fileRange.second; ++fileIt)
{
auto& filePath = fileIt->second.path;
const auto score = computeReversePathMatchScore(accumulated, nodePath, filePath, fsaccess);
if (score > 0) // leaf name must match
{
elements.push_back({score, fileIt->second.fsid, l});
}
}
}
}
// Sort in descending order by score. Elements with highest score come first
std::sort(elements.begin(), elements.end(), [](const Element& e1, const Element& e2)
{
return e1.score > e2.score;
});
std::unordered_set<handle> usedFsIds;
for (const auto& e : elements)
{
if (e.l->fsid == mega::UNDEF // node not assigned
&& usedFsIds.find(e.fsid) == usedFsIds.end()) // fsid not used
{
e.l->setfsid(e.fsid, fsidnodes);
usedFsIds.insert(e.fsid);
++assignmentCount;
}
}
// the fingerprint that these files and localnodes correspond to has now finished processing
files.erase(fileRange.first, fileRange.second);
localnodes.erase(nodeRange.first, nodeRange.second);
}
return assignmentCount;
}
} // anonymous
int computeReversePathMatchScore(string& accumulated, const LocalPath& path1Arg, const LocalPath& path2Arg, const FileSystemAccess& fsaccess)
{
const string& path1 = *path1Arg.editStringDirect();
const string& path2 = *path2Arg.editStringDirect();
if (path1.empty() || path2.empty())
{
return 0;
}
accumulated.clear();
const auto path1End = path1.size() - 1;
const auto path2End = path2.size() - 1;
size_t index = 0;
size_t separatorBias = 0;
while (index <= path1End && index <= path2End)
{
const auto value1 = path1[path1End - index];
const auto value2 = path2[path2End - index];
if (value1 != value2)
{
break;
}
accumulated.push_back(value1);
++index;
if (accumulated.size() >= fsaccess.localseparator.size())
{
const auto diffSize = accumulated.size() - fsaccess.localseparator.size();
if (std::equal(accumulated.begin() + diffSize, accumulated.end(), fsaccess.localseparator.begin()))
{
separatorBias += fsaccess.localseparator.size();
accumulated.clear();
}
}
}
if (index > path1End && index > path2End) // we got to the beginning of both paths (full score)
{
return static_cast<int>(index - separatorBias);
}
else // the paths only partly match
{
return static_cast<int>(index - separatorBias - accumulated.size());
}
}
bool assignFilesystemIds(Sync& sync, MegaApp& app, FileSystemAccess& fsaccess, handlelocalnode_map& fsidnodes,
LocalPath& localdebris)
{
auto& rootpath = sync.localroot->localname;
LOG_info << "Assigning fs IDs at rootpath: " << rootpath.toPath(fsaccess);
auto fa = fsaccess.newfileaccess(false);
if (!fa->fopen(rootpath, true, false))
{
LOG_err << "Unable to open rootpath";
return false;
}
if (fa->type != FOLDERNODE)
{
LOG_err << "rootpath not a folder";
assert(false);
return false;
}
if (fa->mIsSymLink)
{
LOG_err << "rootpath is a symlink";
assert(false);
return false;
}
fa.reset();
bool success = true;
FingerprintCache fingerprints;
FingerprintLocalNodeMap localnodes;
collectAllLocalNodes(fingerprints, localnodes, *sync.localroot, fsidnodes);
LOG_info << "Number of localnodes: " << localnodes.size();
if (localnodes.empty())
{
return success;
}
FingerprintFileMap files;
collectAllFiles(success, fingerprints, files, sync, app, fsaccess, rootpath, localdebris);
LOG_info << "Number of files: " << files.size();
LOG_info << "Number of fingerprints: " << fingerprints.all().size();
const auto assignmentCount = assignFilesystemIdsImpl(fingerprints, localnodes, files, fsidnodes, fsaccess);
LOG_info << "Number of fsid assignments: " << assignmentCount;
return success;
}
SyncConfigBag::SyncConfigBag(DbAccess& dbaccess, FileSystemAccess& fsaccess, PrnGen& rng, const std::string& id)
{
std::string dbname = "syncconfigs_" + id;
mTable.reset(dbaccess.open(rng, &fsaccess, &dbname, false, false));
if (!mTable)
{
LOG_err << "Unable to open DB table: " << dbname;
assert(false);
return;
}
mTable->rewind();
uint32_t tableId;
std::string data;
while (mTable->next(&tableId, &data))
{
auto syncConfig = SyncConfig::unserialize(data);
if (!syncConfig)
{
LOG_err << "Unable to unserialize sync config at id: " << tableId;
assert(false);
continue;
}
syncConfig->dbid = tableId;
mSyncConfigs.insert(std::make_pair(syncConfig->getLocalPath(), *syncConfig));
if (tableId > mTable->nextid)
{
mTable->nextid = tableId;
}
}
++mTable->nextid;
}
void SyncConfigBag::insert(const SyncConfig& syncConfig)
{
auto insertOrUpdate = [this](const uint32_t id, const SyncConfig& syncConfig)
{
std::string data;
const_cast<SyncConfig&>(syncConfig).serialize(&data);
DBTableTransactionCommitter committer{mTable.get()};
if (!mTable->put(id, &data)) // put either inserts or updates
{
LOG_err << "Incomplete database put at id: " << mTable->nextid;
assert(false);
mTable->abort();
return false;
}
return true;
};
map<string, SyncConfig>::iterator syncConfigIt = mSyncConfigs.find(syncConfig.getLocalPath());
if (syncConfigIt == mSyncConfigs.end()) // syncConfig is new
{
if (mTable)
{
if (!insertOrUpdate(mTable->nextid, syncConfig))
{
return;
}
}
auto insertPair = mSyncConfigs.insert(std::make_pair(syncConfig.getLocalPath(), syncConfig));
if (mTable)
{
insertPair.first->second.dbid = mTable->nextid;
++mTable->nextid;
}
}
else // syncConfig exists already
{
const uint32_t tableId = syncConfigIt->second.dbid;
if (mTable)
{
if (!insertOrUpdate(tableId, syncConfig))
{
return;
}
}
syncConfigIt->second = syncConfig;
syncConfigIt->second.dbid = tableId;
}
}
void SyncConfigBag::remove(const std::string& localPath)
{
auto syncConfigPair = mSyncConfigs.find(localPath);
if (syncConfigPair != mSyncConfigs.end())
{
if (mTable)
{
DBTableTransactionCommitter committer{mTable.get()};
if (!mTable->del(syncConfigPair->second.dbid))
{
LOG_err << "Incomplete database del at id: " << syncConfigPair->second.dbid;
assert(false);
mTable->abort();
return;
}
}
mSyncConfigs.erase(syncConfigPair);
}
}
const SyncConfig* SyncConfigBag::get(const std::string& localPath) const
{
auto syncConfigPair = mSyncConfigs.find(localPath);
if (syncConfigPair != mSyncConfigs.end())
{
return &syncConfigPair->second;
}
return nullptr;
}
void SyncConfigBag::clear()
{
if (mTable)
{
mTable->truncate();
mTable->nextid = 0;
}
mSyncConfigs.clear();
}
std::vector<SyncConfig> SyncConfigBag::all() const
{
std::vector<SyncConfig> syncConfigs;
for (const auto& syncConfigPair : mSyncConfigs)
{
syncConfigs.push_back(syncConfigPair.second);
}
return syncConfigs;
}
// new Syncs are automatically inserted into the session's syncs list
// and a full read of the subtree is initiated
Sync::Sync(MegaClient* cclient, SyncConfig config, const char* cdebris,
string* clocaldebris, Node* remotenode, bool cinshare, int ctag, void *cappdata)
: localroot(new LocalNode)
{
isnetwork = false;
client = cclient;
tag = ctag;
inshare = cinshare;
appData = cappdata;
errorcode = API_OK;
tmpfa = NULL;
initializing = true;
updatedfilesize = ~0;
updatedfilets = 0;
updatedfileinitialts = 0;
localbytes = 0;
localnodes[FILENODE] = 0;
localnodes[FOLDERNODE] = 0;
state = SYNC_INITIALSCAN;
statecachetable = NULL;
fullscan = true;
scanseqno = 0;
mLocalPath = config.getLocalPath();
LocalPath crootpath = LocalPath::fromPath(mLocalPath, *client->fsaccess);
if (cdebris)
{
debris = cdebris;
localdebris = LocalPath::fromPath(debris, *client->fsaccess);
dirnotify.reset(client->fsaccess->newdirnotify(crootpath, localdebris, client->waiter));
localdebris.prependWithSeparator(crootpath, client->fsaccess->localseparator);
}
else
{
localdebris = LocalPath::fromLocalname(*clocaldebris);
// FIXME: pass last segment of localdebris
dirnotify.reset(client->fsaccess->newdirnotify(crootpath, localdebris, client->waiter));
}
dirnotify->sync = this;
// set specified fsfp or get from fs if none
const auto cfsfp = config.getLocalFingerprint();
if (cfsfp)
{
fsfp = cfsfp;
}
else
{
fsfp = dirnotify->fsfingerprint();
config.setLocalFingerprint(fsfp);
}
fsstableids = dirnotify->fsstableids();
LOG_info << "Filesystem IDs are stable: " << fsstableids;
mFilesystemType = client->fsaccess->getFilesystemType(crootpath);
localroot->init(this, FOLDERNODE, NULL, crootpath, nullptr); // the root node must have the absolute path. We don't store shortname, to avoid accidentally using relative paths.
localroot->setnode(remotenode);
#ifdef __APPLE__
if (macOSmajorVersion() >= 19) //macOS catalina+
{
LOG_debug << "macOS 10.15+ filesystem detected. Checking fseventspath.";
string supercrootpath = "/System/Volumes/Data" + *crootpath.editStringDirect();
int fd = open(supercrootpath.c_str(), O_RDONLY);
if (fd == -1)
{
LOG_debug << "Unable to open path using fseventspath.";
mFsEventsPath = *crootpath.editStringDirect();
}
else
{
char buf[MAXPATHLEN];
if (fcntl(fd, F_GETPATH, buf) < 0)
{
LOG_debug << "Using standard paths to detect filesystem notifications.";
mFsEventsPath = *crootpath.editStringDirect();
}
else
{
LOG_debug << "Using fsevents paths to detect filesystem notifications.";
mFsEventsPath = supercrootpath;
}
close(fd);
}
}
#endif
sync_it = client->syncs.insert(client->syncs.end(), this);
if (client->dbaccess)
{
// open state cache table
handle tableid[3];
string dbname;
auto fas = client->fsaccess->newfileaccess(false);
if (fas->fopen(crootpath, true, false))
{
tableid[0] = fas->fsid;
tableid[1] = remotenode->nodehandle;
tableid[2] = client->me;
dbname.resize(sizeof tableid * 4 / 3 + 3);
dbname.resize(Base64::btoa((byte*)tableid, sizeof tableid, (char*)dbname.c_str()));
statecachetable = client->dbaccess->open(client->rng, client->fsaccess, &dbname, false, false);
readstatecache();
}
}
if (client->syncConfigs)
{
client->syncConfigs->insert(config);
}
}
Sync::~Sync()
{
// must be set to prevent remote mass deletion while rootlocal destructor runs
assert(state == SYNC_CANCELED || state == SYNC_FAILED);
mDestructorRunning = true;
if (!statecachetable && client->syncConfigs)
{
// if there's no localnode cache then remove the sync config
client->syncConfigs->remove(mLocalPath);
}
// unlock tmp lock
tmpfa.reset();
// stop all active and pending downloads
if (localroot->node)
{
TreeProcDelSyncGet tdsg;
// Create a committer to ensure we update the transfer database in an efficient single commit,
// if there are transactions in progress.
DBTableTransactionCommitter committer(client->tctable);
client->proctree(localroot->node, &tdsg);
}
delete statecachetable;
client->syncs.erase(sync_it);
client->syncactivity = true;
{
// Create a committer and recursively delete all the associated LocalNodes, and their associated transfer and file objects.
// If any have transactions in progress, the committer will ensure we update the transfer database in an efficient single commit.
DBTableTransactionCommitter committer(client->tctable);
localroot.reset();
}
}
void Sync::addstatecachechildren(uint32_t parent_dbid, idlocalnode_map* tmap, LocalPath& localpath, LocalNode *p, int maxdepth)
{
auto range = tmap->equal_range(parent_dbid);
for (auto it = range.first; it != range.second; it++)
{
ScopedLengthRestore restoreLen(localpath);
localpath.appendWithSeparator(it->second->localname, true, client->fsaccess->localseparator);
LocalNode* l = it->second;
Node* node = l->node;
handle fsid = l->fsid;
m_off_t size = l->size;
// clear localname to force newnode = true in setnameparent
l->localname.clear();
// if we already have the shortname from database, use that, otherwise (db is from old code) look it up
std::unique_ptr<LocalPath> shortname;
if (l->slocalname_in_db)
{
// null if there is no shortname, or the shortname matches the localname.
shortname.reset(l->slocalname.release());
}
else
{
shortname = client->fsaccess->fsShortname(localpath);
}
l->init(this, l->type, p, localpath, std::move(shortname));
#ifdef DEBUG
auto fa = client->fsaccess->newfileaccess(false);
if (fa->fopen(localpath)) // exists, is file
{
auto sn = client->fsaccess->fsShortname(localpath);
assert(!l->localname.empty() &&
(!l->slocalname && (!sn || l->localname == *sn) ||
(l->slocalname && sn && !l->slocalname->empty() && *l->slocalname != l->localname && *l->slocalname == *sn)));
}
#endif
l->parent_dbid = parent_dbid;
l->size = size;
l->setfsid(fsid, client->fsidnode);
l->setnode(node);
if (!l->slocalname_in_db)
{
statecacheadd(l);
if (insertq.size() > 50000)
{
cachenodes(); // periodically output updated nodes with shortname updates, so people who restart megasync still make progress towards a fast startup
}
}
if (maxdepth)
{
addstatecachechildren(l->dbid, tmap, localpath, l, maxdepth - 1);
}
}
}
bool Sync::readstatecache()
{
if (statecachetable && state == SYNC_INITIALSCAN)
{
string cachedata;
idlocalnode_map tmap;
uint32_t cid;
LocalNode* l;
statecachetable->rewind();
// bulk-load cached nodes into tmap
while (statecachetable->next(&cid, &cachedata, &client->key))
{
if ((l = LocalNode::unserialize(this, &cachedata)))
{
l->dbid = cid;
tmap.insert(pair<int32_t,LocalNode*>(l->parent_dbid,l));
}
}
// recursively build LocalNode tree, set scanseqnos to sync's current scanseqno
addstatecachechildren(0, &tmap, localroot->localname, localroot.get(), 100);
cachenodes();
// trigger a single-pass full scan to identify deleted nodes
fullscan = true;
scanseqno++;
return true;
}
return false;
}
const SyncConfig& Sync::getConfig() const
{
assert(client->syncConfigs && "Calling getConfig() requires sync configs");
const auto config = client->syncConfigs->get(mLocalPath);
assert(config);
return *config;
}
void Sync::setResumable(const bool isResumable)
{
if (client->syncConfigs)
{
const auto config = client->syncConfigs->get(mLocalPath);
assert(config);
auto newConfig = *config;
newConfig.setResumable(isResumable);
client->syncConfigs->insert(newConfig);
}
}
// remove LocalNode from DB cache
void Sync::statecachedel(LocalNode* l)
{
if (state == SYNC_CANCELED)
{
return;
}
insertq.erase(l);
if (l->dbid)
{
deleteq.insert(l->dbid);
}
}
// insert LocalNode into DB cache
void Sync::statecacheadd(LocalNode* l)
{
if (state == SYNC_CANCELED)
{
return;
}
if (l->dbid)
{
deleteq.erase(l->dbid);
}
insertq.insert(l);
}
void Sync::cachenodes()
{
if (statecachetable && (state == SYNC_ACTIVE || (state == SYNC_INITIALSCAN && insertq.size() > 100)) && (deleteq.size() || insertq.size()))
{
LOG_debug << "Saving LocalNode database with " << insertq.size() << " additions and " << deleteq.size() << " deletions";
statecachetable->begin();
// deletions
for (set<uint32_t>::iterator it = deleteq.begin(); it != deleteq.end(); it++)
{
statecachetable->del(*it);
}
deleteq.clear();
// additions - we iterate until completion or until we get stuck
bool added;
do {
added = false;
for (set<LocalNode*>::iterator it = insertq.begin(); it != insertq.end(); )
{
if ((*it)->parent->dbid || (*it)->parent == localroot.get())
{
statecachetable->put(MegaClient::CACHEDLOCALNODE, *it, &client->key);
insertq.erase(it++);
added = true;
}
else it++;
}
} while (added);
statecachetable->commit();
if (insertq.size())
{
LOG_err << "LocalNode caching did not complete";
}
}
}
void Sync::changestate(syncstate_t newstate)
{
if (newstate != state)
{
client->app->syncupdate_state(this, newstate);
if (newstate == SYNC_FAILED && statecachetable)
{
statecachetable->remove();