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