• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2025 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 "ipc/storage_daemon_provider.h"
17 #include "securec.h"
18 #include "storage_service_errno.h"
19 #include "storage_service_log.h"
20 #include "string_ex.h"
21 #include "system_ability_definition.h"
22 #include "utils/storage_radar.h"
23 #include "utils/storage_xcollie.h"
24 #include <cinttypes>
25 #ifdef EXTERNAL_STORAGE_MANAGER
26 #include "disk/disk_manager.h"
27 #include "volume/volume_manager.h"
28 #endif
29 #include "file_ex.h"
30 #include "hi_audit.h"
31 #include "user/mount_manager.h"
32 #include "utils/string_utils.h"
33 #include <dlfcn.h>
34 #include <fcntl.h>
35 #include <fstream>
36 #include <sys/resource.h>
37 #include <sys/syscall.h>
38 #include <thread>
39 #ifdef USER_CRYPTO_MANAGER
40 #include "crypto/app_clone_key_manager.h"
41 #include "crypto/iam_client.h"
42 #include "crypto/key_crypto_utils.h"
43 #include "crypto/key_manager.h"
44 #endif
45 #include "file_share.h"
46 #include "file_sharing/file_sharing.h"
47 #include "quota/quota_manager.h"
48 #include "user/user_manager.h"
49 namespace OHOS {
50 namespace StorageDaemon {
51 using namespace std;
52 constexpr unsigned int LOCAL_TIME_OUT_SECONDS = 10;
53 constexpr unsigned int INACTIVE_USER_KEY_OUT_SECONDS = 25;
54 constexpr unsigned int UPDATE_RADAR_STATISTIC_INTERVAL_SECONDS = 300;
55 constexpr unsigned int RADAR_REPORT_STATISTIC_INTERVAL_MINUTES = 1440;
56 constexpr unsigned int USER0ID = 0;
57 constexpr unsigned int USER100ID = 100;
58 constexpr unsigned int RADAR_STATISTIC_THREAD_WAIT_SECONDS = 60;
59 constexpr unsigned int MAX_URI_COUNT = 200000;
60 constexpr size_t MAX_IPC_RAW_DATA_SIZE = 128 * 1024 * 1024; // 128M
61 
GetUserStatistics(const uint32_t userId)62 std::map<uint32_t, RadarStatisticInfo>::iterator StorageDaemonProvider::GetUserStatistics(const uint32_t userId)
63 {
64     std::lock_guard<std::mutex> lock(mutexStats_);
65     auto it = opStatistics_.find(userId);
66     if (it != opStatistics_.end()) {
67         return it;
68     }
69     RadarStatisticInfo radarInfo = {0};
70     return opStatistics_.insert(make_pair(userId, radarInfo)).first;
71 }
72 
GetTempStatistics(std::map<uint32_t,RadarStatisticInfo> & statistics)73 void StorageDaemonProvider::GetTempStatistics(std::map<uint32_t, RadarStatisticInfo> &statistics)
74 {
75     std::lock_guard<std::mutex> lock(mutexStats_);
76     statistics.insert(opStatistics_.begin(), opStatistics_.end());
77     opStatistics_.clear();
78 }
79 
StorageRadarThd(void)80 void StorageDaemonProvider::StorageRadarThd(void)
81 {
82     // report radar statistics when restart
83     std::unique_lock<std::mutex> lock(onRadarReportLock_);
84     if (execRadarReportCon_.wait_for(lock, std::chrono::seconds(RADAR_STATISTIC_THREAD_WAIT_SECONDS),
85                                      [this] { return this->stopRadarReport_.load(); })) {
86         LOGI("Storage statistic radar exit.");
87         return;
88     }
89     lock.unlock();
90     LOGI("Storage statistic thread start.");
91     StorageStatisticRadar::GetInstance().CreateStatisticFile();
92     std::map<uint32_t, RadarStatisticInfo> opStatisticsTemp;
93     StorageStatisticRadar::GetInstance().ReadStatisticFile(opStatisticsTemp);
94     if (!opStatisticsTemp.empty()) {
95         for (auto ele : opStatisticsTemp) {
96             StorageService::StorageRadar::ReportStatistics(ele.first, ele.second);
97         }
98         StorageStatisticRadar::GetInstance().CleanStatisticFile();
99     }
100     lastRadarReportTime_ = std::chrono::system_clock::now();
101     while (!stopRadarReport_.load()) {
102         std::unique_lock<std::mutex> lock(onRadarReportLock_);
103         if (execRadarReportCon_.wait_for(lock, std::chrono::seconds(UPDATE_RADAR_STATISTIC_INTERVAL_SECONDS),
104                                          [this] { return this->stopRadarReport_.load(); })) {
105             LOGI("Storage statistic radar exit.");
106             return;
107         }
108         std::chrono::time_point<std::chrono::system_clock> nowTime = std::chrono::system_clock::now();
109         int64_t intervalMinutes =
110             std::chrono::duration_cast<std::chrono::minutes>(nowTime - lastRadarReportTime_).count();
111         if ((intervalMinutes > RADAR_REPORT_STATISTIC_INTERVAL_MINUTES) && !opStatistics_.empty()) {
112             LOGI("Storage statistic report, intervalMinutes:%{public}" PRId64, intervalMinutes);
113             opStatisticsTemp.clear();
114             GetTempStatistics(opStatisticsTemp);
115             for (auto ele : opStatisticsTemp) {
116                 StorageService::StorageRadar::ReportStatistics(ele.first, ele.second);
117             }
118             lastRadarReportTime_ = std::chrono::system_clock::now();
119             StorageStatisticRadar::GetInstance().CleanStatisticFile();
120             continue;
121         }
122         if (!isNeedUpdateRadarFile_) {
123             LOGD("Storage statistic not need update.");
124             continue;
125         }
126         LOGI("Storage statistic update, intervalMinutes:%{public}" PRId64, intervalMinutes);
127         isNeedUpdateRadarFile_ = false;
128         StorageStatisticRadar::GetInstance().UpdateStatisticFile(opStatistics_);
129     }
130 }
131 
StorageDaemonProvider()132 StorageDaemonProvider::StorageDaemonProvider()
133 {
134     callRadarStatisticReportThread_ = std::thread([this]() { StorageRadarThd(); });
135 }
136 
~StorageDaemonProvider()137 StorageDaemonProvider::~StorageDaemonProvider()
138 {
139     std::unique_lock<std::mutex> lock(onRadarReportLock_);
140     stopRadarReport_ = true;
141     execRadarReportCon_.notify_one();
142     lock.unlock();
143     if (callRadarStatisticReportThread_.joinable()) {
144         callRadarStatisticReportThread_.join();
145     }
146 }
147 
Shutdown()148 int32_t StorageDaemonProvider::Shutdown()
149 {
150     return E_OK;
151 }
152 
Mount(const std::string & volId,uint32_t flags)153 int32_t StorageDaemonProvider::Mount(const std::string &volId, uint32_t flags)
154 {
155 #ifdef EXTERNAL_STORAGE_MANAGER
156     LOGI("Handle Mount");
157     int32_t ret = VolumeManager::Instance().Mount(volId, flags);
158     if (ret != E_OK) {
159         LOGW("Mount failed, please check");
160         StorageService::StorageRadar::ReportVolumeOperation("VolumeManager::Mount", ret);
161         AuditLog storageAuditLog = {false, "FAILED TO Mount", "ADD", "Mount", 1, "FAIL"};
162         HiAudit::GetInstance().Write(storageAuditLog);
163     } else {
164         AuditLog storageAuditLog = {false, "SUCCESS TO Mount", "ADD", "Mount", 1, "SUCCESS"};
165         HiAudit::GetInstance().Write(storageAuditLog);
166     }
167     return ret;
168 #else
169     return E_OK;
170 #endif
171 }
172 
UMount(const std::string & volId)173 int32_t StorageDaemonProvider::UMount(const std::string &volId)
174 {
175 #ifdef EXTERNAL_STORAGE_MANAGER
176     LOGI("Handle UMount");
177     int32_t ret = VolumeManager::Instance().UMount(volId);
178     if (ret != E_OK) {
179         LOGW("UMount failed, please check");
180         StorageService::StorageRadar::ReportVolumeOperation("VolumeManager::UMount", ret);
181         AuditLog storageAuditLog = {false, "FAILED TO UMount", "DEL", "UMount", 1, "FAIL"};
182         HiAudit::GetInstance().Write(storageAuditLog);
183     } else {
184         AuditLog storageAuditLog = {false, "SUCCESS TO UMount", "DEL", "UMount", 1, "SUCCESS"};
185         HiAudit::GetInstance().Write(storageAuditLog);
186     }
187     return ret;
188 #else
189     return E_OK;
190 #endif
191 }
192 
TryToFix(const std::string & volId,uint32_t flags)193 int32_t StorageDaemonProvider::TryToFix(const std::string &volId, uint32_t flags)
194 {
195 #ifdef EXTERNAL_STORAGE_MANAGER
196     LOGI("Handle TryToFix");
197     int32_t ret = VolumeManager::Instance().TryToFix(volId, flags);
198     if (ret != E_OK) {
199         LOGW("TryToFix failed, please check");
200         StorageService::StorageRadar::ReportVolumeOperation("VolumeManager::TryToFix", ret);
201     }
202     return ret;
203 #else
204     return E_OK;
205 #endif
206 }
207 
MountUsbFuse(const std::string & volumeId,std::string & fsUuid,int & fuseFd)208 int32_t StorageDaemonProvider::MountUsbFuse(const std::string &volumeId, std::string &fsUuid, int &fuseFd)
209 {
210 #ifdef EXTERNAL_STORAGE_MANAGER
211     int32_t ret = VolumeManager::Instance().MountUsbFuse(volumeId, fsUuid, fuseFd);
212     if (ret != E_OK) {
213         LOGW("MountUsbFuse failed, please check");
214         StorageService::StorageRadar::ReportVolumeOperation("VolumeManager::MountUsbFuse", ret);
215     }
216     return ret;
217 #else
218     return E_OK;
219 #endif
220 }
221 
Check(const std::string & volId)222 int32_t StorageDaemonProvider::Check(const std::string &volId)
223 {
224 #ifdef EXTERNAL_STORAGE_MANAGER
225     LOGI("Handle Check");
226     int32_t ret = VolumeManager::Instance().Check(volId);
227     if (ret != E_OK) {
228         LOGW("Check failed, please check");
229         StorageService::StorageRadar::ReportVolumeOperation("VolumeManager::Check", ret);
230     }
231     return ret;
232 #else
233     return E_OK;
234 #endif
235 }
236 
Format(const std::string & volId,const std::string & fsType)237 int32_t StorageDaemonProvider::Format(const std::string &volId, const std::string &fsType)
238 {
239 #ifdef EXTERNAL_STORAGE_MANAGER
240     LOGI("Handle Format");
241     int32_t ret = VolumeManager::Instance().Format(volId, fsType);
242     if (ret != E_OK) {
243         LOGW("Format failed, please check");
244         StorageService::StorageRadar::ReportVolumeOperation("VolumeManager::Format", ret);
245         AuditLog storageAuditLog = {true, "FAILED TO Format", "UPDATE", "Format", 1, "FAIL"};
246         HiAudit::GetInstance().Write(storageAuditLog);
247     } else {
248         AuditLog storageAuditLog = {true, "SUCCESS TO Format", "UPDATE", "Format", 1, "SUCCESS"};
249         HiAudit::GetInstance().Write(storageAuditLog);
250     }
251     return ret;
252 #else
253     return E_OK;
254 #endif
255 }
256 
Partition(const std::string & diskId,int32_t type)257 int32_t StorageDaemonProvider::Partition(const std::string &diskId, int32_t type)
258 {
259 #ifdef EXTERNAL_STORAGE_MANAGER
260     LOGI("Handle Partition");
261     int32_t ret = DiskManager::Instance().HandlePartition(diskId);
262     if (ret != E_OK) {
263         LOGW("HandlePartition failed, please check");
264         StorageService::StorageRadar::ReportVolumeOperation("VolumeManager::Partition", ret);
265         AuditLog storageAuditLog = {true, "FAILED TO Partition", "UPDATE", "Partition", 1, "FAIL"};
266         HiAudit::GetInstance().Write(storageAuditLog);
267     } else {
268         AuditLog storageAuditLog = {true, "SUCCESS TO Partition", "UPDATE", "Partition", 1, "SUCCESS"};
269         HiAudit::GetInstance().Write(storageAuditLog);
270     }
271     return ret;
272 #else
273     return E_OK;
274 #endif
275 }
276 
SetVolumeDescription(const std::string & volId,const std::string & description)277 int32_t StorageDaemonProvider::SetVolumeDescription(const std::string &volId, const std::string &description)
278 {
279 #ifdef EXTERNAL_STORAGE_MANAGER
280     LOGI("Handle SetVolumeDescription");
281     int32_t ret = VolumeManager::Instance().SetVolumeDescription(volId, description);
282     if (ret != E_OK) {
283         LOGW("SetVolumeDescription failed, please check");
284         StorageService::StorageRadar::ReportVolumeOperation("VolumeManager::SetVolumeDescription", ret);
285         AuditLog storageAuditLog = {true,  "FAILED TO SetVolumeDescription", "UPDATE", "SetVolumeDescription", 1,
286                                     "FAIL"};
287         HiAudit::GetInstance().Write(storageAuditLog);
288     } else {
289         AuditLog storageAuditLog = {true,     "SUCCESS TO SetVolumeDescription", "UPDATE", "SetVolumeDescription", 1,
290                                     "SUCCESS"};
291         HiAudit::GetInstance().Write(storageAuditLog);
292     }
293     return ret;
294 #else
295     return E_OK;
296 #endif
297 }
298 
QueryUsbIsInUse(const std::string & diskPath,bool & isInUse)299 int32_t StorageDaemonProvider::QueryUsbIsInUse(const std::string &diskPath, bool &isInUse)
300 {
301 #ifdef EXTERNAL_STORAGE_MANAGER
302     LOGI("StorageDaemon::QueryUsbIsInUse diskPath: %{public}s", diskPath.c_str());
303     isInUse = true;
304     return VolumeManager::Instance().QueryUsbIsInUse(diskPath, isInUse);
305 #else
306     return E_NOT_SUPPORT;
307 #endif
308 }
309 
StartUser(int32_t userId)310 int32_t StorageDaemonProvider::StartUser(int32_t userId)
311 {
312     auto startTime = StorageService::StorageRadar::RecordCurrentTime();
313     auto it = GetUserStatistics(userId);
314     isNeedUpdateRadarFile_ = true;
315     (void)StorageDaemon::GetInstance().SetPriority();  // set tid priority to 40
316     int32_t ret = UserManager::GetInstance().StartUser(userId);
317     if (ret != E_OK && ret != E_KEY_NOT_ACTIVED) {
318         LOGE("StartUser failed, please check");
319         StorageService::StorageRadar::ReportUserManager("StartUser", userId, ret, "");
320         AuditLog storageAuditLog = { false, "FAILED TO StartUser", "ADD", "StartUser", 1, "FAIL" };
321         HiAudit::GetInstance().Write(storageAuditLog);
322     } else {
323         AuditLog storageAuditLog = { false, "SUCCESS TO StartUser", "ADD", "StartUser", 1, "SUCCESS" };
324         HiAudit::GetInstance().Write(storageAuditLog);
325     }
326     if (ret != E_OK) {
327         it->second.userStartFailCount++;
328     } else {
329         it->second.userStartSuccCount++;
330     }
331     auto delay = StorageService::StorageRadar::ReportDuration("START USER",
332         startTime, StorageService::DELAY_TIME_THRESH_HIGH, userId);
333     LOGI("SD_DURATION: START USER: delay time = %{public}s", delay.c_str());
334     return ret;
335 }
336 
StopUser(int32_t userId)337 int32_t StorageDaemonProvider::StopUser(int32_t userId)
338 {
339     auto it = GetUserStatistics(userId);
340     isNeedUpdateRadarFile_ = true;
341     int32_t ret = UserManager::GetInstance().StopUser(userId);
342     LOGE("StopUser end, ret is %{public}d.", ret);
343     StorageService::StorageRadar::ReportUserManager("StopUser", userId, ret, "");
344     std::string status = ret == E_OK ? "SUCCESS" : "FAIL";
345     std::string cause = ret == E_OK ? "SUCCESS TO StopUser" : "FAILED TO StopUser";
346     AuditLog storageAuditLog = { false, cause, "DEL", "StopUser", 1, status };
347     HiAudit::GetInstance().Write(storageAuditLog);
348     if (ret != E_OK) {
349         it->second.userStopFailCount++;
350     } else {
351         it->second.userStopSuccCount++;
352     }
353     return ret;
354 }
355 
PrepareUserDirs(int32_t userId,uint32_t flags)356 int32_t StorageDaemonProvider::PrepareUserDirs(int32_t userId, uint32_t flags)
357 {
358     std::lock_guard<std::mutex> lock(mutex_);
359     auto it = GetUserStatistics(userId);
360     isNeedUpdateRadarFile_ = true;
361     int32_t err = StorageDaemon::GetInstance().PrepareUserDirs(userId, flags);
362     if (err != E_OK) {
363         it->second.userAddFailCount++;
364     } else {
365         it->second.userAddSuccCount++;
366     }
367     return err;
368 }
369 
DestroyUserDirs(int32_t userId,uint32_t flags)370 int32_t StorageDaemonProvider::DestroyUserDirs(int32_t userId, uint32_t flags)
371 {
372     std::lock_guard<std::mutex> lock(mutex_);
373     auto it = GetUserStatistics(userId);
374     isNeedUpdateRadarFile_ = true;
375     int err = StorageDaemon::GetInstance().DestroyUserDirs(userId, flags);
376     if (err != E_OK) {
377         it->second.userRemoveFailCount++;
378     } else {
379         it->second.userRemoveSuccCount++;
380     }
381     return err;
382 }
383 
CompleteAddUser(int32_t userId)384 int32_t StorageDaemonProvider::CompleteAddUser(int32_t userId)
385 {
386     int32_t err = StorageDaemon::GetInstance().CompleteAddUser(userId);
387     return err;
388 }
389 
InitGlobalKey()390 int32_t StorageDaemonProvider::InitGlobalKey()
391 {
392     std::lock_guard<std::mutex> lock(mutex_);
393     auto it = GetUserStatistics(USER0ID);
394     isNeedUpdateRadarFile_ = true;
395     int err = StorageDaemon::GetInstance().InitGlobalKey();
396     if (err != E_OK) {
397         it->second.keyLoadFailCount++;
398     } else {
399         it->second.keyLoadSuccCount++;
400     }
401     return err;
402 }
403 
InitGlobalUserKeys()404 int32_t StorageDaemonProvider::InitGlobalUserKeys()
405 {
406     LOGI("StorageDaemonProvider_InitGlobalUserKeys start.");
407     std::lock_guard<std::mutex> lock(mutex_);
408     auto it = GetUserStatistics(USER100ID);
409     isNeedUpdateRadarFile_ = true;
410     int32_t err = StorageDaemon::GetInstance().InitGlobalUserKeys();
411     if (err != E_OK) {
412         it->second.keyLoadFailCount++;
413     } else {
414         it->second.keyLoadSuccCount++;
415     }
416     return err;
417 }
418 
GenerateUserKeys(uint32_t userId,uint32_t flags)419 int32_t StorageDaemonProvider::GenerateUserKeys(uint32_t userId, uint32_t flags)
420 {
421     int timerId = StorageXCollie::SetTimer("storage:GenerateUserKeys", LOCAL_TIME_OUT_SECONDS);
422     int err = StorageDaemon::GetInstance().GenerateUserKeys(userId, flags);
423     StorageXCollie::CancelTimer(timerId);
424     return err;
425 }
426 
DeleteUserKeys(uint32_t userId)427 int32_t StorageDaemonProvider::DeleteUserKeys(uint32_t userId)
428 {
429     int timerId = StorageXCollie::SetTimer("storage:DeleteUserKeys", LOCAL_TIME_OUT_SECONDS);
430     int err = StorageDaemon::GetInstance().DeleteUserKeys(userId);
431     StorageXCollie::CancelTimer(timerId);
432     return err;
433 }
434 
UpdateUserAuth(uint32_t userId,uint64_t secureUid,const std::vector<uint8_t> & token,const std::vector<uint8_t> & oldSecret,const std::vector<uint8_t> & newSecret)435 int32_t StorageDaemonProvider::UpdateUserAuth(uint32_t userId,
436                                               uint64_t secureUid,
437                                               const std::vector<uint8_t> &token,
438                                               const std::vector<uint8_t> &oldSecret,
439                                               const std::vector<uint8_t> &newSecret)
440 {
441     int timerId = StorageXCollie::SetTimer("storage:UpdateUserAuth", LOCAL_TIME_OUT_SECONDS);
442     std::lock_guard<std::mutex> lock(mutex_);
443     int err =  StorageDaemon::GetInstance().UpdateUserAuth(userId, secureUid, token, oldSecret, newSecret);
444     StorageXCollie::CancelTimer(timerId);
445     return err;
446 }
447 
UpdateUseAuthWithRecoveryKey(const std::vector<uint8_t> & authToken,const std::vector<uint8_t> & newSecret,uint64_t secureUid,uint32_t userId,const std::vector<std::vector<uint8_t>> & plainText)448 int32_t StorageDaemonProvider::UpdateUseAuthWithRecoveryKey(const std::vector<uint8_t> &authToken,
449                                                             const std::vector<uint8_t> &newSecret,
450                                                             uint64_t secureUid,
451                                                             uint32_t userId,
452                                                             const std::vector<std::vector<uint8_t>> &plainText)
453 {
454     return StorageDaemon::GetInstance().UpdateUseAuthWithRecoveryKey(authToken, newSecret, secureUid, userId,
455                                                                      plainText);
456 }
457 
ActiveUserKey(uint32_t userId,const std::vector<uint8_t> & token,const std::vector<uint8_t> & secret)458 int32_t StorageDaemonProvider::ActiveUserKey(uint32_t userId,
459                                              const std::vector<uint8_t> &token,
460                                              const std::vector<uint8_t> &secret)
461 {
462     auto startTime = StorageService::StorageRadar::RecordCurrentTime();
463     int timerId = StorageXCollie::SetTimer("storage:ActiveUserKey", LOCAL_TIME_OUT_SECONDS);
464     std::lock_guard<std::mutex> lock(mutex_);
465     auto it = GetUserStatistics(userId);
466     isNeedUpdateRadarFile_ = true;
467     int32_t err = StorageDaemon::GetInstance().ActiveUserKey(userId, token, secret);
468     StorageXCollie::CancelTimer(timerId);
469     if ((err == E_OK) || ((err == E_ACTIVE_EL2_FAILED) && token.empty() && secret.empty())) {
470         it->second.keyLoadSuccCount++;
471     } else {
472         it->second.keyLoadFailCount++;
473     }
474     auto delay = StorageService::StorageRadar::ReportDuration("ACTIVE USER KEY",
475         startTime, StorageService::DELAY_TIME_THRESH_HIGH, userId);
476     LOGI("SD_DURATION: ACTIVE USER KEY: delay time = %{public}s", delay.c_str());
477     return err;
478 }
479 
InactiveUserKey(uint32_t userId)480 int32_t StorageDaemonProvider::InactiveUserKey(uint32_t userId)
481 {
482     int timerId = StorageXCollie::SetTimer("storage:InactiveUserKey", INACTIVE_USER_KEY_OUT_SECONDS);
483     std::lock_guard<std::mutex> lock(mutex_);
484     auto it = GetUserStatistics(userId);
485     isNeedUpdateRadarFile_ = true;
486     int32_t ret = StorageDaemon::GetInstance().InactiveUserKey(userId);
487     StorageXCollie::CancelTimer(timerId);
488     if (ret != E_OK) {
489         it->second.keyUnloadFailCount++;
490     } else {
491         it->second.keyUnloadSuccCount++;
492     }
493     return ret;
494 }
495 
UpdateKeyContext(uint32_t userId,bool needRemoveTmpKey)496 int32_t StorageDaemonProvider::UpdateKeyContext(uint32_t userId, bool needRemoveTmpKey)
497 {
498     int timerId = StorageXCollie::SetTimer("storage:UpdateKeyContext", LOCAL_TIME_OUT_SECONDS);
499     std::lock_guard<std::mutex> lock(mutex_);
500     int32_t ret = StorageDaemon::GetInstance().UpdateKeyContext(userId, needRemoveTmpKey);
501     StorageXCollie::CancelTimer(timerId);
502     return ret;
503 }
504 
MountCryptoPathAgain(uint32_t userId)505 int32_t StorageDaemonProvider::MountCryptoPathAgain(uint32_t userId)
506 {
507     LOGI("begin to MountCryptoPathAgain");
508 #ifdef USER_CRYPTO_MANAGER
509     auto ret = MountManager::GetInstance().MountCryptoPathAgain(userId);
510     if (ret != E_OK) {
511         StorageService::StorageRadar::ReportUserManager("MountCryptoPathAgain::MountManager::MountCryptoPathAgain",
512                                                         userId, ret, "");
513     }
514     return ret;
515 #else
516     return E_OK;
517 #endif
518 }
519 
LockUserScreen(uint32_t userId)520 int32_t StorageDaemonProvider::LockUserScreen(uint32_t userId)
521 {
522     int timerId = StorageXCollie::SetTimer("storage:LockUserScreen", LOCAL_TIME_OUT_SECONDS);
523     std::lock_guard<std::mutex> lock(mutex_);
524     auto it = GetUserStatistics(userId);
525     isNeedUpdateRadarFile_ = true;
526     int ret = StorageDaemon::GetInstance().LockUserScreen(userId);
527     StorageXCollie::CancelTimer(timerId);
528     if (ret != E_OK) {
529         it->second.keyUnloadFailCount++;
530     } else {
531         it->second.keyUnloadSuccCount++;
532     }
533     return ret;
534 }
535 
UnlockUserScreen(uint32_t userId,const std::vector<uint8_t> & token,const std::vector<uint8_t> & secret)536 int32_t StorageDaemonProvider::UnlockUserScreen(uint32_t userId,
537                                                 const std::vector<uint8_t> &token,
538                                                 const std::vector<uint8_t> &secret)
539 {
540     int timerId = StorageXCollie::SetTimer("storage:UnlockUserScreen", LOCAL_TIME_OUT_SECONDS);
541     std::unique_lock<std::mutex> lock(mutex_);
542     auto it = GetUserStatistics(userId);
543     isNeedUpdateRadarFile_ = true;
544     int ret = StorageDaemon::GetInstance().UnlockUserScreen(userId, token, secret);
545     StorageXCollie::CancelTimer(timerId);
546     if (ret != E_OK) {
547         it->second.keyLoadFailCount++;
548     } else {
549         it->second.keyLoadSuccCount++;
550     }
551     lock.unlock();
552 
553 #ifdef USER_CRYPTO_MANAGER
554     int cbRet = KeyManager::GetInstance().NotifyUeceActivation(userId, ret, false);
555     if (ret != E_OK) { //unlock EL3-5 failed
556         return ret;
557     }
558     if (cbRet != E_OK) { // unlock userAppkeys failed
559         LOGE("failed to delete appkey2, cbRet=%{public}d", cbRet);
560         return cbRet;
561     }
562 #endif
563     return ret;
564 }
565 
GetLockScreenStatus(uint32_t userId,bool & lockScreenStatus)566 int32_t StorageDaemonProvider::GetLockScreenStatus(uint32_t userId, bool &lockScreenStatus)
567 {
568     lockScreenStatus = false;
569     int timerId = StorageXCollie::SetTimer("storage:GetLockScreenStatus", LOCAL_TIME_OUT_SECONDS);
570     std::lock_guard<std::mutex> lock(mutex_);
571     int32_t ret = StorageDaemon::GetInstance().GetLockScreenStatus(userId, lockScreenStatus);
572     StorageXCollie::CancelTimer(timerId);
573     return ret;
574 }
575 
GenerateAppkey(uint32_t userId,uint32_t hashId,std::string & keyId,bool needReSet)576 int32_t StorageDaemonProvider::GenerateAppkey(uint32_t userId, uint32_t hashId, std::string &keyId, bool needReSet)
577 {
578     int timerId = StorageXCollie::SetTimer("storage:GenerateAppkey", LOCAL_TIME_OUT_SECONDS);
579     int32_t ret = StorageDaemon::GetInstance().GenerateAppkey(userId, hashId, keyId, needReSet);
580     StorageXCollie::CancelTimer(timerId);
581     return ret;
582 }
583 
DeleteAppkey(uint32_t userId,const std::string & keyId)584 int32_t StorageDaemonProvider::DeleteAppkey(uint32_t userId, const std::string &keyId)
585 {
586     int timerId = StorageXCollie::SetTimer("storage:DeleteAppkey", LOCAL_TIME_OUT_SECONDS);
587     std::lock_guard<std::mutex> lock(mutex_);
588     int32_t ret = StorageDaemon::GetInstance().DeleteAppkey(userId, keyId);
589     StorageXCollie::CancelTimer(timerId);
590     return ret;
591 }
592 
CreateRecoverKey(uint32_t userId,uint32_t userType,const std::vector<uint8_t> & token,const std::vector<uint8_t> & secret)593 int32_t StorageDaemonProvider::CreateRecoverKey(uint32_t userId,
594                                                 uint32_t userType,
595                                                 const std::vector<uint8_t> &token,
596                                                 const std::vector<uint8_t> &secret)
597 {
598     return StorageDaemon::GetInstance().CreateRecoverKey(userId, userType, token, secret);
599 }
600 
SetRecoverKey(const std::vector<uint8_t> & key)601 int32_t StorageDaemonProvider::SetRecoverKey(const std::vector<uint8_t> &key)
602 {
603     return StorageDaemon::GetInstance().SetRecoverKey(key);
604 }
605 
RawDataToStringVec(const StorageFileRawData & rawData,std::vector<std::string> & stringVec)606 int32_t StorageDaemonProvider::RawDataToStringVec(const StorageFileRawData &rawData,
607     std::vector<std::string> &stringVec)
608 {
609     if (rawData.data == nullptr) {
610         LOGE("rawData is null");
611         return ERR_DEAD_OBJECT;
612     }
613     if (rawData.size == 0 || rawData.size > MAX_IPC_RAW_DATA_SIZE) {
614         LOGE("size invalid: %{public}u", rawData.size);
615         return ERR_DEAD_OBJECT;
616     }
617     std::stringstream ss;
618     ss.write(reinterpret_cast<const char *>(rawData.data), rawData.size);
619     uint32_t stringVecSize = 0;
620     ss.read(reinterpret_cast<char *>(&stringVecSize), sizeof(stringVecSize));
621     uint32_t ssLength = static_cast<uint32_t>(ss.str().length());
622     if (stringVecSize > MAX_URI_COUNT) {
623         LOGE("out of range: %{public}u", stringVecSize);
624         return ERR_DEAD_OBJECT;
625     }
626     for (uint32_t i = 0; i < stringVecSize; i++) {
627         uint32_t strLen = 0;
628         ss.read(reinterpret_cast<char *>(&strLen), sizeof(strLen));
629         if (strLen > ssLength - static_cast<uint32_t>(ss.tellg())) {
630             LOGE("string length:%{public}u is invalid", strLen);
631             return ERR_DEAD_OBJECT;
632         }
633         std::string str;
634         str.resize(strLen);
635         ss.read(&str[0], strLen);
636         stringVec.emplace_back(str);
637     }
638     return ERR_OK;
639 }
640 
CreateShareFile(const StorageFileRawData & rawData,uint32_t tokenId,uint32_t flag,std::vector<int32_t> & funcResult)641 int32_t StorageDaemonProvider::CreateShareFile(const StorageFileRawData &rawData,
642                                                uint32_t tokenId,
643                                                uint32_t flag,
644                                                std::vector<int32_t> &funcResult)
645 {
646     LOGI("Create Share file list len is %{public}u", rawData.size);
647     funcResult.clear();
648     std::vector<std::string> uriList;
649     int32_t ret = RawDataToStringVec(rawData, uriList);
650     if (ret != E_OK) {
651         LOGI("RawDataToStringVec failed, ret is %{public}d", ret);
652         return ret;
653     }
654     LOGI("StorageDaemonProvider::CreateShareFile start. file size is %{public}zu", uriList.size());
655     AppFileService::FileShare::CreateShareFile(uriList, tokenId, flag, funcResult);
656     LOGI("StorageDaemonProvider::CreateShareFile end. result size is %{public}zu", funcResult.size());
657     return E_OK;
658 }
659 
DeleteShareFile(uint32_t tokenId,const StorageFileRawData & rawData)660 int32_t StorageDaemonProvider::DeleteShareFile(uint32_t tokenId, const StorageFileRawData &rawData)
661 {
662     std::vector<std::string> uriList;
663     int32_t ret = RawDataToStringVec(rawData, uriList);
664     if (ret != E_OK) {
665         LOGI("RawDataToStringVec failed, ret is %{public}d", ret);
666         return ret;
667     }
668     return AppFileService::FileShare::DeleteShareFile(tokenId, uriList);
669 }
670 
SetBundleQuota(const std::string & bundleName,int32_t uid,const std::string & bundleDataDirPath,int32_t limitSizeMb)671 int32_t StorageDaemonProvider::SetBundleQuota(const std::string &bundleName,
672                                               int32_t uid,
673                                               const std::string &bundleDataDirPath,
674                                               int32_t limitSizeMb)
675 {
676     return QuotaManager::GetInstance().SetBundleQuota(bundleName, uid, bundleDataDirPath, limitSizeMb);
677 }
678 
GetOccupiedSpace(int32_t idType,int32_t id,int64_t & size)679 int32_t StorageDaemonProvider::GetOccupiedSpace(int32_t idType, int32_t id, int64_t &size)
680 {
681     size = 0;
682     return QuotaManager::GetInstance().GetOccupiedSpace(idType, id, size);
683 }
684 
UpdateMemoryPara(int32_t size,int32_t & oldSize)685 int32_t StorageDaemonProvider::UpdateMemoryPara(int32_t size, int32_t &oldSize)
686 {
687     oldSize = 0;
688     return E_OK;
689 }
690 
MountDfsDocs(int32_t userId,const std::string & relativePath,const std::string & networkId,const std::string & deviceId)691 int32_t StorageDaemonProvider::MountDfsDocs(int32_t userId,
692                                             const std::string &relativePath,
693                                             const std::string &networkId,
694                                             const std::string &deviceId)
695 {
696     LOGI("StorageDaemon::MountDfsDocs start.");
697     return MountManager::GetInstance().MountDfsDocs(userId, relativePath, networkId, deviceId);
698 }
699 
UMountDfsDocs(int32_t userId,const std::string & relativePath,const std::string & networkId,const std::string & deviceId)700 int32_t StorageDaemonProvider::UMountDfsDocs(int32_t userId,
701                                              const std::string &relativePath,
702                                              const std::string &networkId,
703                                              const std::string &deviceId)
704 {
705     LOGI("StorageDaemon::UMountDfsDocs start.");
706     return MountManager::GetInstance().UMountDfsDocs(userId, relativePath, networkId, deviceId);
707 }
708 
GetFileEncryptStatus(uint32_t userId,bool & isEncrypted,bool needCheckDirMount)709 int32_t StorageDaemonProvider::GetFileEncryptStatus(uint32_t userId, bool &isEncrypted, bool needCheckDirMount)
710 {
711     isEncrypted = true;
712     int timerId = StorageXCollie::SetTimer("storage:GetFileEncryptStatus", LOCAL_TIME_OUT_SECONDS);
713     std::lock_guard<std::mutex> lock(mutex_);
714     int32_t ret = StorageDaemon::GetInstance().GetFileEncryptStatus(userId, isEncrypted, needCheckDirMount);
715     StorageXCollie::CancelTimer(timerId);
716     return ret;
717 }
718 
GetUserNeedActiveStatus(uint32_t userId,bool & needActive)719 int32_t StorageDaemonProvider::GetUserNeedActiveStatus(uint32_t userId, bool &needActive)
720 {
721     needActive = false;
722     int timerId = StorageXCollie::SetTimer("storage:GetUserNeedActiveStatus", LOCAL_TIME_OUT_SECONDS);
723     std::lock_guard<std::mutex> lock(mutex_);
724     int32_t ret = StorageDaemon::GetInstance().GetUserNeedActiveStatus(userId, needActive);
725     StorageXCollie::CancelTimer(timerId);
726     return ret;
727 }
728 
MountMediaFuse(int32_t userId,int32_t & devFd)729 int32_t StorageDaemonProvider::MountMediaFuse(int32_t userId, int32_t &devFd)
730 {
731 #ifdef STORAGE_SERVICE_MEDIA_FUSE
732     LOGI("StorageDaemonProvider::MountMediaFuse start.");
733     devFd = -1;
734     return MountManager::GetInstance().MountMediaFuse(userId, devFd);
735 #endif
736     return E_OK;
737 }
738 
UMountMediaFuse(int32_t userId)739 int32_t StorageDaemonProvider::UMountMediaFuse(int32_t userId)
740 {
741 #ifdef STORAGE_SERVICE_MEDIA_FUSE
742     LOGI("StorageDaemonProvider::UMountMediaFuse start.");
743     return MountManager::GetInstance().UMountMediaFuse(userId);
744 #endif
745     return E_OK;
746 }
747 
MountFileMgrFuse(int32_t userId,const std::string & path,int32_t & fuseFd)748 int32_t StorageDaemonProvider::MountFileMgrFuse(int32_t userId, const std::string &path, int32_t &fuseFd)
749 {
750     LOGI("StorageDaemonProvider::MountFileMgrFuse, userId:%{public}d.", userId);
751     fuseFd = -1;
752     return MountManager::GetInstance().MountFileMgrFuse(userId, path, fuseFd);
753 }
754 
UMountFileMgrFuse(int32_t userId,const std::string & path)755 int32_t StorageDaemonProvider::UMountFileMgrFuse(int32_t userId, const std::string &path)
756 {
757     LOGI("StorageDaemonProvider::UMountFileMgrFuse, userId:%{public}d.", userId);
758     return MountManager::GetInstance().UMountFileMgrFuse(userId, path);
759 }
760 
IsFileOccupied(const std::string & path,const std::vector<std::string> & inputList,std::vector<std::string> & outputList,bool & isOccupy)761 int32_t StorageDaemonProvider::IsFileOccupied(const std::string &path,
762                                               const std::vector<std::string> &inputList,
763                                               std::vector<std::string> &outputList,
764                                               bool &isOccupy)
765 {
766     isOccupy = false;
767     return StorageDaemon::GetInstance().IsFileOccupied(path, inputList, outputList, isOccupy);
768 }
769 
ResetSecretWithRecoveryKey(uint32_t userId,uint32_t rkType,const std::vector<uint8_t> & key)770 int32_t StorageDaemonProvider::ResetSecretWithRecoveryKey(uint32_t userId,
771                                                           uint32_t rkType,
772                                                           const std::vector<uint8_t> &key)
773 {
774     return StorageDaemon::GetInstance().ResetSecretWithRecoveryKey(userId, rkType, key);
775 }
776 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)777 void StorageDaemonProvider::SystemAbilityStatusChangeListener::OnAddSystemAbility(int32_t systemAbilityId,
778                                                                                   const std::string &deviceId)
779 {
780     LOGI("SystemAbilityId:%{public}d", systemAbilityId);
781 #ifdef EXTERNAL_STORAGE_MANAGER
782     if (systemAbilityId == ACCESS_TOKEN_MANAGER_SERVICE_ID) {
783         DiskManager::Instance().ReplayUevent();
784     }
785 #endif
786     if (systemAbilityId == FILEMANAGEMENT_CLOUD_DAEMON_SERVICE_SA_ID) {
787         MountManager::GetInstance().SetCloudState(true);
788     }
789 }
790 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)791 void StorageDaemonProvider::SystemAbilityStatusChangeListener::OnRemoveSystemAbility(int32_t systemAbilityId,
792                                                                                      const std::string &deviceId)
793 {
794     LOGI("SystemAbilityId:%{public}d", systemAbilityId);
795     if (systemAbilityId == FILEMANAGEMENT_CLOUD_DAEMON_SERVICE_SA_ID) {
796         MountManager::GetInstance().SetCloudState(false);
797     }
798 }
799 
MountDisShareFile(int32_t userId,const std::map<std::string,std::string> & shareFiles)800 int32_t StorageDaemonProvider::MountDisShareFile(int32_t userId, const std::map<std::string, std::string> &shareFiles)
801 {
802     return MountManager::GetInstance().MountDisShareFile(userId, shareFiles);
803 }
804 
UMountDisShareFile(int32_t userId,const std::string & networkId)805 int32_t StorageDaemonProvider::UMountDisShareFile(int32_t userId, const std::string &networkId)
806 {
807     return MountManager::GetInstance().UMountDisShareFile(userId, networkId);
808 }
809 
InactiveUserPublicDirKey(uint32_t userId)810 int32_t StorageDaemonProvider::InactiveUserPublicDirKey(uint32_t userId)
811 {
812     std::lock_guard<std::mutex> lock(mutex_);
813     return StorageDaemon::GetInstance().InactiveUserPublicDirKey(userId);
814 }
815 
QueryOccupiedSpaceForSa(const std::string & storageStatus)816 int32_t StorageDaemonProvider::QueryOccupiedSpaceForSa(const std::string &storageStatus)
817 {
818     QuotaManager::GetInstance().GetUidStorageStats(storageStatus);
819     return E_OK;
820 }
821 
RegisterUeceActivationCallback(const sptr<StorageManager::IUeceActivationCallback> & ueceCallback)822 int32_t StorageDaemonProvider::RegisterUeceActivationCallback(
823     const sptr<StorageManager::IUeceActivationCallback> &ueceCallback)
824 {
825     return StorageDaemon::GetInstance().RegisterUeceActivationCallback(ueceCallback);
826 }
827 
UnregisterUeceActivationCallback()828 int32_t StorageDaemonProvider::UnregisterUeceActivationCallback()
829 {
830     return StorageDaemon::GetInstance().UnregisterUeceActivationCallback();
831 }
832 } // namespace StorageDaemon
833 } // namespace OHOS
834