forked from meganz/sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfilesystem.cpp
More file actions
833 lines (727 loc) · 20.4 KB
/
Copy pathfilesystem.cpp
File metadata and controls
833 lines (727 loc) · 20.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
/**
* @file filesystem.cpp
* @brief Generic host filesystem access interfaces
*
* (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 "mega/filesystem.h"
#include "mega/node.h"
#include "mega/megaclient.h"
#include "mega/logging.h"
#include "mega/mega_utf8proc.h"
namespace mega {
FileSystemAccess::FileSystemAccess()
: waiter(NULL)
, skip_errorreport(false)
, transient_error(false)
, notifyerr(false)
, notifyfailed(false)
, target_exists(false)
, client(NULL)
{
}
void FileSystemAccess::captimestamp(m_time_t* t)
{
// FIXME: remove upper bound before the year 2100 and upgrade server-side timestamps to BIGINT
if (*t > (uint32_t)-1) *t = (uint32_t)-1;
else if (*t < 0) *t = 0;
}
bool FileSystemAccess::islchex(char c) const
{
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f');
}
const char *FileSystemAccess::fstypetostring(FileSystemType type) const
{
switch (type)
{
case FS_NTFS:
return "NTFS";
case FS_EXFAT:
return "EXFAT";
case FS_FAT32:
return "FAT32";
case FS_EXT:
return "EXT";
case FS_HFS:
return "HFS";
case FS_APFS:
return "APFS";
case FS_UNKNOWN: // fall through
return "UNKNOWN FS";
}
return "UNKNOWN FS";
}
FileSystemType FileSystemAccess::getlocalfstype(const string *dstPath) const
{
if (!dstPath || dstPath->empty())
{
return FS_UNKNOWN;
}
#if defined (__linux__) || defined (__ANDROID__)
struct statfs fileStat;
if (!statfs(dstPath->c_str(), &fileStat))
{
switch (fileStat.f_type)
{
case EXT2_SUPER_MAGIC:
return FS_EXT;
case MSDOS_SUPER_MAGIC:
return FS_FAT32;
case HFS_SUPER_MAGIC:
return FS_HFS;
case NTFS_SB_MAGIC:
return FS_NTFS;
default:
return FS_UNKNOWN;
}
}
#elif defined (__APPLE__) || defined (USE_IOS)
struct statfs fileStat;
if (!statfs(dstPath->c_str(), &fileStat))
{
if (!strcmp(fileStat.f_fstypename, "apfs"))
{
return FS_APFS;
}
if (!strcmp(fileStat.f_fstypename, "hfs"))
{
return FS_HFS;
}
if (!strcmp(fileStat.f_fstypename, "ntfs"))
{
return FS_NTFS;
}
if (!strcmp(fileStat.f_fstypename, "msdos"))
{
return FS_FAT32;
}
}
#elif defined(_WIN32) || defined(_WIN64) || defined(WINDOWS_PHONE)
TCHAR volumeName[MAX_PATH + 1] = { 0 };
TCHAR fileSystemName[MAX_PATH + 1] = { 0 };
DWORD serialNumber = 0;
DWORD maxComponentLen = 0;
DWORD fileSystemFlags = 0;
if (GetVolumeInformationA(dstPath->c_str(), volumeName, sizeof(volumeName),
&serialNumber, &maxComponentLen, &fileSystemFlags,
fileSystemName, sizeof(fileSystemName)) == true)
{
if (!strcmp(fileSystemName, "NTFS"))
{
return FS_NTFS;
}
if (!strcmp(fileSystemName, "exFAT"))
{
return FS_EXFAT;
}
if (!strcmp(fileSystemName, "FAT32"))
{
return FS_FAT32;
}
}
#endif
return FS_UNKNOWN;
}
// Group different filesystems types in families, according to its restricted charsets
bool FileSystemAccess::islocalfscompatible(unsigned char c, FileSystemType fileSystemType) const
{
switch (fileSystemType)
{
case FS_APFS:
case FS_HFS:
// APFS, HFS, HFS+ restricted characters => :
return c != '\x3A';
case FS_EXT:
// ext2/ext3/ext4 restricted characters => / NULL
return c != '\x00' && c != '\x2F';
case FS_FAT32:
// FAT32 restricted characters => " * / : < > ? \ | + , ; = [ ]
return !strchr("\\/:?\"<>|*+,;=[]", c);
case FS_EXFAT:
case FS_NTFS:
case FS_UNKNOWN:
// ExFAT, NTFS restricted characters => " * / : < > ? \ |
// If filesystem couldn't be detected we'll use a restrictive charset to avoid issues.
return !strchr("\\/:?\"<>|*", c);
}
}
bool FileSystemAccess::getValidPath(const string *originalPath, string &tempPath) const
{
if (!originalPath || originalPath->empty())
{
return false;
}
string separator = getPathSeparator();
for (size_t i = 0; i < separator.size(); i++)
{
size_t pos = originalPath->rfind(separator[i]);
if (pos != std::string::npos && pos != originalPath->size() - 1)
{
tempPath = originalPath->substr(0, pos + 1);
return true;
}
}
return false;
}
// replace characters that are not allowed in local fs names with a %xx escape sequence
void FileSystemAccess::escapefsincompatible(string* name, const string *dstPath) const
{
if (!name->compare(".."))
{
name->replace(0, 2, "%2e%2e");
return;
}
if (!name->compare("."))
{
name->replace(0, 1, "%2e");
return;
}
string tempPath;
const string *validPath = &tempPath;
if (!getValidPath(dstPath, tempPath) && dstPath)
{
// if getValidPath returns false and dstPath is not null, dstPath is valid
validPath = dstPath;
}
char buf[4];
FileSystemType fileSystemType = getlocalfstype(validPath);
size_t utf8seqsize = 0;
size_t i = 0;
unsigned char c = '0';
while (i < name->size())
{
c = static_cast<unsigned char>((*name)[i]);
utf8seqsize = Utils::utf8SequenceSize(c);
assert (utf8seqsize);
if (utf8seqsize == 1 && !islocalfscompatible(c, fileSystemType))
{
const char incompatibleChar = name->at(i);
sprintf(buf, "%%%02x", c);
name->replace(i, 1, buf);
LOG_debug << "Escape incompatible character for filesystem type "
<< fstypetostring(fileSystemType)
<< ", replace '" << std::string(&incompatibleChar, 1) << "' by '" << buf << "'\n";
}
i += utf8seqsize;
}
}
void FileSystemAccess::unescapefsincompatible(string *name, const string *localPath) const
{
if (!name->compare("%2e%2e"))
{
name->replace(0, 6, "..");
return;
}
if (!name->compare("%2e"))
{
name->replace(0, 3, ".");
return;
}
string tempPath;
const string *validPath = &tempPath;
if (!getValidPath(localPath, tempPath) && localPath)
{
// if getValidPath returns false and localPath is not null, localPath is valid
validPath = localPath;
}
FileSystemType fileSystemType = getlocalfstype(validPath);
for (int i = int(name->size()) - 2; i-- > 0; )
{
// conditions for unescaping: %xx must be well-formed
if ((*name)[i] == '%' && islchex((*name)[i + 1]) && islchex((*name)[i + 2]))
{
char c = static_cast<char>((MegaClient::hexval((*name)[i + 1]) << 4) + MegaClient::hexval((*name)[i + 2]));
if (!islocalfscompatible(static_cast<unsigned char>(c), fileSystemType))
{
std::string incompatibleChar = name->substr(i, 3);
name->replace(i, 3, &c, 1);
LOG_debug << "Unescape incompatible character for filesystem type "
<< fstypetostring(fileSystemType)
<< ", replace '" << incompatibleChar << "' by '" << name->substr(i, 1) << "'\n";
}
}
}
}
const char *FileSystemAccess::getPathSeparator()
{
#if defined (__linux__) || defined (__ANDROID__) || defined (__APPLE__) || defined (USE_IOS)
return "/";
#elif defined(_WIN32) || defined(_WIN64) || defined(WINDOWS_PHONE)
return "\\";
#elif
// Default case
LOG_warn << "No path separator found";
return "\\/";
#endif
}
// escape forbidden characters, then convert to local encoding
void FileSystemAccess::name2local(string* filename, const string *dstPath) const
{
assert(filename);
escapefsincompatible(filename, dstPath);
string t = *filename;
path2local(&t, filename);
}
void FileSystemAccess::normalize(string* filename) const
{
if (!filename) return;
const char* cfilename = filename->c_str();
size_t fnsize = filename->size();
string result;
for (size_t i = 0; i < fnsize; )
{
// allow NUL bytes between valid UTF-8 sequences
if (!cfilename[i])
{
result.append("", 1);
i++;
continue;
}
const char* substring = cfilename + i;
char* normalized = (char*)utf8proc_NFC((uint8_t*)substring);
if (!normalized)
{
filename->clear();
return;
}
result.append(normalized);
free(normalized);
i += strlen(substring);
}
*filename = std::move(result);
}
// convert from local encoding, then unescape escaped forbidden characters
void FileSystemAccess::local2name(string *filename, const string *localPath) const
{
assert(filename);
string t = *filename;
local2path(&t, filename);
unescapefsincompatible(filename, localPath);
}
std::unique_ptr<string> FileSystemAccess::fsShortname(string& localname)
{
string s;
if (getsname(&localname, &s))
{
return ::mega::make_unique<string>(std::move(s));
}
return nullptr;
}
// default DirNotify: no notification available
DirNotify::DirNotify(string* clocalbasepath, string* cignore)
{
localbasepath = *clocalbasepath;
ignore = *cignore;
failed = 1;
failreason = "Not initialized";
error = 0;
sync = NULL;
}
// notify base LocalNode + relative path/filename
void DirNotify::notify(notifyqueue q, LocalNode* l, const char* localpath, size_t len, bool immediate)
{
string path;
path.assign(localpath, len);
#ifdef ENABLE_SYNC
if ((q == DirNotify::DIREVENTS || q == DirNotify::EXTRA)
&& notifyq[q].size()
&& notifyq[q].back().localnode == l
&& notifyq[q].back().path == path)
{
if (notifyq[q].back().timestamp)
{
notifyq[q].back().timestamp = immediate ? 0 : Waiter::ds;
}
LOG_debug << "Repeated notification skipped";
return;
}
if (!immediate && sync && !sync->initializing && q == DirNotify::DIREVENTS)
{
string tmppath;
if (l)
{
l->getlocalpath(&tmppath);
}
if (localpath)
{
if (tmppath.size())
{
tmppath.append(sync->client->fsaccess->localseparator);
}
tmppath.append(path);
}
attr_map::iterator ait;
auto fa = sync->client->fsaccess->newfileaccess(false);
bool success = fa->fopen(&tmppath, false, false);
LocalNode *ll = sync->localnodebypath(l, &path);
if ((!ll && !success && !fa->retry) // deleted file
|| (ll && success && ll->node && ll->node->localnode == ll
&& (ll->type != FILENODE || (*(FileFingerprint *)ll) == (*(FileFingerprint *)ll->node))
&& (ait = ll->node->attrs.map.find('n')) != ll->node->attrs.map.end()
&& ait->second == ll->name
&& fa->fsidvalid && fa->fsid == ll->fsid && fa->type == ll->type
&& (ll->type != FILENODE || (ll->mtime == fa->mtime && ll->size == fa->size))))
{
LOG_debug << "Self filesystem notification skipped";
return;
}
}
if (q == DirNotify::DIREVENTS || q == DirNotify::EXTRA)
{
sync->client->syncactivity = true;
}
#endif
notifyq[q].resize(notifyq[q].size() + 1);
notifyq[q].back().timestamp = immediate ? 0 : Waiter::ds;
notifyq[q].back().localnode = l;
notifyq[q].back().path = path;
}
// default: no fingerprint
fsfp_t DirNotify::fsfingerprint() const
{
return 0;
}
bool DirNotify::fsstableids() const
{
return true;
}
DirNotify* FileSystemAccess::newdirnotify(string* localpath, string* ignore)
{
return new DirNotify(localpath, ignore);
}
FileAccess::FileAccess(Waiter *waiter)
{
this->waiter = waiter;
this->isAsyncOpened = false;
this->numAsyncReads = 0;
}
FileAccess::~FileAccess()
{
// All AsyncIOContext objects must be deleted before
assert(!numAsyncReads && !isAsyncOpened);
}
// open file for reading
bool FileAccess::fopen(string* name)
{
nonblocking_localname.resize(1);
updatelocalname(name);
return sysstat(&mtime, &size);
}
bool FileAccess::isfolder(string *name)
{
fopen(name);
return (type == FOLDERNODE);
}
// check if size and mtime are unchanged, then open for reading
bool FileAccess::openf()
{
if (!nonblocking_localname.size())
{
// file was not opened in nonblocking mode
return true;
}
m_time_t curr_mtime;
m_off_t curr_size;
if (!sysstat(&curr_mtime, &curr_size))
{
LOG_warn << "Error opening sync file handle (sysstat) "
<< curr_mtime << " - " << mtime
<< curr_size << " - " << size;
return false;
}
if (curr_mtime != mtime || curr_size != size)
{
mtime = curr_mtime;
size = curr_size;
retry = false;
return false;
}
return sysopen();
}
void FileAccess::closef()
{
if (nonblocking_localname.size())
{
sysclose();
}
}
void FileAccess::asyncopfinished(void *param)
{
Waiter *waiter = (Waiter *)param;
if (waiter)
{
waiter->notify();
}
}
AsyncIOContext *FileAccess::asyncfopen(string *f)
{
nonblocking_localname.resize(1);
updatelocalname(f);
LOG_verbose << "Async open start";
AsyncIOContext *context = newasynccontext();
context->op = AsyncIOContext::OPEN;
context->access = AsyncIOContext::ACCESS_READ;
context->buffer = (byte *)f->data();
context->len = static_cast<unsigned>(f->size());
context->waiter = waiter;
context->userCallback = asyncopfinished;
context->userData = waiter;
context->pos = size;
context->fa = this;
context->failed = !sysstat(&mtime, &size);
context->retry = this->retry;
context->finished = true;
context->userCallback(context->userData);
return context;
}
bool FileAccess::asyncopenf()
{
numAsyncReads++;
if (!nonblocking_localname.size())
{
return true;
}
if (isAsyncOpened)
{
return true;
}
m_time_t curr_mtime = 0;
m_off_t curr_size = 0;
if (!sysstat(&curr_mtime, &curr_size))
{
LOG_warn << "Error opening async file handle (sysstat) "
<< curr_mtime << " - " << mtime
<< curr_size << " - " << size;
return false;
}
if (curr_mtime != mtime || curr_size != size)
{
mtime = curr_mtime;
size = curr_size;
retry = false;
return false;
}
LOG_debug << "Opening async file handle for reading";
bool result = sysopen(true);
if (result)
{
isAsyncOpened = true;
}
else
{
LOG_warn << "Error opening async file handle (sysopen)";
}
return result;
}
void FileAccess::asyncclosef()
{
numAsyncReads--;
if (isAsyncOpened && !numAsyncReads)
{
LOG_debug << "Closing async file handle";
isAsyncOpened = false;
sysclose();
}
}
AsyncIOContext *FileAccess::asyncfopen(string *f, bool read, bool write, m_off_t pos)
{
LOG_verbose << "Async open start";
AsyncIOContext *context = newasynccontext();
context->op = AsyncIOContext::OPEN;
context->access = AsyncIOContext::ACCESS_NONE
| (read ? AsyncIOContext::ACCESS_READ : 0)
| (write ? AsyncIOContext::ACCESS_WRITE : 0);
context->buffer = (byte *)f->data();
context->len = static_cast<unsigned>(f->size());
context->waiter = waiter;
context->userCallback = asyncopfinished;
context->userData = waiter;
context->pos = pos;
context->fa = this;
asyncsysopen(context);
return context;
}
void FileAccess::asyncsysopen(AsyncIOContext *context)
{
context->failed = true;
context->retry = false;
context->finished = true;
if (context->userCallback)
{
context->userCallback(context->userData);
}
}
AsyncIOContext *FileAccess::asyncfread(string *dst, unsigned len, unsigned pad, m_off_t pos)
{
LOG_verbose << "Async read start";
dst->resize(len + pad);
AsyncIOContext *context = newasynccontext();
context->op = AsyncIOContext::READ;
context->pos = pos;
context->len = len;
context->pad = pad;
context->buffer = (byte *)dst->data();
context->waiter = waiter;
context->userCallback = asyncopfinished;
context->userData = waiter;
context->fa = this;
if (!asyncopenf())
{
LOG_err << "Error in asyncopenf";
context->failed = true;
context->retry = this->retry;
context->finished = true;
context->userCallback(context->userData);
return context;
}
asyncsysread(context);
return context;
}
void FileAccess::asyncsysread(AsyncIOContext *context)
{
context->failed = true;
context->retry = false;
context->finished = true;
if (context->userCallback)
{
context->userCallback(context->userData);
}
}
AsyncIOContext *FileAccess::asyncfwrite(const byte* data, unsigned len, m_off_t pos)
{
LOG_verbose << "Async write start";
AsyncIOContext *context = newasynccontext();
context->op = AsyncIOContext::WRITE;
context->pos = pos;
context->len = len;
context->buffer = (byte *)data;
context->waiter = waiter;
context->userCallback = asyncopfinished;
context->userData = waiter;
context->fa = this;
asyncsyswrite(context);
return context;
}
void FileAccess::asyncsyswrite(AsyncIOContext *context)
{
context->failed = true;
context->retry = false;
context->finished = true;
if (context->userCallback)
{
context->userCallback(context->userData);
}
}
AsyncIOContext *FileAccess::newasynccontext()
{
return new AsyncIOContext();
}
bool FileAccess::fread(string* dst, unsigned len, unsigned pad, m_off_t pos)
{
if (!openf())
{
return false;
}
bool r;
dst->resize(len + pad);
if ((r = sysread((byte*)dst->data(), len, pos)))
{
memset((char*)dst->data() + len, 0, pad);
}
closef();
return r;
}
bool FileAccess::frawread(byte* dst, unsigned len, m_off_t pos, bool caller_opened)
{
if (!caller_opened && !openf())
{
return false;
}
bool r = sysread(dst, len, pos);
if (!caller_opened)
{
closef();
}
return r;
}
AsyncIOContext::AsyncIOContext()
{
op = NONE;
pos = 0;
len = 0;
pad = 0;
buffer = NULL;
waiter = NULL;
access = ACCESS_NONE;
userCallback = NULL;
userData = NULL;
finished = false;
failed = false;
retry = false;
}
AsyncIOContext::~AsyncIOContext()
{
finish();
// AsyncIOContext objects must be deleted before the FileAccess object
if (op == AsyncIOContext::READ)
{
fa->asyncclosef();
}
}
void AsyncIOContext::finish()
{
if (!finished)
{
while (!finished)
{
waiter->init(NEVER);
waiter->wait();
}
// We could have been consumed and external event
waiter->notify();
}
}
FileInputStream::FileInputStream(FileAccess *fileAccess)
{
this->fileAccess = fileAccess;
this->offset = 0;
}
m_off_t FileInputStream::size()
{
return fileAccess->size;
}
bool FileInputStream::read(byte *buffer, unsigned size)
{
if (!buffer)
{
if ((offset + size) <= fileAccess->size)
{
offset += size;
return true;
}
LOG_warn << "Invalid seek on FileInputStream";
return false;
}
if (fileAccess->frawread(buffer, size, offset, true))
{
offset += size;
return true;
}
LOG_warn << "Invalid read on FileInputStream";
return false;
}
} // namespace