• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "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,IServiceReverse::Scenario scenario) const43 ErrCode SvcSessionManager::VerifyCallerAndScenario(uint32_t clientToken, IServiceReverse::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 == IServiceReverse::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 == IServiceReverse::Scenario::RESTORE) {
128         AppRadar::GetInstance().RecordRestoreFuncRes(info, "SvcSessionManager::Deactive", impl_.userId,
129             BizStageRestore::BIZ_STAGE_DEACTIVE_SESSION, ERR_OK);
130     } else if (impl_.scenario == IServiceReverse::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 IServiceReverse::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 IServiceReverse::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 == IServiceReverse::Scenario::RESTORE || SAUtils::IsSABundleName(bundleName)) {
221         it->second.isBundleFinished = true;
222         return true;
223     } else if (impl_.scenario == IServiceReverse::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:%{public}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 != IServiceReverse::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 
GetSAExtConnection(const BundleName & bundleName)313 std::weak_ptr<SABackupConnection> SvcSessionManager::GetSAExtConnection(const BundleName &bundleName)
314 {
315     HILOGD("svcMrg:GetExt, bundleName:%{public}s", bundleName.c_str());
316     shared_lock<shared_mutex> lock(lock_);
317     if (!impl_.clientToken) {
318         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
319         return std::weak_ptr<SABackupConnection>();
320     }
321 
322     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
323     if (!findBundleSuc) {
324         HILOGE("BackupExtNameMap can not find current bundle, bundleName:%{public}s", bundleName.c_str());
325         return std::weak_ptr<SABackupConnection>();
326     }
327     if (!it->second.saBackupConnection) {
328         HILOGE("SA backup connection is empty, bundleName:%{public}s", bundleName.c_str());
329         return std::weak_ptr<SABackupConnection>();
330     }
331 
332     return std::weak_ptr<SABackupConnection>(it->second.saBackupConnection);
333 }
334 
GetBackupAbilityExt(const string & bundleName)335 sptr<SvcBackupConnection> SvcSessionManager::GetBackupAbilityExt(const string &bundleName)
336 {
337     auto callDied = [revPtr {reversePtr_}](const string &&bundleName, bool isCleanCalled = false) {
338         auto revPtrStrong = revPtr.promote();
339         if (!revPtrStrong) {
340             // 服务先于客户端死亡是一种异常场景,但该场景对本流程来说也没什么影响,所以只是简单记录一下
341             HILOGW("It's curious that the backup sa dies before the backup client");
342             return;
343         }
344         revPtrStrong->OnBackupExtensionDied(move(bundleName), isCleanCalled);
345     };
346 
347     auto callConnected = [revPtr {reversePtr_}](const string &&bundleName) {
348         auto revPtrStrong = revPtr.promote();
349         if (!revPtrStrong) {
350             // 服务先于客户端死亡是一种异常场景,但该场景对本流程来说也没什么影响,所以只是简单记录一下
351             HILOGW("It's curious that the backup sa dies before the backup client");
352             return;
353         }
354         revPtrStrong->ExtConnectDone(move(bundleName));
355     };
356 
357     return sptr<SvcBackupConnection>(new SvcBackupConnection(callDied, callConnected, bundleName));
358 }
359 
GetBackupSAExt(const std::string & bundleName)360 std::shared_ptr<SABackupConnection> SvcSessionManager::GetBackupSAExt(const std::string &bundleName)
361 {
362     auto callDied = [revPtr {reversePtr_}](const string &&bundleName) {
363         auto revPtrStrong = revPtr.promote();
364         if (!revPtrStrong) {
365             // 服务先于客户端死亡是一种异常场景,但该场景对本流程来说也没什么影响,所以只是简单记录一下
366             HILOGW("It's curious that the backup sa dies before the backup client");
367             return;
368         }
369         revPtrStrong->OnBackupExtensionDied(move(bundleName));
370     };
371 
372     auto callConnected = [revPtr {reversePtr_}](const string &&bundleName) {
373         auto revPtrStrong = revPtr.promote();
374         if (!revPtrStrong) {
375             // 服务先于客户端死亡是一种异常场景,但该场景对本流程来说也没什么影响,所以只是简单记录一下
376             HILOGW("It's curious that the backup sa dies before the backup client");
377             return;
378         }
379         revPtrStrong->ExtConnectDone(move(bundleName));
380     };
381 
382     auto callBackup = [revPtr {reversePtr_}](const string &&bundleName, const int &&fd, const std::string result,
383                                              const ErrCode &&errCode) {
384         auto revPtrStrong = revPtr.promote();
385         if (!revPtrStrong) {
386             // 服务先于客户端死亡是一种异常场景,但该场景对本流程来说也没什么影响,所以只是简单记录一下
387             HILOGW("It's curious that the backup sa dies before the backup client");
388             return;
389         }
390         revPtrStrong->OnSABackup(move(bundleName), move(fd), move(result), move(errCode));
391     };
392 
393     auto callRestore = [revPtr {reversePtr_}](const string &&bundleName, const std::string result,
394                                               const ErrCode &&errCode) {
395         auto revPtrStrong = revPtr.promote();
396         if (!revPtrStrong) {
397             // 服务先于客户端死亡是一种异常场景,但该场景对本流程来说也没什么影响,所以只是简单记录一下
398             HILOGW("It's curious that the backup sa dies before the backup client");
399             return;
400         }
401         revPtrStrong->OnSARestore(move(bundleName), move(result), move(errCode));
402     };
403 
404     return std::make_shared<SABackupConnection>(callDied, callConnected, callBackup, callRestore);
405 }
406 
DumpInfo(const int fd,const std::vector<std::u16string> & args)407 void SvcSessionManager::DumpInfo(const int fd, const std::vector<std::u16string> &args)
408 {
409     dprintf(fd, "---------------------backup info--------------------\n");
410     dprintf(fd, "Scenario: %d\n", impl_.scenario);
411 }
412 
InitClient(Impl & newImpl)413 ErrCode SvcSessionManager::InitClient(Impl &newImpl)
414 {
415     if (!newImpl.clientProxy) {
416         HILOGE("Init client error, Invalid client");
417         return BError(BError::Codes::SA_INVAL_ARG);
418     }
419     auto remoteObj = newImpl.clientProxy->AsObject();
420     if (!remoteObj) {
421         HILOGE("Init client error, Proxy's remote object can't be nullptr");
422         return BError(BError::Codes::SA_BROKEN_IPC);
423     }
424 
425     auto callback = [revPtr {reversePtr_}](const wptr<IRemoteObject> &obj) {
426         HILOGI("Client died.");
427 
428         auto revPtrStrong = revPtr.promote();
429         if (!revPtrStrong) {
430             // 服务先于客户端死亡是一种异常场景,但该场景对本流程来说也没什么影响,所以只是简单记录一下
431             HILOGW("It's curious that the backup sa dies before the backup client");
432             return;
433         }
434         (void)revPtrStrong->SessionDeactive();
435     };
436     deathRecipient_ = sptr(new SvcDeathRecipient(callback));
437     remoteObj->AddDeathRecipient(deathRecipient_);
438     AppRadar::Info info("", "", "active session success");
439     if (newImpl.scenario == IServiceReverse::Scenario::RESTORE) {
440         AppRadar::GetInstance().RecordRestoreFuncRes(info, "SvcSessionManager::InitClient", newImpl.userId,
441             BizStageRestore::BIZ_STAGE_ACTIVE_SESSION, ERR_OK);
442     } else if (newImpl.scenario == IServiceReverse::Scenario::BACKUP) {
443         AppRadar::GetInstance().RecordBackupFuncRes(info, "SvcSessionManager::InitClient", newImpl.userId,
444             BizStageBackup::BIZ_STAGE_ACTIVE_SESSION, ERR_OK);
445     }
446     HILOGI("Succeed to active a session");
447     return BError(BError::Codes::OK);
448 }
449 
SetExtFileNameRequest(const string & bundleName,const string & fileName)450 void SvcSessionManager::SetExtFileNameRequest(const string &bundleName, const string &fileName)
451 {
452     unique_lock<shared_mutex> lock(lock_);
453     if (!impl_.clientToken) {
454         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
455         return;
456     }
457     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
458     if (!findBundleSuc) {
459         HILOGE("BackupExtNameMap can not find current bundle, bundleName:%{public}s", bundleName.c_str());
460         return;
461     }
462     it->second.fileNameInfo.emplace(fileName);
463 }
464 
GetExtFileNameRequest(const std::string & bundleName)465 std::set<std::string> SvcSessionManager::GetExtFileNameRequest(const std::string &bundleName)
466 {
467     unique_lock<shared_mutex> lock(lock_);
468     if (!impl_.clientToken) {
469         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
470         return std::set<std::string>();
471     }
472 
473     if (impl_.scenario != IServiceReverse::Scenario::RESTORE) {
474         HILOGE("Invalid Scenario, bundleName:%{public}s", bundleName.c_str());
475         return std::set<std::string>();
476     }
477     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
478     if (!findBundleSuc) {
479         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
480         return std::set<std::string>();
481     }
482     set<string> fileNameInfo = it->second.fileNameInfo;
483     it->second.fileNameInfo.clear();
484     return fileNameInfo;
485 }
486 
GetBackupExtNameMap(const string & bundleName)487 std::tuple<bool, std::map<BundleName, BackupExtInfo>::iterator> SvcSessionManager::GetBackupExtNameMap(
488     const string &bundleName)
489 {
490     auto it = impl_.backupExtNameMap.find(bundleName);
491     if (it == impl_.backupExtNameMap.end()) {
492         HILOGE("Could not find the bundle from current session, bundleName:%{public}s", bundleName.c_str());
493         return {false, impl_.backupExtNameMap.end()};
494     }
495     return {true, it};
496 }
497 
GetSchedBundleName(string & bundleName)498 bool SvcSessionManager::GetSchedBundleName(string &bundleName)
499 {
500     unique_lock<shared_mutex> lock(lock_);
501     if (extConnectNum_ >= BConstants::EXT_CONNECT_MAX_COUNT) {
502         HILOGE("Sched bundle count is too many");
503         return false;
504     }
505 
506     for (auto &&it : impl_.backupExtNameMap) {
507         if (it.second.schedAction == BConstants::ServiceSchedAction::WAIT) {
508             bundleName = it.first;
509             if (!it.second.isReadyLaunch) {
510                 HILOGE("Current bundle:%{public}s can not sched, baseInfo is not set done", bundleName.c_str());
511                 return false;
512             }
513             it.second.schedAction = BConstants::ServiceSchedAction::START;
514             extConnectNum_++;
515             return true;
516         }
517     }
518     return false;
519 }
520 
GetServiceSchedAction(const std::string & bundleName)521 BConstants::ServiceSchedAction SvcSessionManager::GetServiceSchedAction(const std::string &bundleName)
522 {
523     shared_lock<shared_mutex> lock(lock_);
524     if (!impl_.clientToken) {
525         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
526         return BConstants::ServiceSchedAction::UNKNOWN;
527     }
528     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
529     if (!findBundleSuc) {
530         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
531         return BConstants::ServiceSchedAction::UNKNOWN;
532     }
533     return it->second.schedAction;
534 }
535 
SetServiceSchedAction(const string & bundleName,BConstants::ServiceSchedAction action)536 void SvcSessionManager::SetServiceSchedAction(const string &bundleName, BConstants::ServiceSchedAction action)
537 {
538     unique_lock<shared_mutex> lock(lock_);
539     if (!impl_.clientToken) {
540         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
541         throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified");
542     }
543     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
544     if (!findBundleSuc) {
545         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
546         throw BError(BError::Codes::SA_REFUSED_ACT, "BackupExtNameMap can not find bundle");
547     }
548     it->second.schedAction = action;
549     if (it->second.schedAction == BConstants::ServiceSchedAction::START) {
550         extConnectNum_++;
551     }
552 }
553 
SetBackupExtName(const string & bundleName,const string & backupExtName)554 void SvcSessionManager::SetBackupExtName(const string &bundleName, const string &backupExtName)
555 {
556     unique_lock<shared_mutex> lock(lock_);
557     if (!impl_.clientToken) {
558         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
559         return;
560     }
561 
562     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
563     if (!findBundleSuc) {
564         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
565         return;
566     }
567     it->second.backupExtName = backupExtName;
568 }
569 
GetBackupExtName(const string & bundleName)570 string SvcSessionManager::GetBackupExtName(const string &bundleName)
571 {
572     shared_lock<shared_mutex> lock(lock_);
573     if (!impl_.clientToken) {
574         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
575         return "";
576     }
577 
578     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
579     if (!findBundleSuc) {
580         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
581         return "";
582     }
583     return it->second.backupExtName;
584 }
585 
SetBackupExtInfo(const string & bundleName,const string & extInfo)586 void SvcSessionManager::SetBackupExtInfo(const string &bundleName, const string &extInfo)
587 {
588     unique_lock<shared_mutex> lock(lock_);
589     if (!impl_.clientToken) {
590         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
591         return;
592     }
593 
594     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
595     if (!findBundleSuc) {
596         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
597         return;
598     }
599     it->second.extInfo = extInfo;
600 }
601 
GetBackupExtInfo(const string & bundleName)602 std::string SvcSessionManager::GetBackupExtInfo(const string &bundleName)
603 {
604     shared_lock<shared_mutex> lock(lock_);
605     if (!impl_.clientToken) {
606         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
607         return "";
608     }
609 
610     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
611     if (!findBundleSuc) {
612         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
613         return "";
614     }
615     return it->second.extInfo;
616 }
617 
SetBundleUserId(const string & bundleName,const int32_t userId)618 void SvcSessionManager::SetBundleUserId(const string &bundleName, const int32_t userId)
619 {
620     unique_lock<shared_mutex> lock(lock_);
621     if (!impl_.clientToken) {
622         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
623         return;
624     }
625 
626     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
627     if (!findBundleSuc) {
628         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
629         return;
630     }
631     it->second.userId = userId;
632 }
633 
GetBundleUserId(const string & bundleName)634 int32_t SvcSessionManager::GetBundleUserId(const string &bundleName)
635 {
636     shared_lock<shared_mutex> lock(lock_);
637     if (!impl_.clientToken) {
638         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
639         return BConstants::DEFAULT_USER_ID;
640     }
641 
642     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
643     if (!findBundleSuc) {
644         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
645         return GetSessionUserId();
646     }
647     return it->second.userId;
648 }
649 
AppendBundles(const vector<BundleName> & bundleNames,vector<BundleName> & failedBundles)650 void SvcSessionManager::AppendBundles(const vector<BundleName> &bundleNames, vector<BundleName> &failedBundles)
651 {
652     unique_lock<shared_mutex> lock(lock_);
653     if (!impl_.clientToken) {
654         HILOGE("AppendBundles error, No caller token was specified");
655         return;
656     }
657 
658     for (auto &&bundleName : bundleNames) {
659         HILOGD("bundleName: %{public}s", bundleName.c_str());
660         BackupExtInfo info {};
661         auto it = impl_.backupExtNameMap.find(bundleName);
662         if (it != impl_.backupExtNameMap.end()) {
663             if (impl_.backupExtNameMap[bundleName].userId == GetSessionUserId()) {
664                 HILOGE("BackupExtNameMap already contain %{public}s", bundleName.c_str());
665                 info.backUpConnection = impl_.backupExtNameMap[bundleName].backUpConnection;
666                 info.saBackupConnection = impl_.backupExtNameMap[bundleName].saBackupConnection;
667                 info.appendNum = impl_.backupExtNameMap[bundleName].appendNum + 1;
668                 impl_.backupExtNameMap[bundleName] = info;
669             } else {
670                 failedBundles.push_back(bundleName);
671             }
672             continue;
673         }
674         if (SAUtils::IsSABundleName(bundleName)) {
675             info.saBackupConnection = GetBackupSAExt(bundleName);
676         } else {
677             info.backUpConnection = GetBackupAbilityExt(bundleName);
678         }
679         impl_.backupExtNameMap.emplace(make_pair(bundleName, info));
680     }
681     impl_.isBackupStart = true;
682     impl_.isAppendFinish = true;
683 }
684 
CreateBackupConnection(BundleName & bundleName)685 sptr<SvcBackupConnection> SvcSessionManager::CreateBackupConnection(BundleName &bundleName)
686 {
687     HILOGD("SvcSessionManager::CreateBackupConnection begin.");
688     return GetBackupAbilityExt(bundleName);
689 }
690 
Start()691 ErrCode SvcSessionManager::Start()
692 {
693     unique_lock<shared_mutex> lock(lock_);
694     if (!impl_.clientToken) {
695         HILOGE("Start error, No caller token was specified");
696         return BError(BError::Codes::SA_INVAL_ARG);
697     }
698     impl_.isBackupStart = true;
699     return BError(BError::Codes::OK);
700 }
701 
Finish()702 ErrCode SvcSessionManager::Finish()
703 {
704     unique_lock<shared_mutex> lock(lock_);
705     if (!impl_.clientToken) {
706         HILOGE("Finish error, No caller token was specified");
707         return BError(BError::Codes::SA_INVAL_ARG);
708     }
709     impl_.isAppendFinish = true;
710     return BError(BError::Codes::OK);
711 }
712 
IsOnAllBundlesFinished()713 bool SvcSessionManager::IsOnAllBundlesFinished()
714 {
715     shared_lock<shared_mutex> lock(lock_);
716     if (!impl_.clientToken) {
717         HILOGE("IsOnAllBundlesFinished error, No caller token was specified");
718         return false;
719     }
720     bool isAllBundlesFinished = !impl_.backupExtNameMap.size();
721     if (impl_.scenario == IServiceReverse::Scenario::RESTORE) {
722         bool isAllBundlesRestored = SvcRestoreDepsManager::GetInstance().IsAllBundlesRestored();
723         isAllBundlesFinished = (isAllBundlesFinished && isAllBundlesRestored);
724     }
725     HILOGD("isAllBundlesFinished:%{public}d", isAllBundlesFinished);
726     return isAllBundlesFinished;
727 }
728 
IsOnOnStartSched()729 bool SvcSessionManager::IsOnOnStartSched()
730 {
731     HILOGI("Begin");
732     shared_lock<shared_mutex> lock(lock_);
733     if (!impl_.clientToken) {
734         HILOGE("IsOnOnStartSched error, No caller token was specified");
735         return false;
736     }
737     if (impl_.isBackupStart && impl_.backupExtNameMap.size()) {
738         return true;
739     }
740     HILOGI("End");
741     return false;
742 }
743 
NeedToUnloadService()744 bool SvcSessionManager::NeedToUnloadService()
745 {
746     unique_lock<shared_mutex> lock(lock_);
747     if (impl_.restoreDataType == RestoreTypeEnum::RESTORE_DATA_READDY) {
748         return false;
749     }
750     bool isNeedToUnloadService = (!impl_.backupExtNameMap.size() && (sessionCnt_.load() <= 0));
751     if (impl_.scenario == IServiceReverse::Scenario::RESTORE) {
752         bool isAllBundlesRestored = SvcRestoreDepsManager::GetInstance().IsAllBundlesRestored();
753         isNeedToUnloadService = (isNeedToUnloadService && isAllBundlesRestored);
754     }
755     HILOGD("isNeedToUnloadService:%{public}d", isNeedToUnloadService);
756     return isNeedToUnloadService;
757 }
758 
SetBundleRestoreType(const std::string & bundleName,RestoreTypeEnum restoreType)759 void SvcSessionManager::SetBundleRestoreType(const std::string &bundleName, RestoreTypeEnum restoreType)
760 {
761     unique_lock<shared_mutex> lock(lock_);
762     if (!impl_.clientToken) {
763         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
764         return;
765     }
766 
767     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
768     if (!findBundleSuc) {
769         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
770         return;
771     }
772     it->second.restoreType = restoreType;
773 }
774 
GetBundleRestoreType(const std::string & bundleName)775 RestoreTypeEnum SvcSessionManager::GetBundleRestoreType(const std::string &bundleName)
776 {
777     shared_lock<shared_mutex> lock(lock_);
778     if (!impl_.clientToken) {
779         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
780         return RestoreTypeEnum::RESTORE_DATA_WAIT_SEND;
781     }
782 
783     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
784     if (!findBundleSuc) {
785         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
786         return RestoreTypeEnum::RESTORE_DATA_WAIT_SEND;
787     }
788     return it->second.restoreType;
789 }
790 
SetBundleVersionCode(const std::string & bundleName,int64_t versionCode)791 void SvcSessionManager::SetBundleVersionCode(const std::string &bundleName, int64_t versionCode)
792 {
793     unique_lock<shared_mutex> lock(lock_);
794     if (!impl_.clientToken) {
795         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
796         return;
797     }
798 
799     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
800     if (!findBundleSuc) {
801         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
802         return;
803     }
804     it->second.versionCode = versionCode;
805 }
806 
GetBundleVersionCode(const std::string & bundleName)807 int64_t SvcSessionManager::GetBundleVersionCode(const std::string &bundleName)
808 {
809     shared_lock<shared_mutex> lock(lock_);
810     if (!impl_.clientToken) {
811         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
812         return 0;
813     }
814 
815     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
816     if (!findBundleSuc) {
817         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
818         return 0;
819     }
820     return it->second.versionCode;
821 }
822 
SetBundleVersionName(const std::string & bundleName,std::string versionName)823 void SvcSessionManager::SetBundleVersionName(const std::string &bundleName, std::string versionName)
824 {
825     unique_lock<shared_mutex> lock(lock_);
826     if (!impl_.clientToken) {
827         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
828         return;
829     }
830 
831     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
832     if (!findBundleSuc) {
833         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
834         return;
835     }
836     it->second.versionName = versionName;
837 }
838 
GetBundleVersionName(const std::string & bundleName)839 std::string SvcSessionManager::GetBundleVersionName(const std::string &bundleName)
840 {
841     shared_lock<shared_mutex> lock(lock_);
842     if (!impl_.clientToken) {
843         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
844         return "";
845     }
846 
847     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
848     if (!findBundleSuc) {
849         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
850         return "";
851     }
852     return it->second.versionName;
853 }
854 
SetBundleDataSize(const std::string & bundleName,int64_t dataSize)855 void SvcSessionManager::SetBundleDataSize(const std::string &bundleName, int64_t dataSize)
856 {
857     unique_lock<shared_mutex> lock(lock_);
858     if (!impl_.clientToken) {
859         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
860         return;
861     }
862 
863     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
864     if (!findBundleSuc) {
865         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
866         return;
867     }
868     it->second.dataSize = dataSize;
869     HILOGI("Set bundle data size end, bundlename = %{public}s , datasize = %{public}" PRId64 "",
870         bundleName.c_str(), dataSize);
871 }
872 
CalAppProcessTime(const std::string & bundleName)873 uint32_t SvcSessionManager::CalAppProcessTime(const std::string &bundleName)
874 {
875     const int64_t minTimeout = 900;      /* 900 second */
876     const int64_t defaultTimeout = 30;           /* 30 second */
877     const int64_t processRate = 3 * 1024 * 1024; /* 3M/s */
878     const int64_t multiple = 3;
879     const int64_t invertMillisecond = 1000;
880     int64_t timeout;
881     uint32_t resTimeoutMs;
882 
883     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
884     if (!findBundleSuc) {
885         HILOGE("CalAppProcessTime failed, BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
886         resTimeoutMs = (uint32_t)(minTimeout * invertMillisecond % UINT_MAX);
887         HILOGE("Current app will run timeout=%{public}u(ms), bundleName=%{public}s ", resTimeoutMs, bundleName.c_str());
888         return resTimeoutMs;
889     }
890     int64_t appSize = it->second.dataSize;
891     /* timeout = (AppSize / 3Ms) * 3 + 30 */
892     timeout = defaultTimeout + (appSize / processRate) * multiple;
893     timeout = timeout < minTimeout ? minTimeout : timeout;
894     resTimeoutMs = (uint32_t)(timeout * invertMillisecond % UINT_MAX); /* conver second to millisecond */
895     HILOGI("Calculate App extension process run timeout=%{public}u(ms), bundleName=%{public}s ", resTimeoutMs,
896            bundleName.c_str());
897     return resTimeoutMs;
898 }
899 
StartFwkTimer(const std::string & bundleName,const Utils::Timer::TimerCallback & callback)900 bool SvcSessionManager::StartFwkTimer(const std::string &bundleName, const Utils::Timer::TimerCallback &callback)
901 {
902     unique_lock<shared_mutex> lock(lock_);
903     HILOGI("StartFwkTimer begin bundleName %{public}s", bundleName.c_str());
904     if (!impl_.clientToken) {
905         HILOGE("No caller token was specified");
906         return false;
907     }
908     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
909     if (!findBundleSuc) {
910         HILOGE("Start fwk timer failed, BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
911         return false;
912     }
913     if (it->second.fwkTimerStatus == true) {
914         HILOGE("FwkTimer is registered, unregister first.");
915         return false;
916     }
917     uint32_t timeout = CalAppProcessTime(bundleName);
918 
919     it->second.fwkTimerStatus = true;
920     it->second.timerId = timer_.Register(callback, timeout, true);
921     HILOGI("StartFwkTimer end bundleName %{public}s", bundleName.c_str());
922     return true;
923 }
924 
StopFwkTimer(const std::string & bundleName)925 bool SvcSessionManager::StopFwkTimer(const std::string &bundleName)
926 {
927     unique_lock<shared_mutex> lock(lock_);
928     HILOGI("StopFwkTimer begin bundleName %{public}s", bundleName.c_str());
929     if (!impl_.clientToken) {
930         HILOGE("No caller token was specified");
931         return false;
932     }
933     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
934     if (!findBundleSuc) {
935         HILOGE("Stop fwk timer failed, BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
936         return false;
937     }
938     if (it->second.fwkTimerStatus == false) {
939         HILOGE("FwkTimer is unregistered, register first.");
940         return true;
941     }
942 
943     it->second.fwkTimerStatus = false;
944     timer_.Unregister(it->second.timerId);
945     HILOGI("StopFwkTimer end bundleName %{public}s", bundleName.c_str());
946     return true;
947 }
948 
StartExtTimer(const std::string & bundleName,const Utils::Timer::TimerCallback & callback)949 bool SvcSessionManager::StartExtTimer(const std::string &bundleName, const Utils::Timer::TimerCallback &callback)
950 {
951     unique_lock<shared_mutex> lock(lock_);
952     HILOGI("StartExtTimer begin bundleName %{public}s", bundleName.c_str());
953     if (!impl_.clientToken) {
954         HILOGE("No caller token was specified");
955         return false;
956     }
957     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
958     if (!findBundleSuc) {
959         HILOGE("Start extension timer failed, BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
960         return false;
961     }
962     if (it->second.extTimerStatus == true) {
963         HILOGE("ExtTimer is registered, unregister first.");
964         return false;
965     }
966     uint32_t timeout = it->second.timeout;
967     timeout = (timeout != BConstants::TIMEOUT_INVALID) ? timeout : BConstants::DEFAULT_TIMEOUT;
968     it->second.extTimerStatus = true;
969     it->second.timerId = timer_.Register(callback, timeout, true);
970     HILOGI("StartExtTimer end, timeout %{public}u(ms), bundleName %{public}s", timeout, bundleName.c_str());
971     return true;
972 }
973 
StopExtTimer(const std::string & bundleName)974 bool SvcSessionManager::StopExtTimer(const std::string &bundleName)
975 {
976     unique_lock<shared_mutex> lock(lock_);
977     HILOGI("StopExtTimer begin bundleName %{public}s", bundleName.c_str());
978     if (!impl_.clientToken) {
979         HILOGE("No caller token was specified");
980         return false;
981     }
982     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
983     if (!findBundleSuc) {
984         HILOGE("Stop extension timer failed, BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
985         return false;
986     }
987     if (it->second.extTimerStatus == false) {
988         HILOGE("ExtTimer is unregistered, register first.");
989         return true;
990     }
991 
992     it->second.extTimerStatus = false;
993     it->second.timeout = BConstants::TIMEOUT_INVALID;
994     timer_.Unregister(it->second.timerId);
995     HILOGI("StopExtTimer end bundleName %{public}s", bundleName.c_str());
996     return true;
997 }
998 
UpdateTimer(const std::string & bundleName,uint32_t timeout,const Utils::Timer::TimerCallback & callback)999 bool SvcSessionManager::UpdateTimer(const std::string &bundleName, uint32_t timeout,
1000     const Utils::Timer::TimerCallback &callback)
1001 {
1002     unique_lock<shared_mutex> lock(lock_);
1003     HILOGI("UpdateTimer begin bundleName %{public}s", bundleName.c_str());
1004     if (!impl_.clientToken) {
1005         HILOGE("No caller token was specified");
1006         return false;
1007     }
1008     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
1009     if (!findBundleSuc) {
1010         HILOGE("Update timer failed, BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
1011         return false;
1012     }
1013     it->second.timeout = timeout;
1014     if (it->second.extTimerStatus == false) {
1015         HILOGI("ExtTimer is unregistered, just store timeout %{public}u(ms)", timeout);
1016         return true;
1017     }
1018 
1019     timer_.Unregister(it->second.timerId);
1020     HILOGI("UpdateTimer timeout %{public}u(ms), bundleName %{public}s ", timeout, bundleName.c_str());
1021     it->second.timerId = timer_.Register(callback, timeout, true);
1022     it->second.extTimerStatus = true;
1023     HILOGI("UpdateTimer end bundleName %{public}s", bundleName.c_str());
1024     return true;
1025 }
1026 
IncreaseSessionCnt(const std::string funcName)1027 void SvcSessionManager::IncreaseSessionCnt(const std::string funcName)
1028 {
1029     sessionCnt_++;
1030     HILOGI("func name:%{public}s, %{public}d.", funcName.c_str(), sessionCnt_.load());
1031 }
1032 
DecreaseSessionCnt(const std::string funcName)1033 void SvcSessionManager::DecreaseSessionCnt(const std::string funcName)
1034 {
1035     if (sessionCnt_.load() > 0) {
1036         sessionCnt_--;
1037     } else {
1038         HILOGE("Invalid sessionCount.");
1039     }
1040     HILOGI("func name:%{public}s, %{public}d.", funcName.c_str(), sessionCnt_.load());
1041 }
1042 
ClearSessionData()1043 ErrCode SvcSessionManager::ClearSessionData()
1044 {
1045     unique_lock<shared_mutex> lock(lock_);
1046     ErrCode ret = BError(BError::Codes::OK);
1047     for (auto &&it : impl_.backupExtNameMap) {
1048         // clear timer
1049         if (it.second.fwkTimerStatus == true || it.second.extTimerStatus == true) {
1050             it.second.fwkTimerStatus = false;
1051             it.second.extTimerStatus = false;
1052             timer_.Unregister(it.second.timerId);
1053         }
1054         // disconnect extension
1055         if (it.second.schedAction == BConstants::ServiceSchedAction::RUNNING) {
1056             auto backUpConnection = it.second.backUpConnection;
1057             if (backUpConnection == nullptr) {
1058                 HILOGE("Clear session error, backUpConnection is empty");
1059                 return BError(BError::Codes::SA_INVAL_ARG);
1060             }
1061             auto proxy = backUpConnection->GetBackupExtProxy();
1062             if (proxy == nullptr) {
1063                 HILOGE("Clear session error, proxy is empty");
1064                 return BError(BError::Codes::EXT_INVAL_ARG);
1065             }
1066             if (impl_.restoreDataType != RestoreTypeEnum::RESTORE_DATA_READDY) {
1067                 ret = proxy->HandleClear();
1068             }
1069             backUpConnection->DisconnectBackupExtAbility();
1070         }
1071         if (ret != BError(BError::Codes::OK)) {
1072             return ret;
1073         }
1074         // clear data
1075         it.second.schedAction = BConstants::ServiceSchedAction::FINISH;
1076     }
1077     impl_.backupExtNameMap.clear();
1078     return BError(BError::Codes::OK);
1079 }
1080 
GetIsIncrementalBackup()1081 bool SvcSessionManager::GetIsIncrementalBackup()
1082 {
1083     unique_lock<shared_mutex> lock(lock_);
1084     if (!impl_.clientToken) {
1085         HILOGE("GetIsIncrementalBackup error, No caller token was specified");
1086         return false;
1087     }
1088     return impl_.isIncrementalBackup;
1089 }
1090 
SetIncrementalData(const BIncrementalData & incrementalData)1091 void SvcSessionManager::SetIncrementalData(const BIncrementalData &incrementalData)
1092 {
1093     unique_lock<shared_mutex> lock(lock_);
1094     if (!impl_.clientToken) {
1095         HILOGE("SetIncrementalData error, No caller token was specified");
1096         return;
1097     }
1098     auto [findBundleSuc, it] = GetBackupExtNameMap(incrementalData.bundleName);
1099     if (!findBundleSuc) {
1100         HILOGE("BackupExtNameMap can not find bundle %{public}s", incrementalData.bundleName.c_str());
1101         return;
1102     }
1103     it->second.lastIncrementalTime = incrementalData.lastIncrementalTime;
1104     it->second.manifestFd = incrementalData.manifestFd;
1105     it->second.backupParameters = incrementalData.backupParameters;
1106     it->second.backupPriority = incrementalData.backupPriority;
1107 }
1108 
GetIncrementalManifestFd(const string & bundleName)1109 int32_t SvcSessionManager::GetIncrementalManifestFd(const string &bundleName)
1110 {
1111     unique_lock<shared_mutex> lock(lock_);
1112     if (!impl_.clientToken) {
1113         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
1114         return BConstants::INVALID_FD_NUM;
1115     }
1116     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
1117     if (!findBundleSuc) {
1118         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
1119         return BConstants::INVALID_FD_NUM;
1120     }
1121     return it->second.manifestFd;
1122 }
1123 
GetLastIncrementalTime(const string & bundleName)1124 int64_t SvcSessionManager::GetLastIncrementalTime(const string &bundleName)
1125 {
1126     unique_lock<shared_mutex> lock(lock_);
1127     if (!impl_.clientToken) {
1128         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
1129         return 0;
1130     }
1131     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
1132     if (!findBundleSuc) {
1133         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
1134         return 0;
1135     }
1136     return it->second.lastIncrementalTime;
1137 }
1138 
GetMemParaCurSize()1139 int32_t SvcSessionManager::GetMemParaCurSize()
1140 {
1141     return memoryParaCurSize_;
1142 }
1143 
SetMemParaCurSize(int32_t size)1144 void SvcSessionManager::SetMemParaCurSize(int32_t size)
1145 {
1146     memoryParaCurSize_ = size;
1147 }
1148 
SetClearDataFlag(const std::string & bundleName,bool isClearData)1149 void SvcSessionManager::SetClearDataFlag(const std::string &bundleName, bool isClearData)
1150 {
1151     unique_lock<shared_mutex> lock(lock_);
1152     if (!impl_.clientToken) {
1153         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
1154         return;
1155     }
1156     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
1157     if (!findBundleSuc) {
1158         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
1159         return;
1160     }
1161     it->second.isClearData = isClearData;
1162     HILOGI("bundleName:%{public}s, set clear data flag:%{public}d.", bundleName.c_str(), isClearData);
1163 }
1164 
GetClearDataFlag(const std::string & bundleName)1165 bool SvcSessionManager::GetClearDataFlag(const std::string &bundleName)
1166 {
1167     unique_lock<shared_mutex> lock(lock_);
1168     if (!impl_.clientToken) {
1169         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
1170         return true;
1171     }
1172     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
1173     if (!findBundleSuc) {
1174         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
1175         return true;
1176     }
1177     return it->second.isClearData;
1178 }
1179 
GetTimeoutValue(const std::string & bundleName)1180 uint32_t SvcSessionManager::GetTimeoutValue(const std::string &bundleName)
1181 {
1182     unique_lock<shared_mutex> lock(lock_);
1183     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
1184     if (!findBundleSuc) {
1185         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
1186         return BConstants::TIMEOUT_INVALID;
1187     }
1188     return it->second.timeout;
1189 }
1190 
ValidRestoreDataType(RestoreTypeEnum restoreDataType)1191 bool SvcSessionManager::ValidRestoreDataType(RestoreTypeEnum restoreDataType)
1192 {
1193     return impl_.restoreDataType == restoreDataType;
1194 }
1195 
CleanAndCheckIfNeedWait(ErrCode & ret,std::vector<std::string> & bundleNameList)1196 bool SvcSessionManager::CleanAndCheckIfNeedWait(ErrCode &ret, std::vector<std::string> &bundleNameList)
1197 {
1198     unique_lock<shared_mutex> lock(lock_);
1199     for (auto it = impl_.backupExtNameMap.begin(); it != impl_.backupExtNameMap.end();) {
1200         if (it->second.schedAction == BConstants::ServiceSchedAction::WAIT) {
1201             it = impl_.backupExtNameMap.erase(it);
1202         } else if (it->second.schedAction == BConstants::ServiceSchedAction::START ||
1203             (it->second.schedAction == BConstants::ServiceSchedAction::RUNNING && !it->second.isInPublishFile)) {
1204             if (it->second.fwkTimerStatus == true || it->second.extTimerStatus == true) {
1205                 it->second.fwkTimerStatus = false;
1206                 it->second.extTimerStatus = false;
1207                 timer_.Unregister(it->second.timerId);
1208             }
1209             auto backUpConnection = it->second.backUpConnection;
1210             if (backUpConnection == nullptr) {
1211                 HILOGE("Clear session error, backUpConnection is empty");
1212                 it = impl_.backupExtNameMap.erase(it);
1213                 continue;
1214             }
1215             auto proxy = backUpConnection->GetBackupExtProxy();
1216             // start action
1217             if (proxy == nullptr) {
1218                 HILOGE("Clear session error, backUpConnection is empty");
1219                 backUpConnection->DisconnectBackupExtAbility();
1220                 it = impl_.backupExtNameMap.erase(it);
1221                 continue;
1222             }
1223             // running action
1224             ErrCode retTmp = ERR_OK;
1225             if (impl_.restoreDataType != RestoreTypeEnum::RESTORE_DATA_READDY) {
1226                 retTmp = proxy->HandleClear();
1227             }
1228             if (retTmp == ERR_OK) {
1229                 bundleNameList.emplace_back(it->first);
1230             } else {
1231                 ret = retTmp;
1232             }
1233             backUpConnection->DisconnectBackupExtAbility();
1234             it = impl_.backupExtNameMap.erase(it);
1235         } else {
1236             ++it;
1237         }
1238     }
1239     if (impl_.backupExtNameMap.empty()) {
1240         HILOGI("Release normally, no need wait");
1241         return false;
1242     }
1243     HILOGI("Release abnormally, need wait for restore");
1244     return true;
1245 }
1246 
SetPublishFlag(const std::string & bundleName)1247 void SvcSessionManager::SetPublishFlag(const std::string &bundleName)
1248 {
1249     unique_lock<shared_mutex> lock(lock_);
1250     if (!impl_.clientToken) {
1251         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
1252         return;
1253     }
1254     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
1255     if (!findBundleSuc) {
1256         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
1257         return;
1258     }
1259     it->second.isInPublishFile = true;
1260     HILOGE("Set PublishFile success, bundleName = %{public}s", bundleName.c_str());
1261 }
1262 
SetOldBackupVersion(const std::string & backupVersion)1263 void SvcSessionManager::SetOldBackupVersion(const std::string &backupVersion)
1264 {
1265     unique_lock<shared_mutex> lock(lock_);
1266     if (!impl_.clientToken) {
1267         HILOGE("Error, No caller token was specified");
1268         return;
1269     }
1270     impl_.oldBackupVersion = backupVersion;
1271 }
1272 
GetOldBackupVersion()1273 std::string SvcSessionManager::GetOldBackupVersion()
1274 {
1275     shared_lock<shared_mutex> lock(lock_);
1276     if (!impl_.clientToken) {
1277         HILOGE("Error, No caller token was specified");
1278         return "";
1279     }
1280     return impl_.oldBackupVersion;
1281 }
1282 
SetImplRestoreType(const RestoreTypeEnum restoreType)1283 void SvcSessionManager::SetImplRestoreType(const RestoreTypeEnum restoreType)
1284 {
1285     impl_.restoreDataType = restoreType;
1286 }
1287 
SetIsReadyLaunch(const std::string & bundleName)1288 void SvcSessionManager::SetIsReadyLaunch(const std::string &bundleName)
1289 {
1290     unique_lock<shared_mutex> lock(lock_);
1291     if (!impl_.clientToken) {
1292         HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str());
1293         return;
1294     }
1295     auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName);
1296     if (!findBundleSuc) {
1297         HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str());
1298         return;
1299     }
1300     it->second.isReadyLaunch = true;
1301     HILOGE("SetIsReadyLaunch success, bundleName = %{public}s", bundleName.c_str());
1302 }
1303 } // namespace OHOS::FileManagement::Backup
1304