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