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