1 /*
2 * Copyright (c) 2024 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 "mtpfs_tmp_files_pool.h"
17
18 #include <openssl/sha.h>
19 #include <securec.h>
20 #include <sstream>
21
22 #include "mtpfs_util.h"
23 #include "storage_service_log.h"
24
MtpFsTmpFilesPool()25 MtpFsTmpFilesPool::MtpFsTmpFilesPool() : tmpDir_(SmtpfsGetTmpDir()), pool_() {}
26
~MtpFsTmpFilesPool()27 MtpFsTmpFilesPool::~MtpFsTmpFilesPool() {}
28
GetSha256Hash(const std::string & input)29 std::string GetSha256Hash(const std::string &input)
30 {
31 const int32_t sha256HashBitNum = 2;
32 if (input.size() == 0) {
33 LOGE("Input param invalied.");
34 return "";
35 }
36 unsigned char hash[SHA256_DIGEST_LENGTH * sha256HashBitNum + 1] = "";
37 SHA256_CTX ctx;
38 SHA256_Init(&ctx);
39 SHA256_Update(&ctx, input.c_str(), input.size());
40 SHA256_Final(hash, &ctx);
41
42 char res[SHA256_DIGEST_LENGTH * sha256HashBitNum + 1];
43 for (int i = 0; i < SHA256_DIGEST_LENGTH; ++i) {
44 if (sprintf_s(&res[i * sha256HashBitNum], sizeof(res), "%02x", hash[i]) < 0) {
45 LOGE("sprintf_s error");
46 return "";
47 }
48 }
49 return std::string(res);
50 }
51
RemoveFile(const std::string & path)52 void MtpFsTmpFilesPool::RemoveFile(const std::string &path)
53 {
54 auto it = std::find(pool_.begin(), pool_.end(), path);
55 if (it == pool_.end()) {
56 return;
57 }
58 pool_.erase(it);
59 }
60
GetFile(const std::string & path) const61 const MtpFsTypeTmpFile *MtpFsTmpFilesPool::GetFile(const std::string &path) const
62 {
63 auto it = std::find(pool_.begin(), pool_.end(), path);
64 if (it == pool_.end()) {
65 return nullptr;
66 }
67 return static_cast<const MtpFsTypeTmpFile *>(&*it);
68 }
69
MakeTmpPath(const std::string & pathDevice) const70 std::string MtpFsTmpFilesPool::MakeTmpPath(const std::string &pathDevice) const
71 {
72 static int cnt = 0;
73 std::stringstream ss;
74 ss << pathDevice << ++cnt;
75 return tmpDir_ + std::string("/") + GetSha256Hash(pathDevice);
76 }
77
CreateTmpDir()78 bool MtpFsTmpFilesPool::CreateTmpDir()
79 {
80 if (RemoveTmpDir()) {
81 return SmtpfsCreateDir(tmpDir_);
82 }
83 return false;
84 }
85
RemoveTmpDir()86 bool MtpFsTmpFilesPool::RemoveTmpDir()
87 {
88 if (!tmpDir_.empty()) {
89 return SmtpfsRemoveDir(tmpDir_);
90 }
91 return false;
92 }
93