• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-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 "account_mgr_service.h"
17 #include <cerrno>
18 #include <thread>
19 #include "accesstoken_kit.h"
20 #include "account_constants.h"
21 #include "account_dump_helper.h"
22 #include "account_hisysevent_adapter.h"
23 #ifdef HAS_USER_AUTH_PART
24 #include "account_iam_service.h"
25 #endif
26 #include "account_info.h"
27 #include "account_log_wrapper.h"
28 #include "account_file_operator.h"
29 #ifdef HICOLLIE_ENABLE
30 #include "account_timer.h"
31 #endif // HICOLLIE_ENABLE
32 #ifdef HAS_APP_ACCOUNT_PART
33 #ifdef HAS_CES_PART
34 #include "app_account_common_event_observer.h"
35 #endif // HAS_CES_PART
36 #include "app_account_manager_service.h"
37 #endif
38 #include "datetime_ex.h"
39 #include "directory_ex.h"
40 #include "domain_account_manager_service.h"
41 #include "file_ex.h"
42 #include "hitrace_adapter.h"
43 #include "if_system_ability_manager.h"
44 #include "iinner_os_account_manager.h"
45 #include "ipc_skeleton.h"
46 #include "iservice_registry.h"
47 #include "perf_stat.h"
48 #include "string_ex.h"
49 #include "system_ability_definition.h"
50 #ifdef HICOLLIE_ENABLE
51 #include "xcollie/xcollie.h"
52 #endif // HICOLLIE_ENABLE
53 
54 namespace OHOS {
55 namespace AccountSA {
56 namespace {
57 const char PERMISSION_MANAGE_USERS[] = "ohos.permission.MANAGE_LOCAL_ACCOUNTS";
58 const char PERMISSION_GET_LOCAL_ACCOUNTS[] = "ohos.permission.GET_LOCAL_ACCOUNTS";
59 const char PERMISSION_MANAGE_DISTRIBUTED_ACCOUNTS[] = "ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS";
60 const char PERMISSION_GET_DISTRIBUTED_ACCOUNTS[] = "ohos.permission.GET_DISTRIBUTED_ACCOUNTS";
61 const char PERMISSION_DISTRIBUTED_DATASYNC[] = "ohos.permission.DISTRIBUTED_DATASYNC";
62 const char INTERACT_ACROSS_LOCAL_ACCOUNTS[] = "ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS";
63 const std::set<std::int32_t> WHITE_LIST = {
64     3012, // DISTRIBUTED_KV_DATA_SA_UID
65     3019, // DLP_UID
66     3553, // DLP_CREDENTIAL_SA_UID
67 };
68 #ifdef USE_MUSL
69 constexpr std::int32_t DSOFTBUS_UID = 1024;
70 #else
71 constexpr std::int32_t DSOFTBUS_UID = 5533;
72 #endif
73 #ifndef IS_RELEASE_VERSION
74 constexpr std::int32_t ROOT_UID = 0;
75 #endif
76 #ifdef HICOLLIE_ENABLE
77 constexpr std::int32_t RECOVERY_TIMEOUT = 6; // timeout 6s
78 constexpr int32_t MAX_INIT_TIME = 120;
79 #endif // HICOLLIE_ENABLE
80 const std::set<int32_t> INIT_ACCOUNT_ID_SET = {
81 #ifdef ENABLE_U1_ACCOUNT
82     Constants::U1_ID,
83 #endif // ENABLE_U1_ACCOUNT
84     Constants::START_USER_ID,
85 };
86 const bool REGISTER_RESULT =
87     SystemAbility::MakeAndRegisterAbility(&DelayedRefSingleton<AccountMgrService>::GetInstance());
88 const char DEVICE_OWNER_DIR[] = "/data/service/el1/public/account/0/";
89 
RequestTimer(std::string eventStr)90 std::shared_ptr<void> RequestTimer(std::string eventStr)
91 {
92 #ifdef HICOLLIE_ENABLE
93     return [eventName = eventStr]() -> std::shared_ptr<void> {
94         XCollieCallback callbackFunc = [callingPid = IPCSkeleton::GetCallingPid(),
95             callingUid = IPCSkeleton::GetCallingUid(), eventName](void *) {
96             ACCOUNT_LOGE("%{public}s timeout, callingPid=%{public}d, callingUid=%{public}d.", eventName.c_str(),
97                 callingPid, callingUid);
98             REPORT_OHOS_ACCOUNT_FAIL(callingUid, eventName, -1, "Request time out");
99         };
100         int timerId = HiviewDFX::XCollie::GetInstance().SetTimer(
101             TIMER_NAME, TIMEOUT, callbackFunc, nullptr, HiviewDFX::XCOLLIE_FLAG_LOG);
102         return std::shared_ptr<void>(nullptr, [timerId](void*) {
103             HiviewDFX::XCollie::GetInstance().CancelTimer(timerId);
104         });
105     }();
106 #else
107     return nullptr;
108 #endif
109 }
110 
CreateDeviceDir()111 void CreateDeviceDir()
112 {
113     if (!FileExists(DEVICE_OWNER_DIR)) {
114         ACCOUNT_LOGI("Device owner dir not exist, create!");
115         if (!OHOS::ForceCreateDirectory(DEVICE_OWNER_DIR)) {
116             int32_t err = errno;
117             ACCOUNT_LOGW("Create device owner dir failure! errno %{public}d.", err);
118             ReportOsAccountOperationFail(0, OPERATION_FORCE_CREATE_DIRECTORY, err, DEVICE_OWNER_DIR);
119         } else {
120             if (!OHOS::ChangeModeDirectory(DEVICE_OWNER_DIR, S_IRWXU)) {
121                 int32_t err = errno;
122                 ReportOsAccountOperationFail(0, OPERATION_CHANGE_MODE_DIRECTORY, err, DEVICE_OWNER_DIR);
123                 ACCOUNT_LOGW("failed to create dir, path = %{public}s errno %{public}d.",
124                     DEVICE_OWNER_DIR, err);
125             }
126         }
127     }
128 }
129 }
130 IAccountContext *IAccountContext::instance_ = nullptr;
131 
AccountMgrService()132 AccountMgrService::AccountMgrService() : SystemAbility(SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN, true)
133 {
134     PerfStat::GetInstance().SetInstanceCreateTime(GetTickCount());
135 }
136 
~AccountMgrService()137 AccountMgrService::~AccountMgrService()
138 {}
139 
GetCallingUserID()140 std::int32_t AccountMgrService::GetCallingUserID()
141 {
142     std::int32_t userId = IPCSkeleton::GetCallingUid() / UID_TRANSFORM_DIVISOR;
143     if (userId <= 0) {
144         std::vector<int32_t> userIds;
145         (void)IInnerOsAccountManager::GetInstance().QueryActiveOsAccountIds(userIds);
146         if (userIds.empty()) {
147             return -1;  // invalid user id
148         }
149         userId = userIds[0];
150     }
151     return userId;
152 }
153 
UpdateOhosAccountInfo(const std::string & accountName,const std::string & uid,const std::string & eventStr)154 ErrCode AccountMgrService::UpdateOhosAccountInfo(
155     const std::string &accountName, const std::string &uid, const std::string &eventStr)
156 {
157     [[maybe_unused]] auto timerPtr = RequestTimer(eventStr);
158     if (!HasAccountRequestPermission(PERMISSION_MANAGE_USERS)) {
159         ACCOUNT_LOGE("Check permission failed");
160         REPORT_PERMISSION_FAIL();
161         return ERR_ACCOUNT_COMMON_PERMISSION_DENIED;
162     }
163 
164     if (accountName.empty()) {
165         ACCOUNT_LOGE("empty account name!");
166         return ERR_ACCOUNT_COMMON_INVALID_PARAMETER;
167     }
168 
169     if (uid.empty()) {
170         ACCOUNT_LOGE("empty uid!");
171         return ERR_ACCOUNT_COMMON_INVALID_PARAMETER;
172     }
173 
174     ErrCode res = OhosAccountManager::GetInstance().OhosAccountStateChange(accountName, uid, eventStr);
175     if (res != ERR_OK) {
176         ACCOUNT_LOGE("Ohos account state change failed, res = %{public}d.", res);
177     }
178 
179     return res;
180 }
181 
SetOhosAccountInfo(const OhosAccountInfo & ohosAccountInfo,const std::string & eventStr)182 ErrCode AccountMgrService::SetOhosAccountInfo(const OhosAccountInfo &ohosAccountInfo, const std::string &eventStr)
183 {
184     [[maybe_unused]] auto timerPtr = RequestTimer(eventStr);
185     if (!HasAccountRequestPermission(PERMISSION_MANAGE_DISTRIBUTED_ACCOUNTS)) {
186         ACCOUNT_LOGE("Check permission failed");
187         REPORT_PERMISSION_FAIL();
188         return ERR_ACCOUNT_COMMON_PERMISSION_DENIED;
189     }
190     if (!ohosAccountInfo.IsValid()) {
191         ACCOUNT_LOGE("Check OhosAccountInfo failed");
192         return ERR_ACCOUNT_COMMON_INVALID_PARAMETER;
193     }
194     auto userId = AccountMgrService::GetInstance().GetCallingUserID();
195     ErrCode res = OhosAccountManager::GetInstance().OhosAccountStateChange(userId, ohosAccountInfo, eventStr);
196     if (res != ERR_OK) {
197         ACCOUNT_LOGE("Ohos account state change failed");
198     }
199 
200     return res;
201 }
202 
SetOsAccountDistributedInfo(int32_t localId,const OhosAccountInfo & ohosAccountInfo,const std::string & eventStr)203 ErrCode AccountMgrService::SetOsAccountDistributedInfo(
204     int32_t localId, const OhosAccountInfo &ohosAccountInfo, const std::string &eventStr)
205 {
206     [[maybe_unused]] auto timerPtr = RequestTimer(eventStr);
207     std::int32_t ret = AccountPermissionManager::CheckSystemApp();
208     if (ret != ERR_OK) {
209         ACCOUNT_LOGE("the caller is not system application, ret = %{public}d.", ret);
210         return ret;
211     }
212     if (!HasAccountRequestPermission(PERMISSION_MANAGE_DISTRIBUTED_ACCOUNTS)) {
213         ACCOUNT_LOGE("Check permission failed");
214         REPORT_PERMISSION_FAIL();
215         return ERR_ACCOUNT_COMMON_PERMISSION_DENIED;
216     }
217     ret = CheckUserIdValid(localId);
218     if (ret != ERR_OK) {
219         ACCOUNT_LOGE("CheckUserIdValid failed, ret = %{public}d", ret);
220         return ret;
221     }
222     if (!ohosAccountInfo.IsValid()) {
223         ACCOUNT_LOGE("Check OhosAccountInfo failed");
224         return ERR_ACCOUNT_COMMON_INVALID_PARAMETER;
225     }
226     ret = OhosAccountManager::GetInstance().OhosAccountStateChange(localId, ohosAccountInfo, eventStr);
227     if (ret != ERR_OK) {
228         ACCOUNT_LOGE("Ohos account state change failed");
229     }
230 
231     return ret;
232 }
233 
QueryDistributedVirtualDeviceId(std::string & dvid)234 ErrCode AccountMgrService::QueryDistributedVirtualDeviceId(std::string &dvid)
235 {
236     [[maybe_unused]] auto timerPtr = RequestTimer(Constants::OPERATION_GET_INFO);
237     if (!HasAccountRequestPermission(PERMISSION_MANAGE_USERS) &&
238         !HasAccountRequestPermission(PERMISSION_DISTRIBUTED_DATASYNC)) {
239         ACCOUNT_LOGE("Check permission failed");
240         REPORT_PERMISSION_FAIL();
241         return ERR_ACCOUNT_COMMON_PERMISSION_DENIED;
242     }
243     return OhosAccountManager::GetInstance().QueryDistributedVirtualDeviceId(dvid);
244 }
245 
QueryDistributedVirtualDeviceId(const std::string & bundleName,int32_t localId,std::string & dvid)246 ErrCode AccountMgrService::QueryDistributedVirtualDeviceId(const std::string &bundleName, int32_t localId,
247     std::string &dvid)
248 {
249     [[maybe_unused]] auto timerPtr = RequestTimer(Constants::OPERATION_GET_INFO);
250     ErrCode errCode = AccountPermissionManager::CheckSystemApp();
251     if (errCode != ERR_OK) {
252         ACCOUNT_LOGE("The caller is not system application, errCode = %{public}d.", errCode);
253         return errCode;
254     }
255     if (!HasAccountRequestPermission(PERMISSION_MANAGE_DISTRIBUTED_ACCOUNTS) &&
256         !HasAccountRequestPermission(PERMISSION_MANAGE_USERS) &&
257         !HasAccountRequestPermission(PERMISSION_GET_DISTRIBUTED_ACCOUNTS)) {
258         ACCOUNT_LOGE("Failed to check permission");
259         REPORT_PERMISSION_FAIL();
260         return ERR_ACCOUNT_COMMON_PERMISSION_DENIED;
261     }
262     return OhosAccountManager::GetInstance().QueryDistributedVirtualDeviceId(bundleName, localId, dvid);
263 }
264 
QueryOhosAccountInfo(std::string & accountName,std::string & uid,int32_t & status)265 ErrCode AccountMgrService::QueryOhosAccountInfo(std::string& accountName, std::string& uid, int32_t& status)
266 {
267     if (!HasAccountRequestPermission(PERMISSION_MANAGE_USERS) &&
268         !HasAccountRequestPermission(PERMISSION_DISTRIBUTED_DATASYNC) &&
269         !HasAccountRequestPermission(PERMISSION_GET_LOCAL_ACCOUNTS)) {
270         ACCOUNT_LOGE("Check permission failed");
271         REPORT_PERMISSION_FAIL();
272         return ERR_ACCOUNT_COMMON_PERMISSION_DENIED;
273     }
274 #ifdef HICOLLIE_ENABLE
275     unsigned int flag = HiviewDFX::XCOLLIE_FLAG_LOG | HiviewDFX::XCOLLIE_FLAG_RECOVERY;
276     XCollieCallback callbackFunc = [callingPid = IPCSkeleton::GetCallingPid(),
277         callingUid = IPCSkeleton::GetCallingUid()](void *) {
278         ACCOUNT_LOGE("QueryOhosAccountInfo failed, callingPid: %{public}d, callingUid: %{public}d.",
279             callingPid, callingUid);
280         REPORT_OHOS_ACCOUNT_FAIL(callingUid, Constants::OPERATION_GET_INFO, -1, "Query ohos account info time out");
281     };
282     int timerId = HiviewDFX::XCollie::GetInstance().SetTimer(TIMER_NAME, RECOVERY_TIMEOUT, callbackFunc, nullptr, flag);
283 #endif // HICOLLIE_ENABLE
284     auto ret = InnerQueryOsAccountDistributedInfo(GetCallingUserID(), accountName, uid, status);
285     if (ret != ERR_OK) {
286         ACCOUNT_LOGE("Query ohos account info failed");
287     }
288 #ifdef HICOLLIE_ENABLE
289     HiviewDFX::XCollie::GetInstance().CancelTimer(timerId);
290 #endif // HICOLLIE_ENABLE
291     return ret;
292 }
293 
GetOhosAccountInfo(OhosAccountInfo & info)294 ErrCode AccountMgrService::GetOhosAccountInfo(OhosAccountInfo &info)
295 {
296     [[maybe_unused]] auto timerPtr = RequestTimer(Constants::OPERATION_GET_INFO);
297     if (!HasAccountRequestPermission(PERMISSION_MANAGE_DISTRIBUTED_ACCOUNTS) &&
298         !HasAccountRequestPermission(PERMISSION_DISTRIBUTED_DATASYNC) &&
299         !HasAccountRequestPermission(PERMISSION_GET_DISTRIBUTED_ACCOUNTS)) {
300         ACCOUNT_LOGE("Check permission failed");
301         REPORT_PERMISSION_FAIL();
302         return ERR_ACCOUNT_COMMON_PERMISSION_DENIED;
303     }
304     auto ret = GetOsAccountDistributedInfoInner(GetCallingUserID(), info);
305     info.SetRawUid("");
306     return ret;
307 }
308 
GetOsAccountDistributedInfo(int32_t localId,OhosAccountInfo & info)309 ErrCode AccountMgrService::GetOsAccountDistributedInfo(int32_t localId, OhosAccountInfo &info)
310 {
311     [[maybe_unused]] auto timerPtr = RequestTimer(Constants::OPERATION_GET_INFO);
312     ErrCode errCode = AccountPermissionManager::CheckSystemApp();
313     if (errCode != ERR_OK) {
314         ACCOUNT_LOGE("the caller is not system application, errCode = %{public}d.", errCode);
315         return errCode;
316     }
317     // to support sa calling without adjust sa permission, add bypass permission for sa calling
318     if (AccountPermissionManager::CheckSaCall()) {
319         if (!HasAccountRequestPermission(PERMISSION_MANAGE_DISTRIBUTED_ACCOUNTS) &&
320             !HasAccountRequestPermission(INTERACT_ACROSS_LOCAL_ACCOUNTS) &&
321             !HasAccountRequestPermission(PERMISSION_DISTRIBUTED_DATASYNC) &&
322             !HasAccountRequestPermission(PERMISSION_GET_DISTRIBUTED_ACCOUNTS)) {
323             ACCOUNT_LOGE("Check permission for sa failed");
324             REPORT_PERMISSION_FAIL();
325             return ERR_ACCOUNT_COMMON_PERMISSION_DENIED;
326         }
327         REPORT_OHOS_ACCOUNT_FAIL(IPCSkeleton::GetCallingUid(), "saCalledPermBypass",
328             ERR_OK, "Check for sa called permission passed.");
329     } else {
330         if (!HasAccountRequestPermission(PERMISSION_MANAGE_DISTRIBUTED_ACCOUNTS) &&
331             !(HasAccountRequestPermission(INTERACT_ACROSS_LOCAL_ACCOUNTS) &&
332             HasAccountRequestPermission(PERMISSION_GET_DISTRIBUTED_ACCOUNTS))) {
333             ACCOUNT_LOGE("Check permission failed");
334             REPORT_PERMISSION_FAIL();
335             return ERR_ACCOUNT_COMMON_PERMISSION_DENIED;
336         }
337     }
338 
339     bool isOsAccountExits = false;
340     errCode = IInnerOsAccountManager::GetInstance().IsOsAccountExists(localId, isOsAccountExits);
341     if (errCode != ERR_OK) {
342         ACCOUNT_LOGE("IsOsAccountExists failed errCode is %{public}d", errCode);
343         return errCode;
344     }
345     if (!isOsAccountExits) {
346         ACCOUNT_LOGE("os account is not exit");
347         return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
348     }
349     errCode = GetOsAccountDistributedInfoInner(localId, info);
350     if (errCode != ERR_OK) {
351         ACCOUNT_LOGE("Get ohos account info failed");
352         return errCode;
353     }
354     int32_t uid = IPCSkeleton::GetCallingUid();
355     if (WHITE_LIST.find(uid) == WHITE_LIST.end()) {
356         info.SetRawUid("");
357     }
358     return ERR_OK;
359 }
360 
GetOsAccountDistributedInfoInner(int32_t localId,OhosAccountInfo & info)361 ErrCode AccountMgrService::GetOsAccountDistributedInfoInner(int32_t localId, OhosAccountInfo &info)
362 {
363     ErrCode ret = OhosAccountManager::GetInstance().GetOhosAccountDistributedInfo(localId, info);
364     if (ret != ERR_OK) {
365         return ret;
366     }
367     return ERR_OK;
368 }
369 
QueryOsAccountDistributedInfo(std::int32_t localId,std::string & accountName,std::string & uid,int32_t & status)370 ErrCode AccountMgrService::QueryOsAccountDistributedInfo(
371     std::int32_t localId, std::string& accountName, std::string& uid, int32_t& status)
372 {
373     [[maybe_unused]] auto timerPtr = RequestTimer(Constants::OPERATION_GET_INFO);
374     if ((!HasAccountRequestPermission(PERMISSION_MANAGE_USERS)) &&
375         (!HasAccountRequestPermission(PERMISSION_DISTRIBUTED_DATASYNC)) &&
376         (IPCSkeleton::GetCallingUid() != DSOFTBUS_UID)) {
377         ACCOUNT_LOGE("Check permission failed");
378         REPORT_PERMISSION_FAIL();
379         return ERR_ACCOUNT_COMMON_PERMISSION_DENIED;
380     }
381     if (localId < 0) {
382         ACCOUNT_LOGE("negative userID %{public}d detected!", localId);
383         return ERR_ACCOUNT_ZIDL_ACCOUNT_STUB_USERID_ERROR;
384     }
385     return InnerQueryOsAccountDistributedInfo(localId, accountName, uid, status);
386 }
387 
InnerQueryOsAccountDistributedInfo(std::int32_t localId,std::string & accountName,std::string & uid,int32_t & status)388 ErrCode AccountMgrService::InnerQueryOsAccountDistributedInfo(
389     std::int32_t localId, std::string& accountName, std::string& uid, int32_t& status)
390 {
391     OhosAccountInfo ohosAccountInfo;
392     ErrCode ret = OhosAccountManager::GetInstance().GetOhosAccountDistributedInfo(localId, ohosAccountInfo);
393     if (ret != ERR_OK) {
394         return ret;
395     }
396     accountName = ohosAccountInfo.name_;
397     uid = ohosAccountInfo.uid_;
398     status = ohosAccountInfo.status_;
399     return ERR_OK;
400 }
401 
QueryDeviceAccountId(std::int32_t & accountId)402 ErrCode AccountMgrService::QueryDeviceAccountId(std::int32_t &accountId)
403 {
404     [[maybe_unused]] auto timerPtr = RequestTimer(Constants::OPERATION_GET_INFO);
405     const std::int32_t uid = IPCSkeleton::GetCallingUid();
406     accountId = uid / UID_TRANSFORM_DIVISOR;
407     return ERR_OK;
408 }
409 
SubscribeDistributedAccountEvent(int32_t typeInt,const sptr<IRemoteObject> & eventListener)410 ErrCode AccountMgrService::SubscribeDistributedAccountEvent(int32_t typeInt, const sptr<IRemoteObject>& eventListener)
411 {
412     [[maybe_unused]] auto timerPtr = RequestTimer(Constants::OPERATION_SUBSCRIBE);
413     if (eventListener == nullptr) {
414         ACCOUNT_LOGE("eventListener is nullptr.");
415         return ERR_ACCOUNT_COMMON_NULL_PTR_ERROR;
416     }
417     ErrCode res = AccountPermissionManager::CheckSystemApp(false);
418     if (res != ERR_OK) {
419         ACCOUNT_LOGE("Check systemApp failed.");
420         return res;
421     }
422     auto type = static_cast<DISTRIBUTED_ACCOUNT_SUBSCRIBE_TYPE>(typeInt);
423     return OhosAccountManager::GetInstance().SubscribeDistributedAccountEvent(type, eventListener);
424 }
425 
UnsubscribeDistributedAccountEvent(int32_t typeInt,const sptr<IRemoteObject> & eventListener)426 ErrCode AccountMgrService::UnsubscribeDistributedAccountEvent(int32_t typeInt, const sptr<IRemoteObject>& eventListener)
427 {
428     [[maybe_unused]] auto timerPtr = RequestTimer(Constants::OPERATION_UNSUBSCRIBE);
429     if (eventListener == nullptr) {
430         ACCOUNT_LOGE("eventListener is nullptr.");
431         return ERR_ACCOUNT_COMMON_NULL_PTR_ERROR;
432     }
433     ErrCode res = AccountPermissionManager::CheckSystemApp(false);
434     if (res != ERR_OK) {
435         ACCOUNT_LOGE("Check systemApp failed.");
436         return res;
437     }
438     auto type = static_cast<DISTRIBUTED_ACCOUNT_SUBSCRIBE_TYPE>(typeInt);
439     return OhosAccountManager::GetInstance().UnsubscribeDistributedAccountEvent(type, eventListener);
440 }
441 
GetAppAccountService(sptr<IRemoteObject> & funcResult)442 ErrCode AccountMgrService::GetAppAccountService(sptr<IRemoteObject>& funcResult)
443 {
444     [[maybe_unused]] auto timerPtr = RequestTimer(Constants::OPERATION_GET_SERVICE);
445 #ifdef HAS_APP_ACCOUNT_PART
446     std::lock_guard<std::mutex> lock(serviceMutex_);
447     funcResult = appAccountManagerService_.promote();
448     if (funcResult == nullptr) {
449         funcResult = new (std::nothrow) AppAccountManagerService();
450         appAccountManagerService_ = funcResult;
451     }
452     return ERR_OK;
453 #else
454     funcResult = nullptr;
455     return ERR_OK;
456 #endif
457 }
458 
GetOsAccountService(sptr<IRemoteObject> & funcResult)459 ErrCode AccountMgrService::GetOsAccountService(sptr<IRemoteObject>& funcResult)
460 {
461     [[maybe_unused]] auto timerPtr = RequestTimer(Constants::OPERATION_GET_SERVICE);
462     std::lock_guard<std::mutex> lock(serviceMutex_);
463     funcResult = osAccountManagerService_.promote();
464     if (funcResult == nullptr) {
465         funcResult = new (std::nothrow) OsAccountManagerService();
466         osAccountManagerService_ = funcResult;
467     }
468     return ERR_OK;
469 }
470 
GetAccountIAMService(sptr<IRemoteObject> & funcResult)471 ErrCode AccountMgrService::GetAccountIAMService(sptr<IRemoteObject>& funcResult)
472 {
473     [[maybe_unused]] auto timerPtr = RequestTimer(Constants::OPERATION_GET_SERVICE);
474 #ifdef HAS_USER_AUTH_PART
475     std::lock_guard<std::mutex> lock(serviceMutex_);
476     funcResult = accountIAMService_.promote();
477     if (funcResult == nullptr) {
478         funcResult = new (std::nothrow) AccountIAMService();
479         accountIAMService_ = funcResult;
480     }
481     return ERR_OK;
482 #else
483     funcResult = nullptr;
484     return ERR_OK;
485 #endif // HAS_USER_AUTH_PART
486 }
487 
GetDomainAccountService(sptr<IRemoteObject> & funcResult)488 ErrCode AccountMgrService::GetDomainAccountService(sptr<IRemoteObject>& funcResult)
489 {
490     [[maybe_unused]] auto timerPtr = RequestTimer(Constants::OPERATION_GET_SERVICE);
491 #ifdef SUPPORT_DOMAIN_ACCOUNTS
492     std::lock_guard<std::mutex> lock(serviceMutex_);
493     funcResult = domainAccountMgrService_.promote();
494     if (funcResult == nullptr) {
495         funcResult = new (std::nothrow) DomainAccountManagerService();
496         domainAccountMgrService_ = funcResult;
497     }
498     return ERR_OK;
499 #else
500     funcResult = nullptr;
501     return ERR_DOMAIN_ACCOUNT_NOT_SUPPORT;
502 #endif // SUPPORT_DOMAIN_ACCOUNTS
503 }
504 
IsServiceStarted(void) const505 bool AccountMgrService::IsServiceStarted(void) const
506 {
507     return (state_ == STATE_RUNNING);
508 }
509 
OnStart()510 void AccountMgrService::OnStart()
511 {
512     if (state_ == ServiceRunningState::STATE_RUNNING) {
513         ACCOUNT_LOGI("AccountMgrService has already started.");
514         return;
515     }
516     UpdateTraceLabelAdapter();
517     StartTraceAdapter("accountmgr service onstart");
518     CountTraceAdapter("activeid", -1);
519 
520     PerfStat::GetInstance().SetInstanceStartTime(GetTickCount());
521     ACCOUNT_LOGI("start is triggered");
522     ReportOsAccountLifeCycle(Constants::INVALID_OS_ACCOUNT_ID, "AccountMgr service onstart finished.");
523     if (!Init()) {
524         ACCOUNT_LOGE("failed to init AccountMgrService");
525         FinishTraceAdapter();
526         return;
527     }
528     AddSystemAbilityListener(STORAGE_MANAGER_MANAGER_ID);
529     AddSystemAbilityListener(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
530     AddSystemAbilityListener(ABILITY_MGR_SERVICE_ID);
531 #ifdef HAS_APP_ACCOUNT_PART
532     AddSystemAbilityListener(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID);
533 #endif
534     ACCOUNT_LOGI("AccountMgrService::OnStart start service finished.");
535     FinishTraceAdapter();
536 }
537 
OnStop()538 void AccountMgrService::OnStop()
539 {
540     PerfStat::GetInstance().SetInstanceStopTime(GetTickCount());
541     ACCOUNT_LOGI("onstop is called");
542     IAccountContext::SetInstance(nullptr);
543     SelfClean();
544 }
545 
546 #if defined(HAS_APP_ACCOUNT_PART) && defined(ENABLE_MULTIPLE_OS_ACCOUNTS)
MoveAppAccountData()547 void AccountMgrService::MoveAppAccountData()
548 {
549     auto task = [] { AppAccountControlManager::GetInstance().MoveData(); };
550     std::thread taskThread(task);
551     pthread_setname_np(taskThread.native_handle(), "MoveData");
552     taskThread.detach();
553     ACCOUNT_LOGI("Move app account data to encrypted store");
554 }
555 #endif // defined(HAS_APP_ACCOUNT_PART) && defined(ENABLE_MULTIPLE_OS_ACCOUNTS)
556 
IsDefaultOsAccountVerified()557 bool AccountMgrService::IsDefaultOsAccountVerified()
558 {
559     int32_t defaultAccountId = -1;
560     ErrCode errCode = IInnerOsAccountManager::GetInstance().GetDefaultActivatedOsAccount(defaultAccountId);
561     if (errCode != ERR_OK) {
562         ACCOUNT_LOGE("Failed to get default activated OS account, errCode: %{public}d", errCode);
563         return false;
564     }
565 
566     bool isVerified = false;
567     errCode = IInnerOsAccountManager::GetInstance().IsOsAccountVerified(defaultAccountId, isVerified);
568     if (errCode != ERR_OK) {
569         ACCOUNT_LOGE("Failed get default activated OS account verified info, errCode: %{public}d", errCode);
570         return false;
571     }
572     return isVerified;
573 }
574 
GetUncreatedInitAccounts(std::set<int32_t> & initAccounts)575 void AccountMgrService::GetUncreatedInitAccounts(std::set<int32_t> &initAccounts)
576 {
577     ErrCode errCode = ERR_OK;
578     for (int32_t id : INIT_ACCOUNT_ID_SET) {
579         bool isAccountCompleted = false;
580         errCode = IInnerOsAccountManager::GetInstance().IsOsAccountCompleted(id, isAccountCompleted);
581         if (errCode == ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR || (errCode == ERR_OK && !isAccountCompleted)) {
582             initAccounts.emplace(id);
583         }
584     }
585 }
586 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)587 void AccountMgrService::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
588 {
589     std::lock_guard<std::mutex> lock(statusMutex_);
590     ACCOUNT_LOGI("OnAddSystemAbility systemAbilityId %{public}d", systemAbilityId);
591     switch (systemAbilityId) {
592         case STORAGE_MANAGER_MANAGER_ID: {
593             isStorageReady_ = true;
594             break;
595         }
596         case ABILITY_MGR_SERVICE_ID: {
597             isAmsReady_ = true;
598             break;
599         }
600         case BUNDLE_MGR_SERVICE_SYS_ABILITY_ID: {
601             isBmsReady_ = true;
602             break;
603         }
604 #if defined(HAS_APP_ACCOUNT_PART) && defined(ENABLE_MULTIPLE_OS_ACCOUNTS)
605         case DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID: {
606             MoveAppAccountData();
607             return;
608         }
609 #endif // defined(HAS_APP_ACCOUNT_PART) && defined(ENABLE_MULTIPLE_OS_ACCOUNTS)
610         default:
611             return;
612     }
613     if (!isStorageReady_) {
614         return;
615     }
616 
617     std::set<int32_t> initAccounts;
618     GetUncreatedInitAccounts(initAccounts);
619     if (!initAccounts.empty()) {
620         if (!isBmsReady_) {
621             return;
622         }
623         bool result = IInnerOsAccountManager::GetInstance().Init(initAccounts);
624         if (!result) {
625             return;
626         }
627     }
628 
629     if (!isDefaultOsAccountActivated_ && isAmsReady_) {
630         ErrCode errCode = IInnerOsAccountManager::GetInstance().ActivateDefaultOsAccount();
631         if (errCode == ERR_OK) {
632             isDefaultOsAccountActivated_ = true;
633         }
634     }
635     if (isBmsReady_ && IsDefaultOsAccountVerified()) {
636         IInnerOsAccountManager::GetInstance().CleanGarbageOsAccountsAsync();
637     }
638 }
639 
Init()640 bool AccountMgrService::Init()
641 {
642     if (state_ == ServiceRunningState::STATE_RUNNING) {
643         ACCOUNT_LOGW("Service is already running!");
644         return false;
645     }
646 #ifdef HICOLLIE_ENABLE
647     AccountTimer timer(false);
648     timer.Init(MAX_INIT_TIME);
649 #endif // HICOLLIE_ENABLE
650     CreateDeviceDir();
651     IAccountContext::SetInstance(this);
652     if (!OhosAccountManager::GetInstance().OnInitialize()) {
653         ACCOUNT_LOGE("Ohos account manager initialize failed");
654         ReportServiceStartFail(ERR_ACCOUNT_MGR_OHOS_MGR_INIT_ERROR,
655             "OhosAccountManager::OnInitialize failed, do not block sa startup!");
656     }
657 #if defined(HAS_APP_ACCOUNT_PART) && defined(HAS_CES_PART)
658     AppAccountCommonEventObserver::GetInstance();
659 #endif // defined(HAS_APP_ACCOUNT_PART) && defined(HAS_CES_PART)
660     state_ = ServiceRunningState::STATE_RUNNING;
661     if (!registerToService_) {
662         if (!Publish(&DelayedRefSingleton<AccountMgrService>::GetInstance())) {
663             ACCOUNT_LOGE("AccountMgrService::Init Publish failed!");
664             ReportServiceStartFail(ERR_ACCOUNT_MGR_ADD_TO_SA_ERROR, "Publish service failed!");
665             return false;
666         }
667         registerToService_ = true;
668     }
669     PerfStat::GetInstance().SetInstanceInitTime(GetTickCount());
670 
671     dumpHelper_ = std::make_unique<AccountDumpHelper>(osAccountManagerService_.GetRefPtr());
672     ACCOUNT_LOGI("init end success");
673     return true;
674 }
675 
CreateOsAccountService()676 bool AccountMgrService::CreateOsAccountService()
677 {
678     osAccountManagerService_ = new (std::nothrow) OsAccountManagerService();
679     if (osAccountManagerService_ == nullptr) {
680         ACCOUNT_LOGE("memory alloc failed for osAccountManagerService_!");
681         ReportServiceStartFail(ERR_ACCOUNT_COMMON_INSUFFICIENT_MEMORY_ERROR,
682             "Insufficient memory to create os account manager service");
683         return false;
684     }
685     return true;
686 }
687 
CreateAppAccountService()688 bool AccountMgrService::CreateAppAccountService()
689 {
690 #ifdef HAS_APP_ACCOUNT_PART
691     appAccountManagerService_ = new (std::nothrow) AppAccountManagerService();
692     if (appAccountManagerService_ == nullptr) {
693         ACCOUNT_LOGE("memory alloc failed for appAccountManagerService!");
694         ReportServiceStartFail(ERR_ACCOUNT_COMMON_INSUFFICIENT_MEMORY_ERROR,
695             "Insufficient memory to create app account manager service");
696         return false;
697     }
698 #endif
699     return true;
700 }
701 
CreateIAMService()702 bool AccountMgrService::CreateIAMService()
703 {
704 #ifdef HAS_USER_AUTH_PART
705     accountIAMService_ = new (std::nothrow) AccountIAMService();
706     if (accountIAMService_ == nullptr) {
707         ACCOUNT_LOGE("memory alloc for AccountIAMService failed!");
708         ReportServiceStartFail(ERR_ACCOUNT_COMMON_INSUFFICIENT_MEMORY_ERROR,
709             "Insufficient memory to create account iam service");
710         return false;
711     }
712 #endif
713     return true;
714 }
715 
CreateDomainService()716 bool AccountMgrService::CreateDomainService()
717 {
718 #ifdef SUPPORT_DOMAIN_ACCOUNTS
719     domainAccountMgrService_ = new (std::nothrow) DomainAccountManagerService();
720     if (domainAccountMgrService_ == nullptr) {
721         ACCOUNT_LOGE("memory alloc for DomainAccountManagerService failed!");
722         ReportServiceStartFail(ERR_ACCOUNT_COMMON_INSUFFICIENT_MEMORY_ERROR,
723             "Insufficient memory to create domain account manager service");
724         return false;
725     }
726 #endif // SUPPORT_DOMAIN_ACCOUNTS
727     return true;
728 }
729 
Dump(std::int32_t fd,const std::vector<std::u16string> & args)730 ErrCode AccountMgrService::Dump(std::int32_t fd, const std::vector<std::u16string> &args)
731 {
732     if (fd < 0) {
733         ACCOUNT_LOGE("dump fd invalid");
734         return ERR_ACCOUNT_MGR_DUMP_ERROR;
735     }
736 
737     if (dumpHelper_ == nullptr) {
738         ACCOUNT_LOGE("dumpHelper_ is nullptr!");
739         return ERR_ACCOUNT_MGR_DUMP_ERROR;
740     }
741 
742     std::vector<std::string> argsInStr;
743     std::transform(args.begin(), args.end(), std::back_inserter(argsInStr),
744         [](const auto &arg) { return Str16ToStr8(arg); });
745 
746     std::string result;
747     dumpHelper_->Dump(argsInStr, result);
748     std::int32_t ret = dprintf(fd, "%s", result.c_str());
749     if (ret < 0) {
750         ACCOUNT_LOGE("dprintf to dump fd failed");
751         return ERR_ACCOUNT_MGR_DUMP_ERROR;
752     }
753     return ERR_OK;
754 }
755 
SelfClean()756 void AccountMgrService::SelfClean()
757 {
758     state_ = ServiceRunningState::STATE_NOT_START;
759     registerToService_ = false;
760     ACCOUNT_LOGI("self-clean finished");
761 }
762 
HandleNotificationEvents(const std::string & eventStr)763 void AccountMgrService::HandleNotificationEvents(const std::string &eventStr)
764 {
765     if (state_ == ServiceRunningState::STATE_NOT_START) {
766         ACCOUNT_LOGW("service not running for handling event: %{public}s", eventStr.c_str());
767         return;
768     }
769 }
770 
HasAccountRequestPermission(const std::string & permissionName)771 bool AccountMgrService::HasAccountRequestPermission(const std::string &permissionName)
772 {
773 #ifndef IS_RELEASE_VERSION
774     std::int32_t uid = IPCSkeleton::GetCallingUid();
775     // root check in none release version for test
776     if (uid == ROOT_UID) {
777         return true;
778     }
779 #endif
780 
781     // check permission
782     Security::AccessToken::AccessTokenID callingTokenID = IPCSkeleton::GetCallingTokenID();
783     if (Security::AccessToken::AccessTokenKit::VerifyAccessToken(callingTokenID, permissionName) ==
784         Security::AccessToken::TypePermissionState::PERMISSION_GRANTED) {
785         return true;
786     }
787 
788     return false;
789 }
790 
CallbackEnter(uint32_t code)791 int32_t AccountMgrService::CallbackEnter([[maybe_unused]] uint32_t code)
792 {
793     ACCOUNT_LOGD("Received stub message: %{public}d, callingUid: %{public}d", code, IPCSkeleton::GetCallingUid());
794     if (!IsServiceStarted()) {
795         ACCOUNT_LOGE("account mgr not ready");
796         return ERR_ACCOUNT_ZIDL_MGR_NOT_READY_ERROR;
797     }
798     return ERR_OK;
799 }
800 
CallbackExit(uint32_t code,int32_t result)801 int32_t AccountMgrService::CallbackExit([[maybe_unused]] uint32_t code, [[maybe_unused]] int32_t result)
802 {
803     return ERR_OK;
804 }
805 
CheckUserIdValid(int32_t userId)806 int32_t AccountMgrService::CheckUserIdValid(int32_t userId)
807 {
808     if ((userId >= 0) && (userId < Constants::START_USER_ID)) {
809         ACCOUNT_LOGE("userId %{public}d is system reserved", userId);
810         return ERR_OSACCOUNT_SERVICE_MANAGER_ID_ERROR;
811     }
812     bool isOsAccountExist = false;
813     IInnerOsAccountManager::GetInstance().IsOsAccountExists(userId, isOsAccountExist);
814     if (!isOsAccountExist) {
815         ACCOUNT_LOGE("os account is not exist");
816         return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
817     }
818     return ERR_OK;
819 }
820 }  // namespace AccountSA
821 }  // namespace OHOS