• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "meta_file.h"
17 
18 #include <ctime>
19 #include <fcntl.h>
20 #include <iomanip>
21 #include <sstream>
22 #include <sys/stat.h>
23 
24 #include "cloud_file_utils.h"
25 #include "dfs_error.h"
26 #include "directory_ex.h"
27 #include "file_utils.h"
28 #include "securec.h"
29 #include "string_ex.h"
30 #include "sys/xattr.h"
31 #include "utils_log.h"
32 
33 namespace OHOS {
34 namespace FileManagement {
35 constexpr uint32_t DENTRYGROUP_SIZE = 4096;
36 constexpr uint32_t DENTRY_NAME_LEN = 8;
37 constexpr uint32_t DENTRY_RESERVED_LENGTH = 3;
38 constexpr uint32_t DENTRY_PER_GROUP = 60;
39 constexpr uint32_t DENTRY_BITMAP_LENGTH = 8;
40 constexpr uint32_t DENTRY_GROUP_RESERVED = 7;
41 constexpr uint32_t CLOUD_RECORD_ID_LEN = 33;
42 constexpr uint32_t DENTRYGROUP_HEADER = 4096;
43 constexpr uint32_t MAX_BUCKET_LEVEL = 63;
44 constexpr uint32_t BUCKET_BLOCKS = 2;
45 constexpr uint32_t BITS_PER_BYTE = 8;
46 constexpr uint32_t HMDFS_SLOT_LEN_BITS = 3;
47 constexpr uint32_t DIR_SIZE = 4096;
48 
49 #pragma pack(push, 1)
50 struct HmdfsDentry {
51     uint32_t hash{0};
52     uint16_t mode{0};
53     uint16_t namelen{0};
54     uint64_t size{0};
55     uint64_t mtime{0};
56     uint8_t recordId[CLOUD_RECORD_ID_LEN]{0};
57     /* reserved bytes for long term extend, total 60 bytes */
58     union {
59         struct {
60             uint8_t fileType : 2;
61         };
62         uint8_t reserved[DENTRY_RESERVED_LENGTH];
63     };
64 };
65 
66 struct HmdfsDentryGroup {
67     uint8_t dentryVersion;
68     uint8_t bitmap[DENTRY_BITMAP_LENGTH];
69     HmdfsDentry nsl[DENTRY_PER_GROUP];
70     uint8_t fileName[DENTRY_PER_GROUP][DENTRY_NAME_LEN];
71     uint8_t reserved[DENTRY_GROUP_RESERVED];
72 };
73 static_assert(sizeof(HmdfsDentryGroup) == DENTRYGROUP_SIZE);
74 
75 struct HmdfsDcacheHeader {
76     uint64_t dcacheCrtime{0};
77     uint64_t dcacheCrtimeNsec{0};
78 
79     uint64_t dentryCtime{0};
80     uint64_t dentryCtimeNsec{0};
81 
82     uint64_t dentryCount{0};
83 };
84 #pragma pack(pop)
85 
PathHash(const std::string & path,bool caseSense)86 static uint64_t PathHash(const std::string &path, bool caseSense)
87 {
88     uint64_t res = 0;
89     const char *kp = path.c_str();
90 
91     while (*kp) {
92         char c = *kp;
93         if (!caseSense) {
94             c = tolower(c);
95         }
96         res = (res << 5) - res + static_cast<uint64_t>(c); /* hash shift width 5 */
97         kp++;
98     }
99     return res;
100 }
101 
GetDentryfileName(const std::string & path,bool caseSense)102 static std::string GetDentryfileName(const std::string &path, bool caseSense)
103 {
104     // path should be like "/", "/dir/", "/dir/dir/" ...
105     constexpr uint32_t fileNameLen = 32;
106     char buf[fileNameLen + 1] = {0};
107     uint64_t fileHash = PathHash(path, caseSense);
108     int ret = snprintf_s(buf, fileNameLen + 1, fileNameLen, "cloud_%016llx", fileHash);
109     if (ret < 0) {
110         LOGE("filename failer fileHash ret :%{public}d", ret);
111     }
112     return buf;
113 }
114 
GetDentryfileByPath(uint32_t userId,const std::string & path,bool caseSense=false)115 static std::string GetDentryfileByPath(uint32_t userId, const std::string &path, bool caseSense = false)
116 {
117     std::string cacheDir =
118         "/data/service/el2/" + std::to_string(userId) + "/hmdfs/cache/account_cache/dentry_cache/cloud/";
119     std::string dentryFileName = GetDentryfileName(path, caseSense);
120 
121     return cacheDir + dentryFileName;
122 }
123 
GetParentDir(const std::string & path)124 std::string MetaFile::GetParentDir(const std::string &path)
125 {
126     if ((path == "/") || (path == "")) {
127         return "";
128     }
129 
130     auto pos = path.find_last_of('/');
131     if ((pos == std::string::npos) || (pos == 0)) {
132         return "/";
133     }
134 
135     return path.substr(0, pos);
136 }
137 
GetFileName(const std::string & path)138 std::string MetaFile::GetFileName(const std::string &path)
139 {
140     if ((path == "/") || (path == "")) {
141         return "";
142     }
143 
144     auto pos = path.find_last_of('/');
145     if (pos == std::string::npos) {
146         return "";
147     }
148 
149     return path.substr(pos + 1);
150 }
151 
GetParentMetaFile(uint32_t userId,const std::string & path)152 static std::shared_ptr<MetaFile> GetParentMetaFile(uint32_t userId, const std::string &path)
153 {
154     std::string parentPath = MetaFile::GetParentDir(path);
155     if (parentPath == "") {
156         return nullptr;
157     }
158 
159     return MetaFileMgr::GetInstance().GetMetaFile(userId, parentPath);
160 }
161 
MetaFile(uint32_t userId,const std::string & path)162 MetaFile::MetaFile(uint32_t userId, const std::string &path)
163 {
164     path_ = path;
165     cacheFile_ = GetDentryfileByPath(userId, path);
166     fd_ = UniqueFd{open(cacheFile_.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP)};
167     if (fd_ < 0) {
168         LOGE("fd=%{public}d, errno :%{public}d", fd_.Get(), errno);
169         return;
170     }
171 
172     int ret = fsetxattr(fd_, "user.hmdfs_cache", path.c_str(), path.size(), 0);
173     if (ret != 0) {
174         LOGE("setxattr failed, errno %{public}d, cacheFile_ %s", errno, GetAnonyString(cacheFile_).c_str());
175     }
176 
177     /* lookup and create in parent */
178     parentMetaFile_ = GetParentMetaFile(userId, path);
179     std::string dirName = GetFileName(path);
180     if ((parentMetaFile_ == nullptr) || (dirName == "")) {
181         return;
182     }
183     MetaBase m(dirName, std::to_string(PathHash(path, false)) + std::to_string(std::time(nullptr)));
184     ret = parentMetaFile_->DoLookup(m);
185     if (ret != E_OK) {
186         m.mode = S_IFDIR;
187         m.size = DIR_SIZE;
188         ret = parentMetaFile_->DoCreate(m);
189         if (ret != E_OK) {
190             LOGE("create parent failed, ret %{public}d", ret);
191         }
192     }
193 }
194 
~MetaFile()195 MetaFile::~MetaFile()
196 {
197 }
198 
GetDentrySlots(size_t nameLen)199 static inline uint32_t GetDentrySlots(size_t nameLen)
200 {
201     return static_cast<uint32_t>((nameLen + BITS_PER_BYTE - 1) >> HMDFS_SLOT_LEN_BITS);
202 }
203 
GetDentryGroupPos(size_t bidx)204 static inline off_t GetDentryGroupPos(size_t bidx)
205 {
206     return bidx * DENTRYGROUP_SIZE + DENTRYGROUP_HEADER;
207 }
208 
GetDentryGroupCnt(uint64_t size)209 static inline uint64_t GetDentryGroupCnt(uint64_t size)
210 {
211     return (size >= DENTRYGROUP_HEADER) ? ((size - DENTRYGROUP_HEADER) / DENTRYGROUP_SIZE) : 0;
212 }
213 
GetOverallBucket(uint32_t level)214 static uint32_t GetOverallBucket(uint32_t level)
215 {
216     if (level >= MAX_BUCKET_LEVEL) {
217         LOGI("level = %{public}d overflow", level);
218         return 0;
219     }
220     uint64_t buckets = (1ULL << (level + 1)) - 1;
221     return static_cast<uint32_t>(buckets);
222 }
223 
GetDcacheFileSize(uint32_t level)224 static size_t GetDcacheFileSize(uint32_t level)
225 {
226     size_t buckets = GetOverallBucket(level);
227     return buckets * DENTRYGROUP_SIZE * BUCKET_BLOCKS + DENTRYGROUP_HEADER;
228 }
229 
GetBucketaddr(uint32_t level,uint32_t buckoffset)230 static uint32_t GetBucketaddr(uint32_t level, uint32_t buckoffset)
231 {
232     if (level >= MAX_BUCKET_LEVEL) {
233         return 0;
234     }
235 
236     uint64_t curLevelMaxBucks = (1ULL << level);
237     if (buckoffset >= curLevelMaxBucks) {
238         return 0;
239     }
240 
241     return static_cast<uint32_t>(curLevelMaxBucks) + buckoffset - 1;
242 }
243 
GetBucketByLevel(uint32_t level)244 static uint32_t GetBucketByLevel(uint32_t level)
245 {
246     if (level >= MAX_BUCKET_LEVEL) {
247         LOGI("level = %{public}d overflow", level);
248         return 0;
249     }
250 
251     uint64_t buckets = (1ULL << level);
252     return static_cast<uint32_t>(buckets);
253 }
254 
RoomForFilename(const uint8_t bitmap[],size_t slots,uint32_t maxSlots)255 static uint32_t RoomForFilename(const uint8_t bitmap[], size_t slots, uint32_t maxSlots)
256 {
257     uint32_t bitStart = 0;
258 
259     while (1) {
260         uint32_t zeroStart = BitOps::FindNextZeroBit(bitmap, maxSlots, bitStart);
261         if (zeroStart >= maxSlots) {
262             return maxSlots;
263         }
264 
265         uint32_t zeroEnd = BitOps::FindNextBit(bitmap, maxSlots, zeroStart);
266         if (zeroEnd - zeroStart >= slots) {
267             return zeroStart;
268         }
269 
270         bitStart = zeroEnd + 1;
271         if (zeroEnd + 1 >= maxSlots) {
272             return maxSlots;
273         }
274     }
275     return 0;
276 }
277 
UpdateDentry(HmdfsDentryGroup & d,const MetaBase & base,uint32_t nameHash,uint32_t bitPos)278 static bool UpdateDentry(HmdfsDentryGroup &d, const MetaBase &base, uint32_t nameHash, uint32_t bitPos)
279 {
280     HmdfsDentry *de;
281     const std::string name = base.name;
282     uint32_t slots = GetDentrySlots(name.length());
283 
284     de = &d.nsl[bitPos];
285     de->hash = nameHash;
286     de->namelen = name.length();
287     errno_t ret = memcpy_s(d.fileName[bitPos], slots * DENTRY_NAME_LEN, name.c_str(), name.length());
288     if (ret != EOK) {
289         LOGE("memcpy_s failed, dstLen = %{public}d, srcLen = %{public}zu", slots * DENTRY_NAME_LEN, name.length());
290         return false;
291     }
292     de->mtime = base.mtime;
293     de->fileType = base.fileType;
294     de->size = base.size;
295     de->mode = base.mode;
296     ret = memcpy_s(de->recordId, CLOUD_RECORD_ID_LEN, base.cloudId.c_str(), base.cloudId.length());
297     if (ret != EOK) {
298         LOGE("memcpy_s failed, dstLen = %{public}d, srcLen = %{public}zu", CLOUD_RECORD_ID_LEN, base.cloudId.length());
299         return false;
300     }
301 
302     for (uint32_t i = 0; i < slots; i++) {
303         BitOps::SetBit(bitPos + i, d.bitmap);
304         if (i) {
305             (de + i)->namelen = 0;
306         }
307     }
308     return true;
309 }
310 
HandleFileByFd(unsigned long & endBlock,uint32_t & level)311 int32_t MetaFile::HandleFileByFd(unsigned long &endBlock, uint32_t &level)
312 {
313     struct stat fileStat;
314     int err = fstat(fd_, &fileStat);
315     if (err < 0) {
316         return EINVAL;
317     }
318     if ((endBlock > GetDentryGroupCnt(fileStat.st_size)) &&
319         ftruncate(fd_, GetDcacheFileSize(level))) {
320         return ENOENT;
321     }
322     return E_OK;
323 }
324 
DoCreate(const MetaBase & base)325 int32_t MetaFile::DoCreate(const MetaBase &base)
326 {
327     if (fd_ < 0) {
328         LOGE("bad metafile fd");
329         return EINVAL;
330     }
331 
332     off_t pos = 0;
333     uint32_t level = 0;
334     uint32_t bitPos = 0;
335     unsigned long bidx;
336     HmdfsDentryGroup dentryBlk = {0};
337 
338     std::unique_lock<std::mutex> lock(mtx_);
339     uint32_t namehash = CloudDisk::CloudFileUtils::DentryHash(base.name);
340 
341     bool found = false;
342     while (!found) {
343         if (level == MAX_BUCKET_LEVEL) {
344             return ENOSPC;
345         }
346         bidx = BUCKET_BLOCKS * GetBucketaddr(level, namehash % GetBucketByLevel(level));
347         unsigned long endBlock = bidx + BUCKET_BLOCKS;
348 
349         int32_t ret = MetaFile::HandleFileByFd(endBlock, level);
350         if (ret != E_OK) {
351             return ret;
352         }
353 
354         for (; bidx < endBlock; bidx++) {
355             pos = GetDentryGroupPos(bidx);
356             if (FileUtils::ReadFile(fd_, pos, DENTRYGROUP_SIZE, &dentryBlk) != DENTRYGROUP_SIZE) {
357                 return ENOENT;
358             }
359             bitPos = RoomForFilename(dentryBlk.bitmap, GetDentrySlots(base.name.length()), DENTRY_PER_GROUP);
360             if (bitPos < DENTRY_PER_GROUP) {
361                 found = true;
362                 break;
363             }
364         }
365         ++level;
366     }
367 
368     pos = GetDentryGroupPos(bidx);
369     if (!UpdateDentry(dentryBlk, base, namehash, bitPos)) {
370         LOGI("UpdateDentry fail, stop write.");
371         return EINVAL;
372     }
373     int size = FileUtils::WriteFile(fd_, &dentryBlk, pos, DENTRYGROUP_SIZE);
374     if (size != DENTRYGROUP_SIZE) {
375         LOGI("WriteFile failed, size %{public}d != %{public}d", size, DENTRYGROUP_SIZE);
376         return EINVAL;
377     }
378 
379     return E_OK;
380 }
381 
382 struct DcacheLookupCtx {
383     int fd{-1};
384     std::string name{};
385     uint32_t hash{0};
386     uint32_t bidx{0};
387     std::unique_ptr<HmdfsDentryGroup> page{nullptr};
388 };
389 
InitDcacheLookupCtx(DcacheLookupCtx * ctx,const MetaBase & base,int fd)390 static void InitDcacheLookupCtx(DcacheLookupCtx *ctx, const MetaBase &base, int fd)
391 {
392     ctx->fd = fd;
393     ctx->name = base.name;
394     ctx->bidx = 0;
395     ctx->page = nullptr;
396     ctx->hash = CloudDisk::CloudFileUtils::DentryHash(ctx->name);
397 }
398 
FindDentryPage(uint64_t index,DcacheLookupCtx * ctx)399 static std::unique_ptr<HmdfsDentryGroup> FindDentryPage(uint64_t index, DcacheLookupCtx *ctx)
400 {
401     auto dentryBlk = std::make_unique<HmdfsDentryGroup>();
402 
403     off_t pos = GetDentryGroupPos(index);
404     ssize_t size = FileUtils::ReadFile(ctx->fd, pos, DENTRYGROUP_SIZE, dentryBlk.get());
405     if (size != DENTRYGROUP_SIZE) {
406         return nullptr;
407     }
408     return dentryBlk;
409 }
410 
FindInBlock(HmdfsDentryGroup & dentryBlk,uint32_t namehash,const std::string & name)411 static HmdfsDentry *FindInBlock(HmdfsDentryGroup &dentryBlk, uint32_t namehash, const std::string &name)
412 {
413     int maxLen = 0;
414     uint32_t bitPos = 0;
415     HmdfsDentry *de = nullptr;
416 
417     while (bitPos < DENTRY_PER_GROUP) {
418         if (!BitOps::TestBit(bitPos, dentryBlk.bitmap)) {
419             bitPos++;
420             maxLen++;
421             continue;
422         }
423         de = &dentryBlk.nsl[bitPos];
424         if (!de->namelen) {
425             bitPos++;
426             continue;
427         }
428 
429         if (de->hash == namehash && de->namelen == name.length() &&
430             !memcmp(name.c_str(), dentryBlk.fileName[bitPos], de->namelen)) {
431             return de;
432         }
433         maxLen = 0;
434         bitPos += GetDentrySlots(de->namelen);
435     }
436 
437     return nullptr;
438 }
439 
InLevel(uint32_t level,DcacheLookupCtx * ctx)440 static HmdfsDentry *InLevel(uint32_t level, DcacheLookupCtx *ctx)
441                             __attribute__((no_sanitize("unsigned-integer-overflow")))
442 {
443     HmdfsDentry *de = nullptr;
444 
445     uint32_t nbucket = GetBucketByLevel(level);
446     if (!nbucket) {
447         return de;
448     }
449 
450     uint32_t bidx = GetBucketaddr(level, ctx->hash % nbucket) * BUCKET_BLOCKS;
451     uint32_t endBlock = bidx + BUCKET_BLOCKS;
452 
453     for (; bidx < endBlock; bidx++) {
454         auto dentryBlk = FindDentryPage(bidx, ctx);
455         if (dentryBlk == nullptr) {
456             break;
457         }
458 
459         de = FindInBlock(*dentryBlk, ctx->hash, ctx->name);
460         if (de != nullptr) {
461             ctx->page = std::move(dentryBlk);
462             break;
463         }
464     }
465     ctx->bidx = bidx;
466     return de;
467 }
468 
GetMaxLevel(int32_t fd)469 static uint32_t GetMaxLevel(int32_t fd)
470 {
471     struct stat st;
472     if (fstat(fd, &st) == -1) {
473         return MAX_BUCKET_LEVEL;
474     }
475     uint32_t blkNum = static_cast<uint32_t>(st.st_size) / DENTRYGROUP_SIZE + 1;
476     uint32_t maxLevel = 0;
477     blkNum >>= 1;
478     while (blkNum > 1) {
479         blkNum >>= 1;
480         maxLevel++;
481     }
482     return maxLevel;
483 }
484 
FindDentry(DcacheLookupCtx * ctx)485 static HmdfsDentry *FindDentry(DcacheLookupCtx *ctx)
486 {
487     uint32_t maxLevel = GetMaxLevel(ctx->fd);
488     for (uint32_t level = 0; level < maxLevel; level++) {
489         HmdfsDentry *de = InLevel(level, ctx);
490         if (de != nullptr) {
491             return de;
492         }
493     }
494     return nullptr;
495 }
496 
DoRemove(const MetaBase & base)497 int32_t MetaFile::DoRemove(const MetaBase &base)
498 {
499     if (fd_ < 0) {
500         LOGE("bad metafile fd");
501         return EINVAL;
502     }
503 
504     std::unique_lock<std::mutex> lock(mtx_);
505     DcacheLookupCtx ctx;
506     InitDcacheLookupCtx(&ctx, base, fd_);
507     HmdfsDentry *de = FindDentry(&ctx);
508     if (de == nullptr) {
509         LOGE("find dentry failed");
510         return ENOENT;
511     }
512 
513     uint32_t bitPos = (de - ctx.page->nsl);
514     uint32_t slots = GetDentrySlots(de->namelen);
515     for (uint32_t i = 0; i < slots; i++) {
516         BitOps::ClearBit(bitPos + i, ctx.page->bitmap);
517     }
518 
519     off_t ipos = GetDentryGroupPos(ctx.bidx);
520     ssize_t size = FileUtils::WriteFile(fd_, ctx.page.get(), ipos, sizeof(HmdfsDentryGroup));
521     if (size != sizeof(HmdfsDentryGroup)) {
522         LOGE("WriteFile failed!, ret = %{public}zd", size);
523         return EIO;
524     }
525 
526     return E_OK;
527 }
528 
DoLookup(MetaBase & base)529 int32_t MetaFile::DoLookup(MetaBase &base)
530 {
531     if (fd_ < 0) {
532         LOGE("bad metafile fd");
533         return EINVAL;
534     }
535 
536     std::unique_lock<std::mutex> lock(mtx_);
537     struct DcacheLookupCtx ctx;
538     InitDcacheLookupCtx(&ctx, base, fd_);
539     struct HmdfsDentry *de = FindDentry(&ctx);
540     if (de == nullptr) {
541         LOGD("find dentry failed");
542         return ENOENT;
543     }
544 
545     base.size = de->size;
546     base.mtime = de->mtime;
547     base.mode = de->mode;
548     base.fileType = de->fileType;
549     base.cloudId = std::string(reinterpret_cast<const char *>(de->recordId), CLOUD_RECORD_ID_LEN - 1);
550 
551     return E_OK;
552 }
553 
DoUpdate(const MetaBase & base)554 int32_t MetaFile::DoUpdate(const MetaBase &base)
555 {
556     if (fd_ < 0) {
557         LOGE("bad metafile fd");
558         return EINVAL;
559     }
560 
561     std::unique_lock<std::mutex> lock(mtx_);
562     struct DcacheLookupCtx ctx;
563     InitDcacheLookupCtx(&ctx, base, fd_);
564     struct HmdfsDentry *de = FindDentry(&ctx);
565     if (de == nullptr) {
566         LOGI("find dentry failed");
567         return ENOENT;
568     }
569 
570     de->mtime = base.mtime;
571     de->size = base.size;
572     de->mode = base.mode;
573     de->fileType = base.fileType;
574     if (memcpy_s(de->recordId, CLOUD_RECORD_ID_LEN, base.cloudId.c_str(), base.cloudId.length())) {
575         LOGE("memcpy_s failed, dstLen = %{public}d, srcLen = %{public}zu", CLOUD_RECORD_ID_LEN, base.cloudId.length());
576     }
577 
578     off_t ipos = GetDentryGroupPos(ctx.bidx);
579     ssize_t size = FileUtils::WriteFile(fd_, ctx.page.get(), ipos, sizeof(struct HmdfsDentryGroup));
580     if (size != sizeof(struct HmdfsDentryGroup)) {
581         LOGI("write failed, ret = %{public}zd", size);
582         return EIO;
583     }
584     return E_OK;
585 }
586 
DoRename(const MetaBase & oldBase,const std::string & newName)587 int32_t MetaFile::DoRename(const MetaBase &oldBase, const std::string &newName)
588 {
589     MetaBase base{oldBase.name};
590     int32_t ret = DoLookup(base);
591     if (ret) {
592         LOGE("ret = %{public}d, lookup %s failed", ret, GetAnonyString(base.name).c_str());
593         return ret;
594     }
595 
596     base.name = newName;
597     ret = DoCreate(base);
598     if (ret) {
599         LOGE("ret = %{public}d, create %s failed", ret, GetAnonyString(base.name).c_str());
600         return ret;
601     }
602 
603     base.name = oldBase.name;
604     ret = DoRemove(oldBase);
605     if (ret) {
606         LOGE("ret = %{public}d, remove %s failed", ret, GetAnonyString(oldBase.name).c_str());
607         base.name = newName;
608         (void)DoRemove(base);
609         return ret;
610     }
611 
612     return E_OK;
613 }
614 
DecodeDentrys(const HmdfsDentryGroup & dentryGroup,std::vector<MetaBase> & bases)615 static int32_t DecodeDentrys(const HmdfsDentryGroup &dentryGroup, std::vector<MetaBase> &bases)
616 {
617     for (uint32_t i = 0; i < DENTRY_PER_GROUP; i++) {
618         int len = dentryGroup.nsl[i].namelen;
619         if (!BitOps::TestBit(i, dentryGroup.bitmap) || len == 0 || len >= PATH_MAX) {
620             continue;
621         }
622 
623         std::string name(reinterpret_cast<const char *>(dentryGroup.fileName[i]), len);
624 
625         MetaBase base(name);
626         base.mode = dentryGroup.nsl[i].mode;
627         base.mtime = dentryGroup.nsl[i].mtime;
628         base.size = dentryGroup.nsl[i].size;
629         base.fileType = dentryGroup.nsl[i].fileType;
630         base.cloudId = std::string(reinterpret_cast<const char *>(dentryGroup.nsl[i].recordId), CLOUD_RECORD_ID_LEN);
631         bases.emplace_back(base);
632     }
633     return 0;
634 }
635 
LoadChildren(std::vector<MetaBase> & bases)636 int32_t MetaFile::LoadChildren(std::vector<MetaBase> &bases)
637 {
638     if (fd_ < 0) {
639         LOGE("bad metafile fd");
640         return EINVAL;
641     }
642 
643     std::lock_guard<std::mutex> lock(mtx_);
644     struct stat fileStat;
645     int ret = fstat(fd_, &fileStat);
646     if (ret != E_OK) {
647         return EINVAL;
648     }
649 
650     uint64_t fileSize = static_cast<uint64_t>(fileStat.st_size);
651     uint64_t groupCnt = GetDentryGroupCnt(fileSize);
652     HmdfsDentryGroup dentryGroup;
653 
654     for (uint64_t i = 1; i < groupCnt + 1; i++) {
655         uint64_t off = i * sizeof(HmdfsDentryGroup);
656         FileUtils::ReadFile(fd_, off, sizeof(HmdfsDentryGroup), &dentryGroup);
657         DecodeDentrys(dentryGroup, bases);
658     }
659     return E_OK;
660 }
661 
GetInstance()662 MetaFileMgr& MetaFileMgr::GetInstance()
663 {
664     static MetaFileMgr instance_;
665     return instance_;
666 }
667 
GetMetaFile(uint32_t userId,const std::string & path)668 std::shared_ptr<MetaFile> MetaFileMgr::GetMetaFile(uint32_t userId, const std::string &path)
669 {
670     std::shared_ptr<MetaFile> mFile = nullptr;
671     std::lock_guard<std::recursive_mutex> lock(mtx_);
672 
673     MetaFileKey key(userId, path);
674     auto it = metaFiles_.find(key);
675     if (it != metaFiles_.end()) {
676         metaFileList_.splice(metaFileList_.begin(), metaFileList_, it->second);
677         mFile = it->second->second;
678     } else {
679         if (metaFiles_.size() == MAX_META_FILE_NUM) {
680             auto deleteKey = metaFileList_.back().first;
681             metaFiles_.erase(deleteKey);
682             metaFileList_.pop_back();
683         }
684         mFile = std::make_shared<MetaFile>(userId, path);
685         metaFileList_.emplace_front(key, mFile);
686         metaFiles_[key] = metaFileList_.begin();
687     }
688     return mFile;
689 }
690 
ClearAll()691 void MetaFileMgr::ClearAll()
692 {
693     std::lock_guard<std::recursive_mutex> lock(mtx_);
694     metaFiles_.clear();
695     metaFileList_.clear();
696 }
697 
RecordIdToCloudId(const std::string hexStr)698 std::string MetaFileMgr::RecordIdToCloudId(const std::string hexStr)
699 {
700     std::string result;
701     constexpr std::size_t offset = 2;
702     constexpr int changeBase = 16;
703     for (std::size_t i = 0; i < hexStr.length(); i += offset) {
704         std::string hexByte = hexStr.substr(i, offset);
705         char *endPtr;
706         unsigned long hexValue = std::strtoul(hexByte.c_str(), &endPtr, changeBase);
707 
708         if (endPtr != hexByte.c_str() + hexByte.length()) {
709             LOGE("Invalid hexadecimal string: %{public}s", hexStr.c_str());
710             return "";
711         }
712         result += static_cast<char>(hexValue);
713     }
714     if (result.size() > CLOUD_RECORD_ID_LEN) {
715         LOGE("Invalid result length %{public}zu", result.size());
716         return "";
717     }
718 
719     return result;
720 }
721 
CloudIdToRecordId(const std::string cloudId)722 std::string MetaFileMgr::CloudIdToRecordId(const std::string cloudId)
723 {
724     std::stringstream result;
725     constexpr int width = 2;
726     for (std::size_t i = 0; i < cloudId.length(); i++) {
727         uint8_t u8Byte = cloudId[i];
728         result << std::setw(width) << std::setfill('0') << std::hex << static_cast<int>(u8Byte);
729     }
730     return result.str();
731 }
732 
733 } // namespace FileManagement
734 } // namespace OHOS
735