• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-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 "module_ipc/svc_session_manager.h"
17 
18 #include <algorithm>
19 #include <cinttypes>
20 #include <cstdint>
21 #include <memory>
22 #include <regex>
23 #include <sstream>
24 #include <string>
25 
26 #include "b_anony/b_anony.h"
27 #include "b_error/b_error.h"
28 #include "b_file_info.h"
29 #include "b_json/b_json_entity_caps.h"
30 #include "b_json/b_json_entity_ext_manage.h"
31 #include "b_radar/b_radar.h"
32 #include "b_resources/b_constants.h"
33 #include "b_sa/b_sa_utils.h"
34 #include "b_utils/b_time.h"
35 #include "filemgmt_libhilog.h"
36 #include "module_ipc/service.h"
37 #include "module_ipc/svc_restore_deps_manager.h"
38 #include "unique_fd.h"
39 
40 namespace OHOS::FileManagement::Backup {
41 using namespace std;
42 
VerifyCallerAndScenario(uint32_t clientToken,IServiceReverseType::Scenario scenario) const43 ErrCode SvcSessionManager::VerifyCallerAndScenario(uint32_t clientToken, IServiceReverseType::Scenario scenario) const
44 {
45     shared_lock<shared_mutex> lock(lock_);
46     if (impl_.scenario != scenario) {
47         HILOGE("Verify caller failed, Inconsistent scenario, impl scenario:%{public}d", impl_.scenario);
48         AppRadar::Info info("", "", "Inconsistent scenario");
49         AppRadar::GetInstance().RecordDefaultFuncRes(info, "SvcSessionManager::VerifyCallerAndScenario", impl_.userId,
50                                                      BizStageBackup::BIZ_STAGE_PERMISSION_CHECK_FAIL,
51                                                      BError(BError::Codes::SDK_MIXED_SCENARIO).GetCode());
52         return BError(BError::Codes::SDK_MIXED_SCENARIO);
53     }
54     if (impl_.clientToken != clientToken) {
55         HILOGE("Verify caller failed, Caller mismatched");
56         AppRadar::Info info2("", "", "Caller mismatched");
57         AppRadar::GetInstance().RecordDefaultFuncRes(info2, "SvcSessionManager::VerifyCallerAndScenario", impl_.userId,
58                                                      BizStageBackup::BIZ_STAGE_PERMISSION_CHECK_FAIL,
59                                                      BError(BError::Codes::SDK_MIXED_SCENARIO).GetCode());
60 
61         return BError(BError::Codes::SA_REFUSED_ACT);
62     }
63     HILOGD("Succeed to verify the caller");
64     return BError(BError::Codes::OK);
65 }
66 
GetImpl()67 SvcSessionManager::Impl SvcSessionManager::GetImpl()
68 {
69     return impl_;
70 }
71 
GetSessionCnt()72 int SvcSessionManager::GetSessionCnt()
73 {
74     return sessionCnt_.load();
75 }
76 
Active(Impl newImpl,bool isOccupyingSession)77 ErrCode SvcSessionManager::Active(Impl newImpl, bool isOccupyingSession)
78 {
79     unique_lock<shared_mutex> lock(lock_);
80     const Impl &oldImpl = impl_;
81     if (oldImpl.clientToken) {
82         HILOGE("Already have an active session, userId=%{public}d, caller=%{public}s, activeTime=%{public}s",
83             impl_.userId, impl_.callerName.c_str(), impl_.activeTime.c_str());
84         return BError(BError::Codes::SA_SESSION_CONFLICT);
85     }
86 
87     if (!isOccupyingSession && !newImpl.clientToken) {
88         HILOGE("Active session fail, No caller token was specified");
89         return BError(BError::Codes::SA_INVAL_ARG);
90     }
91     if (!isOccupyingSession && newImpl.scenario == IServiceReverseType::Scenario::UNDEFINED) {
92         HILOGE("Active session fail, No scenario was specified");
93         return BError(BError::Codes::SA_INVAL_ARG);
94     }
95 
96     if (!isOccupyingSession) {
97         ErrCode ret = InitClient(newImpl);
98         if (ret != BError(BError::Codes::OK)) {
99             HILOGE("Active session failed, init client error");
100             return ret;
101         }
102     }
103     impl_ = newImpl;
104     IncreaseSessionCnt(__PRETTY_FUNCTION__);
105     return BError(BError::Codes::OK);
106 }
107 
Deactive(const wptr<IRemoteObject> & remoteInAction,bool force)108 ErrCode SvcSessionManager::Deactive(const wptr<IRemoteObject> &remoteInAction, bool force)
109 {
110     unique_lock<shared_mutex> lock(lock_);
111     HILOGI("Begin Deactive session");
112     if (!impl_.clientToken) {
113         HILOGE("Deactive session fail, caller token is invalid");
114         return BError(BError::Codes::SA_INVAL_ARG);
115     }
116     if (!force && (!impl_.clientToken || !impl_.clientProxy)) {
117         HILOGE("Deactive session fail, client proxy is invalid");
118         return BError(BError::Codes::SA_INVAL_ARG);
119     }
120     if (!force && (remoteInAction != impl_.clientProxy->AsObject())) {
121         HILOGE("Deactive session fail, Only the client actived the session can deactive it");
122         return BError(BError::Codes::SA_INVAL_ARG);
123     }
124 
125     deathRecipient_ = nullptr;
126     AppRadar::Info info("", "", "deactive session success");
127     if (impl_.scenario == IServiceReverseType::Scenario::RESTORE) {
128         AppRadar::GetInstance().RecordRestoreFuncRes(info, "SvcSessionManager::Deactive", impl_.userId,
129             BizStageRestore::BIZ_STAGE_DEACTIVE_SESSION, ERR_OK);
130     } else if (impl_.scenario == IServiceReverseType::Scenario::BACKUP) {
131         AppRadar::GetInstance().RecordBackupFuncRes(info, "SvcSessionManager::Deactive", impl_.userId,
132             BizStageBackup::BIZ_STAGE_DEACTIVE_SESSION, ERR_OK);
133     }
134     HILOGI("Succeed to deactive a session");
135     impl_ = {};
136     extConnectNum_ = 0;
137     DecreaseSessionCnt(__PRETTY_FUNCTION__);
138     return BError(BError::Codes::OK);
139 }
140 
VerifyBundleName(string & bundleName)141 ErrCode SvcSessionManager::VerifyBundleName(string &bundleName)
142 {
143     shared_lock<shared_mutex> lock(lock_);
144     if (!impl_.clientToken) {
145         HILOGE("Verify bundle name failed, No caller token was specified, bundleName:%{public}s", bundleName.c_str());
146         return BError(BError::Codes::SA_INVAL_ARG);
147     }
148     auto asVerify = [&bundleName](const auto &it) { return it.first == bundleName; };
149     if (none_of(impl_.backupExtNameMap.begin(), impl_.backupExtNameMap.end(), asVerify)) {
150         HILOGE("Could not find the bundle from current session, bundleName:%{public}s", bundleName.c_str());
151         return BError(BError::Codes::SA_REFUSED_ACT);
152     }
153     HILOGD("Succeed to verify the bundleName");
154     return BError(BError::Codes::OK);
155 }
156 
GetServiceReverseProxy()157 sptr<IServiceReverse> SvcSessionManager::GetServiceReverseProxy()
158 {
159     unique_lock<shared_mutex> lock(lock_);
160     if (!impl_.clientProxy) {
161         throw BError(BError::Codes::SA_REFUSED_ACT, "Try to deactive an empty session");
162     }
163     return impl_.clientProxy;
164 }
165 
GetScenario()166 IServiceReverseType::Scenario SvcSessionManager::GetScenario()
167 {
168     shared_lock<shared_mutex> lock(lock_);
169     if (!impl_.clientToken) {
170         HILOGE("Get scenario failed, No caller token was specified");
171         return IServiceReverseType::Scenario::UNDEFINED;
172     }
173     return impl_.scenario;
174 }
175 
GetSessionUserId()176 int32_t SvcSessionManager::GetSessionUserId()
177 {
178     return impl_.userId;
179 }
180 
SetSessionUserId(int32_t userId)181 void SvcSessionManager::SetSessionUserId(int32_t userId)
182 {
183     impl_.userId = userId;
184 }
185 
GetSessionCallerName()186 string SvcSessionManager::GetSessionCallerName()
187 {
188     shared_lock<shared_mutex> lock(lock_);
189     if (!impl_.clientToken) {
190         HILOGE("Get scenario failed, No caller token was specified");
191         return "";
192     }
193     return impl_.callerName;
194 }
195 
GetSessionActiveTime()196 string SvcSessionManager::GetSessionActiveTime()
197 {
198     shared_lock<shared_mutex> lock(lock_);
199     if (!impl_.clientToken) {
200         HILOGE("Get scenario failed, No caller token was specified");
201         return "";
202     }
203     return impl_.activeTime;
204 }
205 
OnBundleFileReady(const string & bundleName,const string & fileName)206 bool SvcSessionManager::OnBundleFileReady(const string &bundleName, const string &fileName)
207 {
208     unique_lock<shared_mutex> lock(lock_);
209     if (!impl_.clientToken) {
210         HILOGE("OnBundleFileReady failed, bundleName:%{public}s, fileName:%{public}s", bundleName.c_str(),
211             GetAnonyPath(fileName).c_str());
212         return false;
213     }
214     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
215     if (!findBundleSuc) {
216         HILOGE("BackupExtNameMap can not find the bundle:%{public}s", bundleName.c_str());
217         return false;
218     }
219     // 判断是否结束 通知EXTENTION清理资源  TOOL应用完成备份
220     if (impl_.scenario == IServiceReverseType::Scenario::RESTORE || SAUtils::IsSABundleName(bundleName)) {
221         it->second.isBundleFinished = true;
222         return true;
223     } else if (impl_.scenario == IServiceReverseType::Scenario::BACKUP) {
224         if (!fileName.empty() && fileName != BConstants::EXT_BACKUP_MANAGE) {
225             auto ret = it->second.fileNameInfo.emplace(fileName);
226             if (!ret.second) {
227                 it->second.fileNameInfo.erase(fileName);
228             }
229         } else if (fileName.empty()) {
230             it->second.receExtAppDone = true;
231         }
232         if (it->second.receExtManageJson && it->second.fileNameInfo.empty() && it->second.receExtAppDone) {
233             HILOGI("The bundle manage json info and file info support current app done, bundle:%{public}s",
234                 bundleName.c_str());
235             it->second.isBundleFinished = true;
236             return true;
237         }
238     }
239     HILOGD("End, bundleName name is:%{private}s", bundleName.c_str());
240     return false;
241 }
242 
OnBundleExtManageInfo(const string & bundleName,UniqueFd fd)243 UniqueFd SvcSessionManager::OnBundleExtManageInfo(const string &bundleName, UniqueFd fd)
244 {
245     if (!impl_.clientToken) {
246         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
247         return UniqueFd(-EPERM);
248     }
249     if (impl_.scenario != IServiceReverseType::Scenario::BACKUP) {
250         HILOGE("Invalid Scenario, bundleName:%{public}s", bundleName.c_str());
251         return UniqueFd(-EPERM);
252     }
253 
254     BJsonCachedEntity<BJsonEntityExtManage> cachedEntity(move(fd));
255     auto cache = cachedEntity.Structuralize();
256     auto info = cache.GetExtManage();
257 
258     for (const auto &fileName : info) {
259         HILOGE("fileName %{public}s", GetAnonyPath(fileName).data());
260         OnBundleFileReady(bundleName, fileName);
261     }
262 
263     unique_lock<shared_mutex> lock(lock_);
264     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
265     if (!findBundleSuc) {
266         HILOGE("BackupExtNameMap can not find the bundle:%{public}s", bundleName.c_str());
267         return UniqueFd(-EPERM);
268     }
269     it->second.receExtManageJson = true;
270     return move(cachedEntity.GetFd());
271 }
272 
RemoveExtInfo(const string & bundleName)273 void SvcSessionManager::RemoveExtInfo(const string &bundleName)
274 {
275     HILOGD("svcMrg:RemoveExt, bundleName:%{public}s", bundleName.c_str());
276     unique_lock<shared_mutex> lock(lock_);
277     auto it = impl_.backupExtNameMap.find(bundleName);
278     if (it == impl_.backupExtNameMap.end()) {
279         HILOGE("BackupExtNameMap not contain %{public}s", bundleName.c_str());
280         return;
281     }
282     if (extConnectNum_) {
283         extConnectNum_--;
284     }
285     int32_t &appendNum = impl_.backupExtNameMap[bundleName].appendNum;
286     if (--appendNum > 0) {
287         HILOGI("No need remove bundleName:%{public}s, appendNum=%{public}d", bundleName.c_str(), appendNum);
288         return;
289     }
290     impl_.backupExtNameMap.erase(it);
291 }
292 
GetExtConnection(const BundleName & bundleName)293 wptr<SvcBackupConnection> SvcSessionManager::GetExtConnection(const BundleName &bundleName)
294 {
295     HILOGD("svcMrg:GetExt, bundleName:%{public}s", bundleName.c_str());
296     shared_lock<shared_mutex> lock(lock_);
297     if (!impl_.clientToken) {
298         HILOGE("GetExt connection failed, No caller token was specified, bundleName:%{public}s", bundleName.c_str());
299         return nullptr;
300     }
301     auto it = impl_.backupExtNameMap.find(bundleName);
302     if (it == impl_.backupExtNameMap.end()) {
303         HILOGE("Could not find the bundle from current session, bundleName:%{public}s", bundleName.c_str());
304         return nullptr;
305     }
306     if (!it->second.backUpConnection) {
307         HILOGE("Current bundle extension connection is empty, bundleName:%{public}s", bundleName.c_str());
308         return nullptr;
309     }
310     return wptr(it->second.backUpConnection);
311 }
312 
UpdateDfxInfo(const std::string & bundleName,uint64_t uniqId)313 void SvcSessionManager::UpdateDfxInfo(const std::string &bundleName, uint64_t uniqId)
314 {
315     auto backupConnection = GetExtConnection(bundleName);
316     if (backupConnection == nullptr) {
317         return;
318     }
319     auto proxy = backupConnection->GetBackupExtProxy();
320     if (proxy == nullptr) {
321         return;
322     }
323     proxy->UpdateDfxInfo(uniqId, backupConnection->GetConnectSpan(), bundleName);
324 }
325 
GetSAExtConnection(const BundleName & bundleName)326 std::weak_ptr<SABackupConnection> SvcSessionManager::GetSAExtConnection(const BundleName &bundleName)
327 {
328     HILOGD("svcMrg:GetExt, bundleName:%{public}s", bundleName.c_str());
329     shared_lock<shared_mutex> lock(lock_);
330     if (!impl_.clientToken) {
331         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
332         return std::weak_ptr<SABackupConnection>();
333     }
334 
335     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
336     if (!findBundleSuc) {
337         HILOGE("BackupExtNameMap can not find current bundle, bundleName:%{public}s", bundleName.c_str());
338         return std::weak_ptr<SABackupConnection>();
339     }
340     if (!it->second.saBackupConnection) {
341         HILOGE("SA backup connection is empty, bundleName:%{public}s", bundleName.c_str());
342         return std::weak_ptr<SABackupConnection>();
343     }
344 
345     return std::weak_ptr<SABackupConnection>(it->second.saBackupConnection);
346 }
347 
GetBackupAbilityExt(const string & bundleName)348 sptr<SvcBackupConnection> SvcSessionManager::GetBackupAbilityExt(const string &bundleName)
349 {
350     auto callDied = [revPtr {reversePtr_}](const string &&bundleName, bool isCleanCalled = false) {
351         auto revPtrStrong = revPtr.promote();
352         if (!revPtrStrong) {
353             // 服务先于客户端死亡是一种异常场景,但该场景对本流程来说也没什么影响,所以只是简单记录一下
354             HILOGW("It's curious that the backup sa dies before the backup client");
355             return;
356         }
357         revPtrStrong->OnBackupExtensionDied(move(bundleName), isCleanCalled);
358     };
359 
360     auto callConnected = [revPtr {reversePtr_}](const string &&bundleName) {
361         auto revPtrStrong = revPtr.promote();
362         if (!revPtrStrong) {
363             // 服务先于客户端死亡是一种异常场景,但该场景对本流程来说也没什么影响,所以只是简单记录一下
364             HILOGW("It's curious that the backup sa dies before the backup client");
365             return;
366         }
367         revPtrStrong->ExtConnectDone(move(bundleName));
368     };
369 
370     return sptr<SvcBackupConnection>(new SvcBackupConnection(callDied, callConnected, bundleName));
371 }
372 
GetBackupSAExt(const std::string & bundleName)373 std::shared_ptr<SABackupConnection> SvcSessionManager::GetBackupSAExt(const std::string &bundleName)
374 {
375     auto callDied = [revPtr {reversePtr_}](const string &&bundleName) {
376         auto revPtrStrong = revPtr.promote();
377         if (!revPtrStrong) {
378             // 服务先于客户端死亡是一种异常场景,但该场景对本流程来说也没什么影响,所以只是简单记录一下
379             HILOGW("It's curious that the backup sa dies before the backup client");
380             return;
381         }
382         revPtrStrong->OnBackupExtensionDied(move(bundleName));
383     };
384 
385     auto callConnected = [revPtr {reversePtr_}](const string &&bundleName) {
386         auto revPtrStrong = revPtr.promote();
387         if (!revPtrStrong) {
388             // 服务先于客户端死亡是一种异常场景,但该场景对本流程来说也没什么影响,所以只是简单记录一下
389             HILOGW("It's curious that the backup sa dies before the backup client");
390             return;
391         }
392         revPtrStrong->ExtConnectDone(move(bundleName));
393     };
394 
395     auto callBackup = [revPtr {reversePtr_}](const string &&bundleName, const int &&fd, const std::string result,
396                                              const ErrCode &&errCode) {
397         auto revPtrStrong = revPtr.promote();
398         if (!revPtrStrong) {
399             // 服务先于客户端死亡是一种异常场景,但该场景对本流程来说也没什么影响,所以只是简单记录一下
400             HILOGW("It's curious that the backup sa dies before the backup client");
401             return;
402         }
403         revPtrStrong->OnSABackup(move(bundleName), move(fd), move(result), move(errCode));
404     };
405 
406     auto callRestore = [revPtr {reversePtr_}](const string &&bundleName, const std::string result,
407                                               const ErrCode &&errCode) {
408         auto revPtrStrong = revPtr.promote();
409         if (!revPtrStrong) {
410             // 服务先于客户端死亡是一种异常场景,但该场景对本流程来说也没什么影响,所以只是简单记录一下
411             HILOGW("It's curious that the backup sa dies before the backup client");
412             return;
413         }
414         revPtrStrong->OnSARestore(move(bundleName), move(result), move(errCode));
415     };
416 
417     return std::make_shared<SABackupConnection>(callDied, callConnected, callBackup, callRestore);
418 }
419 
DumpInfo(const int fd,const std::vector<std::u16string> & args)420 void SvcSessionManager::DumpInfo(const int fd, const std::vector<std::u16string> &args)
421 {
422     dprintf(fd, "---------------------backup info--------------------\n");
423     dprintf(fd, "Scenario: %d\n", impl_.scenario);
424 }
425 
InitClient(Impl & newImpl)426 ErrCode SvcSessionManager::InitClient(Impl &newImpl)
427 {
428     if (!newImpl.clientProxy) {
429         HILOGE("Init client error, Invalid client");
430         return BError(BError::Codes::SA_INVAL_ARG);
431     }
432     auto remoteObj = newImpl.clientProxy->AsObject();
433     if (!remoteObj) {
434         HILOGE("Init client error, Proxy's remote object can't be nullptr");
435         return BError(BError::Codes::SA_BROKEN_IPC);
436     }
437 
438     auto callback = [revPtr {reversePtr_}](const wptr<IRemoteObject> &obj) {
439         HILOGI("Client died.");
440 
441         auto revPtrStrong = revPtr.promote();
442         if (!revPtrStrong) {
443             // 服务先于客户端死亡是一种异常场景,但该场景对本流程来说也没什么影响,所以只是简单记录一下
444             HILOGW("It's curious that the backup sa dies before the backup client");
445             return;
446         }
447         (void)revPtrStrong->SessionDeactive();
448     };
449     deathRecipient_ = sptr(new SvcDeathRecipient(callback));
450     remoteObj->AddDeathRecipient(deathRecipient_);
451     AppRadar::Info info("", "", "active session success");
452     if (newImpl.scenario == IServiceReverseType::Scenario::RESTORE) {
453         AppRadar::GetInstance().RecordRestoreFuncRes(info, "SvcSessionManager::InitClient", newImpl.userId,
454             BizStageRestore::BIZ_STAGE_ACTIVE_SESSION, ERR_OK);
455     } else if (newImpl.scenario == IServiceReverseType::Scenario::BACKUP) {
456         AppRadar::GetInstance().RecordBackupFuncRes(info, "SvcSessionManager::InitClient", newImpl.userId,
457             BizStageBackup::BIZ_STAGE_ACTIVE_SESSION, ERR_OK);
458     }
459     HILOGI("Succeed to active a session");
460     return BError(BError::Codes::OK);
461 }
462 
SetExtFileNameRequest(const string & bundleName,const string & fileName)463 void SvcSessionManager::SetExtFileNameRequest(const string &bundleName, const string &fileName)
464 {
465     unique_lock<shared_mutex> lock(lock_);
466     if (!impl_.clientToken) {
467         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
468         return;
469     }
470     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
471     if (!findBundleSuc) {
472         HILOGE("BackupExtNameMap can not find current bundle, bundleName:%{public}s", bundleName.c_str());
473         return;
474     }
475     it->second.fileNameInfo.emplace(fileName);
476 }
477 
GetExtFileNameRequest(const std::string & bundleName)478 std::set<std::string> SvcSessionManager::GetExtFileNameRequest(const std::string &bundleName)
479 {
480     unique_lock<shared_mutex> lock(lock_);
481     if (!impl_.clientToken) {
482         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
483         return std::set<std::string>();
484     }
485 
486     if (impl_.scenario != IServiceReverseType::Scenario::RESTORE) {
487         HILOGE("Invalid Scenario, bundleName:%{public}s", bundleName.c_str());
488         return std::set<std::string>();
489     }
490     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
491     if (!findBundleSuc) {
492         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
493         return std::set<std::string>();
494     }
495     set<string> fileNameInfo = it->second.fileNameInfo;
496     it->second.fileNameInfo.clear();
497     return fileNameInfo;
498 }
499 
GetBackupExtNameMap(const string & bundleName)500 std::tuple<bool, std::map<BundleName, BackupExtInfo>::iterator> SvcSessionManager::GetBackupExtNameMap(
501     const string &bundleName)
502 {
503     auto it = impl_.backupExtNameMap.find(bundleName);
504     if (it == impl_.backupExtNameMap.end()) {
505         HILOGE("Could not find the bundle from current session, bundleName:%{public}s", bundleName.c_str());
506         return {false, impl_.backupExtNameMap.end()};
507     }
508     return {true, it};
509 }
510 
GetSchedBundleName(string & bundleName)511 bool SvcSessionManager::GetSchedBundleName(string &bundleName)
512 {
513     unique_lock<shared_mutex> lock(lock_);
514     if (extConnectNum_ >= BConstants::EXT_CONNECT_MAX_COUNT) {
515         return false;
516     }
517 
518     for (auto &&it : impl_.backupExtNameMap) {
519         if (it.second.schedAction == BConstants::ServiceSchedAction::WAIT) {
520             bundleName = it.first;
521             if (!it.second.isReadyLaunch) {
522                 HILOGE("Current bundle:%{public}s can not sched, baseInfo is not set done", bundleName.c_str());
523                 return false;
524             }
525             it.second.schedAction = BConstants::ServiceSchedAction::START;
526             extConnectNum_++;
527             return true;
528         }
529     }
530     return false;
531 }
532 
GetServiceSchedAction(const std::string & bundleName)533 BConstants::ServiceSchedAction SvcSessionManager::GetServiceSchedAction(const std::string &bundleName)
534 {
535     shared_lock<shared_mutex> lock(lock_);
536     if (!impl_.clientToken) {
537         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
538         return BConstants::ServiceSchedAction::UNKNOWN;
539     }
540     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
541     if (!findBundleSuc) {
542         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
543         return BConstants::ServiceSchedAction::UNKNOWN;
544     }
545     return it->second.schedAction;
546 }
547 
SetServiceSchedAction(const string & bundleName,BConstants::ServiceSchedAction action)548 void SvcSessionManager::SetServiceSchedAction(const string &bundleName, BConstants::ServiceSchedAction action)
549 {
550     unique_lock<shared_mutex> lock(lock_);
551     if (!impl_.clientToken) {
552         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
553         throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified");
554     }
555     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
556     if (!findBundleSuc) {
557         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
558         throw BError(BError::Codes::SA_REFUSED_ACT, "BackupExtNameMap can not find bundle");
559     }
560     it->second.schedAction = action;
561     if (it->second.schedAction == BConstants::ServiceSchedAction::START) {
562         extConnectNum_++;
563     }
564 }
565 
SetBackupExtName(const string & bundleName,const string & backupExtName)566 void SvcSessionManager::SetBackupExtName(const string &bundleName, const string &backupExtName)
567 {
568     unique_lock<shared_mutex> lock(lock_);
569     if (!impl_.clientToken) {
570         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
571         return;
572     }
573 
574     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
575     if (!findBundleSuc) {
576         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
577         return;
578     }
579     it->second.backupExtName = backupExtName;
580 }
581 
GetBackupExtName(const string & bundleName)582 string SvcSessionManager::GetBackupExtName(const string &bundleName)
583 {
584     shared_lock<shared_mutex> lock(lock_);
585     if (!impl_.clientToken) {
586         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
587         return "";
588     }
589 
590     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
591     if (!findBundleSuc) {
592         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
593         return "";
594     }
595     return it->second.backupExtName;
596 }
597 
SetBackupExtInfo(const string & bundleName,const string & extInfo)598 void SvcSessionManager::SetBackupExtInfo(const string &bundleName, const string &extInfo)
599 {
600     unique_lock<shared_mutex> lock(lock_);
601     if (!impl_.clientToken) {
602         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
603         return;
604     }
605 
606     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
607     if (!findBundleSuc) {
608         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
609         return;
610     }
611     it->second.extInfo = extInfo;
612 }
613 
GetBackupExtInfo(const string & bundleName)614 std::string SvcSessionManager::GetBackupExtInfo(const string &bundleName)
615 {
616     shared_lock<shared_mutex> lock(lock_);
617     if (!impl_.clientToken) {
618         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
619         return "";
620     }
621 
622     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
623     if (!findBundleSuc) {
624         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
625         return "";
626     }
627     return it->second.extInfo;
628 }
629 
SetBundleUserId(const string & bundleName,const int32_t userId)630 void SvcSessionManager::SetBundleUserId(const string &bundleName, const int32_t userId)
631 {
632     unique_lock<shared_mutex> lock(lock_);
633     if (!impl_.clientToken) {
634         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
635         return;
636     }
637 
638     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
639     if (!findBundleSuc) {
640         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
641         return;
642     }
643     it->second.userId = userId;
644 }
645 
GetBundleUserId(const string & bundleName)646 int32_t SvcSessionManager::GetBundleUserId(const string &bundleName)
647 {
648     shared_lock<shared_mutex> lock(lock_);
649     if (!impl_.clientToken) {
650         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
651         return BConstants::DEFAULT_USER_ID;
652     }
653 
654     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
655     if (!findBundleSuc) {
656         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
657         return GetSessionUserId();
658     }
659     return it->second.userId;
660 }
661 
AppendBundles(const vector<BundleName> & bundleNames,vector<BundleName> & failedBundles)662 void SvcSessionManager::AppendBundles(const vector<BundleName> &bundleNames, vector<BundleName> &failedBundles)
663 {
664     unique_lock<shared_mutex> lock(lock_);
665     if (!impl_.clientToken) {
666         HILOGE("AppendBundles error, No caller token was specified");
667         return;
668     }
669 
670     for (auto &&bundleName : bundleNames) {
671         HILOGD("bundleName: %{public}s", bundleName.c_str());
672         BackupExtInfo info {};
673         auto it = impl_.backupExtNameMap.find(bundleName);
674         if (it != impl_.backupExtNameMap.end()) {
675             if (impl_.backupExtNameMap[bundleName].userId == GetSessionUserId()) {
676                 HILOGE("BackupExtNameMap already contain %{public}s", bundleName.c_str());
677                 info.backUpConnection = impl_.backupExtNameMap[bundleName].backUpConnection;
678                 info.saBackupConnection = impl_.backupExtNameMap[bundleName].saBackupConnection;
679                 info.appendNum = impl_.backupExtNameMap[bundleName].appendNum + 1;
680                 impl_.backupExtNameMap[bundleName] = info;
681             } else {
682                 failedBundles.push_back(bundleName);
683             }
684             continue;
685         }
686         if (SAUtils::IsSABundleName(bundleName)) {
687             info.saBackupConnection = GetBackupSAExt(bundleName);
688         } else {
689             info.backUpConnection = GetBackupAbilityExt(bundleName);
690         }
691         impl_.backupExtNameMap.emplace(make_pair(bundleName, info));
692     }
693     impl_.isBackupStart = true;
694     impl_.isAppendFinish = true;
695 }
696 
CreateBackupConnection(const BundleName & bundleName)697 sptr<SvcBackupConnection> SvcSessionManager::CreateBackupConnection(const BundleName &bundleName)
698 {
699     HILOGD("SvcSessionManager::CreateBackupConnection begin.");
700     return GetBackupAbilityExt(bundleName);
701 }
702 
Start()703 ErrCode SvcSessionManager::Start()
704 {
705     unique_lock<shared_mutex> lock(lock_);
706     if (!impl_.clientToken) {
707         HILOGE("Start error, No caller token was specified");
708         return BError(BError::Codes::SA_INVAL_ARG);
709     }
710     impl_.isBackupStart = true;
711     return BError(BError::Codes::OK);
712 }
713 
Finish()714 ErrCode SvcSessionManager::Finish()
715 {
716     unique_lock<shared_mutex> lock(lock_);
717     if (!impl_.clientToken) {
718         HILOGE("Finish error, No caller token was specified");
719         return BError(BError::Codes::SA_INVAL_ARG);
720     }
721     impl_.isAppendFinish = true;
722     return BError(BError::Codes::OK);
723 }
724 
IsOnAllBundlesFinished()725 bool SvcSessionManager::IsOnAllBundlesFinished()
726 {
727     shared_lock<shared_mutex> lock(lock_);
728     if (!impl_.clientToken) {
729         HILOGE("IsOnAllBundlesFinished error, No caller token was specified");
730         return false;
731     }
732     bool isAllBundlesFinished = !impl_.backupExtNameMap.size();
733     if (impl_.scenario == IServiceReverseType::Scenario::RESTORE) {
734         bool isAllBundlesRestored = SvcRestoreDepsManager::GetInstance().IsAllBundlesRestored();
735         isAllBundlesFinished = (isAllBundlesFinished && isAllBundlesRestored);
736     }
737     HILOGD("isAllBundlesFinished:%{public}d", isAllBundlesFinished);
738     return isAllBundlesFinished;
739 }
740 
IsOnOnStartSched()741 bool SvcSessionManager::IsOnOnStartSched()
742 {
743     shared_lock<shared_mutex> lock(lock_);
744     if (!impl_.clientToken) {
745         HILOGE("IsOnOnStartSched error, No caller token was specified");
746         return false;
747     }
748     if (impl_.isBackupStart && impl_.backupExtNameMap.size()) {
749         return true;
750     }
751 
752     return false;
753 }
754 
NeedToUnloadService()755 bool SvcSessionManager::NeedToUnloadService()
756 {
757     unique_lock<shared_mutex> lock(lock_);
758     if (impl_.restoreDataType == RestoreTypeEnum::RESTORE_DATA_READDY) {
759         return false;
760     }
761     bool isNeedToUnloadService = (!impl_.backupExtNameMap.size() && (sessionCnt_.load() <= 0));
762     if (impl_.scenario == IServiceReverseType::Scenario::RESTORE) {
763         bool isAllBundlesRestored = SvcRestoreDepsManager::GetInstance().IsAllBundlesRestored();
764         isNeedToUnloadService = (isNeedToUnloadService && isAllBundlesRestored);
765     }
766     HILOGD("isNeedToUnloadService:%{public}d", isNeedToUnloadService);
767     return isNeedToUnloadService;
768 }
769 
SetBundleRestoreType(const std::string & bundleName,RestoreTypeEnum restoreType)770 void SvcSessionManager::SetBundleRestoreType(const std::string &bundleName, RestoreTypeEnum restoreType)
771 {
772     unique_lock<shared_mutex> lock(lock_);
773     if (!impl_.clientToken) {
774         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
775         return;
776     }
777 
778     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
779     if (!findBundleSuc) {
780         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
781         return;
782     }
783     it->second.restoreType = restoreType;
784 }
785 
GetBundleRestoreType(const std::string & bundleName)786 RestoreTypeEnum SvcSessionManager::GetBundleRestoreType(const std::string &bundleName)
787 {
788     shared_lock<shared_mutex> lock(lock_);
789     if (!impl_.clientToken) {
790         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
791         return RestoreTypeEnum::RESTORE_DATA_WAIT_SEND;
792     }
793 
794     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
795     if (!findBundleSuc) {
796         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
797         return RestoreTypeEnum::RESTORE_DATA_WAIT_SEND;
798     }
799     return it->second.restoreType;
800 }
801 
SetBundleVersionCode(const std::string & bundleName,int64_t versionCode)802 void SvcSessionManager::SetBundleVersionCode(const std::string &bundleName, int64_t versionCode)
803 {
804     unique_lock<shared_mutex> lock(lock_);
805     if (!impl_.clientToken) {
806         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
807         return;
808     }
809 
810     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
811     if (!findBundleSuc) {
812         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
813         return;
814     }
815     it->second.versionCode = versionCode;
816 }
817 
GetBundleVersionCode(const std::string & bundleName)818 int64_t SvcSessionManager::GetBundleVersionCode(const std::string &bundleName)
819 {
820     shared_lock<shared_mutex> lock(lock_);
821     if (!impl_.clientToken) {
822         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
823         return 0;
824     }
825 
826     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
827     if (!findBundleSuc) {
828         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
829         return 0;
830     }
831     return it->second.versionCode;
832 }
833 
SetBundleVersionName(const std::string & bundleName,std::string versionName)834 void SvcSessionManager::SetBundleVersionName(const std::string &bundleName, std::string versionName)
835 {
836     unique_lock<shared_mutex> lock(lock_);
837     if (!impl_.clientToken) {
838         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
839         return;
840     }
841 
842     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
843     if (!findBundleSuc) {
844         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
845         return;
846     }
847     it->second.versionName = versionName;
848 }
849 
GetBundleVersionName(const std::string & bundleName)850 std::string SvcSessionManager::GetBundleVersionName(const std::string &bundleName)
851 {
852     shared_lock<shared_mutex> lock(lock_);
853     if (!impl_.clientToken) {
854         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
855         return "";
856     }
857 
858     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
859     if (!findBundleSuc) {
860         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
861         return "";
862     }
863     return it->second.versionName;
864 }
865 
SetBundleDataSize(const std::string & bundleName,int64_t dataSize)866 void SvcSessionManager::SetBundleDataSize(const std::string &bundleName, int64_t dataSize)
867 {
868     unique_lock<shared_mutex> lock(lock_);
869     if (!impl_.clientToken) {
870         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
871         return;
872     }
873 
874     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
875     if (!findBundleSuc) {
876         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
877         return;
878     }
879     it->second.dataSize = dataSize;
880     HILOGI("Set bundle data size end, bundlename = %{public}s , datasize = %{public}" PRId64 "",
881         bundleName.c_str(), dataSize);
882 }
883 
CalAppProcessTime(const std::string & bundleName)884 uint32_t SvcSessionManager::CalAppProcessTime(const std::string &bundleName)
885 {
886     const int64_t minTimeout = 900;      /* 900 second */
887     const int64_t defaultTimeout = 30;           /* 30 second */
888     const int64_t processRate = 3 * 1024 * 1024; /* 3M/s */
889     const int64_t multiple = 3;
890     const int64_t invertMillisecond = 1000;
891     int64_t timeout;
892     uint32_t resTimeoutMs;
893 
894     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
895     if (!findBundleSuc) {
896         HILOGE("CalAppProcessTime failed, BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
897         resTimeoutMs = (uint32_t)(minTimeout * invertMillisecond % UINT_MAX);
898         HILOGE("Current app will run timeout=%{public}u(ms), bundleName=%{public}s ", resTimeoutMs, bundleName.c_str());
899         return resTimeoutMs;
900     }
901     int64_t appSize = it->second.dataSize;
902     /* timeout = (AppSize / 3Ms) * 3 + 30 */
903     timeout = defaultTimeout + (appSize / processRate) * multiple;
904     timeout = timeout < minTimeout ? minTimeout : timeout;
905     resTimeoutMs = (uint32_t)(timeout * invertMillisecond % UINT_MAX); /* conver second to millisecond */
906     HILOGI("Calculate App extension process run timeout=%{public}u(ms), bundleName=%{public}s ", resTimeoutMs,
907            bundleName.c_str());
908     return resTimeoutMs;
909 }
910 
StartFwkTimer(const std::string & bundleName,const Utils::Timer::TimerCallback & callback)911 bool SvcSessionManager::StartFwkTimer(const std::string &bundleName, const Utils::Timer::TimerCallback &callback)
912 {
913     unique_lock<shared_mutex> lock(lock_);
914     HILOGI("StartFwkTimer begin bundleName %{public}s", bundleName.c_str());
915     if (!impl_.clientToken) {
916         HILOGE("No caller token was specified");
917         return false;
918     }
919     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
920     if (!findBundleSuc) {
921         HILOGE("Start fwk timer failed, BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
922         return false;
923     }
924     if (it->second.fwkTimerStatus == true) {
925         HILOGE("FwkTimer is registered, unregister first.");
926         return false;
927     }
928     uint32_t timeout = CalAppProcessTime(bundleName);
929 
930     it->second.fwkTimerStatus = true;
931     it->second.timerId = timer_.Register(callback, timeout, true);
932     HILOGI("StartFwkTimer end bundleName %{public}s", bundleName.c_str());
933     return true;
934 }
935 
StopFwkTimer(const std::string & bundleName)936 bool SvcSessionManager::StopFwkTimer(const std::string &bundleName)
937 {
938     unique_lock<shared_mutex> lock(lock_);
939     HILOGI("StopFwkTimer begin bundleName %{public}s", bundleName.c_str());
940     if (!impl_.clientToken) {
941         HILOGE("No caller token was specified");
942         return false;
943     }
944     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
945     if (!findBundleSuc) {
946         HILOGE("Stop fwk timer failed, BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
947         return false;
948     }
949     if (it->second.fwkTimerStatus == false) {
950         HILOGE("FwkTimer is unregistered, register first.");
951         return true;
952     }
953 
954     it->second.fwkTimerStatus = false;
955     timer_.Unregister(it->second.timerId);
956     HILOGI("StopFwkTimer end bundleName %{public}s", bundleName.c_str());
957     return true;
958 }
959 
StartExtTimer(const std::string & bundleName,const Utils::Timer::TimerCallback & callback)960 bool SvcSessionManager::StartExtTimer(const std::string &bundleName, const Utils::Timer::TimerCallback &callback)
961 {
962     unique_lock<shared_mutex> lock(lock_);
963     HILOGI("StartExtTimer begin bundleName %{public}s", bundleName.c_str());
964     if (!impl_.clientToken) {
965         HILOGE("No caller token was specified");
966         return false;
967     }
968     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
969     if (!findBundleSuc) {
970         HILOGE("Start extension timer failed, BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
971         return false;
972     }
973     if (it->second.extTimerStatus == true) {
974         HILOGE("ExtTimer is registered, unregister first.");
975         return false;
976     }
977     uint32_t timeout = it->second.timeout;
978     timeout = (timeout != BConstants::TIMEOUT_INVALID) ? timeout : BConstants::DEFAULT_TIMEOUT;
979     it->second.extTimerStatus = true;
980     it->second.timerId = timer_.Register(callback, timeout, true);
981     HILOGI("StartExtTimer end, timeout %{public}u(ms), bundleName %{public}s", timeout, bundleName.c_str());
982     return true;
983 }
984 
StopExtTimer(const std::string & bundleName)985 bool SvcSessionManager::StopExtTimer(const std::string &bundleName)
986 {
987     unique_lock<shared_mutex> lock(lock_);
988     HILOGI("StopExtTimer begin bundleName %{public}s", bundleName.c_str());
989     if (!impl_.clientToken) {
990         HILOGE("No caller token was specified");
991         return false;
992     }
993     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
994     if (!findBundleSuc) {
995         HILOGE("Stop extension timer failed, BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
996         return false;
997     }
998     if (it->second.extTimerStatus == false) {
999         HILOGE("ExtTimer is unregistered, register first.");
1000         return true;
1001     }
1002 
1003     it->second.extTimerStatus = false;
1004     it->second.timeout = BConstants::TIMEOUT_INVALID;
1005     timer_.Unregister(it->second.timerId);
1006     HILOGI("StopExtTimer end bundleName %{public}s", bundleName.c_str());
1007     return true;
1008 }
1009 
UpdateTimer(const std::string & bundleName,uint32_t timeout,const Utils::Timer::TimerCallback & callback)1010 bool SvcSessionManager::UpdateTimer(const std::string &bundleName, uint32_t timeout,
1011     const Utils::Timer::TimerCallback &callback)
1012 {
1013     unique_lock<shared_mutex> lock(lock_);
1014     HILOGI("UpdateTimer begin bundleName %{public}s", bundleName.c_str());
1015     if (!impl_.clientToken) {
1016         HILOGE("No caller token was specified");
1017         return false;
1018     }
1019     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
1020     if (!findBundleSuc) {
1021         HILOGE("Update timer failed, BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
1022         return false;
1023     }
1024     it->second.timeout = timeout;
1025     if (it->second.extTimerStatus == false) {
1026         HILOGI("ExtTimer is unregistered, just store timeout %{public}u(ms)", timeout);
1027         return true;
1028     }
1029 
1030     timer_.Unregister(it->second.timerId);
1031     HILOGI("UpdateTimer timeout %{public}u(ms), bundleName %{public}s ", timeout, bundleName.c_str());
1032     it->second.timerId = timer_.Register(callback, timeout, true);
1033     it->second.extTimerStatus = true;
1034     HILOGI("UpdateTimer end bundleName %{public}s", bundleName.c_str());
1035     return true;
1036 }
1037 
IncreaseSessionCnt(const std::string funcName)1038 void SvcSessionManager::IncreaseSessionCnt(const std::string funcName)
1039 {
1040     sessionCnt_++;
1041     HILOGI("func name:%{public}s, %{public}d.", funcName.c_str(), sessionCnt_.load());
1042 }
1043 
DecreaseSessionCnt(const std::string funcName)1044 void SvcSessionManager::DecreaseSessionCnt(const std::string funcName)
1045 {
1046     if (sessionCnt_.load() > 0) {
1047         sessionCnt_--;
1048     } else {
1049         HILOGE("Invalid sessionCount.");
1050     }
1051     HILOGI("func name:%{public}s, %{public}d.", funcName.c_str(), sessionCnt_.load());
1052 }
1053 
ClearSessionData()1054 ErrCode SvcSessionManager::ClearSessionData()
1055 {
1056     unique_lock<shared_mutex> lock(lock_);
1057     ErrCode ret = BError(BError::Codes::OK);
1058     for (auto &&it : impl_.backupExtNameMap) {
1059         // clear timer
1060         if (it.second.fwkTimerStatus == true || it.second.extTimerStatus == true) {
1061             it.second.fwkTimerStatus = false;
1062             it.second.extTimerStatus = false;
1063             timer_.Unregister(it.second.timerId);
1064         }
1065         // disconnect extension
1066         if (it.second.schedAction == BConstants::ServiceSchedAction::RUNNING) {
1067             auto backUpConnection = it.second.backUpConnection;
1068             if (backUpConnection == nullptr) {
1069                 HILOGE("Clear session error, backUpConnection is empty");
1070                 return BError(BError::Codes::SA_INVAL_ARG);
1071             }
1072             auto proxy = backUpConnection->GetBackupExtProxy();
1073             if (proxy == nullptr) {
1074                 HILOGE("Clear session error, proxy is empty");
1075                 return BError(BError::Codes::EXT_INVAL_ARG);
1076             }
1077             if (impl_.restoreDataType != RestoreTypeEnum::RESTORE_DATA_READDY) {
1078                 ret = proxy->HandleClear();
1079             }
1080             HandleOnRelease(proxy);
1081             backUpConnection->DisconnectBackupExtAbility();
1082         }
1083         if (ret != BError(BError::Codes::OK)) {
1084             return ret;
1085         }
1086         // clear data
1087         it.second.schedAction = BConstants::ServiceSchedAction::FINISH;
1088     }
1089     impl_.backupExtNameMap.clear();
1090     return BError(BError::Codes::OK);
1091 }
1092 
GetIsIncrementalBackup()1093 bool SvcSessionManager::GetIsIncrementalBackup()
1094 {
1095     unique_lock<shared_mutex> lock(lock_);
1096     if (!impl_.clientToken) {
1097         HILOGE("GetIsIncrementalBackup error, No caller token was specified");
1098         return false;
1099     }
1100     return impl_.isIncrementalBackup;
1101 }
1102 
SetIncrementalData(const BIncrementalData & incrementalData)1103 void SvcSessionManager::SetIncrementalData(const BIncrementalData &incrementalData)
1104 {
1105     unique_lock<shared_mutex> lock(lock_);
1106     if (!impl_.clientToken) {
1107         HILOGE("SetIncrementalData error, No caller token was specified");
1108         return;
1109     }
1110     auto [findBundleSuc, it] = GetBackupExtNameMap(incrementalData.bundleName);
1111     if (!findBundleSuc) {
1112         HILOGE("BackupExtNameMap can not find bundle %{public}s", incrementalData.bundleName.c_str());
1113         return;
1114     }
1115     it->second.lastIncrementalTime = incrementalData.lastIncrementalTime;
1116     it->second.manifestFd = incrementalData.manifestFd;
1117     it->second.backupParameters = incrementalData.backupParameters;
1118     it->second.backupPriority = incrementalData.backupPriority;
1119 }
1120 
GetIncrementalManifestFd(const string & bundleName)1121 int32_t SvcSessionManager::GetIncrementalManifestFd(const string &bundleName)
1122 {
1123     unique_lock<shared_mutex> lock(lock_);
1124     if (!impl_.clientToken) {
1125         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
1126         return BConstants::INVALID_FD_NUM;
1127     }
1128     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
1129     if (!findBundleSuc) {
1130         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
1131         return BConstants::INVALID_FD_NUM;
1132     }
1133     return it->second.manifestFd;
1134 }
1135 
GetLastIncrementalTime(const string & bundleName)1136 int64_t SvcSessionManager::GetLastIncrementalTime(const string &bundleName)
1137 {
1138     unique_lock<shared_mutex> lock(lock_);
1139     if (!impl_.clientToken) {
1140         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
1141         return 0;
1142     }
1143     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
1144     if (!findBundleSuc) {
1145         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
1146         return 0;
1147     }
1148     return it->second.lastIncrementalTime;
1149 }
1150 
GetMemParaCurSize()1151 int32_t SvcSessionManager::GetMemParaCurSize()
1152 {
1153     return memoryParaCurSize_;
1154 }
1155 
SetMemParaCurSize(int32_t size)1156 void SvcSessionManager::SetMemParaCurSize(int32_t size)
1157 {
1158     memoryParaCurSize_ = size;
1159 }
1160 
SetClearDataFlag(const std::string & bundleName,bool isClearData)1161 void SvcSessionManager::SetClearDataFlag(const std::string &bundleName, bool isClearData)
1162 {
1163     unique_lock<shared_mutex> lock(lock_);
1164     if (!impl_.clientToken) {
1165         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
1166         return;
1167     }
1168     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
1169     if (!findBundleSuc) {
1170         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
1171         return;
1172     }
1173     it->second.isClearData = isClearData;
1174     HILOGI("bundleName:%{public}s, set clear data flag:%{public}d.", bundleName.c_str(), isClearData);
1175 }
1176 
GetClearDataFlag(const std::string & bundleName)1177 bool SvcSessionManager::GetClearDataFlag(const std::string &bundleName)
1178 {
1179     unique_lock<shared_mutex> lock(lock_);
1180     if (!impl_.clientToken) {
1181         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
1182         return true;
1183     }
1184     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
1185     if (!findBundleSuc) {
1186         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
1187         return true;
1188     }
1189     return it->second.isClearData;
1190 }
1191 
GetTimeoutValue(const std::string & bundleName)1192 uint32_t SvcSessionManager::GetTimeoutValue(const std::string &bundleName)
1193 {
1194     unique_lock<shared_mutex> lock(lock_);
1195     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
1196     if (!findBundleSuc) {
1197         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
1198         return BConstants::TIMEOUT_INVALID;
1199     }
1200     return it->second.timeout;
1201 }
1202 
ValidRestoreDataType(RestoreTypeEnum restoreDataType)1203 bool SvcSessionManager::ValidRestoreDataType(RestoreTypeEnum restoreDataType)
1204 {
1205     return impl_.restoreDataType == restoreDataType;
1206 }
1207 
CleanAndCheckIfNeedWait(ErrCode & ret,std::vector<std::string> & bundleNameList)1208 bool SvcSessionManager::CleanAndCheckIfNeedWait(ErrCode &ret, std::vector<std::string> &bundleNameList)
1209 {
1210     unique_lock<shared_mutex> lock(lock_);
1211     for (auto it = impl_.backupExtNameMap.begin(); it != impl_.backupExtNameMap.end();) {
1212         HILOGI("BundleName: %{public}s, schedAction: %{public}d", it->first.c_str(), it->second.schedAction);
1213         if (it->second.schedAction == BConstants::ServiceSchedAction::WAIT) {
1214             it = impl_.backupExtNameMap.erase(it);
1215         } else if (it->second.schedAction == BConstants::ServiceSchedAction::START ||
1216             (it->second.schedAction == BConstants::ServiceSchedAction::RUNNING && !it->second.isInPublishFile)) {
1217             if (it->second.fwkTimerStatus == true || it->second.extTimerStatus == true) {
1218                 it->second.fwkTimerStatus = false;
1219                 it->second.extTimerStatus = false;
1220                 timer_.Unregister(it->second.timerId);
1221             }
1222             auto backUpConnection = it->second.backUpConnection;
1223             if (backUpConnection == nullptr) {
1224                 HILOGE("Clear session error, backUpConnection is empty, bundleName: %{public}s", it->first.c_str());
1225                 it = impl_.backupExtNameMap.erase(it);
1226                 continue;
1227             }
1228             auto proxy = backUpConnection->GetBackupExtProxy();
1229             // start action
1230             if (proxy == nullptr) {
1231                 HILOGE("Clear session error, BackupExtProxy is empty, bundleName: %{public}s", it->first.c_str());
1232                 backUpConnection->DisconnectBackupExtAbility();
1233                 it = impl_.backupExtNameMap.erase(it);
1234                 continue;
1235             }
1236             // running action
1237             ErrCode retTmp = ERR_OK;
1238             if (impl_.restoreDataType != RestoreTypeEnum::RESTORE_DATA_READDY) {
1239                 retTmp = proxy->HandleClear();
1240             }
1241             if (retTmp == ERR_OK) {
1242                 bundleNameList.emplace_back(it->first);
1243             } else {
1244                 ret = retTmp;
1245             }
1246             HandleOnRelease(proxy);
1247             backUpConnection->DisconnectBackupExtAbility();
1248             HILOGI("Disconnect extensionAbility, bundleName: %{public}s", it->first.c_str());
1249             it = impl_.backupExtNameMap.erase(it);
1250         } else {
1251             ++it;
1252         }
1253     }
1254     if (impl_.backupExtNameMap.empty()) {
1255         HILOGI("Release normally, no need wait");
1256         return false;
1257     }
1258     HILOGI("Release abnormally, need wait for restore");
1259     return true;
1260 }
1261 
SetPublishFlag(const std::string & bundleName)1262 void SvcSessionManager::SetPublishFlag(const std::string &bundleName)
1263 {
1264     unique_lock<shared_mutex> lock(lock_);
1265     if (!impl_.clientToken) {
1266         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
1267         return;
1268     }
1269     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
1270     if (!findBundleSuc) {
1271         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
1272         return;
1273     }
1274     it->second.isInPublishFile = true;
1275     HILOGE("Set PublishFile success, bundleName = %{public}s", bundleName.c_str());
1276 }
1277 
SetOldBackupVersion(const std::string & backupVersion)1278 void SvcSessionManager::SetOldBackupVersion(const std::string &backupVersion)
1279 {
1280     unique_lock<shared_mutex> lock(lock_);
1281     if (!impl_.clientToken) {
1282         HILOGE("Error, No caller token was specified");
1283         return;
1284     }
1285     impl_.oldBackupVersion = backupVersion;
1286 }
1287 
GetOldBackupVersion()1288 std::string SvcSessionManager::GetOldBackupVersion()
1289 {
1290     shared_lock<shared_mutex> lock(lock_);
1291     if (!impl_.clientToken) {
1292         HILOGE("Error, No caller token was specified");
1293         return "";
1294     }
1295     return impl_.oldBackupVersion;
1296 }
1297 
SetImplRestoreType(const RestoreTypeEnum restoreType)1298 void SvcSessionManager::SetImplRestoreType(const RestoreTypeEnum restoreType)
1299 {
1300     impl_.restoreDataType = restoreType;
1301 }
1302 
SetIsReadyLaunch(const std::string & bundleName)1303 void SvcSessionManager::SetIsReadyLaunch(const std::string &bundleName)
1304 {
1305     unique_lock<shared_mutex> lock(lock_);
1306     if (!impl_.clientToken) {
1307         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
1308         return;
1309     }
1310     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
1311     if (!findBundleSuc) {
1312         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
1313         return;
1314     }
1315     it->second.isReadyLaunch = true;
1316     HILOGE("SetIsReadyLaunch success, bundleName = %{public}s", bundleName.c_str());
1317 }
1318 
HandleOnRelease(sptr<IExtension> proxy)1319 void SvcSessionManager::HandleOnRelease(sptr<IExtension> proxy)
1320 {
1321     if (proxy == nullptr) {
1322         HILOGE("HandleOnRelease error, proxy is empty");
1323         return;
1324     }
1325     if (impl_.scenario == IServiceReverseType::Scenario::UNDEFINED ||
1326         impl_.scenario == IServiceReverseType::Scenario::CLEAN) {
1327         HILOGE("scenario is %{public}d, not need to HandleOnRelease", impl_.scenario);
1328         return;
1329     }
1330     HILOGI("HandleOnRelease begin");
1331     proxy->HandleOnRelease(static_cast<int32_t>(impl_.scenario));
1332 }
1333 
SetIsRestoreEnd(const std::string & bundleName)1334 void SvcSessionManager::SetIsRestoreEnd(const std::string &bundleName)
1335 {
1336     unique_lock<shared_mutex> lock(lock_);
1337     if (!impl_.clientToken) {
1338         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
1339         return;
1340     }
1341     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
1342     if (!findBundleSuc) {
1343         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
1344         return;
1345     }
1346     it->second.isRestoreEnd = true;
1347     HILOGI("SetIsRestoreEnd success, bundleName = %{public}s", bundleName.c_str());
1348 }
1349 
GetIsRestoreEnd(const std::string & bundleName)1350 bool SvcSessionManager::GetIsRestoreEnd(const std::string &bundleName)
1351 {
1352     shared_lock<shared_mutex> lock(lock_);
1353     if (!impl_.clientToken) {
1354         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
1355         return false;
1356     }
1357     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
1358     if (!findBundleSuc) {
1359         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
1360         return false;
1361     }
1362     return it->second.isRestoreEnd;
1363 }
1364 } // namespace OHOS::FileManagement::Backup
1365