• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-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 "account_mgr_service.h"
17 #include <cerrno>
18 #include <thread>
19 #include "account_dump_helper.h"
20 #include "account_log_wrapper.h"
21 #ifdef HAS_APP_ACCOUNT_PART
22 #ifdef HAS_CES_PART
23 #include "app_account_common_event_observer.h"
24 #endif // HAS_CES_PART
25 #include "app_account_manager_service.h"
26 #endif
27 #include "datetime_ex.h"
28 #include "device_account_info.h"
29 #include "directory_ex.h"
30 #include "domain_account_manager_service.h"
31 #include "file_ex.h"
32 #include "account_hisysevent_adapter.h"
33 #include "hitrace_adapter.h"
34 #include "if_system_ability_manager.h"
35 #include "iinner_os_account_manager.h"
36 #include "ipc_skeleton.h"
37 #include "iservice_registry.h"
38 #include "perf_stat.h"
39 #include "string_ex.h"
40 #include "system_ability_definition.h"
41 #include "account_info.h"
42 #ifdef HAS_USER_AUTH_PART
43 #include "account_iam_service.h"
44 #endif
45 #ifdef HICOLLIE_ENABLE
46 #include "account_timer.h"
47 #endif // HICOLLIE_ENABLE
48 
49 namespace OHOS {
50 namespace AccountSA {
51 namespace {
52 #ifdef HICOLLIE_ENABLE
53 constexpr int32_t MAX_INIT_TIME = 120;
54 #endif // HICOLLIE_ENABLE
55 const bool REGISTER_RESULT =
56     SystemAbility::MakeAndRegisterAbility(&DelayedRefSingleton<AccountMgrService>::GetInstance());
57 const char DEVICE_OWNER_DIR[] = "/data/service/el1/public/account/0/";
CreateDeviceDir()58 void CreateDeviceDir()
59 {
60     if (!OHOS::FileExists(DEVICE_OWNER_DIR)) {
61         ACCOUNT_LOGI("Device owner dir not exist, create!");
62         if (!OHOS::ForceCreateDirectory(DEVICE_OWNER_DIR)) {
63             int32_t err = errno;
64             ACCOUNT_LOGW("Create device owner dir failure! errno %{public}d.", err);
65             ReportOsAccountOperationFail(0, OPERATION_FORCE_CREATE_DIRECTORY, err, DEVICE_OWNER_DIR);
66         } else {
67             if (!OHOS::ChangeModeDirectory(DEVICE_OWNER_DIR, S_IRWXU)) {
68                 int32_t err = errno;
69                 ReportOsAccountOperationFail(0, OPERATION_CHANGE_MODE_DIRECTORY, err, DEVICE_OWNER_DIR);
70                 ACCOUNT_LOGW("failed to create dir, path = %{public}s errno %{public}d.",
71                     DEVICE_OWNER_DIR, err);
72             }
73         }
74     }
75 }
76 }
77 IAccountContext *IAccountContext::instance_ = nullptr;
78 
AccountMgrService()79 AccountMgrService::AccountMgrService() : SystemAbility(SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN, true)
80 {
81     PerfStat::GetInstance().SetInstanceCreateTime(GetTickCount());
82 }
83 
~AccountMgrService()84 AccountMgrService::~AccountMgrService()
85 {}
86 
GetCallingUserID()87 std::int32_t AccountMgrService::GetCallingUserID()
88 {
89     std::int32_t userId = IPCSkeleton::GetCallingUid() / UID_TRANSFORM_DIVISOR;
90     if (userId <= 0) {
91         std::vector<int32_t> userIds;
92         (void)IInnerOsAccountManager::GetInstance().QueryActiveOsAccountIds(userIds);
93         if (userIds.empty()) {
94             return -1;  // invalid user id
95         }
96         userId = userIds[0];
97     }
98     return userId;
99 }
100 
UpdateOhosAccountInfo(const std::string & accountName,const std::string & uid,const std::string & eventStr)101 ErrCode AccountMgrService::UpdateOhosAccountInfo(
102     const std::string &accountName, const std::string &uid, const std::string &eventStr)
103 {
104     ErrCode res = OhosAccountManager::GetInstance().OhosAccountStateChange(accountName, uid, eventStr);
105     if (res != ERR_OK) {
106         ACCOUNT_LOGE("Ohos account state change failed, res = %{public}d.", res);
107     }
108 
109     return res;
110 }
111 
SetOhosAccountInfo(const OhosAccountInfo & ohosAccountInfo,const std::string & eventStr)112 ErrCode AccountMgrService::SetOhosAccountInfo(const OhosAccountInfo &ohosAccountInfo, const std::string &eventStr)
113 {
114     return ERR_OK;
115 }
116 
SetOsAccountDistributedInfo(const int32_t localId,const OhosAccountInfo & ohosAccountInfo,const std::string & eventStr)117 ErrCode AccountMgrService::SetOsAccountDistributedInfo(
118     const int32_t localId, const OhosAccountInfo &ohosAccountInfo, const std::string &eventStr)
119 {
120     ErrCode res = OhosAccountManager::GetInstance().OhosAccountStateChange(localId, ohosAccountInfo, eventStr);
121     if (res != ERR_OK) {
122         ACCOUNT_LOGE("Ohos account state change failed");
123     }
124 
125     return res;
126 }
127 
QueryDistributedVirtualDeviceId(std::string & dvid)128 ErrCode AccountMgrService::QueryDistributedVirtualDeviceId(std::string &dvid)
129 {
130     return OhosAccountManager::GetInstance().QueryDistributedVirtualDeviceId(dvid);
131 }
132 
QueryDistributedVirtualDeviceId(const std::string & bundleName,int32_t localId,std::string & dvid)133 ErrCode AccountMgrService::QueryDistributedVirtualDeviceId(const std::string &bundleName, int32_t localId,
134     std::string &dvid)
135 {
136     return OhosAccountManager::GetInstance().QueryDistributedVirtualDeviceId(bundleName, localId, dvid);
137 }
138 
QueryOhosAccountInfo(OhosAccountInfo & accountInfo)139 ErrCode AccountMgrService::QueryOhosAccountInfo(OhosAccountInfo &accountInfo)
140 {
141     return QueryOsAccountDistributedInfo(GetCallingUserID(), accountInfo);
142 }
143 
GetOhosAccountInfo(OhosAccountInfo & info)144 ErrCode AccountMgrService::GetOhosAccountInfo(OhosAccountInfo &info)
145 {
146     return GetOsAccountDistributedInfo(GetCallingUserID(), info);
147 }
148 
GetOsAccountDistributedInfo(int32_t localId,OhosAccountInfo & info)149 ErrCode AccountMgrService::GetOsAccountDistributedInfo(int32_t localId, OhosAccountInfo &info)
150 {
151     ErrCode ret = OhosAccountManager::GetInstance().GetOhosAccountDistributedInfo(localId, info);
152     if (ret != ERR_OK) {
153         return ret;
154     }
155     return ERR_OK;
156 }
157 
QueryOsAccountDistributedInfo(std::int32_t localId,OhosAccountInfo & accountInfo)158 ErrCode AccountMgrService::QueryOsAccountDistributedInfo(std::int32_t localId, OhosAccountInfo &accountInfo)
159 {
160     OhosAccountInfo ohosAccountInfo;
161     ErrCode ret = OhosAccountManager::GetInstance().GetOhosAccountDistributedInfo(localId, ohosAccountInfo);
162     if (ret != ERR_OK) {
163         return ret;
164     }
165     accountInfo.name_ = ohosAccountInfo.name_;
166     accountInfo.uid_ = ohosAccountInfo.uid_;
167     accountInfo.status_ = ohosAccountInfo.status_;
168     return ERR_OK;
169 }
170 
QueryDeviceAccountId(std::int32_t & accountId)171 ErrCode AccountMgrService::QueryDeviceAccountId(std::int32_t &accountId)
172 {
173     const std::int32_t uid = IPCSkeleton::GetCallingUid();
174     accountId = uid / UID_TRANSFORM_DIVISOR;
175     return ERR_OK;
176 }
177 
SubscribeDistributedAccountEvent(const DISTRIBUTED_ACCOUNT_SUBSCRIBE_TYPE type,const sptr<IRemoteObject> & eventListener)178 ErrCode AccountMgrService::SubscribeDistributedAccountEvent(const DISTRIBUTED_ACCOUNT_SUBSCRIBE_TYPE type,
179     const sptr<IRemoteObject> &eventListener)
180 {
181     ErrCode res = AccountPermissionManager::CheckSystemApp(false);
182     if (res != ERR_OK) {
183         ACCOUNT_LOGE("Check systemApp failed.");
184         return res;
185     }
186     return OhosAccountManager::GetInstance().SubscribeDistributedAccountEvent(type, eventListener);
187 }
188 
UnsubscribeDistributedAccountEvent(const DISTRIBUTED_ACCOUNT_SUBSCRIBE_TYPE type,const sptr<IRemoteObject> & eventListener)189 ErrCode AccountMgrService::UnsubscribeDistributedAccountEvent(const DISTRIBUTED_ACCOUNT_SUBSCRIBE_TYPE type,
190     const sptr<IRemoteObject> &eventListener)
191 {
192     ErrCode res = AccountPermissionManager::CheckSystemApp(false);
193     if (res != ERR_OK) {
194         ACCOUNT_LOGE("Check systemApp failed.");
195         return res;
196     }
197     return OhosAccountManager::GetInstance().UnsubscribeDistributedAccountEvent(type, eventListener);
198 }
199 
GetAppAccountService()200 sptr<IRemoteObject> AccountMgrService::GetAppAccountService()
201 {
202 #ifdef HAS_APP_ACCOUNT_PART
203     std::lock_guard<std::mutex> lock(serviceMutex_);
204     auto service = appAccountManagerService_.promote();
205     if (service == nullptr) {
206         service = new (std::nothrow) AppAccountManagerService();
207         appAccountManagerService_ = service;
208     }
209     return service;
210 #else
211     return nullptr;
212 #endif
213 }
214 
GetOsAccountService()215 sptr<IRemoteObject> AccountMgrService::GetOsAccountService()
216 {
217     std::lock_guard<std::mutex> lock(serviceMutex_);
218     auto service = osAccountManagerService_.promote();
219     if (service == nullptr) {
220         service = new (std::nothrow) OsAccountManagerService();
221         osAccountManagerService_ = service;
222     }
223     return service;
224 }
225 
GetAccountIAMService()226 sptr<IRemoteObject> AccountMgrService::GetAccountIAMService()
227 {
228 #ifdef HAS_USER_AUTH_PART
229     std::lock_guard<std::mutex> lock(serviceMutex_);
230     auto service = accountIAMService_.promote();
231     if (service == nullptr) {
232         service = new (std::nothrow) AccountIAMService();
233         accountIAMService_ = service;
234     }
235     return service;
236 #else
237     return nullptr;
238 #endif // HAS_USER_AUTH_PART
239 }
240 
GetDomainAccountService()241 sptr<IRemoteObject> AccountMgrService::GetDomainAccountService()
242 {
243 #ifdef SUPPORT_DOMAIN_ACCOUNTS
244     std::lock_guard<std::mutex> lock(serviceMutex_);
245     auto service = domainAccountMgrService_.promote();
246     if (service == nullptr) {
247         service = new (std::nothrow) DomainAccountManagerService();
248         domainAccountMgrService_ = service;
249     }
250     return service;
251 #else
252     return nullptr;
253 #endif // SUPPORT_DOMAIN_ACCOUNTS
254 }
255 
IsServiceStarted(void) const256 bool AccountMgrService::IsServiceStarted(void) const
257 {
258     return (state_ == STATE_RUNNING);
259 }
260 
OnStart()261 void AccountMgrService::OnStart()
262 {
263     if (state_ == ServiceRunningState::STATE_RUNNING) {
264         ACCOUNT_LOGI("AccountMgrService has already started.");
265         return;
266     }
267     UpdateTraceLabelAdapter();
268     StartTraceAdapter("accountmgr service onstart");
269     CountTraceAdapter("activeid", -1);
270 
271     PerfStat::GetInstance().SetInstanceStartTime(GetTickCount());
272     ACCOUNT_LOGI("start is triggered");
273     ReportOsAccountLifeCycle(Constants::INVALID_OS_ACCOUNT_ID, "AccountMgr service onstart finished.");
274     if (!Init()) {
275         ACCOUNT_LOGE("failed to init AccountMgrService");
276         FinishTraceAdapter();
277         return;
278     }
279     AddSystemAbilityListener(STORAGE_MANAGER_MANAGER_ID);
280     AddSystemAbilityListener(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
281     AddSystemAbilityListener(ABILITY_MGR_SERVICE_ID);
282 #ifdef HAS_APP_ACCOUNT_PART
283     AddSystemAbilityListener(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID);
284 #endif
285     ACCOUNT_LOGI("AccountMgrService::OnStart start service finished.");
286     FinishTraceAdapter();
287 }
288 
OnStop()289 void AccountMgrService::OnStop()
290 {
291     PerfStat::GetInstance().SetInstanceStopTime(GetTickCount());
292     ACCOUNT_LOGI("onstop is called");
293     IAccountContext::SetInstance(nullptr);
294     SelfClean();
295 }
296 
297 #if defined(HAS_APP_ACCOUNT_PART) && defined(ENABLE_MULTIPLE_OS_ACCOUNTS)
MoveAppAccountData()298 void AccountMgrService::MoveAppAccountData()
299 {
300     auto task = [] { AppAccountControlManager::GetInstance().MoveData(); };
301     std::thread taskThread(task);
302     pthread_setname_np(taskThread.native_handle(), "MoveData");
303     taskThread.detach();
304     ACCOUNT_LOGI("Move app account data to encrypted store");
305 }
306 #endif // defined(HAS_APP_ACCOUNT_PART) && defined(ENABLE_MULTIPLE_OS_ACCOUNTS)
307 
IsDefaultOsAccountVerified()308 bool AccountMgrService::IsDefaultOsAccountVerified()
309 {
310     int32_t defaultAccountId = -1;
311     ErrCode errCode = IInnerOsAccountManager::GetInstance().GetDefaultActivatedOsAccount(defaultAccountId);
312     if (errCode != ERR_OK) {
313         ACCOUNT_LOGE("Failed to get default activated OS account, errCode: %{public}d", errCode);
314         return false;
315     }
316 
317     bool isVerified = false;
318     errCode = IInnerOsAccountManager::GetInstance().IsOsAccountVerified(defaultAccountId, isVerified);
319     if (errCode != ERR_OK) {
320         ACCOUNT_LOGE("Failed get default activated OS account verified info, errCode: %{public}d", errCode);
321         return false;
322     }
323     return isVerified;
324 }
325 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)326 void AccountMgrService::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
327 {
328     std::lock_guard<std::mutex> lock(statusMutex_);
329     ACCOUNT_LOGI("OnAddSystemAbility systemAbilityId %{public}d", systemAbilityId);
330     switch (systemAbilityId) {
331         case STORAGE_MANAGER_MANAGER_ID: {
332             isStorageReady_ = true;
333             break;
334         }
335         case ABILITY_MGR_SERVICE_ID: {
336             isAmsReady_ = true;
337             break;
338         }
339         case BUNDLE_MGR_SERVICE_SYS_ABILITY_ID: {
340             isBmsReady_ = true;
341             break;
342         }
343 #if defined(HAS_APP_ACCOUNT_PART) && defined(ENABLE_MULTIPLE_OS_ACCOUNTS)
344         case DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID: {
345             MoveAppAccountData();
346             return;
347         }
348 #endif // defined(HAS_APP_ACCOUNT_PART) && defined(ENABLE_MULTIPLE_OS_ACCOUNTS)
349         default:
350             return;
351     }
352 
353     if (!isStorageReady_) {
354         return;
355     }
356     bool isAccountCompleted = false;
357     ErrCode errCode =
358         IInnerOsAccountManager::GetInstance().IsOsAccountCompleted(Constants::START_USER_ID, isAccountCompleted);
359     ACCOUNT_LOGI("IsOsAccountCompleted errCode=%{public}d.", errCode);
360     if (errCode == ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR || (errCode == ERR_OK && !isAccountCompleted)) {
361         if (!isBmsReady_) {
362             return;
363         }
364         IInnerOsAccountManager::GetInstance().Init();
365     }
366     if (!isDefaultOsAccountActivated_ && isAmsReady_) {
367         errCode = IInnerOsAccountManager::GetInstance().ActivateDefaultOsAccount();
368         if (errCode == ERR_OK) {
369             isDefaultOsAccountActivated_ = true;
370         }
371     }
372     if (isBmsReady_ && IsDefaultOsAccountVerified()) {
373         IInnerOsAccountManager::GetInstance().CleanGarbageOsAccountsAsync();
374     }
375 }
376 
Init()377 bool AccountMgrService::Init()
378 {
379     if (state_ == ServiceRunningState::STATE_RUNNING) {
380         ACCOUNT_LOGW("Service is already running!");
381         return false;
382     }
383 #ifdef HICOLLIE_ENABLE
384     AccountTimer timer(false);
385     timer.Init(MAX_INIT_TIME);
386 #endif // HICOLLIE_ENABLE
387     CreateDeviceDir();
388     IAccountContext::SetInstance(this);
389     if (!OhosAccountManager::GetInstance().OnInitialize()) {
390         ACCOUNT_LOGE("Ohos account manager initialize failed");
391         ReportServiceStartFail(ERR_ACCOUNT_MGR_OHOS_MGR_INIT_ERROR,
392             "OhosAccountManager::OnInitialize failed, do not block sa startup!");
393     }
394 #if defined(HAS_APP_ACCOUNT_PART) && defined(HAS_CES_PART)
395     AppAccountCommonEventObserver::GetInstance();
396 #endif // defined(HAS_APP_ACCOUNT_PART) && defined(HAS_CES_PART)
397     state_ = ServiceRunningState::STATE_RUNNING;
398     if (!registerToService_) {
399         if (!Publish(&DelayedRefSingleton<AccountMgrService>::GetInstance())) {
400             ACCOUNT_LOGE("AccountMgrService::Init Publish failed!");
401             ReportServiceStartFail(ERR_ACCOUNT_MGR_ADD_TO_SA_ERROR, "Publish service failed!");
402             return false;
403         }
404         registerToService_ = true;
405     }
406     PerfStat::GetInstance().SetInstanceInitTime(GetTickCount());
407 
408     dumpHelper_ = std::make_unique<AccountDumpHelper>(osAccountManagerService_.GetRefPtr());
409     ACCOUNT_LOGI("init end success");
410     return true;
411 }
412 
CreateOsAccountService()413 bool AccountMgrService::CreateOsAccountService()
414 {
415     osAccountManagerService_ = new (std::nothrow) OsAccountManagerService();
416     if (osAccountManagerService_ == nullptr) {
417         ACCOUNT_LOGE("memory alloc failed for osAccountManagerService_!");
418         ReportServiceStartFail(ERR_ACCOUNT_COMMON_INSUFFICIENT_MEMORY_ERROR,
419             "Insufficient memory to create os account manager service");
420         return false;
421     }
422     return true;
423 }
424 
CreateAppAccountService()425 bool AccountMgrService::CreateAppAccountService()
426 {
427 #ifdef HAS_APP_ACCOUNT_PART
428     appAccountManagerService_ = new (std::nothrow) AppAccountManagerService();
429     if (appAccountManagerService_ == nullptr) {
430         ACCOUNT_LOGE("memory alloc failed for appAccountManagerService!");
431         ReportServiceStartFail(ERR_ACCOUNT_COMMON_INSUFFICIENT_MEMORY_ERROR,
432             "Insufficient memory to create app account manager service");
433         return false;
434     }
435 #endif
436     return true;
437 }
438 
CreateIAMService()439 bool AccountMgrService::CreateIAMService()
440 {
441 #ifdef HAS_USER_AUTH_PART
442     accountIAMService_ = new (std::nothrow) AccountIAMService();
443     if (accountIAMService_ == nullptr) {
444         ACCOUNT_LOGE("memory alloc for AccountIAMService failed!");
445         ReportServiceStartFail(ERR_ACCOUNT_COMMON_INSUFFICIENT_MEMORY_ERROR,
446             "Insufficient memory to create account iam service");
447         return false;
448     }
449 #endif
450     return true;
451 }
452 
CreateDomainService()453 bool AccountMgrService::CreateDomainService()
454 {
455 #ifdef SUPPORT_DOMAIN_ACCOUNTS
456     domainAccountMgrService_ = new (std::nothrow) DomainAccountManagerService();
457     if (domainAccountMgrService_ == nullptr) {
458         ACCOUNT_LOGE("memory alloc for DomainAccountManagerService failed!");
459         ReportServiceStartFail(ERR_ACCOUNT_COMMON_INSUFFICIENT_MEMORY_ERROR,
460             "Insufficient memory to create domain account manager service");
461         return false;
462     }
463 #endif // SUPPORT_DOMAIN_ACCOUNTS
464     return true;
465 }
466 
Dump(std::int32_t fd,const std::vector<std::u16string> & args)467 ErrCode AccountMgrService::Dump(std::int32_t fd, const std::vector<std::u16string> &args)
468 {
469     if (fd < 0) {
470         ACCOUNT_LOGE("dump fd invalid");
471         return ERR_ACCOUNT_MGR_DUMP_ERROR;
472     }
473 
474     if (dumpHelper_ == nullptr) {
475         ACCOUNT_LOGE("dumpHelper_ is nullptr!");
476         return ERR_ACCOUNT_MGR_DUMP_ERROR;
477     }
478 
479     std::vector<std::string> argsInStr;
480     std::transform(args.begin(), args.end(), std::back_inserter(argsInStr),
481         [](const auto &arg) { return Str16ToStr8(arg); });
482 
483     std::string result;
484     dumpHelper_->Dump(argsInStr, result);
485     std::int32_t ret = dprintf(fd, "%s", result.c_str());
486     if (ret < 0) {
487         ACCOUNT_LOGE("dprintf to dump fd failed");
488         return ERR_ACCOUNT_MGR_DUMP_ERROR;
489     }
490     return ERR_OK;
491 }
492 
SelfClean()493 void AccountMgrService::SelfClean()
494 {
495     state_ = ServiceRunningState::STATE_NOT_START;
496     registerToService_ = false;
497     ACCOUNT_LOGI("self-clean finished");
498 }
499 
HandleNotificationEvents(const std::string & eventStr)500 void AccountMgrService::HandleNotificationEvents(const std::string &eventStr)
501 {
502     if (state_ == ServiceRunningState::STATE_NOT_START) {
503         ACCOUNT_LOGW("service not running for handling event: %{public}s", eventStr.c_str());
504         return;
505     }
506 }
507 }  // namespace AccountSA
508 }  // namespace OHOS