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 #include "iinner_os_account_manager.h"
16 #include "account_event_provider.h"
17 #include <chrono>
18 #include <dlfcn.h>
19 #include <poll.h>
20 #include <sys/wait.h>
21 #include <sys/stat.h>
22 #include <unistd.h>
23 #include "account_constants.h"
24 #include "account_info.h"
25 #include "account_info_report.h"
26 #include "account_log_wrapper.h"
27 #include "os_account_info.h"
28 #ifdef HAS_CES_PART
29 #include "common_event_support.h"
30 #endif // HAS_CES_PART
31 #include "domain_account_callback_service.h"
32 #include "hitrace_adapter.h"
33 #include "account_hisysevent_adapter.h"
34 #include "data_size_report_adapter.h"
35 #include "account_permission_manager.h"
36 #include "app_account_control_manager.h"
37 #include "ohos_account_kits.h"
38 #include "os_account_constants.h"
39 #ifdef SUPPORT_DOMAIN_ACCOUNTS
40 #include "os_account_domain_account_callback.h"
41 #endif // SUPPORT_DOMAIN_ACCOUNTS
42 #include "os_account_static_subscriber_manager.h"
43 #include "os_account_subscribe_manager.h"
44 #include "parameter.h"
45 #include "parcel.h"
46 #include "string_ex.h"
47 #include <pthread.h>
48 #include <thread>
49 #include <unordered_set>
50 #ifdef HICOLLIE_ENABLE
51 #include "account_timer.h"
52 #include "xcollie/xcollie.h"
53 #endif // HICOLLIE_ENABLE
54
55 namespace OHOS {
56 namespace AccountSA {
57 namespace {
58 const char OPERATION_UPDATE[] = "update";
59 const char OPERATION_SET_TO_BE_REMOVED[] = "setToBeRemoved";
60 const char ADMIN_LOCAL_NAME[] = "admin";
61 #ifdef SUPPORT_LOCK_OS_ACCOUNT
62 const char OPERATION_LOCK[] = "lock";
63 #endif
64 #ifdef ENABLE_DEFAULT_ADMIN_NAME
65 const char STANDARD_LOCAL_NAME[] = "user";
66 #endif
67 const std::string CONSTRAINT_CREATE_ACCOUNT_DIRECTLY = "constraint.os.account.create.directly";
68 const char ACCOUNT_READY_EVENT[] = "bootevent.account.ready";
69 const char PARAM_LOGIN_NAME_MAX[] = "persist.account.login_name_max";
70 constexpr const char DEACTIVATION_ANIMATION_PATH[] = "/system/bin/deactivation_animation";
71 constexpr int32_t TOKEN_NATIVE = 1;
72 constexpr int32_t DELAY_FOR_EXCEPTION = 50;
73 constexpr int32_t MAX_RETRY_TIMES = 50;
74 constexpr int32_t MAX_INSERT_RETRY_TIMES = 3;
75 constexpr int32_t MAX_PRIVATE_TYPE_NUMBER = 1;
76 constexpr int32_t MAX_MAINTENANCE_TYPE_NUMBER = 1;
77 constexpr int32_t DELAY_FOR_REMOVING_FOREGROUND_OS_ACCOUNT = 1500;
78 #ifdef ENABLE_MULTIPLE_ACTIVE_ACCOUNTS
79 constexpr int32_t DELAY_FOR_DEACTIVATE_OS_ACCOUNT = 3000;
80 #endif
81 constexpr int32_t MAX_WAIT_ANIMATION_MSG_BUFFER = 256;
82 constexpr int32_t MAX_WAIT_ANIMATION_READY_TIMEOUT = 1000;
83 constexpr int32_t PIPE_FD_COUNT = 2;
84 constexpr int32_t PIPE_READ_END = 0;
85 constexpr int32_t PIPE_WRITE_END = 1;
86 }
87
88 #ifdef SUPPORT_DOMAIN_ACCOUNTS
GetDomainAccountStatus(OsAccountInfo & osAccountInfo)89 static ErrCode GetDomainAccountStatus(OsAccountInfo &osAccountInfo)
90 {
91 DomainAccountInfo domainAccountInfo;
92 osAccountInfo.GetDomainInfo(domainAccountInfo);
93 DomainAccountInfo resultInfo;
94 ErrCode errCode = InnerDomainAccountManager::GetInstance().GetDomainAccountInfo(domainAccountInfo, resultInfo);
95 if (errCode != ERR_OK) {
96 return errCode;
97 }
98 if (!resultInfo.isAuthenticated) {
99 domainAccountInfo.status_ = DomainAccountStatus::LOGOUT;
100 } else {
101 bool isActivated = false;
102 (void)IInnerOsAccountManager::GetInstance().IsOsAccountActived(osAccountInfo.GetLocalId(), isActivated);
103 domainAccountInfo.status_ = isActivated ? DomainAccountStatus::LOGIN : DomainAccountStatus::LOGIN_BACKGROUND;
104 }
105 osAccountInfo.SetDomainInfo(domainAccountInfo);
106 return ERR_OK;
107 }
108 #endif // SUPPORT_DOMAIN_ACCOUNTS
109
IInnerOsAccountManager()110 IInnerOsAccountManager::IInnerOsAccountManager() : subscribeManager_(OsAccountSubscribeManager::GetInstance()),
111 #ifdef SUPPORT_LOCK_OS_ACCOUNT
112 lockOsAccountPluginManager_(OsAccountLockOsAccountPluginManager::GetInstance()),
113 #endif
114 activateLockPluginManager_(OsAccountActivateLockPluginManager::GetInstance())
115 {
116 activeAccountId_.clear();
117 operatingId_.clear();
118 osAccountControl_ = std::make_shared<OsAccountControlFileManager>();
119 osAccountControl_->Init();
120 osAccountControl_->GetDeviceOwnerId(deviceOwnerId_);
121 osAccountControl_->GetDefaultActivatedOsAccount(defaultActivatedId_);
122 osAccountControl_->GetOsAccountConfig(config_);
123 SetParameter(PARAM_LOGIN_NAME_MAX, std::to_string(Constants::LOCAL_NAME_MAX_SIZE).c_str());
124 ACCOUNT_LOGI("Init end, maxOsAccountNum: %{public}d, maxLoggedInOsAccountNum: %{public}d",
125 config_.maxOsAccountNum, config_.maxLoggedInOsAccountNum);
126 }
127
GetInstance()128 IInnerOsAccountManager &IInnerOsAccountManager::GetInstance()
129 {
130 static IInnerOsAccountManager *instance = new (std::nothrow) IInnerOsAccountManager();
131 return *instance;
132 }
133
134 #ifdef FUZZ_TEST
135 // LCOV_EXCL_START
136 #endif
RetryToInsertOsAccount(OsAccountInfo & osAccountInfo)137 ErrCode IInnerOsAccountManager::RetryToInsertOsAccount(OsAccountInfo &osAccountInfo)
138 {
139 int32_t retryTimes = 0;
140 ErrCode result;
141 while (retryTimes < MAX_INSERT_RETRY_TIMES) {
142 result = osAccountControl_->InsertOsAccount(osAccountInfo);
143 if (result == ERR_OK || result == ERR_OSACCOUNT_SERVICE_CONTROL_INSERT_FILE_EXISTS_ERROR) {
144 return ERR_OK;
145 }
146 ACCOUNT_LOGE("Fail to insert account");
147 retryTimes++;
148 std::this_thread::sleep_for(std::chrono::milliseconds(DELAY_FOR_EXCEPTION));
149 }
150 return result;
151 }
152 #ifdef FUZZ_TEST
153 // LCOV_EXCL_STOP
154 #endif
155
156 #ifdef FUZZ_TEST
157 // LCOV_EXCL_START
158 #endif
CreateBaseAdminAccount()159 void IInnerOsAccountManager::CreateBaseAdminAccount()
160 {
161 ACCOUNT_LOGI("Start to create admin account");
162 bool isExistsAccount = false;
163 osAccountControl_->IsOsAccountExists(Constants::ADMIN_LOCAL_ID, isExistsAccount);
164 if (!isExistsAccount) {
165 ReportOsAccountLifeCycle(Constants::ADMIN_LOCAL_ID, Constants::OPERATION_BOOT_CREATE);
166 int64_t serialNumber =
167 Constants::CARRY_NUM * Constants::SERIAL_NUMBER_NUM_START_FOR_ADMIN + Constants::ADMIN_LOCAL_ID;
168 OsAccountInfo osAccountInfo(
169 Constants::ADMIN_LOCAL_ID, ADMIN_LOCAL_NAME, OsAccountType::ADMIN, serialNumber);
170 int64_t time =
171 std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch())
172 .count();
173 osAccountInfo.SetCreateTime(time);
174 osAccountInfo.SetIsCreateCompleted(true);
175 osAccountInfo.SetIsActived(true); // admin local account is always active
176 osAccountControl_->InsertOsAccount(osAccountInfo);
177 ReportOsAccountLifeCycle(osAccountInfo.GetLocalId(), Constants::OPERATION_CREATE);
178 ACCOUNT_LOGI("OsAccountAccountMgr created admin account end");
179 } else {
180 ACCOUNT_LOGI("OsAccountAccountMgr admin account already exists");
181 }
182 }
183 #ifdef FUZZ_TEST
184 // LCOV_EXCL_STOP
185 #endif
186
187 #ifdef FUZZ_TEST
188 // LCOV_EXCL_START
189 #endif
SendMsgForAccountActivateInBackground(OsAccountInfo & osAccountInfo)190 ErrCode IInnerOsAccountManager::SendMsgForAccountActivateInBackground(OsAccountInfo &osAccountInfo)
191 {
192 // activate
193 subscribeManager_.Publish(osAccountInfo.GetLocalId(), OS_ACCOUNT_SUBSCRIBE_TYPE::ACTIVATING);
194 (void)SendToStorageAccountStart(osAccountInfo);
195 // StorageManager failture does not block boot, continue!
196 ErrCode errCode = SendToAMSAccountStart(osAccountInfo, Constants::INVALID_DISPALY_ID, true);
197 if (errCode != ERR_OK) {
198 return errCode;
199 }
200 subscribeManager_.Publish(osAccountInfo.GetLocalId(), OS_ACCOUNT_SUBSCRIBE_TYPE::ACTIVATED);
201 ReportOsAccountLifeCycle(osAccountInfo.GetLocalId(), Constants::OPERATION_ACTIVATE);
202 OsAccountInterface::PublishCommonEvent(osAccountInfo,
203 OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_USER_BACKGROUND, Constants::OPERATION_ACTIVATE);
204 ACCOUNT_LOGI("SendMsgForAccountActivateInBackground %{public}d ok", osAccountInfo.GetLocalId());
205 return ERR_OK;
206 }
207 #ifdef FUZZ_TEST
208 // LCOV_EXCL_STOP
209 #endif
210
211 #ifdef FUZZ_TEST
212 // LCOV_EXCL_START
213 #endif
ActivateOsAccountInBackground(const int32_t id)214 ErrCode IInnerOsAccountManager::ActivateOsAccountInBackground(const int32_t id)
215 {
216 ACCOUNT_LOGI("Start to activate %{public}d account", id);
217
218 OsAccountInfo osAccountInfo;
219 // check account is exist or not
220 ErrCode errCode = GetRealOsAccountInfoById(id, osAccountInfo);
221 if (errCode != ERR_OK) {
222 REPORT_OS_ACCOUNT_FAIL(id, Constants::OPERATION_ACTIVATE, errCode, "Account not found.");
223 ACCOUNT_LOGE("Account not found, localId: %{public}d, error: %{public}d", id, errCode);
224 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
225 }
226 errCode = IsValidOsAccount(osAccountInfo);
227 if (errCode != ERR_OK) {
228 REPORT_OS_ACCOUNT_FAIL(id, Constants::OPERATION_ACTIVATE, errCode, "Account is invalid.");
229 ACCOUNT_LOGE("Account is invalid, localId: %{public}d, error: %{public}d", id, errCode);
230 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
231 }
232 // activate
233 errCode = SendMsgForAccountActivateInBackground(osAccountInfo);
234 return errCode;
235 }
236 #ifdef FUZZ_TEST
237 // LCOV_EXCL_STOP
238 #endif
239
240 #ifdef FUZZ_TEST
241 // LCOV_EXCL_START
242 #endif
CreateBaseStandardAccount(OsAccountInfo & osAccountInfo)243 bool IInnerOsAccountManager::CreateBaseStandardAccount(OsAccountInfo &osAccountInfo)
244 {
245 ACCOUNT_LOGI("Start to create base account %{public}d", osAccountInfo.GetLocalId());
246 int64_t serialNumber = 0;
247 osAccountControl_->GetSerialNumber(serialNumber);
248 osAccountInfo.SetSerialNumber(serialNumber);
249 std::vector<std::string> constraints;
250 ErrCode errCode = osAccountControl_->GetConstraintsByType(osAccountInfo.GetType(), constraints);
251 if (errCode != ERR_OK) {
252 ACCOUNT_LOGE("Fail to get constraints by type for account %{public}d, errCode %{public}d.",
253 osAccountInfo.GetLocalId(), errCode);
254 ReportOsAccountOperationFail(osAccountInfo.GetLocalId(), Constants::OPERATION_BOOT_CREATE, errCode,
255 "Fail to get constraints by type for account");
256 return false;
257 }
258 osAccountInfo.SetConstraints(constraints);
259 int64_t time =
260 std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch())
261 .count();
262 osAccountInfo.SetCreateTime(time);
263 osAccountInfo.SetIsCreateCompleted(false);
264 osAccountInfo.SetIsDataRemovable(false);
265 errCode = RetryToInsertOsAccount(osAccountInfo);
266 if (errCode != ERR_OK) {
267 ACCOUNT_LOGE("Fail to insert account %{public}d, errCode %{public}d.", osAccountInfo.GetLocalId(), errCode);
268 ReportOsAccountOperationFail(osAccountInfo.GetLocalId(), Constants::OPERATION_BOOT_CREATE, errCode,
269 "Failed to insert start user OS account");
270 }
271 errCode = SendMsgForAccountCreate(osAccountInfo);
272 if (errCode != ERR_OK) {
273 ACCOUNT_LOGE("OS account %{public}d not created completely, errCode %{public}d.",
274 osAccountInfo.GetLocalId(), errCode);
275 ReportOsAccountOperationFail(osAccountInfo.GetLocalId(), Constants::OPERATION_BOOT_CREATE, errCode,
276 "SendMsgForAccountCreate failed");
277 return false;
278 }
279 ReportOsAccountLifeCycle(osAccountInfo.GetLocalId(), Constants::OPERATION_CREATE);
280 ReportOsAccountLifeCycle(osAccountInfo.GetLocalId(), Constants::OPERATION_BOOT_CREATE);
281 ACCOUNT_LOGI("OsAccountAccountMgr created base account end");
282 return true;
283 }
284 #ifdef FUZZ_TEST
285 // LCOV_EXCL_STOP
286 #endif
287
RetryToGetAccount(OsAccountInfo & osAccountInfo)288 void IInnerOsAccountManager::RetryToGetAccount(OsAccountInfo &osAccountInfo)
289 {
290 int32_t retryTimes = 0;
291 while (retryTimes < MAX_RETRY_TIMES) {
292 std::vector<OsAccountInfo> osAccountInfos;
293 QueryAllCreatedOsAccounts(osAccountInfos);
294 if (!osAccountInfos.empty() && (IsValidOsAccount(osAccountInfos[0]) == ERR_OK)) {
295 osAccountInfo = osAccountInfos[0];
296 return;
297 }
298 ACCOUNT_LOGE("Fail to query accounts");
299 retryTimes++;
300 std::this_thread::sleep_for(std::chrono::milliseconds(DELAY_FOR_EXCEPTION));
301 }
302
303 #ifdef ENABLE_DEFAULT_ADMIN_NAME
304 while (CreateOsAccount(STANDARD_LOCAL_NAME, ADMIN, osAccountInfo) != ERR_OK) {
305 #else
306 while (CreateOsAccount("", ADMIN, osAccountInfo) != ERR_OK) {
307 #endif
308 ACCOUNT_LOGE("Fail to create account");
309 std::this_thread::sleep_for(std::chrono::milliseconds(DELAY_FOR_EXCEPTION));
310 }
311 }
312
313 ErrCode IInnerOsAccountManager::GetRealOsAccountInfoById(const int id, OsAccountInfo &osAccountInfo)
314 {
315 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(id, osAccountInfo);
316 if (errCode != ERR_OK) {
317 return errCode;
318 }
319
320 bool isVerified = false;
321 verifiedAccounts_.Find(id, isVerified);
322 osAccountInfo.SetIsVerified(isVerified);
323
324 bool isLoggedIn = false;
325 loggedInAccounts_.Find(id, isLoggedIn);
326 osAccountInfo.SetIsLoggedIn(isLoggedIn);
327
328 bool isActivated = IsOsAccountIDInActiveList(id);
329 osAccountInfo.SetIsActived(isActivated);
330
331 int32_t foregroundId = -1;
332 foregroundAccountMap_.Find(Constants::DEFAULT_DISPALY_ID, foregroundId);
333 osAccountInfo.SetIsForeground(foregroundId == id);
334 osAccountInfo.SetDisplayId(foregroundId == id ? Constants::DEFAULT_DISPALY_ID : Constants::INVALID_DISPALY_ID);
335
336 return ERR_OK;
337 }
338
339 #ifdef FUZZ_TEST
340 // LCOV_EXCL_START
341 #endif
342 ErrCode IInnerOsAccountManager::ActivateDefaultOsAccount()
343 {
344 #ifdef HICOLLIE_ENABLE
345 XCollieCallback callbackFunc = [this](void *) {
346 ACCOUNT_LOGE("ActivateDefaultOsAccount failed due to timeout.");
347 REPORT_OS_ACCOUNT_FAIL(this->defaultActivatedId_, Constants::OPERATION_BOOT_ACTIVATING,
348 ERR_ACCOUNT_COMMON_OPERATION_TIMEOUT, "Activate default os account over time.");
349 };
350 int timerId =
351 HiviewDFX::XCollie::GetInstance().SetTimer(TIMER_NAME, TIMEOUT, callbackFunc, nullptr,
352 HiviewDFX::XCOLLIE_FLAG_LOG);
353 #endif // HICOLLIE_ENABLE
354 ACCOUNT_LOGI("Start to activate default account");
355 ErrCode errCode;
356 #ifdef ENABLE_U1_ACCOUNT
357 if (config_.isU1Enable) {
358 errCode = ActivateOsAccountInBackground(Constants::U1_ID);
359 // if account not exist, do not block boot
360 if (errCode == ERR_OK) {
361 ReportOsAccountLifeCycle(Constants::U1_ID, Constants::OPERATION_BOOT_ACTIVATED);
362 } else {
363 REPORT_OS_ACCOUNT_FAIL(Constants::U1_ID, Constants::OPERATION_BOOT_ACTIVATING, errCode,
364 "ActivateOsAccountInBackground fail isBlockBoot:" + std::to_string(config_.isBlockBoot));
365 if (config_.isBlockBoot && (errCode != ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR)) {
366 return errCode;
367 }
368 }
369 }
370 #endif // ENABLE_U1_ACCOUNT
371 OsAccountInfo osAccountInfo;
372 errCode = GetRealOsAccountInfoById(defaultActivatedId_, osAccountInfo);
373 if ((errCode != ERR_OK) || (IsValidOsAccount(osAccountInfo) != ERR_OK)) {
374 ACCOUNT_LOGE("Account not found, localId: %{public}d, error: %{public}d", defaultActivatedId_, errCode);
375 RetryToGetAccount(osAccountInfo);
376 SetDefaultActivatedOsAccount(osAccountInfo.GetLocalId());
377 }
378 // activate
379 errCode = SendMsgForAccountActivate(osAccountInfo, true, Constants::DEFAULT_DISPALY_ID, true);
380 if (errCode == ERR_OK) {
381 SetParameter(ACCOUNT_READY_EVENT, "true");
382 ReportOsAccountLifeCycle(osAccountInfo.GetLocalId(), Constants::OPERATION_BOOT_ACTIVATED);
383 }
384 #ifdef HICOLLIE_ENABLE
385 HiviewDFX::XCollie::GetInstance().CancelTimer(timerId);
386 #endif // HICOLLIE_ENABLE
387 return errCode;
388 }
389 #ifdef FUZZ_TEST
390 // LCOV_EXCL_STOP
391 #endif
392
393 void IInnerOsAccountManager::RestartActiveAccount()
394 {
395 // query active account to restart and refresh into list
396 std::vector<OsAccountInfo> osAccountInfos;
397 if (QueryAllCreatedOsAccounts(osAccountInfos) != ERR_OK) {
398 return;
399 }
400 for (const auto& osAccountInfo : osAccountInfos) {
401 std::int32_t id = osAccountInfo.GetLocalId();
402 if (osAccountInfo.GetIsActived() && id != Constants::START_USER_ID) {
403 // reactivate account state
404 if (ActivateOsAccount(id) != ERR_OK) {
405 ACCOUNT_LOGE("Active base account failed");
406 return;
407 }
408 }
409 }
410 }
411
412 void IInnerOsAccountManager::ResetAccountStatus(void)
413 {
414 std::vector<int32_t> idList;
415 (void) osAccountControl_->GetOsAccountIdList(idList);
416 for (const auto id : idList) {
417 DeactivateOsAccountById(id);
418 }
419 }
420
421 ErrCode IInnerOsAccountManager::PrepareOsAccountInfo(const std::string &name, const OsAccountType &type,
422 const DomainAccountInfo &domainInfo, OsAccountInfo &osAccountInfo)
423 {
424 return PrepareOsAccountInfo(name, "", type, domainInfo, osAccountInfo);
425 }
426
427 ErrCode IInnerOsAccountManager::PrepareOsAccountInfo(const std::string &localName, const std::string &shortName,
428 const OsAccountType &type, const DomainAccountInfo &domainInfo, OsAccountInfo &osAccountInfo)
429 {
430 ErrCode errCode = FillOsAccountInfo(localName, shortName, type, domainInfo, osAccountInfo);
431 if (errCode != ERR_OK) {
432 return errCode;
433 }
434 errCode = ValidateOsAccount(osAccountInfo);
435 if (errCode != ERR_OK) {
436 ACCOUNT_LOGE("Account name already exist, errCode %{public}d.", errCode);
437 return errCode;
438 }
439 errCode = CheckTypeNumber(type);
440 if (errCode != ERR_OK) {
441 ACCOUNT_LOGE("Check type number failed.");
442 return errCode;
443 }
444 if (!CheckAndAddLocalIdOperating(osAccountInfo.GetLocalId())) {
445 ACCOUNT_LOGW("Account id = %{public}d already in operating", osAccountInfo.GetLocalId());
446 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_OPERATING_ERROR;
447 }
448 errCode = osAccountControl_->InsertOsAccount(osAccountInfo);
449 if (errCode != ERR_OK) {
450 ACCOUNT_LOGE("Insert os account info err, errCode %{public}d.", errCode);
451 return errCode;
452 }
453 osAccountControl_->UpdateAccountIndex(osAccountInfo, false);
454
455 errCode = osAccountControl_->UpdateBaseOAConstraints(std::to_string(osAccountInfo.GetLocalId()),
456 osAccountInfo.GetConstraints(), true);
457 if (errCode != ERR_OK) {
458 ACCOUNT_LOGE("UpdateBaseOAConstraints err");
459 return errCode;
460 }
461 return ERR_OK;
462 }
463
464 ErrCode IInnerOsAccountManager::FillOsAccountInfo(const std::string &localName, const std::string &shortName,
465 const OsAccountType &type, const DomainAccountInfo &domainInfo, OsAccountInfo &osAccountInfo)
466 {
467 int64_t serialNumber;
468 ErrCode errCode = osAccountControl_->GetSerialNumber(serialNumber);
469 if (errCode != ERR_OK) {
470 ACCOUNT_LOGE("Failed to GetSerialNumber, errCode %{public}d.", errCode);
471 return errCode;
472 }
473 int id = 0;
474 if (type == OsAccountType::MAINTENANCE) {
475 id = Constants::MAINTENANCE_USER_ID;
476 } else {
477 errCode = osAccountControl_->GetAllowCreateId(id);
478 if (errCode != ERR_OK) {
479 ACCOUNT_LOGE("Failed to GetAllowCreateId, errCode %{public}d.", errCode);
480 return errCode;
481 }
482 }
483 std::vector<std::string> constraints;
484 constraints.clear();
485 errCode = osAccountControl_->GetConstraintsByType(type, constraints);
486 if (errCode != ERR_OK) {
487 ACCOUNT_LOGE("Failed to GetConstraintsByType, errCode %{public}d.", errCode);
488 return errCode;
489 }
490
491 osAccountInfo = OsAccountInfo(id, localName, shortName, type, serialNumber);
492 if (AccountPermissionManager::CheckSaCall()) {
493 osAccountInfo.SetCreatorType(TOKEN_NATIVE);
494 }
495 osAccountInfo.SetConstraints(constraints);
496 int64_t time =
497 std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();
498 osAccountInfo.SetCreateTime(time);
499 if (!osAccountInfo.SetDomainInfo(domainInfo)) {
500 ACCOUNT_LOGE("Failed to SetDomainInfo");
501 return ERR_OSACCOUNT_KIT_CREATE_OS_ACCOUNT_FOR_DOMAIN_ERROR;
502 }
503 return ERR_OK;
504 }
505
506 ErrCode IInnerOsAccountManager::PrepareOsAccountInfoWithFullInfo(OsAccountInfo &osAccountInfo)
507 {
508 int64_t serialNumber;
509 ErrCode errCode = osAccountControl_->GetSerialNumber(serialNumber);
510 if (errCode != ERR_OK) {
511 ACCOUNT_LOGE("Failed to GetSerialNumber, errCode %{public}d.", errCode);
512 return errCode;
513 }
514 osAccountInfo.SetSerialNumber(serialNumber);
515 osAccountInfo.SetIsCreateCompleted(false);
516 osAccountInfo.SetIsDataRemovable(false);
517 errCode = osAccountControl_->SetNextLocalId(osAccountInfo.GetLocalId() + 1);
518 if (errCode != ERR_OK) {
519 ACCOUNT_LOGE("Failed to SetNextLocalId, errCode %{public}d.", errCode);
520 return errCode;
521 }
522 errCode = osAccountControl_->InsertOsAccount(osAccountInfo);
523 if ((errCode != ERR_OK) && (errCode != ERR_OSACCOUNT_SERVICE_CONTROL_INSERT_FILE_EXISTS_ERROR)) {
524 ACCOUNT_LOGE("Insert os account info err, errCode %{public}d.", errCode);
525 return errCode;
526 }
527
528 osAccountControl_->UpdateAccountIndex(osAccountInfo, false);
529
530 std::vector<std::string> constraints;
531 constraints.clear();
532 OsAccountType type = static_cast<OsAccountType>(osAccountInfo.GetType());
533 errCode = osAccountControl_->GetConstraintsByType(type, constraints);
534 if (errCode != ERR_OK) {
535 ACCOUNT_LOGE("Failed to GetConstraintsByType, errCode %{public}d.", errCode);
536 return errCode;
537 }
538 std::vector<std::string> constraintsExists = osAccountInfo.GetConstraints();
539 std::vector<std::string> constraintsResult;
540 std::merge(constraints.begin(), constraints.end(), constraintsExists.begin(), constraintsExists.end(),
541 std::back_inserter(constraintsResult));
542 osAccountInfo.SetConstraints(constraintsResult);
543 errCode = osAccountControl_->UpdateBaseOAConstraints(
544 std::to_string(osAccountInfo.GetLocalId()), constraintsResult, true);
545 if (errCode != ERR_OK) {
546 ACCOUNT_LOGE("UpdateBaseOAConstraints err");
547 return errCode;
548 }
549 return ERR_OK;
550 }
551
552 bool IInnerOsAccountManager::CheckAndCleanOsAccounts()
553 {
554 unsigned int osAccountNum = 0;
555 GetNonSACreatedOACount(osAccountNum);
556
557 if (osAccountNum < config_.maxOsAccountNum) {
558 return true;
559 }
560
561 ACCOUNT_LOGI("The number of OS accounts has oversize, attempting to clean garbage accounts.");
562 if (CleanGarbageOsAccounts() <= 0) {
563 ACCOUNT_LOGE("The number of OS accounts still oversize after cleaning, max num: %{public}d",
564 config_.maxOsAccountNum);
565 return false;
566 }
567 return true;
568 }
569
570 void IInnerOsAccountManager::RollbackOsAccount(OsAccountInfo &osAccountInfo, bool needDelStorage, bool needDelBms)
571 {
572 if (!osAccountInfo.GetIsDataRemovable()) {
573 (void)osAccountControl_->DelOsAccount(osAccountInfo.GetLocalId());
574 return;
575 }
576
577 if (needDelBms) {
578 ErrCode errCode = OsAccountInterface::SendToBMSAccountDelete(osAccountInfo);
579 if (errCode != ERR_OK) {
580 ACCOUNT_LOGE("Send to bms account delete failed, errCode:%{public}d", errCode);
581 return;
582 }
583 }
584 if (needDelStorage) {
585 ErrCode errCode = OsAccountInterface::SendToStorageAccountRemove(osAccountInfo);
586 if (errCode != ERR_OK) {
587 ACCOUNT_LOGE("Send to storage account remove failed, errCode:%{public}d", errCode);
588 return;
589 }
590 }
591
592 DomainAccountInfo curDomainInfo;
593 osAccountInfo.GetDomainInfo(curDomainInfo);
594 if (curDomainInfo.accountName_.empty()) {
595 (void)osAccountControl_->DelOsAccount(osAccountInfo.GetLocalId());
596 }
597 }
598
599 ErrCode IInnerOsAccountManager::SendMsgForAccountCreate(
600 OsAccountInfo &osAccountInfo, const CreateOsAccountOptions &options)
601 {
602 ErrCode errCode = OsAccountInterface::SendToStorageAccountCreate(osAccountInfo);
603 int32_t localId = osAccountInfo.GetLocalId();
604 if (errCode != ERR_OK) {
605 ACCOUNT_LOGE("Create os account SendToStorageAccountCreate failed, errCode %{public}d.", errCode);
606 RollbackOsAccount(osAccountInfo, false, false);
607 return ERR_ACCOUNT_COMMON_GET_SYSTEM_ABILITY_MANAGER;
608 }
609 OsAccountStaticSubscriberManager::GetInstance().Publish(localId, OsAccountState::CREATING, localId);
610 errCode = OsAccountInterface::SendToBMSAccountCreate(
611 osAccountInfo, options.disallowedHapList, options.allowedHapList);
612 if (errCode != ERR_OK) {
613 ACCOUNT_LOGE("Create os account SendToBMSAccountCreate failed, errCode %{public}d.", errCode);
614 RollbackOsAccount(osAccountInfo, true, false);
615 return errCode;
616 }
617 #ifdef ENABLE_MULTIPLE_OS_ACCOUNTS
618 AppAccountControlManager::GetInstance().SetOsAccountRemoved(osAccountInfo.GetLocalId(), false);
619 #endif // ENABLE_MULTIPLE_OS_ACCOUNTS
620 osAccountInfo.SetIsCreateCompleted(true);
621 errCode = osAccountControl_->UpdateOsAccount(osAccountInfo);
622 if (errCode != ERR_OK) {
623 ACCOUNT_LOGE("Create os account when update isCreateCompleted");
624 ReportOsAccountOperationFail(localId, Constants::OPERATION_CREATE, errCode, "Failed to update OS account");
625 RollbackOsAccount(osAccountInfo, true, true);
626 return ERR_OSACCOUNT_SERVICE_INNER_UPDATE_ACCOUNT_ERROR;
627 }
628 errCode = OsAccountInterface::SendToStorageAccountCreateComplete(localId);
629 if (errCode != ERR_OK) {
630 ACCOUNT_LOGE("Failed to send storage account create complete.");
631 ReportOsAccountOperationFail(localId, Constants::OPERATION_CREATE, errCode,
632 "Failed to send storage account create complete");
633 }
634 ReportOsAccountLifeCycle(localId, Constants::OPERATION_CREATE);
635 OsAccountInterface::SendToCESAccountCreate(osAccountInfo);
636 subscribeManager_.Publish(localId, OS_ACCOUNT_SUBSCRIBE_TYPE::CREATED);
637 ACCOUNT_LOGI("OsAccountAccountMgr send to storage and bm for start success");
638 // report data size when account created
639 ReportUserDataSize(GetVerifiedAccountIds(verifiedAccounts_));
640 return ERR_OK;
641 }
642
643 ErrCode IInnerOsAccountManager::CreateOsAccount(
644 const std::string &name, const OsAccountType &type, OsAccountInfo &osAccountInfo)
645 {
646 if (!activateLockPluginManager_.IsCreationAllowed()) {
647 ACCOUNT_LOGI("Not allow creation account.");
648 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_PLUGIN_NOT_ALLOWED_CREATION_ERROR;
649 }
650 #ifdef HICOLLIE_ENABLE
651 AccountTimer timer;
652 #endif // HICOLLIE_ENABLE
653 if (!AccountPermissionManager::CheckSaCall() && !CheckAndCleanOsAccounts()) {
654 return ERR_OSACCOUNT_SERVICE_CONTROL_MAX_CAN_CREATE_ERROR;
655 }
656 DomainAccountInfo domainInfo; // default empty domain info
657 ErrCode errCode = PrepareOsAccountInfo(name, type, domainInfo, osAccountInfo);
658 if (errCode != ERR_OK) {
659 RemoveLocalIdToOperating(osAccountInfo.GetLocalId());
660 return errCode;
661 }
662 errCode = SendMsgForAccountCreate(osAccountInfo);
663 RemoveLocalIdToOperating(osAccountInfo.GetLocalId());
664 return errCode;
665 }
666
667 ErrCode IInnerOsAccountManager::UpdateFirstOsAccountInfo(OsAccountInfo& accountInfoOld, OsAccountInfo& osAccountInfo)
668 {
669 ErrCode code = osAccountControl_->UpdateOsAccount(accountInfoOld);
670 if (code != ERR_OK) {
671 ReportOsAccountOperationFail(Constants::START_USER_ID, Constants::OPERATION_CREATE, code,
672 "Failed to update OS account");
673 return code;
674 }
675 osAccountControl_->UpdateAccountIndex(accountInfoOld, false);
676 osAccountInfo = accountInfoOld;
677 return ERR_OK;
678 }
679
680 ErrCode IInnerOsAccountManager::CreateOsAccount(const std::string &localName, const std::string &shortName,
681 const OsAccountType &type, OsAccountInfo &osAccountInfo, const CreateOsAccountOptions &options)
682 {
683 if (!activateLockPluginManager_.IsCreationAllowed()) {
684 ACCOUNT_LOGI("Not allow creation account.");
685 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_PLUGIN_NOT_ALLOWED_CREATION_ERROR;
686 }
687 #ifdef HICOLLIE_ENABLE
688 AccountTimer timer;
689 #endif // HICOLLIE_ENABLE
690 osAccountInfo.SetLocalName(localName);
691 if (!AccountPermissionManager::CheckSaCall() && !CheckAndCleanOsAccounts()) {
692 return ERR_OSACCOUNT_SERVICE_CONTROL_MAX_CAN_CREATE_ERROR;
693 }
694 DomainAccountInfo domainInfo; // default empty domain info
695 ErrCode errCode = PrepareOsAccountInfo(localName, shortName, type, domainInfo, osAccountInfo);
696 if (errCode != ERR_OK) {
697 RemoveLocalIdToOperating(osAccountInfo.GetLocalId());
698 return errCode;
699 }
700 errCode = SendMsgForAccountCreate(osAccountInfo, options);
701 RemoveLocalIdToOperating(osAccountInfo.GetLocalId());
702 return errCode;
703 }
704
705 ErrCode IInnerOsAccountManager::CreateOsAccountWithFullInfo(OsAccountInfo &osAccountInfo,
706 const CreateOsAccountOptions &options)
707 {
708 if (!activateLockPluginManager_.IsCreationAllowed()) {
709 ACCOUNT_LOGI("Not allow creation account.");
710 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_PLUGIN_NOT_ALLOWED_CREATION_ERROR;
711 }
712 #ifdef HICOLLIE_ENABLE
713 AccountTimer timer;
714 #endif // HICOLLIE_ENABLE
715 if (!CheckAndAddLocalIdOperating(osAccountInfo.GetLocalId())) {
716 ACCOUNT_LOGW("Account id = %{public}d already in operating", osAccountInfo.GetLocalId());
717 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_OPERATING_ERROR;
718 }
719
720 OsAccountInfo oldInfo;
721 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(osAccountInfo.GetLocalId(), oldInfo);
722 if (errCode != ERR_OK && errCode != ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR) {
723 ReportOsAccountOperationFail(osAccountInfo.GetLocalId(), Constants::OPERATION_CREATE, errCode,
724 "Get account info failed when create osaccount with full info");
725 RemoveLocalIdToOperating(osAccountInfo.GetLocalId());
726 return errCode;
727 }
728 if (errCode == ERR_OK && oldInfo.GetIsCreateCompleted()) {
729 if (oldInfo.GetToBeRemoved()) {
730 ReportOsAccountOperationFail(osAccountInfo.GetLocalId(), Constants::OPERATION_CREATE, errCode,
731 "Remove garbage account before create osaccount with full info");
732 ACCOUNT_LOGW("Account %{public}d is to be removed, remove it first.", osAccountInfo.GetLocalId());
733 errCode = RemoveOsAccountOperate(osAccountInfo.GetLocalId(), osAccountInfo);
734 if (errCode != ERR_OK) {
735 RemoveLocalIdToOperating(osAccountInfo.GetLocalId());
736 return errCode;
737 }
738 } else {
739 ReportOsAccountOperationFail(osAccountInfo.GetLocalId(), Constants::OPERATION_CREATE, errCode,
740 "Account already exists when create osaccount with full info");
741 ACCOUNT_LOGW("Account %{public}d already exists.", osAccountInfo.GetLocalId());
742 RemoveLocalIdToOperating(osAccountInfo.GetLocalId());
743 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_ALREADY_EXIST_ERROR;
744 }
745 }
746
747 errCode = PrepareOsAccountInfoWithFullInfo(osAccountInfo);
748 if (errCode != ERR_OK) {
749 RemoveLocalIdToOperating(osAccountInfo.GetLocalId());
750 return errCode;
751 }
752 errCode = SendMsgForAccountCreate(osAccountInfo, options);
753 RemoveLocalIdToOperating(osAccountInfo.GetLocalId());
754 return errCode;
755 }
756
757 #ifdef SUPPORT_DOMAIN_ACCOUNTS
758 ErrCode IInnerOsAccountManager::UpdateAccountStatusForDomain(const int id, DomainAccountStatus status)
759 {
760 OsAccountInfo accountInfo;
761 DomainAccountInfo domainInfo;
762 ErrCode errCode = GetOsAccountInfoById(id, accountInfo);
763 if (errCode != ERR_OK) {
764 return errCode;
765 }
766 accountInfo.GetDomainInfo(domainInfo);
767 domainInfo.status_ = status;
768 accountInfo.SetDomainInfo(domainInfo);
769
770 errCode = osAccountControl_->UpdateOsAccount(accountInfo);
771 if (errCode != ERR_OK) {
772 ACCOUNT_LOGE("update osaccount info error %{public}d, id: %{public}d", errCode, accountInfo.GetLocalId());
773 return errCode;
774 }
775 return ERR_OK;
776 }
777 #endif // SUPPORT_DOMAIN_ACCOUNTS
778
779 ErrCode IInnerOsAccountManager::UpdateOsAccountWithFullInfo(OsAccountInfo &newInfo)
780 {
781 int32_t localId = newInfo.GetLocalId();
782 if (!CheckAndAddLocalIdOperating(localId)) {
783 ACCOUNT_LOGE("The %{public}d already in operating", localId);
784 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_OPERATING_ERROR;
785 }
786 OsAccountInfo oldInfo;
787 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(localId, oldInfo);
788 if (errCode != ERR_OK) {
789 RemoveLocalIdToOperating(localId);
790 return errCode;
791 }
792 oldInfo.SetLocalName(newInfo.GetLocalName());
793 oldInfo.SetType(newInfo.GetType());
794 oldInfo.SetPhoto(newInfo.GetPhoto());
795 oldInfo.SetConstraints(newInfo.GetConstraints());
796 errCode = osAccountControl_->UpdateOsAccount(oldInfo);
797 osAccountControl_->UpdateAccountIndex(oldInfo, false);
798 newInfo = oldInfo;
799 if (errCode != ERR_OK) {
800 ReportOsAccountOperationFail(localId, OPERATION_UPDATE, errCode, "UpdateOsAccount failed!");
801 } else {
802 OsAccountInterface::PublishCommonEvent(oldInfo,
803 OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_USER_INFO_UPDATED, OPERATION_UPDATE);
804 }
805 RemoveLocalIdToOperating(localId);
806 return errCode;
807 }
808
809 #ifdef SUPPORT_DOMAIN_ACCOUNTS
810 ErrCode IInnerOsAccountManager::GetOsAccountsByDomainInfo(const DomainAccountInfo &info,
811 std::vector<OsAccountInfo> &osAccountInfos)
812 {
813 std::vector<int32_t> allOsAccountIds;
814 ErrCode errCode = osAccountControl_->GetOsAccountIdList(allOsAccountIds);
815 if (errCode != ERR_OK) {
816 ACCOUNT_LOGE("Get osaccount info list error, errCode %{public}d.", errCode);
817 return errCode;
818 }
819 for (auto id : allOsAccountIds) {
820 OsAccountInfo osAccountInfo;
821 GetRealOsAccountInfoById(id, osAccountInfo);
822 DomainAccountInfo curInfo;
823 osAccountInfo.GetDomainInfo(curInfo);
824 errCode = InnerDomainAccountManager::GetInstance().CheckAndRecoverBindDomainForUncomplete(osAccountInfo);
825 if (errCode != ERR_OK) {
826 ACCOUNT_LOGE("Recover bind domain error, errCode = %{public}d.", errCode);
827 REPORT_OS_ACCOUNT_FAIL(osAccountInfo.GetLocalId(), Constants::OPERATION_RECOVER_BIND_DOMAIN_ACCOUNT,
828 errCode, "Recover bind domain error.");
829 return errCode;
830 }
831 if ((!info.accountId_.empty() && curInfo.accountId_ == info.accountId_) ||
832 ((curInfo.accountName_ == info.accountName_) && (curInfo.domain_ == info.domain_))) {
833 osAccountInfos.emplace_back(osAccountInfo);
834 }
835 }
836 return ERR_OK;
837 }
838
839 ErrCode IInnerOsAccountManager::CheckDomainAccountBound(const DomainAccountInfo &info, bool &isBound)
840 {
841 std::vector<OsAccountInfo> osAccountInfos;
842 ErrCode result = GetOsAccountsByDomainInfo(info, osAccountInfos);
843 if (result != ERR_OK) {
844 return result;
845 }
846 osAccountInfos.erase(std::remove_if(osAccountInfos.begin(), osAccountInfos.end(),
847 [this](OsAccountInfo osAccountInfo) {
848 if (osAccountInfo.GetIsCreateCompleted() && !osAccountInfo.GetToBeRemoved()) {
849 ACCOUNT_LOGI("The domain account is already bound.");
850 return false;
851 }
852 int32_t id = osAccountInfo.GetLocalId();
853 if (!this->CheckAndAddLocalIdOperating(id)) {
854 ACCOUNT_LOGE("Account id = %{public}d already in operating", id);
855 return false;
856 }
857 ErrCode errCode = this->RemoveOsAccountOperate(id, osAccountInfo, true);
858 this->RemoveLocalIdToOperating(id);
859 if (errCode != ERR_OK) {
860 REPORT_OS_ACCOUNT_FAIL(id, Constants::OPERATION_CLEAN,
861 errCode, "Clean garbage os accounts failed");
862 ACCOUNT_LOGE("Remove account %{public}d failed! errCode %{public}d.", id, errCode);
863 return false;
864 }
865 ACCOUNT_LOGI("Remove account %{public}d succeed!", id);
866 return true;
867 }), osAccountInfos.end());
868 isBound = osAccountInfos.size() != 0;
869 return ERR_OK;
870 }
871
872 ErrCode IInnerOsAccountManager::BindDomainAccount(const OsAccountType &type,
873 const DomainAccountInfo &domainAccountInfo, OsAccountInfo &osAccountInfo,
874 const CreateOsAccountForDomainOptions &options)
875 {
876 bool isBound = false;
877 ErrCode errCode = CheckDomainAccountBound(domainAccountInfo, isBound);
878 if (errCode != ERR_OK) {
879 return errCode;
880 }
881 if (isBound) {
882 ACCOUNT_LOGE("The domain account is already bound");
883 return ERR_OSACCOUNT_SERVICE_INNER_DOMAIN_ALREADY_BIND_ERROR;
884 }
885 #ifdef ENABLE_MULTIPLE_OS_ACCOUNTS
886 bool isEnabled = false;
887 if (IsOsAccountConstraintEnable(Constants::START_USER_ID,
888 CONSTRAINT_CREATE_ACCOUNT_DIRECTLY, isEnabled) != ERR_OK) {
889 return ERR_OSACCOUNT_KIT_IS_OS_ACCOUNT_CONSTRAINT_ENABLE_ERROR;
890 }
891 #else
892 bool isEnabled = true;
893 #endif // ENABLE_MULTIPLE_OS_ACCOUNTS
894 std::vector<OsAccountInfo> osAccountInfos;
895 errCode = QueryAllCreatedOsAccounts(osAccountInfos);
896 if (errCode != ERR_OK) {
897 ACCOUNT_LOGE("Query all created osAccount failed, errCode:%{public}d", errCode);
898 return errCode;
899 }
900 if (isEnabled && (osAccountInfos.size() == 1) && (osAccountInfos[0].GetLocalId() == Constants::START_USER_ID)) {
901 DomainAccountInfo curDomainInfo;
902 osAccountInfos[0].GetDomainInfo(curDomainInfo);
903 if (curDomainInfo.domain_.empty()) {
904 osAccountInfos[0].SetLocalName(domainAccountInfo.accountName_);
905 osAccountInfos[0].SetShortName(options.shortName);
906 osAccountInfos[0].SetDomainInfo(domainAccountInfo);
907 osAccountInfo = osAccountInfos[0];
908 }
909 }
910 if (osAccountInfo.GetLocalId() != Constants::START_USER_ID) {
911 #ifdef ENABLE_MULTIPLE_OS_ACCOUNTS
912 errCode = PrepareOsAccountInfo(domainAccountInfo.accountName_, options.shortName,
913 type, domainAccountInfo, osAccountInfo);
914 RemoveLocalIdToOperating(osAccountInfo.GetLocalId());
915 if (errCode != ERR_OK) {
916 return errCode;
917 }
918 #else
919 ACCOUNT_LOGW("Multiple os accounts feature not enabled");
920 return ERR_OSACCOUNT_SERVICE_MANAGER_NOT_ENABLE_MULTI_ERROR;
921 #endif // ENABLE_MULTIPLE_OS_ACCOUNTS
922 }
923 errCode = osAccountControl_->UpdateAccountIndex(osAccountInfo, false);
924 if (errCode != ERR_OK) {
925 ACCOUNT_LOGE("Failed to update account index.");
926 return errCode;
927 }
928 errCode = osAccountControl_->UpdateOsAccount(osAccountInfo);
929 if (errCode != ERR_OK) {
930 ACCOUNT_LOGE("Failed to update osaccount.");
931 }
932 return errCode;
933 }
934 #endif // SUPPORT_DOMAIN_ACCOUNTS
935
936 ErrCode IInnerOsAccountManager::CreateOsAccountForDomain(
937 const OsAccountType &type, const DomainAccountInfo &domainInfo, const sptr<IDomainAccountCallback> &callback,
938 const CreateOsAccountForDomainOptions &options)
939 {
940 #ifdef SUPPORT_DOMAIN_ACCOUNTS
941 std::lock_guard<std::mutex> lock(createOrBindDomainAccountMutex_);
942 if (!activateLockPluginManager_.IsCreationAllowed()) {
943 ACCOUNT_LOGI("Not allow creation account.");
944 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_PLUGIN_NOT_ALLOWED_CREATION_ERROR;
945 }
946 #ifdef HICOLLIE_ENABLE
947 AccountTimer timer;
948 #endif // HICOLLIE_ENABLE
949 bool isBound = false;
950 ErrCode errCode = CheckDomainAccountBound(domainInfo, isBound);
951 if (errCode != ERR_OK) {
952 ACCOUNT_LOGE("The domain account is already bound");
953 return errCode;
954 }
955 if (isBound) {
956 return ERR_OSACCOUNT_SERVICE_INNER_DOMAIN_ALREADY_BIND_ERROR;
957 }
958 std::vector<OsAccountInfo> osAccountInfos;
959 errCode = QueryAllCreatedOsAccounts(osAccountInfos);
960 if (errCode != ERR_OK) {
961 ACCOUNT_LOGE("Query all created osAccount failed, errCode:%{public}d", errCode);
962 return errCode;
963 }
964 unsigned int saCreatedNum = 0;
965 for (const auto& it : osAccountInfos) {
966 if (it.GetCreatorType() == TOKEN_NATIVE) {
967 ++saCreatedNum;
968 }
969 }
970 if (!AccountPermissionManager::CheckSaCall() && (osAccountInfos.size() - saCreatedNum) >= config_.maxOsAccountNum) {
971 ACCOUNT_LOGE("The number of OS accounts has oversize, max num: %{public}d", config_.maxOsAccountNum);
972 return ERR_OSACCOUNT_SERVICE_CONTROL_MAX_CAN_CREATE_ERROR;
973 }
974 if (!InnerDomainAccountManager::GetInstance().IsPluginAvailable()) {
975 ACCOUNT_LOGE("Plugin is not available");
976 return ERR_DOMAIN_ACCOUNT_SERVICE_PLUGIN_NOT_EXIST;
977 }
978 sptr<CheckAndCreateDomainAccountCallback> callbackWrapper =
979 new (std::nothrow) CheckAndCreateDomainAccountCallback(osAccountControl_, type, callback, options);
980 if (callbackWrapper == nullptr) {
981 ACCOUNT_LOGE("New DomainCreateDomainCallback failed");
982 return ERR_ACCOUNT_COMMON_INSUFFICIENT_MEMORY_ERROR;
983 }
984 return InnerDomainAccountManager::GetInstance().GetDomainAccountInfo(domainInfo, callbackWrapper);
985 #else
986 return ERR_DOMAIN_ACCOUNT_NOT_SUPPORT;
987 #endif // SUPPORT_DOMAIN_ACCOUNTS
988 }
989
990 void IInnerOsAccountManager::CheckAndRefreshLocalIdRecord(const int id)
991 {
992 std::lock_guard<std::mutex> lock(operatingMutex_);
993 if (id == defaultActivatedId_) {
994 ACCOUNT_LOGI("Remove default activated id %{public}d", id);
995 osAccountControl_->SetDefaultActivatedOsAccount(Constants::START_USER_ID);
996 defaultActivatedId_ = Constants::START_USER_ID;
997 }
998 if (id == deviceOwnerId_) {
999 osAccountControl_->UpdateDeviceOwnerId(-1);
1000 }
1001 return;
1002 }
1003
1004 ErrCode IInnerOsAccountManager::PrepareRemoveOsAccount(OsAccountInfo &osAccountInfo, bool isCleanGarbage)
1005 {
1006 int32_t id = osAccountInfo.GetLocalId();
1007 ErrCode errCode = ERR_OK;
1008 #ifdef HAS_USER_IDM_PART
1009 errCode = OsAccountInterface::SendToIDMAccountDelete(osAccountInfo);
1010 if (errCode != ERR_OK) {
1011 ACCOUNT_LOGE("SendToIDMAccountDelete failed, id %{public}d, errCode %{public}d",
1012 osAccountInfo.GetLocalId(), errCode);
1013 return errCode;
1014 }
1015 #endif // HAS_USER_IDM_PART
1016 #ifdef SUPPORT_DOMAIN_ACCOUNTS
1017 DomainAccountInfo curDomainInfo;
1018 osAccountInfo.GetDomainInfo(curDomainInfo);
1019 if (!curDomainInfo.accountName_.empty()) {
1020 InnerDomainAccountManager::GetInstance().OnAccountUnBound(curDomainInfo, nullptr, id);
1021 InnerDomainAccountManager::GetInstance().RemoveTokenFromMap(id);
1022 }
1023 #endif // SUPPORT_DOMAIN_ACCOUNTS
1024 if (isCleanGarbage) {
1025 ACCOUNT_LOGI("Clean garbage account data, no need to deal foreground status.");
1026 return ERR_OK;
1027 }
1028 if (osAccountInfo.GetIsForeground()) {
1029 ACCOUNT_LOGI("Remove foreground account id=%{public}d.", id);
1030 if (ActivateOsAccount(Constants::START_USER_ID) != ERR_OK) {
1031 ACCOUNT_LOGE("RemoveOsAccount active base account failed");
1032 return ERR_OSACCOUNT_SERVICE_INNER_REMOVE_ACCOUNT_ACTIVED_ERROR;
1033 }
1034 std::this_thread::sleep_for(std::chrono::milliseconds(DELAY_FOR_REMOVING_FOREGROUND_OS_ACCOUNT));
1035 }
1036 loggedInAccounts_.Erase(id);
1037 verifiedAccounts_.Erase(id);
1038 // stop account
1039 OsAccountInterface::PublishCommonEvent(
1040 osAccountInfo, OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_USER_STOPPING, Constants::OPERATION_STOP);
1041 subscribeManager_.Publish(id, OS_ACCOUNT_SUBSCRIBE_TYPE::STOPPING);
1042 errCode = SendMsgForAccountStop(osAccountInfo);
1043 if (errCode != ERR_OK) {
1044 ReportOsAccountOperationFail(id, "stop", errCode, "stop os account failed");
1045 return errCode;
1046 }
1047
1048 OsAccountInterface::PublishCommonEvent(
1049 osAccountInfo, OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_USER_STOPPED, Constants::OPERATION_STOP);
1050 subscribeManager_.Publish(id, OS_ACCOUNT_SUBSCRIBE_TYPE::STOPPED);
1051 ReportOsAccountLifeCycle(id, Constants::OPERATION_STOP);
1052 return errCode;
1053 }
1054
1055 ErrCode IInnerOsAccountManager::RemoveOsAccountOperate(const int id, OsAccountInfo &osAccountInfo, bool isCleanGarbage)
1056 {
1057 if (isCleanGarbage && (!osAccountInfo.GetIsCreateCompleted()) && (!osAccountInfo.GetIsDataRemovable())) {
1058 ACCOUNT_LOGI("Account cannot be removed id=%{public}d.", id);
1059 return ERR_OK;
1060 }
1061 ErrCode errCode = PrepareRemoveOsAccount(osAccountInfo, isCleanGarbage);
1062 if (errCode != ERR_OK) {
1063 ACCOUNT_LOGE("PrepareRemoveOsAccount failed, errCode %{public}d.", errCode);
1064 return errCode;
1065 }
1066 #ifdef SUPPORT_DOMAIN_ACCOUNTS
1067 DomainAccountInfo domainAccountInfo;
1068 osAccountInfo.GetDomainInfo(domainAccountInfo);
1069 if (!domainAccountInfo.accountName_.empty()) {
1070 InnerDomainAccountManager::GetInstance().NotifyDomainAccountEvent(
1071 id, DomainAccountEvent::LOG_OUT, DomainAccountStatus::LOGOUT, domainAccountInfo);
1072 }
1073 #endif // SUPPORT_DOMAIN_ACCOUNTS
1074 AccountInfo ohosInfo;
1075 (void)OhosAccountManager::GetInstance().GetAccountInfoByUserId(id, ohosInfo);
1076 if (ohosInfo.ohosAccountInfo_.name_ != DEFAULT_OHOS_ACCOUNT_NAME) {
1077 #ifdef HAS_CES_PART
1078 AccountEventProvider::EventPublishAsUser(
1079 EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT, id);
1080 AccountEventProvider::EventPublishAsUser(
1081 EventFwk::CommonEventSupport::COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGOUT, id);
1082 #else // HAS_CES_PART
1083 ACCOUNT_LOGI("No common event part! Publish nothing!");
1084 #endif // HAS_CES_PART
1085 }
1086 errCode = SendMsgForAccountRemove(osAccountInfo);
1087 if (errCode != ERR_OK) {
1088 return errCode;
1089 }
1090
1091 errCode = osAccountControl_->RemoveOAConstraintsInfo(id);
1092 if (errCode != ERR_OK) {
1093 ACCOUNT_LOGE("RemoveOsAccount failed to remove os account constraints info");
1094 return errCode;
1095 }
1096 CheckAndRefreshLocalIdRecord(id);
1097 subscribeManager_.Publish(id, OS_ACCOUNT_SUBSCRIBE_TYPE::REMOVED);
1098 return errCode;
1099 }
1100
1101 ErrCode IInnerOsAccountManager::RemoveOsAccount(const int id)
1102 {
1103 ACCOUNT_LOGI("Remove id is %{public}d", id);
1104 if (!CheckAndAddLocalIdOperating(id)) {
1105 ACCOUNT_LOGE("The %{public}d already in operating", id);
1106 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_OPERATING_ERROR;
1107 }
1108
1109 OsAccountInfo osAccountInfo;
1110 ErrCode errCode = GetRealOsAccountInfoById(id, osAccountInfo);
1111 if (errCode != ERR_OK) {
1112 RemoveLocalIdToOperating(id);
1113 ACCOUNT_LOGE("RemoveOsAccount cannot find os account info, errCode %{public}d.", errCode);
1114 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1115 }
1116 errCode = OsAccountInterface::SendToStorageAccountCreateComplete(id);
1117 if (errCode != ERR_OK) {
1118 RemoveLocalIdToOperating(id);
1119 ACCOUNT_LOGE("SendToStorageAccountCreateComplete failed, errCode=%{public}d, id=%{public}d", errCode, id);
1120 return errCode;
1121 }
1122 // set remove flag first
1123 osAccountInfo.SetToBeRemoved(true);
1124 errCode = osAccountControl_->UpdateOsAccount(osAccountInfo);
1125 if (errCode != ERR_OK) {
1126 ACCOUNT_LOGE("Failed to update ToBeRemoved status, errCode=%{public}d.", errCode);
1127 ReportOsAccountOperationFail(id, Constants::OPERATION_REMOVE, errCode, "Failed to update ToBeRemoved status");
1128 return errCode;
1129 }
1130
1131 // then remove account
1132 errCode = RemoveOsAccountOperate(id, osAccountInfo);
1133 RemoveLocalIdToOperating(id);
1134 return errCode;
1135 }
1136
1137 ErrCode IInnerOsAccountManager::SendMsgForAccountStop(OsAccountInfo &osAccountInfo)
1138 {
1139 ErrCode errCode = OsAccountInterface::SendToAMSAccountStop(osAccountInfo);
1140 if (errCode != ERR_OK) {
1141 ACCOUNT_LOGE("SendToAMSAccountStop failed, id %{public}d, errCode %{public}d",
1142 osAccountInfo.GetLocalId(), errCode);
1143 return errCode;
1144 }
1145 errCode = OsAccountInterface::CheckAllAppDied(osAccountInfo.GetLocalId());
1146 if (errCode != ERR_OK) {
1147 ACCOUNT_LOGE("CheckAllAppDied failed, operation is timeout");
1148 return errCode;
1149 }
1150 errCode = OsAccountInterface::SendToStorageAccountStop(osAccountInfo);
1151 if (errCode != ERR_OK && errCode != ERR_OSACCOUNT_SERVICE_STORAGE_STOP_USER_FAILED) {
1152 ACCOUNT_LOGE("SendToStorageAccountStop failed, id %{public}d, errCode %{public}d",
1153 osAccountInfo.GetLocalId(), errCode);
1154 return ERR_ACCOUNT_COMMON_GET_SYSTEM_ABILITY_MANAGER;
1155 }
1156 return DeactivateOsAccountByInfo(osAccountInfo);
1157 }
1158
1159 ErrCode IInnerOsAccountManager::SendMsgForAccountDeactivate(OsAccountInfo &osAccountInfo, bool isStopStorage)
1160 {
1161 int32_t localId = osAccountInfo.GetLocalId();
1162 ErrCode errCode = OsAccountInterface::SendToAMSAccountDeactivate(osAccountInfo);
1163 if (errCode != ERR_OK) {
1164 ACCOUNT_LOGE("SendToAMSAccountDeactivate failed, id %{public}d, errCode %{public}d", localId, errCode);
1165 return errCode;
1166 }
1167 int32_t foregroundId = -1;
1168 if (foregroundAccountMap_.Find(Constants::DEFAULT_DISPALY_ID, foregroundId) && foregroundId == localId) {
1169 foregroundAccountMap_.Erase(Constants::DEFAULT_DISPALY_ID);
1170 }
1171 errCode = subscribeManager_.Publish(localId, OS_ACCOUNT_SUBSCRIBE_TYPE::STOPPING);
1172 if (errCode != ERR_OK) {
1173 ReportOsAccountOperationFail(localId, Constants::OPERATION_STOP, errCode,
1174 "Failed to publish stopping notification");
1175 }
1176 if (isStopStorage) {
1177 errCode = OsAccountInterface::SendToStorageAccountStop(osAccountInfo);
1178 if (errCode != ERR_OK) {
1179 ACCOUNT_LOGE("SendToStorageAccountStop failed, id %{public}d, errCode %{public}d", localId, errCode);
1180 return errCode;
1181 }
1182 }
1183
1184 return DeactivateOsAccountByInfo(osAccountInfo);
1185 }
1186
1187 bool IInnerOsAccountManager::IsToBeRemoved(int32_t localId)
1188 {
1189 OsAccountInfo osAccountInfo;
1190 ErrCode ret = GetRealOsAccountInfoById(localId, osAccountInfo);
1191 if (ret == ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR) {
1192 return true;
1193 }
1194 return osAccountInfo.GetToBeRemoved();
1195 }
1196
1197 ErrCode IInnerOsAccountManager::ValidateOsAccount(const OsAccountInfo &osAccountInfo)
1198 {
1199 if (osAccountInfo.GetType() == OsAccountType::PRIVATE) {
1200 return ERR_OK;
1201 }
1202 auto accountIndexJson = CreateJson();
1203 ErrCode result = osAccountControl_->GetAccountIndexFromFile(accountIndexJson);
1204 if (result != ERR_OK) {
1205 return result;
1206 }
1207 int32_t id = osAccountInfo.GetLocalId();
1208 cJSON *element = nullptr;
1209 cJSON_ArrayForEach(element, accountIndexJson) {
1210 int32_t localId = 0;
1211 std::string key(element->string);
1212 if (!StrToInt(key, localId)) {
1213 ACCOUNT_LOGE("Convert localId failed");
1214 continue;
1215 }
1216 cJSON *nameObj = GetObjFromJson(accountIndexJson, key);
1217 std::string localName;
1218 if (GetStringFromJson(nameObj, Constants::LOCAL_NAME, localName) &&
1219 (osAccountInfo.GetLocalName() == localName) && (localId != id) && !IsToBeRemoved(localId)) {
1220 return ERR_ACCOUNT_COMMON_NAME_HAD_EXISTED;
1221 }
1222 if (!osAccountInfo.GetShortName().empty()) {
1223 std::string shortName;
1224 if (GetStringFromJson(nameObj, Constants::SHORT_NAME, shortName) &&
1225 (osAccountInfo.GetShortName() == shortName) && (localId != id) && !IsToBeRemoved(localId)) {
1226 return ERR_ACCOUNT_COMMON_SHORT_NAME_HAD_EXISTED;
1227 }
1228 }
1229 }
1230 return ERR_OK;
1231 }
1232
1233 ErrCode IInnerOsAccountManager::GetTypeNumber(const OsAccountType& type, int32_t& typeNumber)
1234 {
1235 typeNumber = 0;
1236 std::vector<OsAccountInfo> osAccountList;
1237 ErrCode result = QueryAllCreatedOsAccounts(osAccountList);
1238 if (result != ERR_OK) {
1239 ACCOUNT_LOGE("Get os account list failed.");
1240 return result;
1241 }
1242
1243 typeNumber = std::count_if(osAccountList.begin(), osAccountList.end(),
1244 [&type](const OsAccountInfo& info) { return info.GetType() == type; });
1245 return ERR_OK;
1246 }
1247
1248 ErrCode IInnerOsAccountManager::CheckTypeNumber(const OsAccountType& type)
1249 {
1250 if (type != OsAccountType::PRIVATE && type != OsAccountType::MAINTENANCE) {
1251 return ERR_OK;
1252 }
1253 int32_t typeNumber = 0;
1254 ErrCode result = GetTypeNumber(type, typeNumber);
1255 if (result != ERR_OK) {
1256 ACCOUNT_LOGE("Count type number failed.");
1257 return result;
1258 }
1259 if (type == OsAccountType::PRIVATE && typeNumber >= MAX_PRIVATE_TYPE_NUMBER) {
1260 ACCOUNT_LOGE("Check type number failed, private type number=%{public}d", typeNumber);
1261 return ERR_OSACCOUNT_SERVICE_CONTROL_MAX_CAN_CREATE_ERROR;
1262 }
1263 if (type == OsAccountType::MAINTENANCE && typeNumber >= MAX_MAINTENANCE_TYPE_NUMBER) {
1264 ACCOUNT_LOGE("Check type number failed, maintenance type number=%{public}d", typeNumber);
1265 return ERR_OSACCOUNT_SERVICE_CONTROL_MAX_CAN_CREATE_ERROR;
1266 }
1267 return ERR_OK;
1268 }
1269
1270 ErrCode IInnerOsAccountManager::SendMsgForAccountRemove(OsAccountInfo &osAccountInfo)
1271 {
1272 int32_t localId = osAccountInfo.GetLocalId();
1273 #ifdef ENABLE_MULTIPLE_OS_ACCOUNTS
1274 AppAccountControlManager::GetInstance().SetOsAccountRemoved(localId, true);
1275 #endif // ENABLE_MULTIPLE_OS_ACCOUNTS
1276 ErrCode errCode = OsAccountInterface::SendToBMSAccountDelete(osAccountInfo);
1277 if (errCode != ERR_OK) {
1278 ACCOUNT_LOGE("SendToBMSAccountDelete failed, id %{public}d, errCode %{public}d", localId, errCode);
1279 return errCode;
1280 }
1281 errCode = OsAccountInterface::SendToStorageAccountRemove(osAccountInfo);
1282 if (errCode != ERR_OK) {
1283 ACCOUNT_LOGE("SendToStorageAccountRemove failed, id %{public}d, errCode %{public}d", localId, errCode);
1284 return ERR_ACCOUNT_COMMON_GET_SYSTEM_ABILITY_MANAGER;
1285 }
1286 errCode = osAccountControl_->DelOsAccount(localId);
1287 if (errCode != ERR_OK) {
1288 ACCOUNT_LOGE("Remove osaccount info failed, id: %{public}d, errCode %{public}d", localId, errCode);
1289 return errCode;
1290 }
1291 OsAccountInterface::SendToCESAccountDelete(osAccountInfo);
1292 ReportOsAccountLifeCycle(localId, Constants::OPERATION_REMOVE);
1293 // report data size when account removed
1294 ReportUserDataSize(GetVerifiedAccountIds(verifiedAccounts_));
1295 return errCode;
1296 }
1297
1298 bool IInnerOsAccountManager::Init(const std::set<int32_t> &initAccounts)
1299 {
1300 ACCOUNT_LOGI("Start to create base os accounts");
1301 CreateBaseAdminAccount();
1302 // 100 need created
1303 bool isFirstBoot = initAccounts.find(Constants::START_USER_ID) != initAccounts.end();
1304 #ifdef ENABLE_U1_ACCOUNT
1305 if (initAccounts.find(Constants::U1_ID) != initAccounts.end() && config_.isU1Enable) {
1306 OsAccountInfo osAccountInfo(Constants::U1_ID, config_.u1AccountName, config_.u1AccountType);
1307 bool result = CreateBaseStandardAccount(osAccountInfo);
1308 // create u1 fail and block boot and 100 has not created
1309 if (!result) {
1310 ACCOUNT_LOGE("Create u1 error, result:%{public}d, isBlockBoot:%{public}d, isFirstBoot:%{public}d.",
1311 result, config_.isBlockBoot, isFirstBoot);
1312 ReportOsAccountOperationFail(Constants::U1_ID, Constants::OPERATION_BOOT_CREATE,
1313 result, "Create u1 error, isBlockBoot:" +
1314 std::to_string(config_.isBlockBoot) + ", isFirstBoot:%{public}d." + std::to_string(isFirstBoot));
1315 if (config_.isBlockBoot && isFirstBoot) {
1316 return false;
1317 }
1318 }
1319 }
1320 #endif // ENABLE_U1_ACCOUNT
1321 if (isFirstBoot) {
1322 #ifdef ENABLE_DEFAULT_ADMIN_NAME
1323 OsAccountInfo osAccountInfo(Constants::START_USER_ID, STANDARD_LOCAL_NAME,
1324 OsAccountType::ADMIN);
1325 #else
1326 OsAccountInfo osAccountInfo(Constants::START_USER_ID, "", OsAccountType::ADMIN);
1327 #endif //ENABLE_DEFAULT_ADMIN_NAME
1328 CreateBaseStandardAccount(osAccountInfo);
1329 SetDefaultActivatedOsAccount(osAccountInfo.GetLocalId());
1330 }
1331 ACCOUNT_LOGI("End to create base os accounts");
1332 return true;
1333 }
1334
1335 ErrCode IInnerOsAccountManager::IsOsAccountExists(const int id, bool &isOsAccountExits)
1336 {
1337 isOsAccountExits = false;
1338 osAccountControl_->IsOsAccountExists(id, isOsAccountExits);
1339 return ERR_OK;
1340 }
1341
1342 ErrCode IInnerOsAccountManager::IsOsAccountActived(const int id, bool &isOsAccountActived)
1343 {
1344 isOsAccountActived = false;
1345
1346 // check if os account exists
1347 OsAccountInfo osAccountInfo;
1348 ErrCode errCode = GetRealOsAccountInfoById(id, osAccountInfo);
1349 if (errCode != ERR_OK) {
1350 ACCOUNT_LOGE("Get osaccount info error, errCode %{public}d.", errCode);
1351 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1352 }
1353 if (id == Constants::ADMIN_LOCAL_ID) {
1354 isOsAccountActived = true;
1355 return ERR_OK;
1356 }
1357 isOsAccountActived = osAccountInfo.GetIsActived();
1358 return ERR_OK;
1359 }
1360
1361 ErrCode IInnerOsAccountManager::IsOsAccountConstraintEnable(
1362 const int id, const std::string &constraint, bool &isOsAccountConstraintEnable)
1363 {
1364 isOsAccountConstraintEnable = false;
1365 OsAccountInfo osAccountInfo;
1366 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(id, osAccountInfo);
1367 if (errCode != ERR_OK) {
1368 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1369 }
1370 std::vector<std::string> constraints;
1371 constraints = osAccountInfo.GetConstraints();
1372 if (std::find(constraints.begin(), constraints.end(), constraint) != constraints.end()) {
1373 isOsAccountConstraintEnable = true;
1374 return ERR_OK;
1375 }
1376 constraints.clear();
1377 if (osAccountControl_->GetGlobalOAConstraintsList(constraints) == ERR_OK) {
1378 if (std::find(constraints.begin(), constraints.end(), constraint) != constraints.end()) {
1379 isOsAccountConstraintEnable = true;
1380 return ERR_OK;
1381 }
1382 }
1383 constraints.clear();
1384 if (osAccountControl_->GetSpecificOAConstraintsList(id, constraints) == ERR_OK) {
1385 if (std::find(constraints.begin(), constraints.end(), constraint) != constraints.end()) {
1386 isOsAccountConstraintEnable = true;
1387 return ERR_OK;
1388 }
1389 }
1390 return ERR_OK;
1391 }
1392
1393 ErrCode IInnerOsAccountManager::IsOsAccountVerified(const int id, bool &isVerified)
1394 {
1395 OsAccountInfo osAccountInfo;
1396 ErrCode errCode = GetRealOsAccountInfoById(id, osAccountInfo);
1397 if (errCode != ERR_OK) {
1398 ACCOUNT_LOGE("Get osaccount fail, errCode=%{public}d, id=%{public}d", errCode, id);
1399 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1400 }
1401 isVerified = osAccountInfo.GetIsVerified();
1402 return ERR_OK;
1403 }
1404
1405 ErrCode IInnerOsAccountManager::IsOsAccountDeactivating(const int id, bool &isDeactivating)
1406 {
1407 isDeactivating = false;
1408 deactivatingAccounts_.Find(id, isDeactivating);
1409 return ERR_OK;
1410 }
1411
1412 #ifdef FUZZ_TEST
1413 // LCOV_EXCL_START
1414 #endif
1415 ErrCode IInnerOsAccountManager::GetCreatedOsAccountsCount(unsigned int &createdOsAccountCount)
1416 {
1417 std::vector<int32_t> idList;
1418 ErrCode errCode = osAccountControl_->GetOsAccountIdList(idList);
1419 if (errCode != ERR_OK) {
1420 ACCOUNT_LOGE("Get osaccount info list error, errCode %{public}d.", errCode);
1421 return errCode;
1422 }
1423 createdOsAccountCount = idList.size();
1424 return ERR_OK;
1425 }
1426 #ifdef FUZZ_TEST
1427 // LCOV_EXCL_STOP
1428 #endif
1429
1430 #ifdef FUZZ_TEST
1431 // LCOV_EXCL_START
1432 #endif
1433 ErrCode IInnerOsAccountManager::GetNonSACreatedOACount(unsigned int &nonSACreatedOACount) const
1434 {
1435 std::vector<int32_t> idList;
1436 ErrCode errCode = osAccountControl_->GetOsAccountIdList(idList);
1437 if (errCode != ERR_OK) {
1438 ACCOUNT_LOGE("Get osaccount info list error, errCode %{public}d.", errCode);
1439 return errCode;
1440 }
1441 unsigned int saCreatedNum = 0;
1442 for (const auto& it : idList) {
1443 OsAccountInfo osAccountInfo;
1444 if (osAccountControl_->GetOsAccountInfoById(it, osAccountInfo) == ERR_OK &&
1445 osAccountInfo.GetCreatorType() == TOKEN_NATIVE) {
1446 ++saCreatedNum;
1447 }
1448 }
1449 nonSACreatedOACount = idList.size() - saCreatedNum;
1450 return ERR_OK;
1451 }
1452 #ifdef FUZZ_TEST
1453 // LCOV_EXCL_STOP
1454 #endif
1455
1456 #ifdef FUZZ_TEST
1457 // LCOV_EXCL_START
1458 #endif
1459 ErrCode IInnerOsAccountManager::QueryMaxOsAccountNumber(uint32_t &maxOsAccountNumber)
1460 {
1461 #ifdef ENABLE_MULTIPLE_OS_ACCOUNTS
1462 maxOsAccountNumber = config_.maxOsAccountNum;
1463 #else
1464 maxOsAccountNumber = 1;
1465 #endif // ENABLE_MULTIPLE_OS_ACCOUNTS
1466 return ERR_OK;
1467 }
1468 #ifdef FUZZ_TEST
1469 // LCOV_EXCL_STOP
1470 #endif
1471
1472 #ifdef FUZZ_TEST
1473 // LCOV_EXCL_START
1474 #endif
1475 ErrCode IInnerOsAccountManager::QueryMaxLoggedInOsAccountNumber(uint32_t &maxNum)
1476 {
1477 #ifdef ENABLE_MULTIPLE_OS_ACCOUNTS
1478 maxNum = config_.maxLoggedInOsAccountNum;
1479 #else
1480 maxNum = 1;
1481 #endif // ENABLE_MULTIPLE_OS_ACCOUNTS
1482 return ERR_OK;
1483 }
1484 #ifdef FUZZ_TEST
1485 // LCOV_EXCL_STOP
1486 #endif
1487
1488 #ifdef FUZZ_TEST
1489 // LCOV_EXCL_START
1490 #endif
1491 ErrCode IInnerOsAccountManager::GetOsAccountAllConstraints(const int id, std::vector<std::string> &constraints)
1492 {
1493 OsAccountInfo osAccountInfo;
1494 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(id, osAccountInfo);
1495 if (errCode != ERR_OK) {
1496 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1497 }
1498 constraints = osAccountInfo.GetConstraints();
1499 std::vector<std::string> globalConstraints;
1500 errCode = osAccountControl_->GetGlobalOAConstraintsList(globalConstraints);
1501 if (errCode != ERR_OK) {
1502 ACCOUNT_LOGE("Get globalConstraints info error");
1503 return errCode;
1504 }
1505 for (auto it = globalConstraints.begin(); it != globalConstraints.end(); it++) {
1506 if (std::find(constraints.begin(), constraints.end(), *it) == constraints.end()) {
1507 constraints.push_back(*it);
1508 }
1509 }
1510 std::vector<std::string> specificConstraints;
1511 errCode = osAccountControl_->GetSpecificOAConstraintsList(id, specificConstraints);
1512 if (errCode != ERR_OK) {
1513 ACCOUNT_LOGE("Get specificConstraints info error");
1514 return errCode;
1515 }
1516 for (auto it = specificConstraints.begin(); it != specificConstraints.end(); it++) {
1517 if (std::find(constraints.begin(), constraints.end(), *it) == constraints.end()) {
1518 constraints.push_back(*it);
1519 }
1520 }
1521 return ERR_OK;
1522 }
1523 #ifdef FUZZ_TEST
1524 // LCOV_EXCL_STOP
1525 #endif
1526
1527 ErrCode IInnerOsAccountManager::QueryOsAccountConstraintSourceTypes(const int32_t id,
1528 const std::string &constraint, std::vector<ConstraintSourceTypeInfo> &constraintSourceTypeInfos)
1529 {
1530 ACCOUNT_LOGD("Enter.");
1531 bool isOsAccountConstraintEnable = false;
1532 ErrCode errCode = IsOsAccountConstraintEnable(id, constraint, isOsAccountConstraintEnable);
1533 if (errCode != ERR_OK) {
1534 ACCOUNT_LOGE("Get os account constraint enable info error");
1535 return errCode;
1536 }
1537 if (!isOsAccountConstraintEnable) {
1538 ACCOUNT_LOGI("Constraint not exist");
1539 ConstraintSourceTypeInfo constraintSourceTypeInfo;
1540 constraintSourceTypeInfo.localId = -1;
1541 constraintSourceTypeInfo.typeInfo = ConstraintSourceType::CONSTRAINT_NOT_EXIST;
1542 constraintSourceTypeInfos.push_back(constraintSourceTypeInfo);
1543 return ERR_OK;
1544 }
1545
1546 bool isExits;
1547 if (osAccountControl_->IsFromBaseOAConstraintsList(id, constraint, isExits) == ERR_OK) {
1548 if (isExits) {
1549 ACCOUNT_LOGI("Constraint is exist in base os account constraints list");
1550 ConstraintSourceTypeInfo constraintSourceTypeInfo;
1551 constraintSourceTypeInfo.localId = -1;
1552 constraintSourceTypeInfo.typeInfo = ConstraintSourceType::CONSTRAINT_TYPE_BASE;
1553 constraintSourceTypeInfos.push_back(constraintSourceTypeInfo);
1554 }
1555 }
1556 std::vector<ConstraintSourceTypeInfo> globalSourceList;
1557 errCode = osAccountControl_->IsFromGlobalOAConstraintsList(id, deviceOwnerId_, constraint, globalSourceList);
1558 if (errCode == ERR_OK && globalSourceList.size() != 0) {
1559 ACCOUNT_LOGI("Constraint is exist in global os account constraints list");
1560 constraintSourceTypeInfos.insert(
1561 constraintSourceTypeInfos.end(), globalSourceList.begin(), globalSourceList.end());
1562 }
1563 std::vector<ConstraintSourceTypeInfo> specificSourceList;
1564 errCode = osAccountControl_->IsFromSpecificOAConstraintsList(id, deviceOwnerId_, constraint, specificSourceList);
1565 if (errCode == ERR_OK && specificSourceList.size() != 0) {
1566 ACCOUNT_LOGI("Constraint is exist in specific os account constraints list");
1567 constraintSourceTypeInfos.insert(
1568 constraintSourceTypeInfos.end(), specificSourceList.begin(), specificSourceList.end());
1569 }
1570 return ERR_OK;
1571 }
1572
1573 ErrCode IInnerOsAccountManager::SetBaseOsAccountConstraints(const int32_t id,
1574 const std::vector<std::string> &constraints, const bool enable)
1575 {
1576 ErrCode errCode = SetOsAccountConstraints(id, constraints, enable);
1577 if (errCode != ERR_OK) {
1578 ACCOUNT_LOGE("Set os account %{public}d constraints failed! errCode %{public}d.", id, errCode);
1579 return errCode;
1580 }
1581
1582 errCode = osAccountControl_->UpdateBaseOAConstraints(std::to_string(id), constraints, enable);
1583 if (errCode != ERR_OK) {
1584 ACCOUNT_LOGE("Update base os account %{public}d constraints failed! errCode %{public}d.", id, errCode);
1585 return errCode;
1586 }
1587 return ERR_OK;
1588 }
1589
1590 ErrCode IInnerOsAccountManager::SetGlobalOsAccountConstraints(const std::vector<std::string> &constraints,
1591 const bool enable, const int32_t enforcerId, const bool isDeviceOwner)
1592 {
1593 OsAccountInfo osAccountInfo;
1594 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(enforcerId, osAccountInfo);
1595 if (errCode != ERR_OK) {
1596 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1597 }
1598 if (osAccountInfo.GetToBeRemoved()) {
1599 ACCOUNT_LOGE("Account %{public}d will be removed, cannot change constraints!", enforcerId);
1600 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_TO_BE_REMOVED_ERROR;
1601 }
1602
1603 if (!osAccountControl_->CheckConstraints(constraints)) {
1604 ACCOUNT_LOGE("Invalid constraints");
1605 return ERR_ACCOUNT_COMMON_INVALID_PARAMETER;
1606 }
1607
1608 osAccountControl_->UpdateGlobalOAConstraints(std::to_string(enforcerId), constraints, enable);
1609
1610 errCode = DealWithDeviceOwnerId(isDeviceOwner, enforcerId);
1611 if (errCode != ERR_OK) {
1612 ACCOUNT_LOGE("Deal with device owner id error");
1613 return errCode;
1614 }
1615 return ERR_OK;
1616 }
1617
1618 ErrCode IInnerOsAccountManager::SetSpecificOsAccountConstraints(const std::vector<std::string> &constraints,
1619 const bool enable, const int32_t targetId, const int32_t enforcerId, const bool isDeviceOwner)
1620 {
1621 OsAccountInfo enforcerOsAccountInfo;
1622 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(enforcerId, enforcerOsAccountInfo);
1623 if (errCode != ERR_OK) {
1624 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1625 }
1626
1627 OsAccountInfo targetOsAccountInfo;
1628 errCode = osAccountControl_->GetOsAccountInfoById(targetId, targetOsAccountInfo);
1629 if (errCode != ERR_OK) {
1630 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1631 }
1632 if (targetOsAccountInfo.GetToBeRemoved() || enforcerOsAccountInfo.GetToBeRemoved()) {
1633 ACCOUNT_LOGE("Account %{public}d or %{public}d will be removed, cannot change constraints!",
1634 enforcerId, targetId);
1635 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_TO_BE_REMOVED_ERROR;
1636 }
1637
1638 if (!osAccountControl_->CheckConstraints(constraints)) {
1639 ACCOUNT_LOGE("Invalid constraints");
1640 return ERR_ACCOUNT_COMMON_INVALID_PARAMETER;
1641 }
1642
1643 osAccountControl_->UpdateSpecificOAConstraints(
1644 std::to_string(enforcerId), std::to_string(targetId), constraints, enable);
1645
1646 errCode = DealWithDeviceOwnerId(isDeviceOwner, enforcerId);
1647 if (errCode != ERR_OK) {
1648 ACCOUNT_LOGE("Deal with device owner id error");
1649 return errCode;
1650 }
1651 return ERR_OK;
1652 }
1653
1654 #ifdef FUZZ_TEST
1655 // LCOV_EXCL_START
1656 #endif
1657 ErrCode IInnerOsAccountManager::QueryAllCreatedOsAccounts(std::vector<OsAccountInfo> &createdOsAccounts)
1658 {
1659 std::vector<int32_t> allOsAccountIds;
1660 ErrCode errCode = osAccountControl_->GetOsAccountIdList(allOsAccountIds);
1661 if (errCode != ERR_OK) {
1662 ACCOUNT_LOGE("Get osaccount info list error, errCode %{public}d.", errCode);
1663 return errCode;
1664 }
1665 for (auto id : allOsAccountIds) {
1666 OsAccountInfo osAccountInfo;
1667 GetRealOsAccountInfoById(id, osAccountInfo);
1668 if (osAccountInfo.GetIsCreateCompleted() && !osAccountInfo.GetToBeRemoved()) {
1669 std::string photo = osAccountInfo.GetPhoto();
1670 osAccountControl_->GetPhotoById(id, photo);
1671 osAccountInfo.SetPhoto(photo);
1672 createdOsAccounts.push_back(osAccountInfo);
1673 }
1674 }
1675 return ERR_OK;
1676 }
1677 #ifdef FUZZ_TEST
1678 // LCOV_EXCL_STOP
1679 #endif
1680
1681 ErrCode IInnerOsAccountManager::DealWithDeviceOwnerId(const bool isDeviceOwner, const int32_t localId)
1682 {
1683 ACCOUNT_LOGD("Enter.");
1684 if (isDeviceOwner && localId != deviceOwnerId_) {
1685 ACCOUNT_LOGI("This device owner os account id is changed!");
1686 deviceOwnerId_ = localId;
1687 return osAccountControl_->UpdateDeviceOwnerId(localId);
1688 }
1689 if (isDeviceOwner == false && localId == deviceOwnerId_) {
1690 deviceOwnerId_ = -1;
1691 return osAccountControl_->UpdateDeviceOwnerId(-1);
1692 }
1693 return ERR_OK;
1694 }
1695
1696 int32_t IInnerOsAccountManager::CleanGarbageOsAccounts(int32_t excludeId)
1697 {
1698 ACCOUNT_LOGI("Enter");
1699 std::vector<int32_t> idList;
1700 if (osAccountControl_->GetOsAccountIdList(idList) != ERR_OK) {
1701 ACCOUNT_LOGI("GetOsAccountIdList failed.");
1702 return 0;
1703 }
1704
1705 int32_t removeNum = 0;
1706
1707 for (auto id : idList) {
1708 if (id == Constants::START_USER_ID || id == Constants::ADMIN_LOCAL_ID || id == Constants::U1_ID ||
1709 id == excludeId) {
1710 continue;
1711 }
1712 if (!CheckAndAddLocalIdOperating(id)) {
1713 ACCOUNT_LOGI("Account id = %{public}d already in operating", id);
1714 continue;
1715 }
1716 OsAccountInfo osAccountInfo;
1717 ErrCode ret = GetRealOsAccountInfoById(id, osAccountInfo);
1718 if (ret != ERR_OK && ret != ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR) {
1719 continue;
1720 }
1721 osAccountInfo.SetLocalId(id);
1722
1723 if (!osAccountInfo.GetToBeRemoved() && osAccountInfo.GetIsCreateCompleted()) {
1724 RemoveLocalIdToOperating(id);
1725 continue;
1726 }
1727 ErrCode errCode = RemoveOsAccountOperate(id, osAccountInfo, true);
1728 RemoveLocalIdToOperating(id);
1729 if (errCode != ERR_OK) {
1730 REPORT_OS_ACCOUNT_FAIL(id, Constants::OPERATION_CLEAN,
1731 errCode, "Clean garbage os accounts failed");
1732 ACCOUNT_LOGE("Remove account %{public}d failed! errCode %{public}d.", id, errCode);
1733 } else {
1734 ACCOUNT_LOGI("Remove account %{public}d succeed!", id);
1735 removeNum++;
1736 }
1737 }
1738 if (removeNum > 0) {
1739 ReportOsAccountLifeCycle(removeNum, Constants::OPERATION_CLEAN);
1740 }
1741 ACCOUNT_LOGI("Finished.");
1742 return removeNum;
1743 }
1744
1745 #ifdef SUPPORT_DOMAIN_ACCOUNTS
1746 bool IInnerOsAccountManager::IsSameAccount(
1747 const DomainAccountInfo &domainInfoSrc, const DomainAccountInfo &domainInfoTar)
1748 {
1749 return (((!domainInfoSrc.accountId_.empty()) && (domainInfoSrc.accountId_ == domainInfoTar.accountId_)) ||
1750 ((!domainInfoSrc.accountName_.empty()) && (domainInfoSrc.accountName_ == domainInfoTar.accountName_) &&
1751 (!domainInfoSrc.domain_.empty()) && (domainInfoSrc.domain_ == domainInfoTar.domain_)));
1752 }
1753 #endif // SUPPORT_DOMAIN_ACCOUNTS
1754
1755 ErrCode IInnerOsAccountManager::GetOsAccountLocalIdFromDomain(const DomainAccountInfo &domainInfo, int &id)
1756 {
1757 #ifdef SUPPORT_DOMAIN_ACCOUNTS
1758 if (domainInfo.domain_.size() > Constants::DOMAIN_NAME_MAX_SIZE) {
1759 ACCOUNT_LOGE("Invalid domain name length %{public}zu.", domainInfo.domain_.size());
1760 return ERR_ACCOUNT_COMMON_INVALID_PARAMETER;
1761 }
1762
1763 if (domainInfo.accountName_.size() > Constants::LOCAL_NAME_MAX_SIZE) {
1764 ACCOUNT_LOGE("Invalid domain account name length %{public}zu.", domainInfo.accountName_.size());
1765 return ERR_ACCOUNT_COMMON_INVALID_PARAMETER;
1766 }
1767
1768 id = -1;
1769 std::vector<OsAccountInfo> osAccountInfos;
1770 ErrCode errCode = osAccountControl_->GetOsAccountList(osAccountInfos);
1771 if (errCode != ERR_OK) {
1772 return errCode;
1773 }
1774
1775 DomainAccountInfo curDomainInfo;
1776 for (auto osAccountInfosPtr = osAccountInfos.begin(); osAccountInfosPtr != osAccountInfos.end();
1777 ++osAccountInfosPtr) {
1778 osAccountInfosPtr->GetDomainInfo(curDomainInfo);
1779 if (IsSameAccount(curDomainInfo, domainInfo)) {
1780 id = osAccountInfosPtr->GetLocalId();
1781 return ERR_OK;
1782 }
1783 }
1784 return ERR_DOMAIN_ACCOUNT_SERVICE_NOT_DOMAIN_ACCOUNT;
1785 #else
1786 return ERR_DOMAIN_ACCOUNT_NOT_SUPPORT;
1787 #endif // SUPPORT_DOMAIN_ACCOUNTS
1788 }
1789
1790 ErrCode IInnerOsAccountManager::GetOsAccountShortName(const int id, std::string &shortName)
1791 {
1792 OsAccountInfo osAccountInfo;
1793 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(id, osAccountInfo);
1794 if (errCode != ERR_OK) {
1795 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1796 }
1797 shortName = osAccountInfo.GetShortName();
1798 return ERR_OK;
1799 }
1800
1801 ErrCode IInnerOsAccountManager::GetOsAccountName(const int id, std::string &name)
1802 {
1803 OsAccountInfo osAccountInfo;
1804 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(id, osAccountInfo);
1805 if (errCode != ERR_OK) {
1806 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1807 }
1808 name = osAccountInfo.GetLocalName();
1809 return ERR_OK;
1810 }
1811
1812 ErrCode IInnerOsAccountManager::QueryOsAccountById(const int id, OsAccountInfo &osAccountInfo)
1813 {
1814 ErrCode errCode = GetRealOsAccountInfoById(id, osAccountInfo);
1815 if (errCode != ERR_OK) {
1816 ACCOUNT_LOGE("Get osaccount info error, errCode %{public}d.", errCode);
1817 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1818 }
1819
1820 if (osAccountInfo.GetPhoto() != "") {
1821 std::string photo = osAccountInfo.GetPhoto();
1822 errCode = osAccountControl_->GetPhotoById(osAccountInfo.GetLocalId(), photo);
1823 if (errCode != ERR_OK) {
1824 ACCOUNT_LOGE("Get osaccount photo error, errCode %{public}d.", errCode);
1825 return errCode;
1826 }
1827 osAccountInfo.SetPhoto(photo);
1828 }
1829 #ifdef SUPPORT_DOMAIN_ACCOUNTS
1830 GetDomainAccountStatus(osAccountInfo);
1831 #endif // SUPPORT_DOMAIN_ACCOUNTS
1832 return ERR_OK;
1833 }
1834
1835 ErrCode IInnerOsAccountManager::GetOsAccountType(const int id, OsAccountType &type)
1836 {
1837 OsAccountInfo osAccountInfo;
1838 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(id, osAccountInfo);
1839 if (errCode != ERR_OK) {
1840 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1841 }
1842 type = osAccountInfo.GetType();
1843 return ERR_OK;
1844 }
1845
1846 ErrCode IInnerOsAccountManager::GetOsAccountProfilePhoto(const int id, std::string &photo)
1847 {
1848 OsAccountInfo osAccountInfo;
1849 ErrCode errCode = QueryOsAccountById(id, osAccountInfo);
1850 if (errCode != ERR_OK) {
1851 ACCOUNT_LOGE("QueryOsAccountById return error, errCode %{public}d.", errCode);
1852 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1853 }
1854 photo = osAccountInfo.GetPhoto();
1855 return ERR_OK;
1856 }
1857
1858 #ifdef FUZZ_TEST
1859 // LCOV_EXCL_START
1860 #endif
1861 ErrCode IInnerOsAccountManager::IsMultiOsAccountEnable(bool &isMultiOsAccountEnable)
1862 {
1863 #ifdef ENABLE_MULTIPLE_OS_ACCOUNTS
1864 ErrCode errCode = osAccountControl_->GetIsMultiOsAccountEnable(isMultiOsAccountEnable);
1865 if (errCode != ERR_OK) {
1866 ACCOUNT_LOGE("GetIsMultiOsAccountEnable error, errCode %{public}d.", errCode);
1867 return errCode;
1868 }
1869 #else
1870 isMultiOsAccountEnable = false;
1871 #endif // ENABLE_MULTIPLE_OS_ACCOUNTS
1872 return ERR_OK;
1873 }
1874 #ifdef FUZZ_TEST
1875 // LCOV_EXCL_STOP
1876 #endif
1877
1878 ErrCode IInnerOsAccountManager::SetOsAccountName(const int id, const std::string &name)
1879 {
1880 OsAccountInfo osAccountInfo;
1881 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(id, osAccountInfo);
1882 if (errCode != ERR_OK) {
1883 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1884 }
1885
1886 // to be removed, cannot change any thing
1887 if (osAccountInfo.GetToBeRemoved()) {
1888 ACCOUNT_LOGE("Account %{public}d will be removed, cannot change name!", id);
1889 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_TO_BE_REMOVED_ERROR;
1890 }
1891
1892 std::string localName = osAccountInfo.GetLocalName();
1893 if (localName == name) {
1894 return ERR_OK;
1895 }
1896
1897 osAccountInfo.SetLocalName(name);
1898 errCode = ValidateOsAccount(osAccountInfo);
1899 if (errCode != ERR_OK) {
1900 ACCOUNT_LOGE("Account name already exist, errCode %{public}d.", errCode);
1901 return errCode;
1902 }
1903
1904 errCode = osAccountControl_->UpdateOsAccount(osAccountInfo);
1905 if (errCode != ERR_OK) {
1906 ACCOUNT_LOGE("Update osaccount info error %{public}d, id: %{public}d", errCode, osAccountInfo.GetLocalId());
1907 return ERR_OSACCOUNT_SERVICE_INNER_UPDATE_ACCOUNT_ERROR;
1908 }
1909 osAccountControl_->UpdateAccountIndex(osAccountInfo, false);
1910 OsAccountInterface::PublishCommonEvent(
1911 osAccountInfo, OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_USER_INFO_UPDATED, OPERATION_UPDATE);
1912 return ERR_OK;
1913 }
1914
1915 ErrCode IInnerOsAccountManager::SetOsAccountConstraints(
1916 const int id, const std::vector<std::string> &constraints, const bool enable)
1917 {
1918 OsAccountInfo osAccountInfo;
1919 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(id, osAccountInfo);
1920 if (errCode != ERR_OK) {
1921 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1922 }
1923
1924 // to be removed, cannot change any thing
1925 if (osAccountInfo.GetToBeRemoved()) {
1926 ACCOUNT_LOGE("Account %{public}d will be removed, cannot change constraints!", id);
1927 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_TO_BE_REMOVED_ERROR;
1928 }
1929
1930 if (!osAccountControl_->CheckConstraints(constraints)) {
1931 ACCOUNT_LOGE("Invalid constraints");
1932 return ERR_ACCOUNT_COMMON_INVALID_PARAMETER;
1933 }
1934 std::vector<std::string> oldConstraints = osAccountInfo.GetConstraints();
1935 for (auto it = constraints.begin(); it != constraints.end(); it++) {
1936 if (enable) {
1937 if (std::find(oldConstraints.begin(), oldConstraints.end(), *it) == oldConstraints.end()) {
1938 oldConstraints.push_back(*it);
1939 }
1940 } else {
1941 oldConstraints.erase(
1942 std::remove(oldConstraints.begin(), oldConstraints.end(), *it), oldConstraints.end());
1943 }
1944 }
1945 osAccountInfo.SetConstraints(oldConstraints);
1946 errCode = osAccountControl_->UpdateOsAccount(osAccountInfo);
1947 if (errCode != ERR_OK) {
1948 ACCOUNT_LOGE("Update osaccount info error %{public}d, id: %{public}d", errCode, osAccountInfo.GetLocalId());
1949 return ERR_OSACCOUNT_SERVICE_INNER_UPDATE_ACCOUNT_ERROR;
1950 }
1951 return ERR_OK;
1952 }
1953
1954 ErrCode IInnerOsAccountManager::SetOsAccountProfilePhoto(const int id, const std::string &photo)
1955 {
1956 OsAccountInfo osAccountInfo;
1957 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(id, osAccountInfo);
1958 if (errCode != ERR_OK) {
1959 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1960 }
1961
1962 // to be removed, cannot change any thing
1963 if (osAccountInfo.GetToBeRemoved()) {
1964 ACCOUNT_LOGE("Account %{public}d will be removed, cannot change photo!", id);
1965 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_TO_BE_REMOVED_ERROR;
1966 }
1967
1968 if (osAccountInfo.GetPhoto() == photo) {
1969 return ERR_OK;
1970 }
1971 errCode = osAccountControl_->SetPhotoById(id, photo);
1972 if (errCode != ERR_OK) {
1973 ACCOUNT_LOGE("Set photo error, code=%{public}d, id=%{public}d.", errCode, id);
1974 return errCode;
1975 }
1976 osAccountInfo.SetPhoto(Constants::USER_PHOTO_FILE_TXT_NAME);
1977 errCode = osAccountControl_->UpdateOsAccount(osAccountInfo);
1978 if (errCode != ERR_OK) {
1979 ACCOUNT_LOGE("Update osaccount info faile code=%{public}d, id=%{public}d", errCode, osAccountInfo.GetLocalId());
1980 return ERR_OSACCOUNT_SERVICE_INNER_UPDATE_ACCOUNT_ERROR;
1981 }
1982 // report data size when profile photo updated
1983 ReportUserDataSize(GetVerifiedAccountIds(verifiedAccounts_));
1984 OsAccountInterface::PublishCommonEvent(
1985 osAccountInfo, OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_USER_INFO_UPDATED, OPERATION_UPDATE);
1986 return ERR_OK;
1987 }
1988
1989 ErrCode IInnerOsAccountManager::DeactivateOsAccountByInfo(OsAccountInfo &osAccountInfo)
1990 {
1991 int localId = osAccountInfo.GetLocalId();
1992 loggedInAccounts_.Erase(localId);
1993 verifiedAccounts_.Erase(localId);
1994 int32_t foregroundId = -1;
1995 if (foregroundAccountMap_.Find(Constants::DEFAULT_DISPALY_ID, foregroundId) && foregroundId == localId) {
1996 foregroundAccountMap_.Erase(Constants::DEFAULT_DISPALY_ID);
1997 }
1998 EraseIdFromActiveList(localId);
1999
2000 DomainAccountInfo domainAccountInfo;
2001 osAccountInfo.GetDomainInfo(domainAccountInfo);
2002 domainAccountInfo.status_ = DomainAccountStatus::LOGOUT;
2003 osAccountInfo.SetDomainInfo(domainAccountInfo);
2004 ErrCode errCode = osAccountControl_->UpdateOsAccount(osAccountInfo);
2005 if (errCode != ERR_OK && errCode != ERR_ACCOUNT_COMMON_DATA_NO_SPACE) {
2006 ACCOUNT_LOGE("Update account failed, id=%{public}d, errCode=%{public}d.", osAccountInfo.GetLocalId(), errCode);
2007 return ERR_OSACCOUNT_SERVICE_INNER_UPDATE_ACCOUNT_ERROR;
2008 }
2009
2010 AccountInfoReport::ReportSecurityInfo(osAccountInfo.GetLocalName(), localId,
2011 ReportEvent::EVENT_LOGOUT, 0);
2012 return ERR_OK;
2013 }
2014
2015 ErrCode IInnerOsAccountManager::DeactivateOsAccountById(const int id)
2016 {
2017 OsAccountInfo osAccountInfo;
2018 ErrCode errCode = GetRealOsAccountInfoById(id, osAccountInfo);
2019 if (errCode != ERR_OK) {
2020 ACCOUNT_LOGE("Cannot get os account %{public}d info. error %{public}d.",
2021 id, errCode);
2022 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
2023 }
2024 return DeactivateOsAccountByInfo(osAccountInfo);
2025 }
2026
2027 /**
2028 * This function sets the isAppRecovery flag to true in two scenarios:
2029 * 1. During boot stage (including fast boot) when activating the main user
2030 * - When active account list is empty and system is starting up
2031 * 2. When re-activating a user after it has been logged out
2032 * - When active after user logout and the same user is activated again
2033 */
2034 static void SetAppRecovery(bool &isAppRecovery,
2035 const std::vector<int32_t> &activeAccountId, std::int32_t id, std::int32_t defaultActivatedId)
2036 {
2037 #ifdef SUPPORT_STOP_MAIN_OS_ACCOUNT
2038 if (!isAppRecovery && activeAccountId.empty()) {
2039 isAppRecovery = true;
2040 }
2041 #endif
2042 }
2043
2044 bool IInnerOsAccountManager::IsLoggedInAccountsOversize()
2045 {
2046 uint32_t logginAccountSize = static_cast<uint32_t>(loggedInAccounts_.Size());
2047 #ifdef ENABLE_U1_ACCOUNT
2048 bool isLoggedIn = false;
2049 loggedInAccounts_.Find(Constants::U1_ID, isLoggedIn);
2050 if (isLoggedIn) {
2051 logginAccountSize = logginAccountSize - 1;
2052 }
2053 #endif // ENABLE_U1_ACCOUNT
2054 if (logginAccountSize >= config_.maxLoggedInOsAccountNum) {
2055 return true;
2056 }
2057 return false;
2058 }
2059
2060 ErrCode IInnerOsAccountManager::ActivateOsAccount
2061 (const int id, const bool startStorage, const uint64_t displayId, bool isAppRecovery)
2062 {
2063 if (!CheckAndAddLocalIdOperating(id)) {
2064 ACCOUNT_LOGE("The %{public}d already in operating", id);
2065 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_OPERATING_ERROR;
2066 }
2067 std::lock_guard<std::mutex> lock(*GetOrInsertUpdateLock(id));
2068 // get information
2069 OsAccountInfo osAccountInfo;
2070 ErrCode errCode = GetRealOsAccountInfoById(id, osAccountInfo);
2071 if (errCode != ERR_OK) {
2072 RemoveLocalIdToOperating(id);
2073 ACCOUNT_LOGE("Cannot find os account info by id:%{public}d, errCode %{public}d.", id, errCode);
2074 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
2075 }
2076 int32_t foregroundId = -1;
2077 if (foregroundAccountMap_.Find(displayId, foregroundId) && (foregroundId == id) && osAccountInfo.GetIsVerified()) {
2078 ACCOUNT_LOGI("Account %{public}d already is foreground", id);
2079 RemoveLocalIdToOperating(id);
2080 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_ALREADY_ACTIVE_ERROR;
2081 }
2082 errCode = IsValidOsAccount(osAccountInfo);
2083 if (errCode != ERR_OK) {
2084 RemoveLocalIdToOperating(id);
2085 return errCode;
2086 }
2087 if (!osAccountInfo.GetIsActived() && IsLoggedInAccountsOversize()) {
2088 RemoveLocalIdToOperating(id);
2089 ACCOUNT_LOGE("The number of logged in account reaches the upper limit, maxLoggedInNum: %{public}d",
2090 config_.maxLoggedInOsAccountNum);
2091 return ERR_OSACCOUNT_SERVICE_LOGGED_IN_ACCOUNTS_OVERSIZE;
2092 }
2093 if (foregroundId != id) {
2094 subscribeManager_.Publish(id, OS_ACCOUNT_SUBSCRIBE_TYPE::ACTIVATING);
2095 }
2096 SetAppRecovery(isAppRecovery, activeAccountId_, id, defaultActivatedId_);
2097 errCode = SendMsgForAccountActivate(osAccountInfo, startStorage, displayId, isAppRecovery);
2098 RemoveLocalIdToOperating(id);
2099 if (errCode != ERR_OK) {
2100 return errCode;
2101 }
2102 DomainAccountInfo domainInfo;
2103 osAccountInfo.GetDomainInfo(domainInfo);
2104 if (domainInfo.accountId_.empty() && (osAccountInfo.GetCredentialId() == 0)) {
2105 AccountInfoReport::ReportSecurityInfo(osAccountInfo.GetLocalName(), id, ReportEvent::EVENT_LOGIN, 0);
2106 }
2107 ACCOUNT_LOGI("Activate end");
2108 return ERR_OK;
2109 }
2110
2111 #ifdef FUZZ_TEST
2112 // LCOV_EXCL_START
2113 #endif
2114 void IInnerOsAccountManager::ExecuteDeactivationAnimation(int32_t pipeFd, const OsAccountInfo &osAccountInfo)
2115 {
2116 std::string pipeFdStr = std::to_string(pipeFd);
2117 std::string displayIdStr = std::to_string(osAccountInfo.GetDisplayId());
2118 char *const args[] = { const_cast<char *>(DEACTIVATION_ANIMATION_PATH),
2119 const_cast<char *>(displayIdStr.c_str()), const_cast<char *>(pipeFdStr.c_str()), nullptr };
2120 if (execv(DEACTIVATION_ANIMATION_PATH, args) == -1) {
2121 int32_t err = errno;
2122 ACCOUNT_LOGE("Failed to execv animation: %{public}s", strerror(err));
2123 ReportOsAccountOperationFail(osAccountInfo.GetLocalId(), "deactivate", err,
2124 "Failed to launch deactivation animation, execv error");
2125 close(pipeFd);
2126 exit(EXIT_FAILURE);
2127 }
2128 }
2129 #ifdef FUZZ_TEST
2130 // LCOV_EXCL_STOP
2131 #endif
2132
2133 #ifdef FUZZ_TEST
2134 // LCOV_EXCL_START
2135 #endif
2136 ErrCode IInnerOsAccountManager::WaitForAnimationReady(int32_t pipeFd)
2137 {
2138 char buf[MAX_WAIT_ANIMATION_MSG_BUFFER];
2139 struct pollfd fds[1];
2140 fds[0].fd = pipeFd;
2141 fds[0].events = POLLIN;
2142
2143 int ret = poll(fds, 1, MAX_WAIT_ANIMATION_READY_TIMEOUT);
2144 if (ret < 0) {
2145 ACCOUNT_LOGE("Error in poll: %{public}s", strerror(errno));
2146 return ERR_OSACCOUNT_SERVICE_INNER_ANIMATION_POLL_ERROR;
2147 }
2148 if (ret == 0) {
2149 ACCOUNT_LOGE("Timeout waiting for message from child process.");
2150 return ERR_OSACCOUNT_SERVICE_INNER_ANIMATION_TIMEOUT;
2151 }
2152 if (!(static_cast<uint16_t>(fds[0].revents) & POLLIN)) {
2153 ACCOUNT_LOGE("Unexpected event in poll: %{public}d", fds[0].revents);
2154 return ERR_OSACCOUNT_SERVICE_INNER_ANIMATION_UNEXPECTED_EVENT;
2155 }
2156 ssize_t bytesRead = read(pipeFd, buf, sizeof(buf));
2157 if (bytesRead <= 0) {
2158 ACCOUNT_LOGE("Error reading from pipe: %{public}s", strerror(errno));
2159 return ERR_OSACCOUNT_SERVICE_INNER_ANIMATION_READ_ERROR;
2160 }
2161 buf[bytesRead] = '\0';
2162 ACCOUNT_LOGI("Received message from child process: %{public}s", buf);
2163 return ERR_OK;
2164 }
2165 #ifdef FUZZ_TEST
2166 // LCOV_EXCL_STOP
2167 #endif
2168
2169 #ifdef FUZZ_TEST
2170 // LCOV_EXCL_START
2171 #endif
2172 void IInnerOsAccountManager::LaunchDeactivationAnimation(const OsAccountInfo &osAccountInfo)
2173 {
2174 int32_t localId = osAccountInfo.GetLocalId();
2175 ACCOUNT_LOGI("Start launching deactivation animation for account: %{public}d", localId);
2176 struct stat buffer;
2177 if (stat(DEACTIVATION_ANIMATION_PATH, &buffer) != 0) {
2178 ACCOUNT_LOGW("Animation launch file does not exist: %{public}s, %{public}s,",
2179 DEACTIVATION_ANIMATION_PATH, strerror(errno));
2180 return;
2181 }
2182
2183 int pipeFd[PIPE_FD_COUNT];
2184 if (pipe(pipeFd) == -1) {
2185 int32_t err = errno;
2186 ACCOUNT_LOGE("Failed to create pipe: %{public}s", strerror(err));
2187 ReportOsAccountOperationFail(localId, "deactivate", err,
2188 "Failed to launch deactivation animation, create pipe error");
2189 return;
2190 }
2191
2192 pid_t pid = fork();
2193 if (pid == 0) {
2194 close(pipeFd[PIPE_READ_END]);
2195 ExecuteDeactivationAnimation(pipeFd[PIPE_WRITE_END], osAccountInfo);
2196 } else if (pid > 0) {
2197 close(pipeFd[PIPE_WRITE_END]);
2198 ErrCode ret = WaitForAnimationReady(pipeFd[PIPE_READ_END]);
2199 if (ret != ERR_OK) {
2200 ReportOsAccountOperationFail(localId, "deactivate", ret,
2201 "Failed to launch deactivation animation, wait msg error");
2202 }
2203 close(pipeFd[PIPE_READ_END]);
2204 } else {
2205 int32_t err = errno;
2206 ACCOUNT_LOGE("Failed to fork deactivation animation process: %{public}s", strerror(err));
2207 ReportOsAccountOperationFail(localId, "deactivate", err,
2208 "Failed to launch deactivation animation, fork error");
2209 close(pipeFd[PIPE_READ_END]);
2210 close(pipeFd[PIPE_WRITE_END]);
2211 }
2212 }
2213 #ifdef FUZZ_TEST
2214 // LCOV_EXCL_STOP
2215 #endif
2216
2217 ErrCode IInnerOsAccountManager::DeactivateOsAccount(const int id, bool isStopStorage)
2218 {
2219 if (!CheckAndAddLocalIdOperating(id)) {
2220 ACCOUNT_LOGW("The %{public}d already in operating", id);
2221 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_OPERATING_ERROR;
2222 }
2223 std::lock_guard<std::mutex> lock(*GetOrInsertUpdateLock(id));
2224 OsAccountInfo osAccountInfo;
2225 ErrCode errCode = GetRealOsAccountInfoById(id, osAccountInfo);
2226 if (errCode != ERR_OK) {
2227 RemoveLocalIdToOperating(id);
2228 ACCOUNT_LOGW("Cannot find os account info by id:%{public}d, errCode %{public}d.", id, errCode);
2229 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
2230 }
2231
2232 if ((!osAccountInfo.GetIsActived()) && (!osAccountInfo.GetIsVerified())) {
2233 RemoveLocalIdToOperating(id);
2234 ACCOUNT_LOGW("Account %{public}d is neither active nor verified, don't need to deactivate!", id);
2235 return ERR_OK;
2236 }
2237 errCode = IsValidOsAccount(osAccountInfo);
2238 if (errCode != ERR_OK) {
2239 RemoveLocalIdToOperating(id);
2240 return errCode;
2241 }
2242
2243 deactivatingAccounts_.EnsureInsert(id, true);
2244
2245 OsAccountInterface::PublishCommonEvent(
2246 osAccountInfo, OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_USER_STOPPING, Constants::OPERATION_STOP);
2247
2248 if (osAccountInfo.GetIsForeground()) {
2249 LaunchDeactivationAnimation(osAccountInfo);
2250 }
2251
2252 errCode = SendMsgForAccountDeactivate(osAccountInfo, isStopStorage);
2253 deactivatingAccounts_.Erase(id);
2254 if (errCode != ERR_OK) {
2255 RemoveLocalIdToOperating(id);
2256 ReportOsAccountOperationFail(id, "deactivate", errCode, "deactivate os account failed");
2257 return errCode;
2258 }
2259
2260 OsAccountInterface::PublishCommonEvent(osAccountInfo, OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_USER_STOPPED,
2261 Constants::OPERATION_STOP);
2262 subscribeManager_.Publish(id, OS_ACCOUNT_SUBSCRIBE_TYPE::STOPPED);
2263 ReportOsAccountLifeCycle(id, Constants::OPERATION_STOP);
2264
2265 RemoveLocalIdToOperating(id);
2266 ACCOUNT_LOGI("Deactivate end");
2267 return ERR_OK;
2268 }
2269
2270 #ifdef FUZZ_TEST
2271 // LCOV_EXCL_START
2272 #endif
2273 void IInnerOsAccountManager::RollBackToEarlierAccount(int32_t fromId, int32_t toId)
2274 {
2275 ACCOUNT_LOGI("Enter.");
2276 if (fromId == toId) {
2277 return;
2278 }
2279 subscribeManager_.Publish(toId, OS_ACCOUNT_SUBSCRIBE_TYPE::SWITCHED, fromId);
2280 ReportOsAccountSwitch(fromId, toId);
2281 ACCOUNT_LOGI("End pushlishing pre switch event.");
2282 OsAccountInfo osAccountInfo;
2283 osAccountInfo.SetLocalId(toId);
2284 subscribeManager_.Publish(fromId, OS_ACCOUNT_SUBSCRIBE_TYPE::SWITCHING, toId);
2285 OsAccountInterface::PublishCommonEvent(osAccountInfo,
2286 OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_USER_FOREGROUND, Constants::OPERATION_SWITCH);
2287 subscribeManager_.Publish(fromId, OS_ACCOUNT_SUBSCRIBE_TYPE::SWITCHED, toId);
2288 ReportOsAccountSwitch(toId, fromId);
2289 ACCOUNT_LOGI("End pushlishing post switch event.");
2290 }
2291 #ifdef FUZZ_TEST
2292 // LCOV_EXCL_STOP
2293 #endif
2294
2295 ErrCode IInnerOsAccountManager::SendToStorageAndAMSAccountStart(OsAccountInfo &osAccountInfo, const bool startStorage,
2296 const uint64_t displayId, const bool isAppRecovery, int32_t oldId)
2297 {
2298 int32_t localId = static_cast<int32_t>(osAccountInfo.GetLocalId());
2299
2300 if (startStorage) {
2301 ErrCode errCode = SendToStorageAccountStart(osAccountInfo);
2302 if (errCode != ERR_OK && !isAppRecovery) {
2303 RollBackToEarlierAccount(localId, oldId);
2304 return errCode;
2305 }
2306 }
2307
2308 ErrCode errCode = SendToAMSAccountStart(osAccountInfo, displayId, isAppRecovery);
2309 if (errCode != ERR_OK) {
2310 RollBackToEarlierAccount(localId, oldId);
2311 return errCode;
2312 }
2313
2314 return ERR_OK;
2315 }
2316
2317 ErrCode IInnerOsAccountManager::SendMsgForAccountActivate(OsAccountInfo &osAccountInfo, const bool startStorage,
2318 const uint64_t displayId, const bool isAppRecovery)
2319 {
2320 // activate
2321 int32_t oldId = -1;
2322 bool oldIdExist = foregroundAccountMap_.Find(displayId, oldId);
2323 int32_t localId = static_cast<int32_t>(osAccountInfo.GetLocalId());
2324 bool preActivated = osAccountInfo.GetIsActived();
2325 if (!preActivated) {
2326 OsAccountInterface::PublishCommonEvent(osAccountInfo,
2327 OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_USER_STARTING, Constants::OPERATION_STARTING);
2328 }
2329 if (oldId != localId) {
2330 subscribeManager_.Publish(oldId, OS_ACCOUNT_SUBSCRIBE_TYPE::SWITCHING, localId);
2331 }
2332 ErrCode errCode = SendToStorageAndAMSAccountStart(osAccountInfo, startStorage, displayId, isAppRecovery, oldId);
2333 if (errCode != ERR_OK) {
2334 return errCode;
2335 }
2336 if (oldId != localId) {
2337 OsAccountInterface::PublishCommonEvent(osAccountInfo,
2338 OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_USER_FOREGROUND, Constants::OPERATION_SWITCH);
2339 }
2340 if (osAccountInfo.GetIsLoggedIn()) {
2341 #ifdef ACTIVATE_LAST_LOGGED_IN_ACCOUNT
2342 std::lock_guard<std::mutex> operatingLock(operatingMutex_);
2343 osAccountControl_->SetDefaultActivatedOsAccount(localId);
2344 defaultActivatedId_ = localId;
2345 #endif
2346 }
2347
2348 if (oldId != localId) {
2349 OsAccountInterface::SendToCESAccountSwitched(localId, oldId);
2350 subscribeManager_.Publish(localId, OS_ACCOUNT_SUBSCRIBE_TYPE::ACTIVATED);
2351 subscribeManager_.Publish(oldId, OS_ACCOUNT_SUBSCRIBE_TYPE::SWITCHED, localId);
2352 ReportOsAccountSwitch(localId, oldId);
2353 }
2354 if (oldIdExist && (oldId != localId)) {
2355 if ((errCode = UpdateAccountToBackground(oldId)) != ERR_OK) {
2356 return errCode;
2357 }
2358 }
2359 if (!preActivated) {
2360 OsAccountInterface::PublishCommonEvent(osAccountInfo,
2361 OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_USER_STARTED, Constants::OPERATION_STARTED);
2362 ReportOsAccountLifeCycle(defaultActivatedId_, Constants::OPERATION_ACTIVATE);
2363 }
2364 ACCOUNT_LOGI("SendMsgForAccountActivate ok");
2365 return errCode;
2366 }
2367
2368 ErrCode IInnerOsAccountManager::SendToStorageAccountStart(OsAccountInfo &osAccountInfo)
2369 {
2370 bool preVerified = osAccountInfo.GetIsVerified();
2371 int32_t localId = osAccountInfo.GetLocalId();
2372 ErrCode err = OsAccountInterface::SendToStorageAccountStart(osAccountInfo);
2373 if (err != ERR_OK) {
2374 ACCOUNT_LOGE("Failed to SendToStorageAccountStart, localId %{public}d, error: %{public}d.", localId, err);
2375 return ERR_ACCOUNT_COMMON_GET_SYSTEM_ABILITY_MANAGER;
2376 }
2377 if (osAccountInfo.GetIsVerified()) {
2378 verifiedAccounts_.EnsureInsert(osAccountInfo.GetLocalId(), true);
2379 // report data size when account without verification login
2380 ReportUserDataSize(GetVerifiedAccountIds(verifiedAccounts_));
2381 }
2382 if (osAccountInfo.GetIsLoggedIn()) {
2383 loggedInAccounts_.EnsureInsert(osAccountInfo.GetLocalId(), true);
2384 }
2385
2386 if (!preVerified && osAccountInfo.GetIsVerified()) {
2387 OsAccountInterface::PublishCommonEvent(osAccountInfo,
2388 OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED, Constants::OPERATION_UNLOCK);
2389 subscribeManager_.Publish(localId, OS_ACCOUNT_SUBSCRIBE_TYPE::UNLOCKED);
2390 ReportOsAccountLifeCycle(localId, Constants::OPERATION_UNLOCK);
2391
2392 err = osAccountControl_->UpdateOsAccount(osAccountInfo);
2393 if (err != ERR_OK) {
2394 ACCOUNT_LOGE("Update account info failed, errCode: %{public}d, id: %{public}d", err, localId);
2395 REPORT_OS_ACCOUNT_FAIL(
2396 localId, Constants::OPERATION_ACTIVATE, err, "Failed to update OS account");
2397 }
2398 }
2399 return ERR_OK;
2400 }
2401
2402 ErrCode IInnerOsAccountManager::SendToAMSAccountStart(OsAccountInfo &osAccountInfo,
2403 uint64_t displayId, const bool isAppRecovery)
2404 {
2405 OsAccountStartCallbackFunc callbackFunc = [this, displayId](int32_t localId) {
2406 this->PushIdIntoActiveList(localId);
2407 if (displayId != Constants::INVALID_DISPALY_ID) {
2408 this->foregroundAccountMap_.EnsureInsert(displayId, localId);
2409 }
2410 };
2411 ErrCode errCode = OsAccountInterface::SendToAMSAccountStart(osAccountInfo, callbackFunc, isAppRecovery);
2412 if (errCode != ERR_OK) {
2413 ACCOUNT_LOGE("Failed to call SendToAMSAccountStart, localId: %{public}d, error: %{public}d.",
2414 osAccountInfo.GetLocalId(), errCode);
2415 return errCode;
2416 }
2417
2418 return ERR_OK;
2419 }
2420
2421 ErrCode IInnerOsAccountManager::StartOsAccount(const int id)
2422 {
2423 return ERR_OK;
2424 }
2425
2426 ErrCode IInnerOsAccountManager::GetOsAccountLocalIdBySerialNumber(const int64_t serialNumber, int &id)
2427 {
2428 if (serialNumber ==
2429 Constants::CARRY_NUM * Constants::SERIAL_NUMBER_NUM_START_FOR_ADMIN + Constants::ADMIN_LOCAL_ID) {
2430 id = Constants::ADMIN_LOCAL_ID;
2431 return ERR_OK;
2432 }
2433 std::vector<OsAccountInfo> osAccountInfos;
2434 id = -1;
2435 ErrCode errCode = osAccountControl_->GetOsAccountList(osAccountInfos);
2436 if (errCode != ERR_OK) {
2437 ACCOUNT_LOGE("Get osaccount info list error");
2438 return errCode;
2439 }
2440 for (auto it = osAccountInfos.begin(); it != osAccountInfos.end(); it++) {
2441 if (serialNumber == it->GetSerialNumber()) {
2442 id = it->GetLocalId();
2443 break;
2444 }
2445 }
2446 if (id == -1) {
2447 ACCOUNT_LOGE("Cannot find id by serialNumber");
2448 return ERR_OSACCOUNT_SERVICE_INNER_SELECT_ERROR;
2449 }
2450 return ERR_OK;
2451 }
2452
2453 ErrCode IInnerOsAccountManager::GetOsAccountInfoById(const int id, OsAccountInfo &osAccountInfo)
2454 {
2455 ErrCode errCode = GetRealOsAccountInfoById(id, osAccountInfo);
2456 if (errCode != ERR_OK) {
2457 ACCOUNT_LOGE("Get osaccount info error, errCode %{public}d.", errCode);
2458 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
2459 }
2460 return ERR_OK;
2461 }
2462
2463 ErrCode IInnerOsAccountManager::GetSerialNumberByOsAccountLocalId(const int &id, int64_t &serialNumber)
2464 {
2465 OsAccountInfo osAccountInfo;
2466 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(id, osAccountInfo);
2467 if (errCode != ERR_OK) {
2468 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
2469 }
2470 serialNumber = osAccountInfo.GetSerialNumber();
2471 return ERR_OK;
2472 }
2473
2474 ErrCode IInnerOsAccountManager::SubscribeOsAccount(
2475 const OsAccountSubscribeInfo &subscribeInfo, const sptr<IRemoteObject> &eventListener)
2476 {
2477 auto subscribeInfoPtr = std::make_shared<OsAccountSubscribeInfo>(subscribeInfo);
2478 if (subscribeInfoPtr == nullptr) {
2479 ACCOUNT_LOGE("SubscribeInfoPtr is nullptr");
2480 }
2481 return subscribeManager_.SubscribeOsAccount(subscribeInfoPtr, eventListener);
2482 }
2483
2484 ErrCode IInnerOsAccountManager::UnsubscribeOsAccount(const sptr<IRemoteObject> &eventListener)
2485 {
2486 return subscribeManager_.UnsubscribeOsAccount(eventListener);
2487 }
2488
2489 const std::shared_ptr<OsAccountSubscribeInfo> IInnerOsAccountManager::GetSubscribeRecordInfo(
2490 const sptr<IRemoteObject> &eventListener)
2491 {
2492 return subscribeManager_.GetSubscribeRecordInfo(eventListener);
2493 }
2494
2495 OS_ACCOUNT_SWITCH_MOD IInnerOsAccountManager::GetOsAccountSwitchMod()
2496 {
2497 return Constants::NOW_OS_ACCOUNT_SWITCH_MOD;
2498 }
2499
2500 ErrCode IInnerOsAccountManager::IsOsAccountCompleted(const int id, bool &isOsAccountCompleted)
2501 {
2502 OsAccountInfo osAccountInfo;
2503 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(id, osAccountInfo);
2504 if (errCode != ERR_OK) {
2505 return errCode;
2506 }
2507 isOsAccountCompleted = osAccountInfo.GetIsCreateCompleted();
2508 return ERR_OK;
2509 }
2510
2511 void IInnerOsAccountManager::CleanGarbageOsAccountsAsync()
2512 {
2513 auto task = [] {
2514 IInnerOsAccountManager::GetInstance().CleanGarbageOsAccounts();
2515 #ifdef SUPPORT_DOMAIN_ACCOUNTS
2516 InnerDomainAccountManager::GetInstance().CleanUnbindDomainAccount();
2517 #endif // SUPPORT_DOMAIN_ACCOUNTS
2518 };
2519 std::thread cleanThread(task);
2520 pthread_setname_np(cleanThread.native_handle(), "CleanGarbage");
2521 cleanThread.detach();
2522 }
2523
2524 ErrCode IInnerOsAccountManager::SetOsAccountIsVerified(const int id, const bool isVerified)
2525 {
2526 std::lock_guard<std::mutex> lock(*GetOrInsertUpdateLock(id));
2527 OsAccountInfo osAccountInfo;
2528 ErrCode errCode = GetRealOsAccountInfoById(id, osAccountInfo);
2529 if (errCode != ERR_OK) {
2530 ACCOUNT_LOGE("Get osaccount info error, errCode %{public}d.", errCode);
2531 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
2532 }
2533
2534 // to be removed, cannot change any thing
2535 if (osAccountInfo.GetToBeRemoved()) {
2536 ACCOUNT_LOGE("Account %{public}d will be removed, cannot change verify state!", id);
2537 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_TO_BE_REMOVED_ERROR;
2538 }
2539 bool preVerified = osAccountInfo.GetIsVerified();
2540
2541 if (isVerified) {
2542 verifiedAccounts_.EnsureInsert(id, true);
2543 // report data size when account with verification verified
2544 ReportUserDataSize(GetVerifiedAccountIds(verifiedAccounts_));
2545 } else {
2546 verifiedAccounts_.Erase(id);
2547 }
2548 if (isVerified && !preVerified) {
2549 OsAccountInterface::PublishCommonEvent(osAccountInfo,
2550 OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED, Constants::OPERATION_UNLOCK);
2551 subscribeManager_.Publish(id, OS_ACCOUNT_SUBSCRIBE_TYPE::UNLOCKED);
2552 ReportOsAccountLifeCycle(id, Constants::OPERATION_UNLOCK);
2553
2554 CleanGarbageOsAccountsAsync();
2555 }
2556
2557 return ERR_OK;
2558 }
2559
2560 ErrCode IInnerOsAccountManager::SetOsAccountIsLoggedIn(const int32_t id, const bool isLoggedIn)
2561 {
2562 std::lock_guard<std::mutex> lock(*GetOrInsertUpdateLock(id));
2563 OsAccountInfo osAccountInfo;
2564 ErrCode errCode = GetRealOsAccountInfoById(id, osAccountInfo);
2565 if (errCode != ERR_OK) {
2566 ACCOUNT_LOGE("Get osaccount info error, errCode %{public}d.", errCode);
2567 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
2568 }
2569 if (osAccountInfo.GetToBeRemoved()) {
2570 ACCOUNT_LOGE("Account %{public}d will be removed, cannot change verify state!", id);
2571 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_TO_BE_REMOVED_ERROR;
2572 }
2573 if (isLoggedIn) {
2574 loggedInAccounts_.EnsureInsert(id, true);
2575 } else {
2576 loggedInAccounts_.Erase(id);
2577 }
2578 if (!osAccountInfo.GetIsLoggedIn()) {
2579 #ifdef ACTIVATE_LAST_LOGGED_IN_ACCOUNT
2580 {
2581 std::lock_guard<std::mutex> operatingLock(operatingMutex_);
2582 osAccountControl_->SetDefaultActivatedOsAccount(id);
2583 defaultActivatedId_ = id;
2584 }
2585 #endif
2586 osAccountInfo.SetLastLoginTime(std::chrono::duration_cast<std::chrono::seconds>(
2587 std::chrono::system_clock::now().time_since_epoch()).count());
2588 }
2589 errCode = osAccountControl_->UpdateOsAccount(osAccountInfo);
2590 if (errCode != ERR_OK && errCode != ERR_ACCOUNT_COMMON_DATA_NO_SPACE) {
2591 ACCOUNT_LOGE("Update account info failed, errCode: %{public}d, id: %{public}d", errCode, id);
2592 return ERR_OSACCOUNT_SERVICE_INNER_UPDATE_ACCOUNT_ERROR;
2593 }
2594 return ERR_OK;
2595 }
2596
2597 ErrCode IInnerOsAccountManager::GetOsAccountCredentialId(const int id, uint64_t &credentialId)
2598 {
2599 credentialId = 0;
2600 OsAccountInfo osAccountInfo;
2601 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(id, osAccountInfo);
2602 if (errCode == ERR_OK) {
2603 credentialId = osAccountInfo.GetCredentialId();
2604 }
2605 return errCode;
2606 }
2607
2608 ErrCode IInnerOsAccountManager::SetOsAccountCredentialId(const int id, uint64_t credentialId)
2609 {
2610 OsAccountInfo osAccountInfo;
2611 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(id, osAccountInfo);
2612 if (errCode != ERR_OK) {
2613 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
2614 }
2615
2616 osAccountInfo.SetCredentialId(credentialId);
2617 errCode = osAccountControl_->UpdateOsAccount(osAccountInfo);
2618 if (errCode != ERR_OK) {
2619 ACCOUNT_LOGE("Update osaccount info error %{public}d, id: %{public}d",
2620 errCode, osAccountInfo.GetLocalId());
2621 return ERR_OSACCOUNT_SERVICE_INNER_UPDATE_ACCOUNT_ERROR;
2622 }
2623 return ERR_OK;
2624 }
2625
2626 ErrCode IInnerOsAccountManager::SetDefaultActivatedOsAccount(const int32_t id)
2627 {
2628 std::lock_guard<std::mutex> lock(operatingMutex_);
2629 if (id == defaultActivatedId_) {
2630 ACCOUNT_LOGW("No need to repeat set initial start id %{public}d", id);
2631 return ERR_OK;
2632 }
2633 OsAccountInfo osAccountInfo;
2634 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(id, osAccountInfo);
2635 if (errCode != ERR_OK) {
2636 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
2637 }
2638
2639 errCode = IsValidOsAccount(osAccountInfo);
2640 if (errCode != ERR_OK) {
2641 return errCode;
2642 }
2643 errCode = osAccountControl_->SetDefaultActivatedOsAccount(id);
2644 if (errCode != ERR_OK) {
2645 ACCOUNT_LOGE("Set default activated account id error %{public}d, id: %{public}d", errCode, id);
2646 return errCode;
2647 }
2648 defaultActivatedId_ = id;
2649 return ERR_OK;
2650 }
2651
2652 ErrCode IInnerOsAccountManager::IsOsAccountForeground(const int32_t localId, const uint64_t displayId,
2653 bool &isForeground)
2654 {
2655 int32_t id;
2656 if (!foregroundAccountMap_.Find(displayId, id)) {
2657 return ERR_ACCOUNT_COMMON_ACCOUNT_IN_DISPLAY_ID_NOT_FOUND_ERROR;
2658 }
2659 isForeground = (id == localId);
2660 return ERR_OK;
2661 }
2662
2663 ErrCode IInnerOsAccountManager::GetForegroundOsAccountLocalId(const uint64_t displayId, int32_t &localId)
2664 {
2665 if (!foregroundAccountMap_.Find(displayId, localId)) {
2666 return ERR_ACCOUNT_COMMON_ACCOUNT_IN_DISPLAY_ID_NOT_FOUND_ERROR;
2667 }
2668 return ERR_OK;
2669 }
2670
2671 ErrCode IInnerOsAccountManager::GetForegroundOsAccounts(std::vector<ForegroundOsAccount> &accounts)
2672 {
2673 accounts.clear();
2674 auto it = [&](uint64_t displayId, int32_t localId) {
2675 ForegroundOsAccount foregroundOsAccount;
2676 foregroundOsAccount.displayId = displayId;
2677 foregroundOsAccount.localId = localId;
2678 accounts.emplace_back(foregroundOsAccount);
2679 };
2680 foregroundAccountMap_.Iterate(it);
2681 return ERR_OK;
2682 }
2683
2684 ErrCode IInnerOsAccountManager::GetBackgroundOsAccountLocalIds(std::vector<int32_t> &localIds)
2685 {
2686 localIds.clear();
2687 std::vector<int32_t> activatedIds;
2688 CopyFromActiveList(activatedIds);
2689
2690 std::vector<int32_t> foregroundIds;
2691 auto it = [&](uint64_t displayId, int32_t localId) {
2692 foregroundIds.emplace_back(localId);
2693 };
2694 foregroundAccountMap_.Iterate(it);
2695 std::unordered_set<int32_t> foregroundSet(foregroundIds.begin(), foregroundIds.end());
2696 for (const auto &id : activatedIds) {
2697 if (foregroundSet.find(id) == foregroundSet.end()) {
2698 localIds.emplace_back(id);
2699 }
2700 }
2701 ACCOUNT_LOGI("Get background list successful, total=%{public}zu.", localIds.size());
2702 return ERR_OK;
2703 }
2704
2705 ErrCode IInnerOsAccountManager::GetDefaultActivatedOsAccount(int32_t &id)
2706 {
2707 std::lock_guard<std::mutex> lock(operatingMutex_);
2708 id = defaultActivatedId_;
2709 return ERR_OK;
2710 }
2711
2712 ErrCode IInnerOsAccountManager::IsAllowedCreateAdmin(bool &isAllowedCreateAdmin)
2713 {
2714 return osAccountControl_->IsAllowedCreateAdmin(isAllowedCreateAdmin);
2715 }
2716
2717 ErrCode IInnerOsAccountManager::GetCreatedOsAccountNumFromDatabase(const std::string& storeID,
2718 int &createdOsAccountNum)
2719 {
2720 return osAccountControl_->GetCreatedOsAccountNumFromDatabase(storeID, createdOsAccountNum);
2721 }
2722
2723 ErrCode IInnerOsAccountManager::GetSerialNumberFromDatabase(const std::string& storeID,
2724 int64_t &serialNumber)
2725 {
2726 return osAccountControl_->GetSerialNumberFromDatabase(storeID, serialNumber);
2727 }
2728
2729 ErrCode IInnerOsAccountManager::GetMaxAllowCreateIdFromDatabase(const std::string& storeID, int &id)
2730 {
2731 #ifdef ENABLE_MULTIPLE_OS_ACCOUNTS
2732 return osAccountControl_->GetMaxAllowCreateIdFromDatabase(storeID, id);
2733 #else
2734 id = Constants::START_USER_ID;
2735 return ERR_OK;
2736 #endif // ENABLE_MULTIPLE_OS_ACCOUNTS
2737 }
2738
2739 ErrCode IInnerOsAccountManager::GetOsAccountFromDatabase(const std::string& storeID, const int id,
2740 OsAccountInfo &osAccountInfo)
2741 {
2742 return osAccountControl_->GetOsAccountFromDatabase(storeID, id, osAccountInfo);
2743 }
2744
2745 ErrCode IInnerOsAccountManager::GetOsAccountListFromDatabase(const std::string& storeID,
2746 std::vector<OsAccountInfo> &osAccountList)
2747 {
2748 return osAccountControl_->GetOsAccountListFromDatabase(storeID, osAccountList);
2749 }
2750
2751 void IInnerOsAccountManager::RemoveLocalIdToOperating(int32_t localId)
2752 {
2753 std::lock_guard<std::mutex> lock(operatingMutex_);
2754 auto it = std::find(operatingId_.begin(), operatingId_.end(), localId);
2755 if (it != operatingId_.end()) {
2756 operatingId_.erase(it);
2757 }
2758 }
2759
2760 bool IInnerOsAccountManager::CheckAndAddLocalIdOperating(int32_t localId)
2761 {
2762 std::lock_guard<std::mutex> lock(operatingMutex_);
2763 if (std::find(operatingId_.begin(), operatingId_.end(), localId) != operatingId_.end()) {
2764 return false;
2765 }
2766 operatingId_.push_back(localId);
2767 return true;
2768 }
2769
2770 #ifdef FUZZ_TEST
2771 // LCOV_EXCL_START
2772 #endif
2773 ErrCode IInnerOsAccountManager::QueryActiveOsAccountIds(std::vector<int32_t>& ids)
2774 {
2775 CopyFromActiveList(ids);
2776 #ifdef ENABLE_U1_ACCOUNT
2777 if (ids.size() == 1 && ids[0] == Constants::U1_ID) {
2778 ids.clear();
2779 }
2780 #endif // ENABLE_U1_ACCOUNT
2781 return ERR_OK;
2782 }
2783 #ifdef FUZZ_TEST
2784 // LCOV_EXCL_STOP
2785 #endif
2786
2787 void IInnerOsAccountManager::PushIdIntoActiveList(int32_t id)
2788 {
2789 std::lock_guard<std::mutex> lock(ativeMutex_);
2790 if (std::find(activeAccountId_.begin(), activeAccountId_.end(), id) == activeAccountId_.end()) {
2791 CountTraceAdapter("activeId", (int64_t)id);
2792 }
2793 #ifndef ENABLE_MULTIPLE_ACTIVE_ACCOUNTS
2794 activeAccountId_.clear();
2795 #else
2796 activeAccountId_.erase(std::remove(activeAccountId_.begin(), activeAccountId_.end(), id), activeAccountId_.end());
2797 #endif
2798 //Compatible with the QueryActiveOsAccountIds
2799 activeAccountId_.insert(activeAccountId_.begin(), id);
2800 return;
2801 }
2802
2803 void IInnerOsAccountManager::EraseIdFromActiveList(int32_t id)
2804 {
2805 std::lock_guard<std::mutex> lock(ativeMutex_);
2806 if (std::find(activeAccountId_.begin(), activeAccountId_.end(), id) != activeAccountId_.end()) {
2807 ACCOUNT_LOGE("EraseIdFromActiveList enter0");
2808 activeAccountId_.erase(
2809 std::remove(activeAccountId_.begin(), activeAccountId_.end(), id), activeAccountId_.end());
2810 } else {
2811 ACCOUNT_LOGI("Os account is not in active list, no need to erase!");
2812 }
2813 CountTraceAdapter("deActiveId", (int64_t)id);
2814 }
2815
2816 bool IInnerOsAccountManager::IsOsAccountIDInActiveList(int32_t id)
2817 {
2818 std::lock_guard<std::mutex> lock(ativeMutex_);
2819 auto it = std::find(activeAccountId_.begin(), activeAccountId_.end(), id);
2820 return (it != activeAccountId_.end());
2821 }
2822
2823 void IInnerOsAccountManager::CopyFromActiveList(std::vector<int32_t>& idList)
2824 {
2825 idList.clear();
2826 std::lock_guard<std::mutex> lock(ativeMutex_);
2827 for (auto it = activeAccountId_.begin(); it != activeAccountId_.end(); it++) {
2828 idList.push_back(*it);
2829 }
2830 }
2831
2832 #ifdef SUPPORT_DOMAIN_ACCOUNTS
2833 ErrCode IInnerOsAccountManager::UpdateAccountInfoByDomainAccountInfo(
2834 int32_t userId, const DomainAccountInfo &newDomainAccountInfo)
2835 {
2836 if (!CheckAndAddLocalIdOperating(userId)) {
2837 ACCOUNT_LOGW("Account id = %{public}d already in operating", userId);
2838 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_OPERATING_ERROR;
2839 }
2840 OsAccountInfo accountInfo;
2841 ErrCode result = osAccountControl_->GetOsAccountInfoById(userId, accountInfo);
2842 if (result != ERR_OK) {
2843 RemoveLocalIdToOperating(userId);
2844 return result;
2845 }
2846 DomainAccountInfo oldDomainAccountInfo;
2847 accountInfo.GetDomainInfo(oldDomainAccountInfo);
2848 if (!newDomainAccountInfo.accountName_.empty()) {
2849 oldDomainAccountInfo.accountName_ = newDomainAccountInfo.accountName_;
2850 }
2851 if (!newDomainAccountInfo.accountId_.empty()) {
2852 oldDomainAccountInfo.accountId_ = newDomainAccountInfo.accountId_;
2853 }
2854 if (!newDomainAccountInfo.serverConfigId_.empty()) {
2855 oldDomainAccountInfo.serverConfigId_ = newDomainAccountInfo.serverConfigId_;
2856 }
2857 if (!newDomainAccountInfo.domain_.empty()) {
2858 oldDomainAccountInfo.domain_ = newDomainAccountInfo.domain_;
2859 }
2860 accountInfo.SetDomainInfo(oldDomainAccountInfo);
2861 result = osAccountControl_->UpdateOsAccount(accountInfo);
2862 if (result != ERR_OK) {
2863 ACCOUNT_LOGE("Update account info failed, result = %{public}d", result);
2864 ReportOsAccountOperationFail(userId, OPERATION_UPDATE, result,
2865 "Failed to update domain account info");
2866 RemoveLocalIdToOperating(userId);
2867 return result;
2868 }
2869 RemoveLocalIdToOperating(userId);
2870 #ifdef HAS_CES_PART
2871 AccountEventProvider::EventPublish(EventFwk::CommonEventSupport::COMMON_EVENT_USER_INFO_UPDATED,
2872 userId, nullptr);
2873 #endif // HAS_CES_PART
2874 return ERR_OK;
2875 }
2876 #endif // SUPPORT_DOMAIN_ACCOUNTS
2877
2878 ErrCode IInnerOsAccountManager::UpdateAccountToBackground(int32_t oldId)
2879 {
2880 OsAccountInfo oldOsAccountInfo;
2881 {
2882 std::lock_guard<std::mutex> lock(*GetOrInsertUpdateLock(oldId));
2883 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(oldId, oldOsAccountInfo);
2884 if (errCode != ERR_OK) {
2885 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
2886 }
2887 }
2888 OsAccountInterface::PublishCommonEvent(oldOsAccountInfo,
2889 OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_USER_BACKGROUND, Constants::OPERATION_SWITCH);
2890 #ifdef ENABLE_MULTIPLE_ACTIVE_ACCOUNTS
2891 #ifndef SUPPORT_STOP_MAIN_OS_ACCOUNT
2892 if (oldId == Constants::START_USER_ID) {
2893 return ERR_OK;
2894 }
2895 #endif
2896 bool isLoggedIn = false;
2897 if ((oldOsAccountInfo.GetType() != OsAccountType::PRIVATE) && (!loggedInAccounts_.Find(oldId, isLoggedIn))) {
2898 std::this_thread::sleep_for(std::chrono::milliseconds(DELAY_FOR_DEACTIVATE_OS_ACCOUNT));
2899 DeactivateOsAccount(oldId, false);
2900 }
2901 #else
2902 DeactivateOsAccountByInfo(oldOsAccountInfo);
2903 #endif // ENABLE_MULTIPLE_ACTIVE_ACCOUNTS
2904 return ERR_OK;
2905 }
2906
2907 std::shared_ptr<std::mutex> IInnerOsAccountManager::GetOrInsertUpdateLock(int32_t id)
2908 {
2909 std::lock_guard<std::mutex> lock(updateLockMutex_);
2910 auto it = updateLocks_.find(id);
2911 if (it == updateLocks_.end()) {
2912 auto mutexPtr = std::make_shared<std::mutex>();
2913 updateLocks_.insert(std::make_pair(id, mutexPtr));
2914 return mutexPtr;
2915 } else {
2916 return it->second;
2917 }
2918 }
2919
2920 ErrCode IInnerOsAccountManager::SetOsAccountToBeRemoved(int32_t localId, bool toBeRemoved)
2921 {
2922 if (!CheckAndAddLocalIdOperating(localId)) {
2923 ACCOUNT_LOGE("The account %{public}d already in operating", localId);
2924 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_OPERATING_ERROR;
2925 }
2926 OsAccountInfo osAccountInfo;
2927 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(localId, osAccountInfo);
2928 if (errCode != ERR_OK) {
2929 ACCOUNT_LOGE("Get osaccount info error, errCode %{public}d.", errCode);
2930 ReportOsAccountOperationFail(localId, OPERATION_SET_TO_BE_REMOVED, errCode,
2931 "Get account info failed when set ToBeRemoved");
2932 RemoveLocalIdToOperating(localId);
2933 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
2934 }
2935
2936 if (toBeRemoved && (localId == defaultActivatedId_)) {
2937 ErrCode result = osAccountControl_->SetDefaultActivatedOsAccount(Constants::START_USER_ID);
2938 if (result != ERR_OK) {
2939 ReportOsAccountOperationFail(localId, OPERATION_SET_TO_BE_REMOVED, result,
2940 "Persist defaultActivatedId to START_USER_ID failed");
2941 ACCOUNT_LOGE("SetDefaultActivatedOsAccount persist failed, err=%{public}d, keep memory unchanged", result);
2942 RemoveLocalIdToOperating(localId);
2943 return result;
2944 }
2945 defaultActivatedId_ = Constants::START_USER_ID;
2946 ACCOUNT_LOGE("Default activated account updated to START_USER_ID");
2947 }
2948
2949 osAccountInfo.SetToBeRemoved(toBeRemoved);
2950 errCode = osAccountControl_->UpdateOsAccount(osAccountInfo);
2951 if (errCode != ERR_OK) {
2952 ReportOsAccountOperationFail(localId, OPERATION_SET_TO_BE_REMOVED, errCode,
2953 "Update ToBeRemoved flag failed");
2954 ACCOUNT_LOGE("Update ToBeRemoved flag failed, err=%{public}d", errCode);
2955 }
2956 RemoveLocalIdToOperating(localId);
2957 ReportOsAccountLifeCycle(localId, OPERATION_SET_TO_BE_REMOVED);
2958 return errCode;
2959 }
2960
2961 ErrCode IInnerOsAccountManager::IsValidOsAccount(const OsAccountInfo &osAccountInfo)
2962 {
2963 if (!osAccountInfo.GetIsCreateCompleted()) {
2964 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_IS_UNCOMPLETED_ERROR;
2965 }
2966
2967 if (osAccountInfo.GetToBeRemoved()) {
2968 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_TO_BE_REMOVED_ERROR;
2969 }
2970 return ERR_OK;
2971 }
2972
2973 ErrCode IInnerOsAccountManager::GetOsAccountDomainInfo(const int32_t localId, DomainAccountInfo &domainInfo)
2974 {
2975 #ifdef SUPPORT_DOMAIN_ACCOUNTS
2976 return InnerDomainAccountManager::GetInstance().GetDomainAccountInfoByUserId(localId, domainInfo);
2977 #else
2978 OsAccountInfo accountInfo;
2979 ErrCode errCode = GetRealOsAccountInfoById(localId, accountInfo);
2980 if (errCode != ERR_OK) {
2981 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
2982 }
2983 accountInfo.GetDomainInfo(domainInfo);
2984 if (domainInfo.accountName_.empty()) {
2985 return ERR_DOMAIN_ACCOUNT_SERVICE_NOT_DOMAIN_ACCOUNT;
2986 }
2987 return ERR_OK;
2988 #endif // SUPPORT_DOMAIN_ACCOUNTS
2989 }
2990
2991 ErrCode IInnerOsAccountManager::UpdateServerConfig(const std::string &configId,
2992 const DomainServerConfig &config)
2993 {
2994 #ifdef SUPPORT_DOMAIN_ACCOUNTS
2995 std::vector<OsAccountInfo> osAccountInfos;
2996 ErrCode errCode = osAccountControl_->GetOsAccountList(osAccountInfos);
2997 if (errCode != ERR_OK) {
2998 REPORT_OS_ACCOUNT_FAIL(-1, Constants::OPERATION_UPDATE_SERVER_CONFIG,
2999 errCode, "Get osAcount list error.");
3000 ACCOUNT_LOGE("GetOsAccountList error:%{public}d", errCode);
3001 return errCode;
3002 }
3003 errCode = ERR_OK;
3004 for (auto osAccountInfosPtr = osAccountInfos.begin(); osAccountInfosPtr != osAccountInfos.end();
3005 ++osAccountInfosPtr) {
3006 DomainAccountInfo curDomainInfo;
3007 osAccountInfosPtr->GetDomainInfo(curDomainInfo);
3008 if (curDomainInfo.IsSameServerConfigId(configId)) {
3009 curDomainInfo.SetServerConfigId(config.id_);
3010 curDomainInfo.SetDomain(config.domain_);
3011 osAccountInfosPtr->SetDomainInfo(curDomainInfo);
3012 ErrCode err = osAccountControl_->UpdateOsAccount(*osAccountInfosPtr);
3013 if (err != ERR_OK) {
3014 REPORT_OS_ACCOUNT_FAIL(osAccountInfosPtr->GetLocalId(), Constants::OPERATION_UPDATE_SERVER_CONFIG,
3015 errCode, "Update serverConfig error.");
3016 ACCOUNT_LOGE("UpdateOsAccount localId:%{public}d error:%{public}d",
3017 osAccountInfosPtr->GetLocalId(), errCode);
3018 errCode = err;
3019 }
3020 }
3021 }
3022 return errCode;
3023 #else
3024 return ERR_OK;
3025 #endif // SUPPORT_DOMAIN_ACCOUNTS
3026 }
3027
3028 std::vector<int32_t> IInnerOsAccountManager::GetVerifiedAccountIds(const SafeMap<int32_t, bool> &verifiedAccounts)
3029 {
3030 std::vector<int32_t> verifiedAccountIds;
3031
3032 //find verified account id vector
3033 SafeMap<int32_t, bool>::SafeMapCallBack callback = [&](const int32_t key, bool& value) {
3034 if (value) {
3035 verifiedAccountIds.push_back(static_cast<int32_t>(key));
3036 }
3037 };
3038
3039 (static_cast<SafeMap<int32_t, bool>>(verifiedAccounts)).Iterate(callback);
3040 return verifiedAccountIds;
3041 }
3042
3043 #ifdef SUPPORT_LOCK_OS_ACCOUNT
3044 ErrCode IInnerOsAccountManager::IsOsAccountLocking(const int id, bool &isLocking)
3045 {
3046 isLocking = false;
3047 lockingAccounts_.Find(id, isLocking);
3048 return ERR_OK;
3049 }
3050
3051 ErrCode IInnerOsAccountManager::PublishOsAccountLockEvent(const int32_t localId, bool isLocking)
3052 {
3053 if (isLocking) {
3054 #ifdef HAS_CES_PART
3055 AccountEventProvider::EventPublishAsUser(
3056 EventFwk::CommonEventSupport::COMMON_EVENT_USER_LOCKING, localId);
3057 #else // HAS_CES_PART
3058 ACCOUNT_LOGI("No common event part! Publish nothing!");
3059 #endif // HAS_CES_PART
3060 return subscribeManager_.Publish(localId, OS_ACCOUNT_SUBSCRIBE_TYPE::LOCKING);
3061 } else {
3062 #ifdef HAS_CES_PART
3063 AccountEventProvider::EventPublishAsUser(
3064 EventFwk::CommonEventSupport::COMMON_EVENT_USER_LOCKED, localId);
3065 #else // HAS_CES_PART
3066 ACCOUNT_LOGI("No common event part! Publish nothing!");
3067 #endif // HAS_CES_PART
3068 return subscribeManager_.Publish(localId, OS_ACCOUNT_SUBSCRIBE_TYPE::LOCKED);
3069 }
3070 return ERR_OK;
3071 }
3072
3073 ErrCode IInnerOsAccountManager::LockOsAccount(const int32_t localId)
3074 {
3075 if (!lockOsAccountPluginManager_.IsPluginAvailable()) {
3076 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_PLUGIN_NOT_EXIST_ERROR;
3077 }
3078
3079 if (!CheckAndAddLocalIdOperating(localId)) {
3080 ACCOUNT_LOGW("Account id = %{public}d already in operating", localId);
3081 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_OPERATING_ERROR;
3082 }
3083 OsAccountInfo osAccountInfo;
3084 ErrCode errCode = GetRealOsAccountInfoById(localId, osAccountInfo);
3085 if (errCode != ERR_OK) {
3086 RemoveLocalIdToOperating(localId);
3087 ACCOUNT_LOGW("Cannot find os account info by id:%{public}d, errCode %{public}d.", localId, errCode);
3088 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
3089 }
3090
3091 errCode = IsValidOsAccount(osAccountInfo);
3092 if (errCode != ERR_OK) {
3093 RemoveLocalIdToOperating(localId);
3094 return errCode;
3095 }
3096
3097 if (!osAccountInfo.GetIsVerified()) {
3098 RemoveLocalIdToOperating(localId);
3099 ACCOUNT_LOGW("Account %{public}d is neither active nor verified, don't need to lock!", localId);
3100 return ERR_OK;
3101 }
3102
3103 lockingAccounts_.EnsureInsert(localId, true);
3104
3105 int32_t ret = lockOsAccountPluginManager_.LockOsAccount(localId);
3106 if (ret != ERR_OK) {
3107 lockingAccounts_.Erase(localId);
3108 RemoveLocalIdToOperating(localId);
3109 ACCOUNT_LOGE("Failed to lock os account, ret is %{public}d", ret);
3110 ReportOsAccountOperationFail(localId, OPERATION_LOCK, ret, "Lock OsAccount failed!");
3111 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_LOCK_ERROR;
3112 }
3113 lockingAccounts_.Erase(localId);
3114 verifiedAccounts_.Erase(localId);
3115
3116 RemoveLocalIdToOperating(localId);
3117
3118 ReportOsAccountLifeCycle(localId, Constants::OPERATION_LOCKED);
3119
3120 return ERR_OK;
3121 }
3122 #endif
3123
3124 OsAccountControlFileManager &IInnerOsAccountManager::GetFileController()
3125 {
3126 return *std::reinterpret_pointer_cast<OsAccountControlFileManager>(osAccountControl_);
3127 }
3128 } // namespace AccountSA
3129 } // namespace OHOS