forked from meganz/sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSync_test.cpp
More file actions
4531 lines (3811 loc) · 178 KB
/
Sync_test.cpp
File metadata and controls
4531 lines (3811 loc) · 178 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 tests/synctests.cpp
* @brief Mega SDK test file
*
* (c) 2018 by Mega Limited, Wellsford, 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.
*/
// Many of these tests are still being worked on.
// The file uses some C++17 mainly for the very convenient std::filesystem library, though the main SDK must still build with C++11 (and prior)
#include "test.h"
#include <mega.h>
#include "gtest/gtest.h"
#include <stdio.h>
#include <map>
#include <future>
//#include <mega/tsthooks.h>
#include <fstream>
#include <atomic>
#include <random>
#include <megaapi_impl.h>
#define DEFAULTWAIT std::chrono::seconds(20)
#ifdef ENABLE_SYNC
using namespace ::mega;
using namespace ::std;
#ifdef WIN32
#include <filesystem>
namespace fs = ::std::filesystem;
#define LOCAL_TEST_FOLDER "c:\\tmp\\synctests"
#else
#include <experimental/filesystem>
namespace fs = ::std::experimental::filesystem;
#define LOCAL_TEST_FOLDER (string(getenv("HOME"))+"/synctests_mega_auto")
#endif
/*
** TestFS implementation
*/
const string& TestFS::GetTestFolder()
{
// This function should probably contain the definition of LOCAL_TEST_FOLDER,
// and replace it in all other places.
static string testfolder(LOCAL_TEST_FOLDER);
return testfolder;
}
const string& TestFS::GetTrashFolder()
{
static string trashfolder((fs::path(GetTestFolder()).parent_path() / "trash").string());
return trashfolder;
}
void TestFS::DeleteFolder(const std::string& folder)
{
// rename folder, so that tests can still create one and add to it
error_code ec;
fs::path oldpath(folder);
fs::path newpath(folder + "_del"); // this can be improved later if needed
fs::rename(oldpath, newpath, ec);
// if renaming failed, then there's nothing to delete
if (ec)
{
// report failures, other than the case when it didn't exist
if (ec != errc::no_such_file_or_directory)
{
cout << "Renaming " << folder << " failed." << endl
<< ec.message() << endl;
}
return;
}
// delete folder in a separate thread
m_cleaners.emplace_back(thread([=]() mutable // ...mostly for fun, to avoid declaring another ec
{
fs::remove_all(newpath, ec);
if (ec)
{
cout << "Deleting " << folder << " failed." << endl
<< ec.message() << endl;
}
}));
}
TestFS::~TestFS()
{
for_each(m_cleaners.begin(), m_cleaners.end(), [](thread& t) { t.join(); });
}
namespace {
bool suppressfiles = false;
typedef ::mega::byte byte;
// Creates a temporary directory in the current path
fs::path makeTmpDir(const int maxTries = 1000)
{
const auto cwd = fs::current_path();
std::random_device dev;
std::mt19937 prng{dev()};
std::uniform_int_distribution<uint64_t> rand{0};
fs::path path;
for (int i = 0;; ++i)
{
std::ostringstream os;
os << std::hex << rand(prng);
path = cwd / os.str();
if (fs::create_directory(path))
{
break;
}
if (i == maxTries)
{
throw std::runtime_error{"Couldn't create tmp dir"};
}
}
return path;
}
// Copies a file while maintaining the write time.
void copyFile(const fs::path& source, const fs::path& target)
{
assert(fs::is_regular_file(source));
const auto tmpDir = makeTmpDir();
const auto tmpFile = tmpDir / "copied_file";
fs::copy_file(source, tmpFile);
fs::last_write_time(tmpFile, fs::last_write_time(source));
fs::rename(tmpFile, target);
fs::remove(tmpDir);
}
string leafname(const string& p)
{
auto n = p.find_last_of("/");
return n == string::npos ? p : p.substr(n+1);
}
string parentpath(const string& p)
{
auto n = p.find_last_of("/");
return n == string::npos ? "" : p.substr(0, n-1);
}
void WaitMillisec(unsigned n)
{
#ifdef _WIN32
Sleep(n);
#else
usleep(n * 1000);
#endif
}
struct Model
{
// records what we think the tree should look like after sync so we can confirm it
struct ModelNode
{
enum nodetype { file, folder };
nodetype type = folder;
string name;
string content;
vector<unique_ptr<ModelNode>> kids;
ModelNode* parent = nullptr;
string path()
{
string s;
for (auto p = this; p; p = p->parent)
s = "/" + p->name + s;
return s;
}
void addkid(unique_ptr<ModelNode>&& p)
{
p->parent = this;
kids.emplace_back(move(p));
}
bool typematchesnodetype(nodetype_t nodetype)
{
switch (type)
{
case file: return nodetype == FILENODE;
case folder: return nodetype == FOLDERNODE;
}
return false;
}
void print(string prefix="")
{
cout << prefix << name << endl;
prefix.append(name).append("/");
for (const auto &in: kids)
{
in->print(prefix);
}
}
std::unique_ptr<ModelNode> clone()
{
auto result = std::make_unique<ModelNode>();
result->name = name;
result->type = type;
result->content = content;
for (auto& k : kids) result->addkid(k->clone());
return result;
}
};
unique_ptr<ModelNode> makeModelSubfolder(const string& utf8Name)
{
unique_ptr<ModelNode> n(new ModelNode);
n->name = utf8Name;
return n;
}
unique_ptr<ModelNode> makeModelSubfile(const string& utf8Name, string content = {})
{
unique_ptr<ModelNode> n(new ModelNode);
n->name = utf8Name;
n->type = ModelNode::file;
n->content = content.empty() ? utf8Name : std::move(content);
return n;
}
unique_ptr<ModelNode> buildModelSubdirs(const string& prefix, int n, int recurselevel, int filesperdir)
{
if (suppressfiles) filesperdir = 0;
unique_ptr<ModelNode> nn = makeModelSubfolder(prefix);
for (int i = 0; i < filesperdir; ++i)
{
nn->addkid(makeModelSubfile("file" + to_string(i) + "_" + prefix));
}
if (recurselevel > 0)
{
for (int i = 0; i < n; ++i)
{
unique_ptr<ModelNode> sn = buildModelSubdirs(prefix + "_" + to_string(i), n, recurselevel - 1, filesperdir);
sn->parent = nn.get();
nn->addkid(move(sn));
}
}
return nn;
}
ModelNode* childnodebyname(ModelNode* n, const std::string& s)
{
for (auto& m : n->kids)
{
if (m->name == s)
{
return m.get();
}
}
return nullptr;
}
ModelNode* findnode(string path, ModelNode* startnode = nullptr)
{
ModelNode* n = startnode ? startnode : root.get();
while (n && !path.empty())
{
auto pos = path.find("/");
n = childnodebyname(n, path.substr(0, pos));
path.erase(0, pos == string::npos ? path.size() : pos + 1);
}
return n;
}
unique_ptr<ModelNode> removenode(const string& path)
{
ModelNode* n = findnode(path);
if (n && n->parent)
{
unique_ptr<ModelNode> extracted;
ModelNode* parent = n->parent;
auto newend = std::remove_if(parent->kids.begin(), parent->kids.end(), [&extracted, n](unique_ptr<ModelNode>& v) { if (v.get() == n) return extracted = move(v), true; else return false; });
parent->kids.erase(newend, parent->kids.end());
return extracted;
}
return nullptr;
}
bool movenode(const string& sourcepath, const string& destpath)
{
ModelNode* source = findnode(sourcepath);
ModelNode* dest = findnode(destpath);
if (source && source && source->parent && dest)
{
auto replaced_node = removenode(destpath + "/" + source->name);
unique_ptr<ModelNode> n;
ModelNode* parent = source->parent;
auto newend = std::remove_if(parent->kids.begin(), parent->kids.end(), [&n, source](unique_ptr<ModelNode>& v) { if (v.get() == source) return n = move(v), true; else return false; });
parent->kids.erase(newend, parent->kids.end());
if (n)
{
dest->addkid(move(n));
return true;
}
}
return false;
}
bool movetosynctrash(const string& path, const string& syncrootpath)
{
ModelNode* syncroot;
if (!(syncroot = findnode(syncrootpath)))
{
return false;
}
ModelNode* trash;
if (!(trash = childnodebyname(syncroot, DEBRISFOLDER)))
{
auto uniqueptr = makeModelSubfolder(DEBRISFOLDER);
trash = uniqueptr.get();
syncroot->addkid(move(uniqueptr));
}
char today[50];
auto rawtime = time(NULL);
strftime(today, sizeof today, "%F", localtime(&rawtime));
ModelNode* dayfolder;
if (!(dayfolder = findnode(today, trash)))
{
auto uniqueptr = makeModelSubfolder(today);
dayfolder = uniqueptr.get();
trash->addkid(move(uniqueptr));
}
if (auto uniqueptr = removenode(path))
{
dayfolder->addkid(move(uniqueptr));
return true;
}
return false;
}
void ensureLocalDebrisTmpLock(const string& syncrootpath)
{
// if we've downloaded a file then it's put in debris/tmp initially, and there is a lock file
if (ModelNode* syncroot = findnode(syncrootpath))
{
ModelNode* trash;
if (!(trash = childnodebyname(syncroot, DEBRISFOLDER)))
{
auto uniqueptr = makeModelSubfolder(DEBRISFOLDER);
trash = uniqueptr.get();
syncroot->addkid(move(uniqueptr));
}
ModelNode* tmpfolder;
if (!(tmpfolder = findnode("tmp", trash)))
{
auto uniqueptr = makeModelSubfolder("tmp");
tmpfolder = uniqueptr.get();
trash->addkid(move(uniqueptr));
}
ModelNode* lockfile;
if (!(lockfile = findnode("lock", tmpfolder)))
{
tmpfolder->addkid(makeModelSubfile("lock"));
}
}
}
bool removesynctrash(const string& syncrootpath, const string& subpath = "")
{
if (subpath.empty())
{
return removenode(syncrootpath + "/" + DEBRISFOLDER).get();
}
else
{
char today[50];
auto rawtime = time(NULL);
strftime(today, sizeof today, "%F", localtime(&rawtime));
return removenode(syncrootpath + "/" + DEBRISFOLDER + "/" + today + "/" + subpath).get();
}
}
void emulate_rename(std::string nodepath, std::string newname)
{
auto node = findnode(nodepath);
ASSERT_TRUE(!!node);
if (node) node->name = newname;
}
void emulate_move(std::string nodepath, std::string newparentpath)
{
auto removed = removenode(newparentpath + "/" + leafname(nodepath));
ASSERT_TRUE(movenode(nodepath, newparentpath));
}
void emulate_copy(std::string nodepath, std::string newparentpath)
{
auto node = findnode(nodepath);
auto newparent = findnode(newparentpath);
ASSERT_TRUE(!!node);
ASSERT_TRUE(!!newparent);
newparent->addkid(node->clone());
}
void emulate_rename_copy(std::string nodepath, std::string newparentpath, std::string newname)
{
auto node = findnode(nodepath);
auto newparent = findnode(newparentpath);
ASSERT_TRUE(!!node);
ASSERT_TRUE(!!newparent);
auto newnode = node->clone();
newnode->name = newname;
newparent->addkid(std::move(newnode));
}
void emulate_delete(std::string nodepath)
{
auto removed = removenode(nodepath);
// ASSERT_TRUE(!!removed);
}
Model() : root(makeModelSubfolder("root"))
{
}
unique_ptr<ModelNode> root;
};
bool waitonresults(future<bool>* r1 = nullptr, future<bool>* r2 = nullptr, future<bool>* r3 = nullptr, future<bool>* r4 = nullptr)
{
if (r1) r1->wait();
if (r2) r2->wait();
if (r3) r3->wait();
if (r4) r4->wait();
return (!r1 || r1->get()) && (!r2 || r2->get()) && (!r3 || r3->get()) && (!r4 || r4->get());
}
atomic<int> next_request_tag{ 1 << 30 };
struct StandardClient : public MegaApp
{
WAIT_CLASS waiter;
#ifdef GFX_CLASS
GFX_CLASS gfx;
#endif
string client_dbaccess_path;
std::unique_ptr<HttpIO> httpio;
std::unique_ptr<FileSystemAccess> fsaccess;
MegaClient client;
std::atomic<bool> clientthreadexit{false};
bool fatalerror = false;
string clientname;
std::function<void(MegaClient&, promise<bool>&)> nextfunctionMC;
std::promise<bool> nextfunctionMCpromise;
std::function<void(StandardClient&, promise<bool>&)> nextfunctionSC;
std::promise<bool> nextfunctionSCpromise;
std::condition_variable functionDone;
std::mutex functionDoneMutex;
std::string salt;
std::set<fs::path> localFSFilesThatMayDiffer;
fs::path fsBasePath;
handle basefolderhandle = UNDEF;
// thread as last member so everything else is initialised before we start it
std::thread clientthread;
fs::path ensureDir(const fs::path& p)
{
fs::create_directories(p);
return p;
}
StandardClient(const fs::path& basepath, const string& name)
: client_dbaccess_path(ensureDir(basepath / name / "").u8string())
, httpio(new HTTPIO_CLASS)
, fsaccess(new FSACCESS_CLASS)
, client(this, &waiter, httpio.get(), fsaccess.get(),
#ifdef DBACCESS_CLASS
new DBACCESS_CLASS(&client_dbaccess_path),
#else
NULL,
#endif
#ifdef GFX_CLASS
&gfx,
#else
NULL,
#endif
"N9tSBJDC", USER_AGENT.c_str(), THREADS_PER_MEGACLIENT )
, clientname(name)
, fsBasePath(basepath / fs::u8path(name))
, resultproc(client)
, clientthread([this]() { threadloop(); })
{
client.clientname = clientname + " ";
#ifdef GFX_CLASS
gfx.startProcessingThread();
#endif
}
~StandardClient()
{
// shut down any syncs on the same thread, or they stall the client destruction (CancelIo instead of CancelIoEx on the WinDirNotify)
thread_do([](MegaClient& mc, promise<bool>&) {
#ifdef _WIN32
// logout stalls in windows due to the issue above
mc.purgenodesusersabortsc(false);
#else
mc.logout();
#endif
});
clientthreadexit = true;
waiter.notify();
clientthread.join();
}
void localLogout()
{
thread_do([](MegaClient& mc, promise<bool>&) {
#ifdef _WIN32
// logout stalls in windows due to the issue above
mc.purgenodesusersabortsc(false);
#else
mc.locallogout(false);
#endif
});
}
static mutex om;
bool logcb = false;
chrono::steady_clock::time_point lastcb = std::chrono::steady_clock::now();
string lp(LocalNode* ln) { return ln->getLocalPath().toName(*client.fsaccess, FS_UNKNOWN); }
void onCallback() { lastcb = chrono::steady_clock::now(); };
void syncupdate_state(Sync*, syncstate_t state) override { onCallback(); if (logcb) { lock_guard<mutex> g(om); cout << clientname << " syncupdate_state() " << state << endl; } }
void syncupdate_scanning(bool b) override { if (logcb) { onCallback(); lock_guard<mutex> g(om); cout << clientname << " syncupdate_scanning()" << b << endl; } }
//void syncupdate_local_folder_addition(Sync* s, LocalNode* ln, const char* cp) override { onCallback(); if (logcb) { lock_guard<mutex> g(om); cout << clientname << " syncupdate_local_folder_addition() " << lp(ln) << " " << cp << endl; }}
//void syncupdate_local_folder_deletion(Sync*, LocalNode* ln) override { if (logcb) { onCallback(); lock_guard<mutex> g(om); cout << clientname << " syncupdate_local_folder_deletion() " << lp(ln) << endl; }}
void syncupdate_local_folder_addition(Sync*, LocalNode* ln, const char* cp) override { onCallback(); }
void syncupdate_local_folder_deletion(Sync*, LocalNode* ln) override { onCallback(); }
void syncupdate_local_file_addition(Sync*, LocalNode* ln, const char* cp) override { onCallback(); if (logcb) { lock_guard<mutex> g(om); cout << clientname << " syncupdate_local_file_addition() " << lp(ln) << " " << cp << endl; }}
void syncupdate_local_file_deletion(Sync*, LocalNode* ln) override { if (logcb) { onCallback(); lock_guard<mutex> g(om); cout << clientname << " syncupdate_local_file_deletion() " << lp(ln) << endl; }}
void syncupdate_local_file_change(Sync*, LocalNode* ln, const char* cp) override { onCallback(); if (logcb) { lock_guard<mutex> g(om); cout << clientname << " syncupdate_local_file_change() " << lp(ln) << " " << cp << endl; }}
void syncupdate_local_move(Sync*, LocalNode* ln, const char* cp) override { onCallback(); if (logcb) { lock_guard<mutex> g(om); cout << clientname << " syncupdate_local_move() " << lp(ln) << " " << cp << endl; }}
void syncupdate_local_lockretry(bool b) override { if (logcb) { onCallback(); lock_guard<mutex> g(om); cout << clientname << " syncupdate_local_lockretry() " << b << endl; }}
//void syncupdate_get(Sync*, Node* n, const char* cp) override { onCallback(); if (logcb) { lock_guard<mutex> g(om); cout << clientname << " syncupdate_get()" << n->displaypath() << " " << cp << endl; }}
void syncupdate_put(Sync*, LocalNode* ln, const char* cp) override { onCallback(); if (logcb) { lock_guard<mutex> g(om); cout << clientname << " syncupdate_put()" << lp(ln) << " " << cp << endl; }}
void syncupdate_remote_file_addition(Sync*, Node* n) override { onCallback(); if (logcb) { lock_guard<mutex> g(om); cout << clientname << " syncupdate_remote_file_addition() " << n->displaypath() << endl; }}
void syncupdate_remote_file_deletion(Sync*, Node* n) override { onCallback(); if (logcb) { lock_guard<mutex> g(om); cout << clientname << " syncupdate_remote_file_deletion() " << n->displaypath() << endl; }}
//void syncupdate_remote_folder_addition(Sync*, Node* n) override { onCallback(); if (logcb) { lock_guard<mutex> g(om); cout << clientname << " syncupdate_remote_folder_addition() " << n->displaypath() << endl; }}
//void syncupdate_remote_folder_deletion(Sync*, Node* n) override { onCallback(); if (logcb) { lock_guard<mutex> g(om); cout << clientname << " syncupdate_remote_folder_deletion() " << n->displaypath() << endl; }}
void syncupdate_remote_folder_addition(Sync*, Node* n) override { onCallback(); }
void syncupdate_remote_folder_deletion(Sync*, Node* n) override { onCallback(); }
void syncupdate_remote_copy(Sync*, const char* cp) override { onCallback(); if (logcb) { lock_guard<mutex> g(om); cout << clientname << " syncupdate_remote_copy() " << cp << endl; }}
void syncupdate_remote_move(Sync*, Node* n1, Node* n2) override { onCallback(); if (logcb) { lock_guard<mutex> g(om); cout << clientname << " syncupdate_remote_move() " << n1->displaypath() << " " << n2->displaypath() << endl; }}
void syncupdate_remote_rename(Sync*, Node* n, const char* cp) override { onCallback(); if (logcb) { lock_guard<mutex> g(om); cout << clientname << " syncupdate_remote_rename() " << n->displaypath() << " " << cp << endl; }}
//void syncupdate_treestate(LocalNode* ln) override { onCallback(); if (logcb) { lock_guard<mutex> g(om); cout << clientname << " syncupdate_treestate() " << ln->ts << " " << ln->dts << " " << lp(ln) << endl; }}
bool sync_syncable(Sync* sync, const char* name, LocalPath& path, Node*) override
{
return sync_syncable(sync, name, path);
}
bool sync_syncable(Sync*, const char*, LocalPath&) override
{
onCallback();
return true;
}
std::atomic<unsigned> transfersAdded{0}, transfersRemoved{0}, transfersPrepared{0}, transfersFailed{0}, transfersUpdated{0}, transfersComplete{0};
void transfer_added(Transfer*) override { onCallback(); ++transfersAdded; }
void transfer_removed(Transfer*) override { onCallback(); ++transfersRemoved; }
void transfer_prepare(Transfer*) override { onCallback(); ++transfersPrepared; }
void transfer_failed(Transfer*, const Error&, dstime = 0) override { onCallback(); ++transfersFailed; }
void transfer_update(Transfer*) override { onCallback(); ++transfersUpdated; }
void transfer_complete(Transfer*) override { onCallback(); ++transfersComplete; }
void threadloop()
try
{
while (!clientthreadexit)
{
int r = client.wait();
{
std::lock_guard<mutex> g(functionDoneMutex);
if (nextfunctionMC)
{
nextfunctionMC(client, nextfunctionMCpromise);
nextfunctionMC = nullptr;
functionDone.notify_all();
r = Waiter::NEEDEXEC;
}
if (nextfunctionSC)
{
nextfunctionSC(*this, nextfunctionSCpromise);
nextfunctionSC = nullptr;
functionDone.notify_all();
r = Waiter::NEEDEXEC;
}
}
if (r & Waiter::NEEDEXEC)
{
client.exec();
}
}
cout << clientname << " thread exiting naturally" << endl;
}
catch (std::exception& e)
{
cout << clientname << " thread exception, StandardClient " << clientname << " terminated: " << e.what() << endl;
}
catch (...)
{
cout << clientname << " thread exception, StandardClient " << clientname << " terminated" << endl;
}
static bool debugging; // turn this on to prevent the main thread timing out when stepping in the MegaClient
future<bool> thread_do(std::function<void(MegaClient&, promise<bool>&)>&& f)
{
unique_lock<mutex> guard(functionDoneMutex);
nextfunctionMCpromise = promise<bool>();
nextfunctionMC = std::move(f);
waiter.notify();
while (!functionDone.wait_until(guard, chrono::steady_clock::now() + chrono::seconds(600), [this]() { return !nextfunctionMC; }))
{
if (!debugging)
{
nextfunctionMCpromise.set_value(false);
break;
}
}
return nextfunctionMCpromise.get_future();
}
future<bool> thread_do(std::function<void(StandardClient&, promise<bool>&)>&& f)
{
unique_lock<mutex> guard(functionDoneMutex);
nextfunctionSCpromise = promise<bool>();
nextfunctionSC = std::move(f);
waiter.notify();
while (!functionDone.wait_until(guard, chrono::steady_clock::now() + chrono::seconds(600), [this]() { return !nextfunctionSC; }))
{
if (!debugging)
{
nextfunctionSCpromise.set_value(false);
break;
}
}
return nextfunctionSCpromise.get_future();
}
enum resultprocenum { PRELOGIN, LOGIN, FETCHNODES, PUTNODES, UNLINK, MOVENODE, CATCHUP };
void preloginFromEnv(const string& userenv, promise<bool>& pb)
{
string user = getenv(userenv.c_str());
ASSERT_FALSE(user.empty());
resultproc.prepresult(PRELOGIN, ++next_request_tag,
[&](){ client.prelogin(user.c_str()); },
[this, &pb](error e) { pb.set_value(!e); return true; });
}
void loginFromEnv(const string& userenv, const string& pwdenv, promise<bool>& pb)
{
string user = getenv(userenv.c_str());
string pwd = getenv(pwdenv.c_str());
ASSERT_FALSE(user.empty());
ASSERT_FALSE(pwd.empty());
byte pwkey[SymmCipher::KEYLENGTH];
resultproc.prepresult(LOGIN, ++next_request_tag,
[&](){
if (client.accountversion == 1)
{
if (error e = client.pw_key(pwd.c_str(), pwkey))
{
ASSERT_TRUE(false) << "login error: " << e;
}
else
{
client.login(user.c_str(), pwkey);
}
}
else if (client.accountversion == 2 && !salt.empty())
{
client.login2(user.c_str(), pwd.c_str(), &salt);
}
else
{
ASSERT_TRUE(false) << "Login unexpected error";
}
},
[this, &pb](error e) { pb.set_value(!e); return true; });
}
void loginFromSession(const string& session, promise<bool>& pb)
{
resultproc.prepresult(LOGIN, ++next_request_tag,
[&](){ client.login((byte*)session.data(), (int)session.size()); },
[this, &pb](error e) { pb.set_value(!e); return true; });
}
void cloudCopyTreeAs(Node* n1, Node* n2, std::string newname, promise<bool>& pb)
{
resultproc.prepresult(PUTNODES, ++next_request_tag,
[&](){
TreeProcCopy tc;
client.proctree(n1, &tc, false, true);
tc.allocnodes();
auto nc = tc.nc;
client.proctree(n1, &tc, false, true);
tc.nn[0].parenthandle = UNDEF;
SymmCipher key;
AttrMap attrs;
string attrstring;
key.setkey((const ::mega::byte*)tc.nn[0].nodekey.data(), n1->type);
attrs = n1->attrs;
client.fsaccess->normalize(&newname);
attrs.map['n'] = newname;
attrs.getjson(&attrstring);
client.makeattr(&key, tc.nn[0].attrstring, attrstring.c_str());
client.putnodes(n2->nodehandle, tc.nn, nc);
},
[this, &pb](error e) {
pb.set_value(!e);
return true;
});
}
void uploadFolderTree_recurse(handle parent, handle& h, const fs::path& p, vector<NewNode>& newnodes)
{
NewNode n;
client.putnodes_prepareOneFolder(&n, p.filename().u8string());
handle thishandle = n.nodehandle = h++;
n.parenthandle = parent;
newnodes.emplace_back(std::move(n));
for (fs::directory_iterator i(p); i != fs::directory_iterator(); ++i)
{
if (fs::is_directory(*i))
{
uploadFolderTree_recurse(thishandle, h, *i, newnodes);
}
}
}
void uploadFolderTree(fs::path p, Node* n2, promise<bool>& pb)
{
resultproc.prepresult(PUTNODES, ++next_request_tag,
[&](){
vector<NewNode> newnodes;
handle h = 1;
uploadFolderTree_recurse(UNDEF, h, p, newnodes);
auto nn = new NewNode[newnodes.size()];
for (auto i = newnodes.size(); i--; ) nn[i] = std::move(newnodes[i]);
client.putnodes(n2->nodehandle, nn, (int)newnodes.size());
},
[this, &pb](error e) { pb.set_value(!e); return true; });
}
void uploadFilesInTree_recurse(Node* target, const fs::path& p, std::atomic<int>& inprogress, DBTableTransactionCommitter& committer)
{
if (fs::is_regular_file(p))
{
++inprogress;
File* f = new File();
// full local path
f->localname = LocalPath::fromPath(p.u8string(), *client.fsaccess);
f->h = target->nodehandle;
f->name = p.filename().u8string();
client.startxfer(PUT, f, committer);
}
else if (fs::is_directory(p))
{
if (auto newtarget = client.childnodebyname(target, p.filename().u8string().c_str()))
{
for (fs::directory_iterator i(p); i != fs::directory_iterator(); ++i)
{
uploadFilesInTree_recurse(newtarget, *i, inprogress, committer);
}
}
}
}
void uploadFilesInTree(fs::path p, Node* n2, std::atomic<int>& inprogress, std::promise<bool>& pb)
{
resultproc.prepresult(PUTNODES, ++next_request_tag,
[&](){
DBTableTransactionCommitter committer(client.tctable);
uploadFilesInTree_recurse(n2, p, inprogress, committer);
},
[this, &pb, &inprogress](error e)
{
if (!--inprogress)
pb.set_value(true);
return !inprogress;
});
}
class TreeProcPrintTree : public TreeProc
{
public:
void proc(MegaClient* client, Node* n) override
{
//cout << "fetchnodes tree: " << n->displaypath() << endl;;
}
};
// mark node as removed and notify
std::function<void (StandardClient& mc, promise<bool>& pb)> onFetchNodes;
void fetchnodes(promise<bool>& pb)
{
resultproc.prepresult(FETCHNODES, ++next_request_tag,
[&](){ client.fetchnodes(); },
[this, &pb](error e)
{
if (e)
{
pb.set_value(false);
}
else
{
TreeProcPrintTree tppt;
client.proctree(client.nodebyhandle(client.rootnodes[0]), &tppt);
if (onFetchNodes)
{
onFetchNodes(*this, pb);
}
else
{
pb.set_value(true);
}
}
onFetchNodes = nullptr;
return true;
});
}
NewNode makeSubfolder(const string& utf8Name)
{
NewNode newnode;
client.putnodes_prepareOneFolder(&newnode, utf8Name);
return newnode;
}
struct ResultProc
{
MegaClient& client;
ResultProc(MegaClient& c) : client(c) {}
struct id_callback
{
int request_tag = 0;
handle h = UNDEF;
std::function<bool(error)> f;
id_callback(std::function<bool(error)> cf, int tag, handle ch) : request_tag(tag), h(ch), f(cf) {}
};
recursive_mutex mtx; // recursive because sometimes we need to set up new operations during a completion callback
map<resultprocenum, deque<id_callback>> m;
void prepresult(resultprocenum rpe, int tag, std::function<void()>&& requestfunc, std::function<bool(error)>&& f, handle h = UNDEF)
{
lock_guard<recursive_mutex> g(mtx);
auto& entry = m[rpe];
entry.emplace_back(move(f), tag, h);
assert(tag > 0);
int oldtag = client.reqtag;
client.reqtag = tag;
requestfunc();
client.reqtag = oldtag;
client.waiter->notify();
}
void processresult(resultprocenum rpe, error e, handle h = UNDEF)
{
int tag = client.restag;
if (tag == 0 && rpe != CATCHUP)
{
//cout << "received notification of SDK initiated operation " << rpe << " tag " << tag << endl; // too many of those to output
return;
}
if (tag < (2 << 30))
{
cout << "ignoring callback from SDK internal sync operation " << rpe << " tag " << tag << endl;
return;
}
lock_guard<recursive_mutex> g(mtx);
auto& entry = m[rpe];
if (rpe == CATCHUP)
{
while (!entry.empty())
{
entry.front().f(e);
entry.pop_front();
}
return;
}
if (entry.empty())
{
cout << "received notification of operation type " << rpe << " completion but we don't have a record of it. tag: " << tag << endl;
return;
}
if (tag != entry.front().request_tag)
{
cout << "tag mismatch for operation completion of " << rpe << " tag " << tag << ", we expected " << entry.front().request_tag << endl;
return;
}
if (entry.front().f(e))
{
entry.pop_front();
}
}
} resultproc;
void catchup(promise<bool>& pb)
{
resultproc.prepresult(CATCHUP, ++next_request_tag,
[&](){
auto request_sent = thread_do([](StandardClient& sc, promise<bool>& pb) { sc.client.catchup(); pb.set_value(true); });
if (!waitonresults(&request_sent)) {
cout << "catchup not sent" << endl;
}
},
[this, &pb](error e) {
if (e)
{
cout << "catchup reports: " << e << endl;
}
pb.set_value(!e);
return true;
});