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 <unistd.h>
20 #include "account_constants.h"
21 #include "account_info.h"
22 #include "account_info_report.h"
23 #include "account_log_wrapper.h"
24 #include "os_account_info.h"
25 #ifdef HAS_CES_PART
26 #include "common_event_support.h"
27 #endif // HAS_CES_PART
28 #include "domain_account_callback_service.h"
29 #include "hitrace_adapter.h"
30 #include "account_hisysevent_adapter.h"
31 #include "app_account_control_manager.h"
32 #include "ohos_account_kits.h"
33 #include "os_account_constants.h"
34 #include "os_account_control_file_manager.h"
35 #include "os_account_domain_account_callback.h"
36 #include "os_account_subscribe_manager.h"
37 #include "parameter.h"
38 #include "parcel.h"
39 #include <pthread.h>
40 #include <thread>
41 #include <unordered_set>
42 #ifdef HICOLLIE_ENABLE
43 #include "account_timer.h"
44 #include "xcollie/xcollie.h"
45 #endif // HICOLLIE_ENABLE
46
47 namespace OHOS {
48 namespace AccountSA {
49 namespace {
50 const std::string CONSTRAINT_CREATE_ACCOUNT_DIRECTLY = "constraint.os.account.create.directly";
51 const std::string ACCOUNT_READY_EVENT = "bootevent.account.ready";
52 const std::string PARAM_LOGIN_NAME_MAX = "persist.account.login_name_max";
53 const std::string SPECIAL_CHARACTER_ARRAY = "<>|\":*?/\\";
54 const std::vector<std::string> SHORT_NAME_CANNOT_BE_NAME_ARRAY = {".", ".."};
55 constexpr int32_t DELAY_FOR_EXCEPTION = 50;
56 constexpr int32_t MAX_RETRY_TIMES = 50;
57 constexpr int32_t MAX_PRIVATE_TYPE_NUMBER = 1;
58 constexpr int32_t DELAY_FOR_REMOVING_FOREGROUND_OS_ACCOUNT = 1500;
59 }
60
IInnerOsAccountManager()61 IInnerOsAccountManager::IInnerOsAccountManager() : subscribeManager_(OsAccountSubscribeManager::GetInstance()),
62 pluginManager_(OsAccountPluginManager::GetInstance())
63 {
64 activeAccountId_.clear();
65 operatingId_.clear();
66 osAccountControl_ = std::make_shared<OsAccountControlFileManager>();
67 osAccountControl_->Init();
68 osAccountControl_->GetDeviceOwnerId(deviceOwnerId_);
69 osAccountControl_->GetDefaultActivatedOsAccount(defaultActivatedId_);
70 osAccountControl_->GetOsAccountConfig(config_);
71 ACCOUNT_LOGI("Init end, maxOsAccountNum: %{public}d, maxLoggedInOsAccountNum: %{public}d",
72 config_.maxOsAccountNum, config_.maxLoggedInOsAccountNum);
73 }
74
GetInstance()75 IInnerOsAccountManager &IInnerOsAccountManager::GetInstance()
76 {
77 static IInnerOsAccountManager *instance = new (std::nothrow) IInnerOsAccountManager();
78 return *instance;
79 }
80
SetOsAccountControl(std::shared_ptr<IOsAccountControl> ptr)81 void IInnerOsAccountManager::SetOsAccountControl(std::shared_ptr<IOsAccountControl> ptr)
82 {
83 osAccountControl_ = ptr;
84 }
85
CreateBaseAdminAccount()86 void IInnerOsAccountManager::CreateBaseAdminAccount()
87 {
88 ACCOUNT_LOGI("start to create admin account");
89 bool isExistsAccount = false;
90 osAccountControl_->IsOsAccountExists(Constants::ADMIN_LOCAL_ID, isExistsAccount);
91 if (!isExistsAccount) {
92 int64_t serialNumber =
93 Constants::CARRY_NUM * Constants::SERIAL_NUMBER_NUM_START_FOR_ADMIN + Constants::ADMIN_LOCAL_ID;
94 OsAccountInfo osAccountInfo(
95 Constants::ADMIN_LOCAL_ID, Constants::ADMIN_LOCAL_NAME, OsAccountType::ADMIN, serialNumber);
96 int64_t time =
97 std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch())
98 .count();
99 osAccountInfo.SetCreateTime(time);
100 osAccountInfo.SetIsCreateCompleted(true);
101 osAccountInfo.SetIsActived(true); // admin local account is always active
102 osAccountControl_->InsertOsAccount(osAccountInfo);
103 ReportOsAccountLifeCycle(osAccountInfo.GetLocalId(), Constants::OPERATION_CREATE);
104 ACCOUNT_LOGI("OsAccountAccountMgr created admin account end");
105 } else {
106 ACCOUNT_LOGI("OsAccountAccountMgr admin account already exists");
107 }
108 }
109
CreateBaseStandardAccount()110 void IInnerOsAccountManager::CreateBaseStandardAccount()
111 {
112 ACCOUNT_LOGI("start to create base account");
113 int64_t serialNumber = 0;
114 osAccountControl_->GetSerialNumber(serialNumber);
115 #ifdef ENABLE_DEFAULT_ADMIN_NAME
116 OsAccountInfo osAccountInfo(Constants::START_USER_ID, Constants::STANDARD_LOCAL_NAME,
117 OsAccountType::ADMIN, serialNumber);
118 #else
119 OsAccountInfo osAccountInfo(Constants::START_USER_ID, "", OsAccountType::ADMIN, serialNumber);
120 #endif //ENABLE_DEFAULT_ADMIN_NAME
121 std::vector<std::string> constraints;
122 ErrCode errCode = osAccountControl_->GetConstraintsByType(OsAccountType::ADMIN, constraints);
123 if (errCode != ERR_OK) {
124 ACCOUNT_LOGE("Fail to get constraints by type for the system OS account, errCode %{public}d.", errCode);
125 return;
126 }
127 osAccountInfo.SetConstraints(constraints);
128 int64_t time =
129 std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch())
130 .count();
131 osAccountInfo.SetCreateTime(time);
132 osAccountInfo.SetIsCreateCompleted(false);
133 osAccountInfo.SetIsDataRemovable(false);
134 osAccountControl_->InsertOsAccount(osAccountInfo);
135 if (SendMsgForAccountCreate(osAccountInfo) != ERR_OK) {
136 ACCOUNT_LOGE("First OS account not created completely");
137 return;
138 }
139 SetDefaultActivatedOsAccount(Constants::START_USER_ID);
140 ACCOUNT_LOGI("OsAccountAccountMgr created base account end");
141 }
142
RetryToGetAccount(OsAccountInfo & osAccountInfo)143 void IInnerOsAccountManager::RetryToGetAccount(OsAccountInfo &osAccountInfo)
144 {
145 int32_t retryTimes = 0;
146 while (retryTimes < MAX_RETRY_TIMES) {
147 std::vector<OsAccountInfo> osAccountInfos;
148 QueryAllCreatedOsAccounts(osAccountInfos);
149 if (!osAccountInfos.empty() && (IsValidOsAccount(osAccountInfos[0]) == ERR_OK)) {
150 osAccountInfo = osAccountInfos[0];
151 return;
152 }
153 ACCOUNT_LOGE("fail to query accounts");
154 retryTimes++;
155 std::this_thread::sleep_for(std::chrono::milliseconds(DELAY_FOR_EXCEPTION));
156 }
157
158 #ifdef ENABLE_DEFAULT_ADMIN_NAME
159 while (CreateOsAccount(Constants::STANDARD_LOCAL_NAME, ADMIN, osAccountInfo) != ERR_OK) {
160 #else
161 while (CreateOsAccount("", ADMIN, osAccountInfo) != ERR_OK) {
162 #endif
163 ACCOUNT_LOGE("fail to create account");
164 std::this_thread::sleep_for(std::chrono::milliseconds(DELAY_FOR_EXCEPTION));
165 }
166 }
167
168 ErrCode IInnerOsAccountManager::GetRealOsAccountInfoById(const int id, OsAccountInfo &osAccountInfo)
169 {
170 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(id, osAccountInfo);
171 if (errCode != ERR_OK) {
172 return errCode;
173 }
174
175 bool isVerified = false;
176 verifiedAccounts_.Find(id, isVerified);
177 osAccountInfo.SetIsVerified(isVerified);
178
179 bool isLoggedIn = false;
180 loggedInAccounts_.Find(id, isLoggedIn);
181 osAccountInfo.SetIsLoggedIn(isLoggedIn);
182
183 bool isActivated = IsOsAccountIDInActiveList(id);
184 osAccountInfo.SetIsActived(isActivated);
185
186 int32_t foregroundId = -1;
187 foregroundAccountMap_.Find(Constants::DEFAULT_DISPALY_ID, foregroundId);
188 osAccountInfo.SetIsForeground(foregroundId == id);
189
190 return ERR_OK;
191 }
192
193 ErrCode IInnerOsAccountManager::ActivateDefaultOsAccount()
194 {
195 #ifdef HICOLLIE_ENABLE
196 int timerId =
197 HiviewDFX::XCollie::GetInstance().SetTimer(TIMER_NAME, TIMEOUT, nullptr, nullptr, HiviewDFX::XCOLLIE_FLAG_LOG);
198 #endif // HICOLLIE_ENABLE
199 ACCOUNT_LOGI("start to activate default account");
200 OsAccountInfo osAccountInfo;
201 ErrCode errCode = GetRealOsAccountInfoById(defaultActivatedId_, osAccountInfo);
202 if ((errCode != ERR_OK) || (IsValidOsAccount(osAccountInfo) != ERR_OK)) {
203 ACCOUNT_LOGE("account not found, localId: %{public}d, error: %{public}d", defaultActivatedId_, errCode);
204 ReportOsAccountOperationFail(defaultActivatedId_, Constants::OPERATION_ACTIVATE, errCode,
205 "Account not found or to be removed");
206 RetryToGetAccount(osAccountInfo);
207 ReportOsAccountOperationFail(osAccountInfo.GetLocalId(), Constants::OPERATION_ACTIVATE, errCode,
208 "Retry to get account");
209 SetDefaultActivatedOsAccount(osAccountInfo.GetLocalId());
210 }
211 // activate
212 errCode = SendMsgForAccountActivate(osAccountInfo);
213 if (errCode == ERR_OK) {
214 SetParameter(ACCOUNT_READY_EVENT.c_str(), "true");
215 }
216 #ifdef HICOLLIE_ENABLE
217 HiviewDFX::XCollie::GetInstance().CancelTimer(timerId);
218 #endif // HICOLLIE_ENABLE
219 return errCode;
220 }
221
222 void IInnerOsAccountManager::RestartActiveAccount()
223 {
224 // query active account to restart and refresh into list
225 std::vector<OsAccountInfo> osAccountInfos;
226 if (QueryAllCreatedOsAccounts(osAccountInfos) != ERR_OK) {
227 return;
228 }
229 for (size_t i = 0; i < osAccountInfos.size(); ++i) {
230 OsAccountInfo osAccountInfo = osAccountInfos[i];
231 std::int32_t id = osAccountInfo.GetLocalId();
232 if (osAccountInfo.GetIsActived() && id != Constants::START_USER_ID) {
233 // reactivate account state
234 if (ActivateOsAccount(id) != ERR_OK) {
235 ACCOUNT_LOGE("active base account failed");
236 return;
237 }
238 }
239 }
240 }
241
242 void IInnerOsAccountManager::ResetAccountStatus(void)
243 {
244 std::vector<int32_t> idList;
245 (void) osAccountControl_->GetOsAccountIdList(idList);
246 for (const auto id : idList) {
247 DeactivateOsAccountById(id);
248 }
249 }
250
251 ErrCode IInnerOsAccountManager::PrepareOsAccountInfo(const std::string &name, const OsAccountType &type,
252 const DomainAccountInfo &domainInfo, OsAccountInfo &osAccountInfo)
253 {
254 return PrepareOsAccountInfo(name, "", type, domainInfo, osAccountInfo);
255 }
256
257 ErrCode IInnerOsAccountManager::PrepareOsAccountInfo(const std::string &localName, const std::string &shortName,
258 const OsAccountType &type, const DomainAccountInfo &domainInfo, OsAccountInfo &osAccountInfo)
259 {
260 ErrCode errCode = FillOsAccountInfo(localName, shortName, type, domainInfo, osAccountInfo);
261 if (errCode != ERR_OK) {
262 return errCode;
263 }
264 errCode = ValidateOsAccount(osAccountInfo);
265 if (errCode != ERR_OK) {
266 ACCOUNT_LOGE("account name already exist, errCode %{public}d.", errCode);
267 return errCode;
268 }
269 errCode = CheckTypeNumber(type);
270 if (errCode != ERR_OK) {
271 ACCOUNT_LOGE("Check type number failed.");
272 return errCode;
273 }
274 if (!CheckAndAddLocalIdOperating(osAccountInfo.GetLocalId())) {
275 ACCOUNT_LOGW("Account id = %{public}d already in operating", osAccountInfo.GetLocalId());
276 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_OPERATING_ERROR;
277 }
278 errCode = osAccountControl_->InsertOsAccount(osAccountInfo);
279 if (errCode != ERR_OK) {
280 ACCOUNT_LOGE("insert os account info err, errCode %{public}d.", errCode);
281 return errCode;
282 }
283 osAccountControl_->UpdateAccountIndex(osAccountInfo, false);
284
285 errCode = osAccountControl_->UpdateBaseOAConstraints(std::to_string(osAccountInfo.GetLocalId()),
286 osAccountInfo.GetConstraints(), true);
287 if (errCode != ERR_OK) {
288 ACCOUNT_LOGE("UpdateBaseOAConstraints err");
289 return errCode;
290 }
291 return ERR_OK;
292 }
293
294 ErrCode IInnerOsAccountManager::FillOsAccountInfo(const std::string &localName, const std::string &shortName,
295 const OsAccountType &type, const DomainAccountInfo &domainInfo, OsAccountInfo &osAccountInfo)
296 {
297 int64_t serialNumber;
298 ErrCode errCode = osAccountControl_->GetSerialNumber(serialNumber);
299 if (errCode != ERR_OK) {
300 ACCOUNT_LOGE("failed to GetSerialNumber, errCode %{public}d.", errCode);
301 return errCode;
302 }
303 int id = 0;
304 errCode = osAccountControl_->GetAllowCreateId(id);
305 if (errCode != ERR_OK) {
306 ACCOUNT_LOGE("failed to GetAllowCreateId, errCode %{public}d.", errCode);
307 return errCode;
308 }
309 std::vector<std::string> constraints;
310 constraints.clear();
311 errCode = osAccountControl_->GetConstraintsByType(type, constraints);
312 if (errCode != ERR_OK) {
313 ACCOUNT_LOGE("Failed to GetConstraintsByType, errCode %{public}d.", errCode);
314 return errCode;
315 }
316
317 osAccountInfo = OsAccountInfo(id, localName, shortName, type, serialNumber);
318 osAccountInfo.SetConstraints(constraints);
319 int64_t time =
320 std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();
321 osAccountInfo.SetCreateTime(time);
322 if (!osAccountInfo.SetDomainInfo(domainInfo)) {
323 ACCOUNT_LOGE("failed to SetDomainInfo");
324 return ERR_OSACCOUNT_KIT_CREATE_OS_ACCOUNT_FOR_DOMAIN_ERROR;
325 }
326 return ERR_OK;
327 }
328
329 ErrCode IInnerOsAccountManager::PrepareOsAccountInfoWithFullInfo(OsAccountInfo &osAccountInfo)
330 {
331 int64_t serialNumber;
332 ErrCode errCode = osAccountControl_->GetSerialNumber(serialNumber);
333 if (errCode != ERR_OK) {
334 ACCOUNT_LOGE("Failed to GetSerialNumber, errCode %{public}d.", errCode);
335 return errCode;
336 }
337 osAccountInfo.SetSerialNumber(serialNumber);
338 osAccountInfo.SetIsDataRemovable(false);
339 errCode = osAccountControl_->SetNextLocalId(osAccountInfo.GetLocalId() + 1);
340 if (errCode != ERR_OK) {
341 ACCOUNT_LOGE("Failed to SetNextLocalId, errCode %{public}d.", errCode);
342 return errCode;
343 }
344 errCode = osAccountControl_->InsertOsAccount(osAccountInfo);
345 if ((errCode != ERR_OK) && (errCode != ERR_OSACCOUNT_SERVICE_CONTROL_INSERT_FILE_EXISTS_ERROR)) {
346 ACCOUNT_LOGE("Insert os account info err, errCode %{public}d.", errCode);
347 return errCode;
348 }
349
350 osAccountControl_->UpdateAccountIndex(osAccountInfo, false);
351
352 std::vector<std::string> constraints;
353 constraints.clear();
354 OsAccountType type = static_cast<OsAccountType>(osAccountInfo.GetType());
355 errCode = osAccountControl_->GetConstraintsByType(type, constraints);
356 if (errCode != ERR_OK) {
357 ACCOUNT_LOGE("Failed to GetConstraintsByType, errCode %{public}d.", errCode);
358 return errCode;
359 }
360 std::vector<std::string> constraintsExists = osAccountInfo.GetConstraints();
361 std::vector<std::string> constraintsResult;
362 std::merge(constraints.begin(), constraints.end(), constraintsExists.begin(), constraintsExists.end(),
363 std::back_inserter(constraintsResult));
364 osAccountInfo.SetConstraints(constraintsResult);
365 errCode = osAccountControl_->UpdateBaseOAConstraints(
366 std::to_string(osAccountInfo.GetLocalId()), constraintsResult, true);
367 if (errCode != ERR_OK) {
368 ACCOUNT_LOGE("UpdateBaseOAConstraints err");
369 return errCode;
370 }
371 return ERR_OK;
372 }
373
374 bool IInnerOsAccountManager::CheckAndCleanOsAccounts()
375 {
376 unsigned int osAccountNum = 0;
377 GetCreatedOsAccountsCount(osAccountNum);
378
379 if (osAccountNum < config_.maxOsAccountNum) {
380 return true;
381 }
382
383 ACCOUNT_LOGI("The number of OS accounts has oversize, attempting to clean garbage accounts.");
384 if (CleanGarbageOsAccounts() <= 0) {
385 ACCOUNT_LOGE("The number of OS accounts still oversize after cleaning, max num: %{public}d",
386 config_.maxOsAccountNum);
387 return false;
388 }
389 return true;
390 }
391
392 ErrCode IInnerOsAccountManager::SendMsgForAccountCreate(
393 OsAccountInfo &osAccountInfo, const CreateOsAccountOptions &options)
394 {
395 ErrCode errCode = OsAccountInterface::SendToStorageAccountCreate(osAccountInfo);
396 if (errCode != ERR_OK) {
397 ACCOUNT_LOGE("create os account SendToStorageAccountCreate failed, errCode %{public}d.", errCode);
398 return ERR_ACCOUNT_COMMON_GET_SYSTEM_ABILITY_MANAGER;
399 }
400 int32_t localId = osAccountInfo.GetLocalId();
401 #ifdef HAS_THEME_SERVICE_PART
402 auto task = [localId] { OsAccountInterface::InitThemeResource(localId); };
403 std::thread theme_thread(task);
404 pthread_setname_np(theme_thread.native_handle(), "InitTheme");
405 #endif
406 errCode = OsAccountInterface::SendToBMSAccountCreate(osAccountInfo, options.disallowedHapList);
407 if (errCode != ERR_OK) {
408 ACCOUNT_LOGE("create os account SendToBMSAccountCreate failed, errCode %{public}d.", errCode);
409 if (osAccountInfo.GetIsDataRemovable()) {
410 (void)OsAccountInterface::SendToStorageAccountRemove(osAccountInfo);
411 }
412 #ifdef HAS_THEME_SERVICE_PART
413 if (theme_thread.joinable()) {
414 theme_thread.join();
415 }
416 #endif
417 return errCode;
418 }
419 #ifdef HAS_THEME_SERVICE_PART
420 if (theme_thread.joinable()) {
421 theme_thread.join();
422 }
423 #endif
424 AppAccountControlManager::GetInstance().SetOsAccountRemoved(osAccountInfo.GetLocalId(), false);
425 osAccountInfo.SetIsCreateCompleted(true);
426 errCode = osAccountControl_->UpdateOsAccount(osAccountInfo);
427 if (errCode != ERR_OK) {
428 ACCOUNT_LOGE("create os account when update isCreateCompleted");
429 ReportOsAccountOperationFail(localId, Constants::OPERATION_CREATE, errCode, "Failed to update OS account");
430 if (osAccountInfo.GetIsDataRemovable()) {
431 (void)OsAccountInterface::SendToBMSAccountDelete(osAccountInfo);
432 (void)OsAccountInterface::SendToStorageAccountRemove(osAccountInfo);
433 }
434 return ERR_OSACCOUNT_SERVICE_INNER_UPDATE_ACCOUNT_ERROR;
435 }
436 (void)OsAccountInterface::SendToStorageAccountCreateComplete(localId);
437 ReportOsAccountLifeCycle(localId, Constants::OPERATION_CREATE);
438 OsAccountInterface::SendToCESAccountCreate(osAccountInfo);
439 subscribeManager_.Publish(localId, OS_ACCOUNT_SUBSCRIBE_TYPE::CREATED);
440 ACCOUNT_LOGI("OsAccountAccountMgr send to storage and bm for start success");
441 return ERR_OK;
442 }
443
444 ErrCode IInnerOsAccountManager::CreateOsAccount(
445 const std::string &name, const OsAccountType &type, OsAccountInfo &osAccountInfo)
446 {
447 if (!pluginManager_.IsCreationAllowed()) {
448 ACCOUNT_LOGI("Not allow creation account.");
449 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_PLUGIN_NOT_ALLOWED_CREATION_ERROR;
450 }
451 #ifdef HICOLLIE_ENABLE
452 AccountTimer timer;
453 #endif // HICOLLIE_ENABLE
454 if (!CheckAndCleanOsAccounts()) {
455 return ERR_OSACCOUNT_SERVICE_CONTROL_MAX_CAN_CREATE_ERROR;
456 }
457 DomainAccountInfo domainInfo; // default empty domain info
458 ErrCode errCode = PrepareOsAccountInfo(name, type, domainInfo, osAccountInfo);
459 if (errCode != ERR_OK) {
460 RemoveLocalIdToOperating(osAccountInfo.GetLocalId());
461 return errCode;
462 }
463 errCode = SendMsgForAccountCreate(osAccountInfo);
464 RemoveLocalIdToOperating(osAccountInfo.GetLocalId());
465 if (errCode != ERR_OK) {
466 (void)osAccountControl_->DelOsAccount(osAccountInfo.GetLocalId());
467 }
468 return errCode;
469 }
470
471 ErrCode IInnerOsAccountManager::CreateOsAccount(const std::string &localName, const std::string &shortName,
472 const OsAccountType &type, OsAccountInfo &osAccountInfo, const CreateOsAccountOptions &options)
473 {
474 if (!pluginManager_.IsCreationAllowed()) {
475 ACCOUNT_LOGI("Not allow creation account.");
476 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_PLUGIN_NOT_ALLOWED_CREATION_ERROR;
477 }
478 #ifdef HICOLLIE_ENABLE
479 AccountTimer timer;
480 #endif // HICOLLIE_ENABLE
481 osAccountInfo.SetLocalName(localName);
482 #ifdef ENABLE_ACCOUNT_SHORT_NAME
483 OsAccountInfo accountInfoOld;
484 ErrCode code = QueryOsAccountById(Constants::START_USER_ID, accountInfoOld);
485 if (code != ERR_OK) {
486 ACCOUNT_LOGE("QueryOsAccountById error, errCode %{public}d.", code);
487 return code;
488 }
489 if (accountInfoOld.GetShortName().empty()) {
490 accountInfoOld.SetType(type);
491 accountInfoOld.SetLocalName(localName);
492 accountInfoOld.SetShortName(shortName);
493 code = osAccountControl_->UpdateOsAccount(accountInfoOld);
494 if (code != ERR_OK) {
495 ReportOsAccountOperationFail(Constants::START_USER_ID, Constants::OPERATION_CREATE, code,
496 "Failed to update OS account");
497 }
498 osAccountControl_->UpdateAccountIndex(accountInfoOld, false);
499 osAccountInfo = accountInfoOld;
500 return code;
501 }
502 #endif // ENABLE_ACCOUNT_SHORT_NAME
503 if (!CheckAndCleanOsAccounts()) {
504 return ERR_OSACCOUNT_SERVICE_CONTROL_MAX_CAN_CREATE_ERROR;
505 }
506 DomainAccountInfo domainInfo; // default empty domain info
507 ErrCode errCode = PrepareOsAccountInfo(localName, shortName, type, domainInfo, osAccountInfo);
508 if (errCode != ERR_OK) {
509 RemoveLocalIdToOperating(osAccountInfo.GetLocalId());
510 return errCode;
511 }
512 errCode = SendMsgForAccountCreate(osAccountInfo, options);
513 RemoveLocalIdToOperating(osAccountInfo.GetLocalId());
514 if (errCode != ERR_OK) {
515 (void)osAccountControl_->DelOsAccount(osAccountInfo.GetLocalId());
516 }
517 return errCode;
518 }
519
520 ErrCode IInnerOsAccountManager::ValidateShortName(const std::string &shortName)
521 {
522 size_t shortNameSize = shortName.size();
523 if (shortNameSize == 0 || shortNameSize > Constants::SHORT_NAME_MAX_SIZE) {
524 ACCOUNT_LOGE("CreateOsAccount short name length %{public}zu is invalid!", shortNameSize);
525 return ERR_ACCOUNT_COMMON_INVALID_PARAMETER;
526 }
527
528 if (shortName.find_first_of(SPECIAL_CHARACTER_ARRAY) != std::string::npos) {
529 ACCOUNT_LOGE("CreateOsAccount short name is invalidate, short name is %{public}s !", shortName.c_str());
530 return ERR_ACCOUNT_COMMON_INVALID_PARAMETER;
531 }
532
533 for (size_t i = 0; i < SHORT_NAME_CANNOT_BE_NAME_ARRAY.size(); i++) {
534 if (shortName == SHORT_NAME_CANNOT_BE_NAME_ARRAY[i]) {
535 ACCOUNT_LOGE("CreateOsAccount short name is invalidate, short name is %{public}s !", shortName.c_str());
536 return ERR_ACCOUNT_COMMON_INVALID_PARAMETER;
537 }
538 }
539 return ERR_OK;
540 }
541
542 ErrCode IInnerOsAccountManager::CreateOsAccountWithFullInfo(OsAccountInfo &osAccountInfo,
543 const CreateOsAccountOptions &options)
544 {
545 if (!pluginManager_.IsCreationAllowed()) {
546 ACCOUNT_LOGI("Not allow creation account.");
547 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_PLUGIN_NOT_ALLOWED_CREATION_ERROR;
548 }
549 #ifdef HICOLLIE_ENABLE
550 AccountTimer timer;
551 #endif // HICOLLIE_ENABLE
552 if (!CheckAndAddLocalIdOperating(osAccountInfo.GetLocalId())) {
553 ACCOUNT_LOGW("Account id = %{public}d already in operating", osAccountInfo.GetLocalId());
554 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_OPERATING_ERROR;
555 }
556 ErrCode errCode = PrepareOsAccountInfoWithFullInfo(osAccountInfo);
557 if (errCode != ERR_OK) {
558 RemoveLocalIdToOperating(osAccountInfo.GetLocalId());
559 return errCode;
560 }
561 errCode = SendMsgForAccountCreate(osAccountInfo, options);
562 RemoveLocalIdToOperating(osAccountInfo.GetLocalId());
563 if (errCode != ERR_OK) {
564 (void)osAccountControl_->DelOsAccount(osAccountInfo.GetLocalId());
565 }
566 return errCode;
567 }
568
569 ErrCode IInnerOsAccountManager::UpdateAccountStatusForDomain(const int id, DomainAccountStatus status)
570 {
571 OsAccountInfo accountInfo;
572 DomainAccountInfo domainInfo;
573 ErrCode errCode = GetOsAccountInfoById(id, accountInfo);
574 if (errCode != ERR_OK) {
575 return errCode;
576 }
577 accountInfo.GetDomainInfo(domainInfo);
578 domainInfo.status_ = status;
579 accountInfo.SetDomainInfo(domainInfo);
580
581 errCode = osAccountControl_->UpdateOsAccount(accountInfo);
582 if (errCode != ERR_OK) {
583 ACCOUNT_LOGE("update osaccount info error %{public}d, id: %{public}d", errCode, accountInfo.GetLocalId());
584 return errCode;
585 }
586 return ERR_OK;
587 }
588
589 ErrCode IInnerOsAccountManager::UpdateOsAccountWithFullInfo(OsAccountInfo &newInfo)
590 {
591 int32_t localId = newInfo.GetLocalId();
592 if (!CheckAndAddLocalIdOperating(localId)) {
593 ACCOUNT_LOGE("the %{public}d already in operating", localId);
594 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_OPERATING_ERROR;
595 }
596 OsAccountInfo oldInfo;
597 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(localId, oldInfo);
598 if (errCode != ERR_OK) {
599 RemoveLocalIdToOperating(localId);
600 return errCode;
601 }
602 oldInfo.SetLocalName(newInfo.GetLocalName());
603 oldInfo.SetType(newInfo.GetType());
604 oldInfo.SetPhoto(newInfo.GetPhoto());
605 oldInfo.SetConstraints(newInfo.GetConstraints());
606 errCode = osAccountControl_->UpdateOsAccount(oldInfo);
607 osAccountControl_->UpdateAccountIndex(oldInfo, false);
608 newInfo = oldInfo;
609 if (errCode != ERR_OK) {
610 ReportOsAccountOperationFail(localId, Constants::OPERATION_UPDATE, errCode, "UpdateOsAccount failed!");
611 } else {
612 OsAccountInterface::PublishCommonEvent(oldInfo,
613 OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_USER_INFO_UPDATED, Constants::OPERATION_UPDATE);
614 }
615 RemoveLocalIdToOperating(localId);
616 return errCode;
617 }
618
619 bool IInnerOsAccountManager::CheckDomainAccountBound(
620 const std::vector<OsAccountInfo> &osAccountInfos, const DomainAccountInfo &info)
621 {
622 for (size_t i = 0; i < osAccountInfos.size(); ++i) {
623 DomainAccountInfo curInfo;
624 osAccountInfos[i].GetDomainInfo(curInfo);
625 if ((!info.accountId_.empty() && curInfo.accountId_ == info.accountId_) ||
626 ((curInfo.accountName_ == info.accountName_) && (curInfo.domain_ == info.domain_))) {
627 return true;
628 }
629 }
630 return false;
631 }
632
633 ErrCode IInnerOsAccountManager::BindDomainAccount(const OsAccountType &type, const DomainAccountInfo &domainAccountInfo,
634 const sptr<IDomainAccountCallback> &callback, const CreateOsAccountForDomainOptions &options)
635 {
636 std::vector<OsAccountInfo> osAccountInfos;
637 (void)QueryAllCreatedOsAccounts(osAccountInfos);
638 if (CheckDomainAccountBound(osAccountInfos, domainAccountInfo)) {
639 ACCOUNT_LOGE("the domain account is already bound");
640 return ERR_OSACCOUNT_SERVICE_INNER_DOMAIN_ALREADY_BIND_ERROR;
641 }
642 #ifdef ENABLE_MULTIPLE_OS_ACCOUNTS
643 bool isEnabled = false;
644 (void)IsOsAccountConstraintEnable(Constants::START_USER_ID, CONSTRAINT_CREATE_ACCOUNT_DIRECTLY, isEnabled);
645 #else
646 bool isEnabled = true;
647 #endif // ENABLE_MULTIPLE_OS_ACCOUNTS
648 OsAccountInfo osAccountInfo;
649 if (isEnabled && (osAccountInfos.size() == 1) && (osAccountInfos[0].GetLocalId() == Constants::START_USER_ID)) {
650 DomainAccountInfo curDomainInfo;
651 osAccountInfos[0].GetDomainInfo(curDomainInfo);
652 if (curDomainInfo.domain_.empty()) {
653 osAccountInfos[0].SetLocalName(domainAccountInfo.accountName_);
654 osAccountInfos[0].SetShortName(options.shortName);
655 osAccountInfos[0].SetDomainInfo(domainAccountInfo);
656 osAccountInfo = osAccountInfos[0];
657 }
658 }
659 if (osAccountInfo.GetLocalId() != Constants::START_USER_ID) {
660 #ifdef ENABLE_MULTIPLE_OS_ACCOUNTS
661 ErrCode errCode = PrepareOsAccountInfo(domainAccountInfo.accountName_, options.shortName,
662 type, domainAccountInfo, osAccountInfo);
663 if (errCode != ERR_OK) {
664 RemoveLocalIdToOperating(osAccountInfo.GetLocalId());
665 return errCode;
666 }
667 RemoveLocalIdToOperating(osAccountInfo.GetLocalId());
668 #else
669 ACCOUNT_LOGW("multiple os accounts feature not enabled");
670 return ERR_OSACCOUNT_SERVICE_MANAGER_NOT_ENABLE_MULTI_ERROR;
671 #endif // ENABLE_MULTIPLE_OS_ACCOUNTS
672 }
673 auto callbackWrapper =
674 std::make_shared<BindDomainAccountCallback>(osAccountControl_, domainAccountInfo, osAccountInfo, callback);
675 if (callbackWrapper == nullptr) {
676 ACCOUNT_LOGE("create BindDomainAccountCallback failed");
677 return ERR_ACCOUNT_COMMON_INSUFFICIENT_MEMORY_ERROR;
678 }
679 return InnerDomainAccountManager::GetInstance().OnAccountBound(
680 domainAccountInfo, osAccountInfo.GetLocalId(), callbackWrapper);
681 }
682
683 ErrCode IInnerOsAccountManager::CreateOsAccountForDomain(
684 const OsAccountType &type, const DomainAccountInfo &domainInfo, const sptr<IDomainAccountCallback> &callback,
685 const CreateOsAccountForDomainOptions &options)
686 {
687 if (!pluginManager_.IsCreationAllowed()) {
688 ACCOUNT_LOGI("Not allow creation account.");
689 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_PLUGIN_NOT_ALLOWED_CREATION_ERROR;
690 }
691 #ifdef HICOLLIE_ENABLE
692 AccountTimer timer;
693 #endif // HICOLLIE_ENABLE
694 std::vector<OsAccountInfo> osAccountInfos;
695 (void)QueryAllCreatedOsAccounts(osAccountInfos);
696 if (CheckDomainAccountBound(osAccountInfos, domainInfo)) {
697 ACCOUNT_LOGE("the domain account is already bound");
698 return ERR_OSACCOUNT_SERVICE_INNER_DOMAIN_ALREADY_BIND_ERROR;
699 }
700 if (osAccountInfos.size() >= config_.maxOsAccountNum) {
701 ACCOUNT_LOGE("The number of OS accounts has oversize, max num: %{public}d", config_.maxOsAccountNum);
702 return ERR_OSACCOUNT_SERVICE_CONTROL_MAX_CAN_CREATE_ERROR;
703 }
704 if (!InnerDomainAccountManager::GetInstance().IsPluginAvailable()) {
705 ACCOUNT_LOGE("plugin is not available");
706 return ERR_DOMAIN_ACCOUNT_SERVICE_PLUGIN_NOT_EXIST;
707 }
708 sptr<CheckAndCreateDomainAccountCallback> callbackWrapper =
709 new (std::nothrow) CheckAndCreateDomainAccountCallback(type, domainInfo, callback, options);
710 if (callbackWrapper == nullptr) {
711 ACCOUNT_LOGE("new DomainCreateDomainCallback failed");
712 return ERR_ACCOUNT_COMMON_INSUFFICIENT_MEMORY_ERROR;
713 }
714 return InnerDomainAccountManager::GetInstance().GetDomainAccountInfo(domainInfo, callbackWrapper);
715 }
716
717 void IInnerOsAccountManager::CheckAndRefreshLocalIdRecord(const int id)
718 {
719 if (id == defaultActivatedId_) {
720 ACCOUNT_LOGI("remove default activated id %{public}d", id);
721 osAccountControl_->SetDefaultActivatedOsAccount(Constants::START_USER_ID);
722 defaultActivatedId_ = Constants::START_USER_ID;
723 }
724 if (id == deviceOwnerId_) {
725 osAccountControl_->UpdateDeviceOwnerId(-1);
726 }
727 return;
728 }
729
730 ErrCode IInnerOsAccountManager::PrepareRemoveOsAccount(OsAccountInfo &osAccountInfo, bool isCleanGarbage)
731 {
732 int32_t id = osAccountInfo.GetLocalId();
733 ErrCode errCode = ERR_OK;
734 #ifdef HAS_USER_IDM_PART
735 errCode = OsAccountInterface::SendToIDMAccountDelete(osAccountInfo);
736 if (errCode != ERR_OK) {
737 ACCOUNT_LOGE("SendToIDMAccountDelete failed, id %{public}d, errCode %{public}d",
738 osAccountInfo.GetLocalId(), errCode);
739 return errCode;
740 }
741 #endif // HAS_USER_IDM_PART
742 DomainAccountInfo curDomainInfo;
743 osAccountInfo.GetDomainInfo(curDomainInfo);
744 if (!curDomainInfo.accountId_.empty()) {
745 InnerDomainAccountManager::GetInstance().OnAccountUnBound(curDomainInfo, nullptr);
746 InnerDomainAccountManager::GetInstance().RemoveTokenFromMap(id);
747 }
748 if (isCleanGarbage) {
749 ACCOUNT_LOGI("Clean garbage account data, no need to deal foreground status.");
750 return ERR_OK;
751 }
752 if (osAccountInfo.GetIsForeground()) {
753 ACCOUNT_LOGI("Remove foreground account id=%{public}d.", id);
754 if (ActivateOsAccount(Constants::START_USER_ID) != ERR_OK) {
755 ACCOUNT_LOGE("RemoveOsAccount active base account failed");
756 return ERR_OSACCOUNT_SERVICE_INNER_REMOVE_ACCOUNT_ACTIVED_ERROR;
757 }
758 std::this_thread::sleep_for(std::chrono::milliseconds(DELAY_FOR_REMOVING_FOREGROUND_OS_ACCOUNT));
759 }
760 loggedInAccounts_.Erase(id);
761 verifiedAccounts_.Erase(id);
762 // stop account
763 errCode = SendMsgForAccountStop(osAccountInfo);
764 if (errCode != ERR_OK) {
765 ReportOsAccountOperationFail(id, "stop", errCode, "stop os account failed");
766 return errCode;
767 }
768 return errCode;
769 }
770
771 ErrCode IInnerOsAccountManager::RemoveOsAccountOperate(const int id, OsAccountInfo &osAccountInfo, bool isCleanGarbage)
772 {
773 if (isCleanGarbage && (!osAccountInfo.GetIsCreateCompleted()) && (!osAccountInfo.GetIsDataRemovable())) {
774 ACCOUNT_LOGI("Account cannot be removed id=%{public}d.", id);
775 return ERR_OK;
776 }
777 ErrCode errCode = PrepareRemoveOsAccount(osAccountInfo, isCleanGarbage);
778 if (errCode != ERR_OK) {
779 ACCOUNT_LOGE("PrepareRemoveOsAccount failed, errCode %{public}d.", errCode);
780 return errCode;
781 }
782 DomainAccountInfo domainAccountInfo;
783 osAccountInfo.GetDomainInfo(domainAccountInfo);
784 if (!domainAccountInfo.accountId_.empty()) {
785 InnerDomainAccountManager::GetInstance().NotifyDomainAccountEvent(
786 id, DomainAccountEvent::LOG_OUT, DomainAccountStatus::LOGOUT, domainAccountInfo);
787 }
788 AccountInfo ohosInfo;
789 (void)OhosAccountManager::GetInstance().GetAccountInfoByUserId(id, ohosInfo);
790 if (ohosInfo.ohosAccountInfo_.name_ != DEFAULT_OHOS_ACCOUNT_NAME) {
791 #ifdef HAS_CES_PART
792 AccountEventProvider::EventPublishAsUser(
793 EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT, id);
794 AccountEventProvider::EventPublishAsUser(
795 EventFwk::CommonEventSupport::COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGOUT, id);
796 #else // HAS_CES_PART
797 ACCOUNT_LOGI("No common event part! Publish nothing!");
798 #endif // HAS_CES_PART
799 }
800 errCode = SendMsgForAccountRemove(osAccountInfo);
801 if (errCode != ERR_OK) {
802 return errCode;
803 }
804
805 errCode = osAccountControl_->RemoveOAConstraintsInfo(id);
806 if (errCode != ERR_OK) {
807 ACCOUNT_LOGE("RemoveOsAccount failed to remove os account constraints info");
808 return errCode;
809 }
810 CheckAndRefreshLocalIdRecord(id);
811 subscribeManager_.Publish(id, OS_ACCOUNT_SUBSCRIBE_TYPE::REMOVED);
812 return errCode;
813 }
814
815 ErrCode IInnerOsAccountManager::RemoveOsAccount(const int id)
816 {
817 ACCOUNT_LOGI("RemoveOsAccount delete id is %{public}d", id);
818 if (!CheckAndAddLocalIdOperating(id)) {
819 ACCOUNT_LOGE("the %{public}d already in operating", id);
820 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_OPERATING_ERROR;
821 }
822
823 OsAccountInfo osAccountInfo;
824 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(id, osAccountInfo);
825 if (errCode != ERR_OK) {
826 RemoveLocalIdToOperating(id);
827 ACCOUNT_LOGE("RemoveOsAccount cannot find os account info, errCode %{public}d.", errCode);
828 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
829 }
830 errCode = OsAccountInterface::SendToStorageAccountCreateComplete(id);
831 if (errCode != ERR_OK) {
832 RemoveLocalIdToOperating(id);
833 ACCOUNT_LOGE("SendToStorageAccountCreateComplete failed, errCode=%{public}d, id=%{public}d", errCode, id);
834 return errCode;
835 }
836 // set remove flag first
837 osAccountInfo.SetToBeRemoved(true);
838 errCode = osAccountControl_->UpdateOsAccount(osAccountInfo);
839 if (errCode != ERR_OK) {
840 ACCOUNT_LOGE("Failed to update ToBeRemoved status, errCode=%{public}d.", errCode);
841 ReportOsAccountOperationFail(id, Constants::OPERATION_REMOVE, errCode, "Failed to update ToBeRemoved status");
842 return errCode;
843 }
844
845 // then remove account
846 errCode = RemoveOsAccountOperate(id, osAccountInfo);
847 RemoveLocalIdToOperating(id);
848 return errCode;
849 }
850
851 ErrCode IInnerOsAccountManager::SendMsgForAccountStop(OsAccountInfo &osAccountInfo)
852 {
853 ErrCode errCode = OsAccountInterface::SendToAMSAccountStop(osAccountInfo);
854 if (errCode != ERR_OK) {
855 ACCOUNT_LOGE("SendToAMSAccountStop failed, id %{public}d, errCode %{public}d",
856 osAccountInfo.GetLocalId(), errCode);
857 return errCode;
858 }
859 errCode = OsAccountInterface::SendToStorageAccountStop(osAccountInfo);
860 if (errCode != ERR_OK) {
861 ACCOUNT_LOGE("SendToStorageAccountStop failed, id %{public}d, errCode %{public}d",
862 osAccountInfo.GetLocalId(), errCode);
863 return ERR_ACCOUNT_COMMON_GET_SYSTEM_ABILITY_MANAGER;
864 }
865 return DeactivateOsAccountByInfo(osAccountInfo);
866 }
867
868 ErrCode IInnerOsAccountManager::SendMsgForAccountDeactivate(OsAccountInfo &osAccountInfo, bool isStopStorage)
869 {
870 ErrCode errCode = OsAccountInterface::SendToAMSAccountDeactivate(osAccountInfo);
871 if (errCode != ERR_OK) {
872 ACCOUNT_LOGE("SendToAMSAccountDeactivate failed, id %{public}d, errCode %{public}d",
873 osAccountInfo.GetLocalId(), errCode);
874 return errCode;
875 }
876 if (isStopStorage) {
877 errCode = OsAccountInterface::SendToStorageAccountStop(osAccountInfo);
878 if (errCode != ERR_OK) {
879 ACCOUNT_LOGE("SendToStorageAccountStop failed, id %{public}d, errCode %{public}d",
880 osAccountInfo.GetLocalId(), errCode);
881 return ERR_ACCOUNT_COMMON_GET_SYSTEM_ABILITY_MANAGER;
882 }
883 }
884
885 return DeactivateOsAccountByInfo(osAccountInfo);
886 }
887
888 bool IInnerOsAccountManager::IsToBeRemoved(int32_t localId)
889 {
890 OsAccountInfo osAccountInfo;
891 ErrCode ret = QueryOsAccountById(localId, osAccountInfo);
892 if (ret == ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR) {
893 return true;
894 }
895 return osAccountInfo.GetToBeRemoved();
896 }
897
898 ErrCode IInnerOsAccountManager::ValidateOsAccount(const OsAccountInfo &osAccountInfo)
899 {
900 if (osAccountInfo.GetType() == OsAccountType::PRIVATE) {
901 return ERR_OK;
902 }
903 Json accountIndexJson;
904 ErrCode result = osAccountControl_->GetAccountIndexFromFile(accountIndexJson);
905 if (result != ERR_OK) {
906 return result;
907 }
908 std::string localIdStr = std::to_string(osAccountInfo.GetLocalId());
909 for (const auto& element : accountIndexJson.items()) {
910 std::string localIdKey = element.key();
911 auto value = element.value();
912 std::string localName = value[Constants::LOCAL_NAME].get<std::string>();
913 if ((osAccountInfo.GetLocalName() == localName) && (localIdKey != localIdStr)
914 && !IsToBeRemoved(std::stoi(localIdKey))) {
915 return ERR_ACCOUNT_COMMON_NAME_HAD_EXISTED;
916 }
917 if (!osAccountInfo.GetShortName().empty() && value.contains(Constants::SHORT_NAME)) {
918 std::string shortName = value[Constants::SHORT_NAME].get<std::string>();
919 if ((osAccountInfo.GetShortName() == shortName) && (localIdKey != localIdStr)
920 && !IsToBeRemoved(std::stoi(localIdKey))) {
921 return ERR_ACCOUNT_COMMON_SHORT_NAME_HAD_EXISTED;
922 }
923 }
924 }
925
926 return ERR_OK;
927 }
928
929 ErrCode IInnerOsAccountManager::GetTypeNumber(const OsAccountType& type, int32_t& typeNumber)
930 {
931 typeNumber = 0;
932 std::vector<OsAccountInfo> osAccountList;
933 ErrCode result = QueryAllCreatedOsAccounts(osAccountList);
934 if (result != ERR_OK) {
935 ACCOUNT_LOGE("Get os account list failed.");
936 return result;
937 }
938
939 typeNumber = std::count_if(osAccountList.begin(), osAccountList.end(),
940 [&type](const OsAccountInfo& info) { return info.GetType() == type; });
941 return ERR_OK;
942 }
943
944 ErrCode IInnerOsAccountManager::CheckTypeNumber(const OsAccountType& type)
945 {
946 if (type != OsAccountType::PRIVATE) {
947 return ERR_OK;
948 }
949 int32_t typeNumber = 0;
950 ErrCode result = GetTypeNumber(type, typeNumber);
951 if (result != ERR_OK) {
952 ACCOUNT_LOGE("Count type number failed.");
953 return result;
954 }
955 if (type == OsAccountType::PRIVATE && typeNumber >= MAX_PRIVATE_TYPE_NUMBER) {
956 ACCOUNT_LOGE("Check type number failed, private type number=%{public}d", typeNumber);
957 return ERR_OSACCOUNT_SERVICE_CONTROL_MAX_CAN_CREATE_ERROR;
958 }
959 return ERR_OK;
960 }
961
962 ErrCode IInnerOsAccountManager::SendMsgForAccountRemove(OsAccountInfo &osAccountInfo)
963 {
964 int32_t localId = osAccountInfo.GetLocalId();
965 AppAccountControlManager::GetInstance().SetOsAccountRemoved(localId, true);
966 ErrCode errCode = OsAccountInterface::SendToBMSAccountDelete(osAccountInfo);
967 if (errCode != ERR_OK) {
968 ACCOUNT_LOGE("SendToBMSAccountDelete failed, id %{public}d, errCode %{public}d", localId, errCode);
969 return errCode;
970 }
971 errCode = OsAccountInterface::SendToStorageAccountRemove(osAccountInfo);
972 if (errCode != ERR_OK) {
973 ACCOUNT_LOGE("SendToStorageAccountRemove failed, id %{public}d, errCode %{public}d", localId, errCode);
974 return ERR_ACCOUNT_COMMON_GET_SYSTEM_ABILITY_MANAGER;
975 }
976 errCode = osAccountControl_->DelOsAccount(localId);
977 if (errCode != ERR_OK) {
978 ACCOUNT_LOGE("remove osaccount info failed, id: %{public}d, errCode %{public}d", localId, errCode);
979 return errCode;
980 }
981 OsAccountInterface::SendToCESAccountDelete(osAccountInfo);
982 ReportOsAccountLifeCycle(localId, Constants::OPERATION_REMOVE);
983 return errCode;
984 }
985
986 void IInnerOsAccountManager::Init()
987 {
988 ACCOUNT_LOGI("Start to create base os accounts");
989 CreateBaseAdminAccount();
990 CreateBaseStandardAccount();
991 SetParameter(PARAM_LOGIN_NAME_MAX.c_str(), std::to_string(Constants::LOCAL_NAME_MAX_SIZE).c_str());
992 ACCOUNT_LOGI("End to create base os accounts");
993 }
994
995 ErrCode IInnerOsAccountManager::IsOsAccountExists(const int id, bool &isOsAccountExits)
996 {
997 isOsAccountExits = false;
998 osAccountControl_->IsOsAccountExists(id, isOsAccountExits);
999 return ERR_OK;
1000 }
1001
1002 ErrCode IInnerOsAccountManager::IsOsAccountActived(const int id, bool &isOsAccountActived)
1003 {
1004 isOsAccountActived = false;
1005
1006 // check if os account exists
1007 OsAccountInfo osAccountInfo;
1008 ErrCode errCode = GetRealOsAccountInfoById(id, osAccountInfo);
1009 if (errCode != ERR_OK) {
1010 ACCOUNT_LOGE("get osaccount info error, errCode %{public}d.", errCode);
1011 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1012 }
1013 if (id == Constants::ADMIN_LOCAL_ID) {
1014 isOsAccountActived = true;
1015 return ERR_OK;
1016 }
1017 isOsAccountActived = osAccountInfo.GetIsActived();
1018 return ERR_OK;
1019 }
1020
1021 ErrCode IInnerOsAccountManager::IsOsAccountConstraintEnable(
1022 const int id, const std::string &constraint, bool &isOsAccountConstraintEnable)
1023 {
1024 isOsAccountConstraintEnable = false;
1025 OsAccountInfo osAccountInfo;
1026 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(id, osAccountInfo);
1027 if (errCode != ERR_OK) {
1028 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1029 }
1030 std::vector<std::string> constraints;
1031 constraints = osAccountInfo.GetConstraints();
1032 if (std::find(constraints.begin(), constraints.end(), constraint) != constraints.end()) {
1033 isOsAccountConstraintEnable = true;
1034 return ERR_OK;
1035 }
1036 constraints.clear();
1037 if (osAccountControl_->GetGlobalOAConstraintsList(constraints) == ERR_OK) {
1038 if (std::find(constraints.begin(), constraints.end(), constraint) != constraints.end()) {
1039 isOsAccountConstraintEnable = true;
1040 return ERR_OK;
1041 }
1042 }
1043 constraints.clear();
1044 if (osAccountControl_->GetSpecificOAConstraintsList(id, constraints) == ERR_OK) {
1045 if (std::find(constraints.begin(), constraints.end(), constraint) != constraints.end()) {
1046 isOsAccountConstraintEnable = true;
1047 return ERR_OK;
1048 }
1049 }
1050 return ERR_OK;
1051 }
1052
1053 ErrCode IInnerOsAccountManager::IsOsAccountVerified(const int id, bool &isVerified)
1054 {
1055 OsAccountInfo osAccountInfo;
1056 ErrCode errCode = GetRealOsAccountInfoById(id, osAccountInfo);
1057 if (errCode != ERR_OK) {
1058 ACCOUNT_LOGE("Get osaccount fail, errCode=%{public}d, id=%{public}d", errCode, id);
1059 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1060 }
1061 isVerified = osAccountInfo.GetIsVerified();
1062 return ERR_OK;
1063 }
1064
1065 ErrCode IInnerOsAccountManager::GetCreatedOsAccountsCount(unsigned int &createdOsAccountCount)
1066 {
1067 std::vector<int32_t> idList;
1068 ErrCode errCode = osAccountControl_->GetOsAccountIdList(idList);
1069 if (errCode != ERR_OK) {
1070 ACCOUNT_LOGE("get osaccount info list error, errCode %{public}d.", errCode);
1071 return errCode;
1072 }
1073 createdOsAccountCount = idList.size();
1074 return ERR_OK;
1075 }
1076
1077 ErrCode IInnerOsAccountManager::QueryMaxOsAccountNumber(uint32_t &maxOsAccountNumber)
1078 {
1079 #ifdef ENABLE_MULTIPLE_OS_ACCOUNTS
1080 maxOsAccountNumber = config_.maxOsAccountNum;
1081 #else
1082 maxOsAccountNumber = 1;
1083 #endif // ENABLE_MULTIPLE_OS_ACCOUNTS
1084 return ERR_OK;
1085 }
1086
1087 ErrCode IInnerOsAccountManager::QueryMaxLoggedInOsAccountNumber(uint32_t &maxNum)
1088 {
1089 #ifdef ENABLE_MULTIPLE_OS_ACCOUNTS
1090 maxNum = config_.maxLoggedInOsAccountNum;
1091 #else
1092 maxNum = 1;
1093 #endif // ENABLE_MULTIPLE_OS_ACCOUNTS
1094 return ERR_OK;
1095 }
1096
1097 ErrCode IInnerOsAccountManager::GetOsAccountAllConstraints(const int id, std::vector<std::string> &constraints)
1098 {
1099 OsAccountInfo osAccountInfo;
1100 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(id, osAccountInfo);
1101 if (errCode != ERR_OK) {
1102 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1103 }
1104 constraints = osAccountInfo.GetConstraints();
1105 std::vector<std::string> globalConstraints;
1106 errCode = osAccountControl_->GetGlobalOAConstraintsList(globalConstraints);
1107 if (errCode != ERR_OK) {
1108 ACCOUNT_LOGE("get globalConstraints info error");
1109 return errCode;
1110 }
1111 for (auto it = globalConstraints.begin(); it != globalConstraints.end(); it++) {
1112 if (std::find(constraints.begin(), constraints.end(), *it) == constraints.end()) {
1113 constraints.push_back(*it);
1114 }
1115 }
1116 std::vector<std::string> specificConstraints;
1117 errCode = osAccountControl_->GetSpecificOAConstraintsList(id, specificConstraints);
1118 if (errCode != ERR_OK) {
1119 ACCOUNT_LOGE("get specificConstraints info error");
1120 return errCode;
1121 }
1122 for (auto it = specificConstraints.begin(); it != specificConstraints.end(); it++) {
1123 if (std::find(constraints.begin(), constraints.end(), *it) == constraints.end()) {
1124 constraints.push_back(*it);
1125 }
1126 }
1127 return ERR_OK;
1128 }
1129
1130 ErrCode IInnerOsAccountManager::QueryOsAccountConstraintSourceTypes(const int32_t id,
1131 const std::string &constraint, std::vector<ConstraintSourceTypeInfo> &constraintSourceTypeInfos)
1132 {
1133 ACCOUNT_LOGD("enter.");
1134 bool isOsAccountConstraintEnable = false;
1135 ErrCode errCode = IsOsAccountConstraintEnable(id, constraint, isOsAccountConstraintEnable);
1136 if (errCode != ERR_OK) {
1137 ACCOUNT_LOGE("get os account constraint enable info error");
1138 return errCode;
1139 }
1140 if (!isOsAccountConstraintEnable) {
1141 ACCOUNT_LOGI("constraint not exist");
1142 ConstraintSourceTypeInfo constraintSourceTypeInfo;
1143 constraintSourceTypeInfo.localId = -1;
1144 constraintSourceTypeInfo.typeInfo = ConstraintSourceType::CONSTRAINT_NOT_EXIST;
1145 constraintSourceTypeInfos.push_back(constraintSourceTypeInfo);
1146 return ERR_OK;
1147 }
1148
1149 bool isExits;
1150 if (osAccountControl_->IsFromBaseOAConstraintsList(id, constraint, isExits) == ERR_OK) {
1151 if (isExits) {
1152 ACCOUNT_LOGI("constraint is exist in base os account constraints list");
1153 ConstraintSourceTypeInfo constraintSourceTypeInfo;
1154 constraintSourceTypeInfo.localId = -1;
1155 constraintSourceTypeInfo.typeInfo = ConstraintSourceType::CONSTRAINT_TYPE_BASE;
1156 constraintSourceTypeInfos.push_back(constraintSourceTypeInfo);
1157 }
1158 }
1159 std::vector<ConstraintSourceTypeInfo> globalSourceList;
1160 errCode = osAccountControl_->IsFromGlobalOAConstraintsList(id, deviceOwnerId_, constraint, globalSourceList);
1161 if (errCode == ERR_OK && globalSourceList.size() != 0) {
1162 ACCOUNT_LOGI("constraint is exist in global os account constraints list");
1163 constraintSourceTypeInfos.insert(
1164 constraintSourceTypeInfos.end(), globalSourceList.begin(), globalSourceList.end());
1165 }
1166 std::vector<ConstraintSourceTypeInfo> specificSourceList;
1167 errCode = osAccountControl_->IsFromSpecificOAConstraintsList(id, deviceOwnerId_, constraint, specificSourceList);
1168 if (errCode == ERR_OK && specificSourceList.size() != 0) {
1169 ACCOUNT_LOGI("constraint is exist in specific os account constraints list");
1170 constraintSourceTypeInfos.insert(
1171 constraintSourceTypeInfos.end(), specificSourceList.begin(), specificSourceList.end());
1172 }
1173 return ERR_OK;
1174 }
1175
1176 ErrCode IInnerOsAccountManager::SetBaseOsAccountConstraints(const int32_t id,
1177 const std::vector<std::string> &constraints, const bool enable)
1178 {
1179 ErrCode errCode = SetOsAccountConstraints(id, constraints, enable);
1180 if (errCode != ERR_OK) {
1181 ACCOUNT_LOGE("set os account %{public}d constraints failed! errCode %{public}d.", id, errCode);
1182 return errCode;
1183 }
1184
1185 errCode = osAccountControl_->UpdateBaseOAConstraints(std::to_string(id), constraints, enable);
1186 if (errCode != ERR_OK) {
1187 ACCOUNT_LOGE("update base os account %{public}d constraints failed! errCode %{public}d.", id, errCode);
1188 return errCode;
1189 }
1190 return ERR_OK;
1191 }
1192
1193 ErrCode IInnerOsAccountManager::SetGlobalOsAccountConstraints(const std::vector<std::string> &constraints,
1194 const bool enable, const int32_t enforcerId, const bool isDeviceOwner)
1195 {
1196 OsAccountInfo osAccountInfo;
1197 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(enforcerId, osAccountInfo);
1198 if (errCode != ERR_OK) {
1199 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1200 }
1201 if (osAccountInfo.GetToBeRemoved()) {
1202 ACCOUNT_LOGE("account %{public}d will be removed, cannot change constraints!", enforcerId);
1203 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_TO_BE_REMOVED_ERROR;
1204 }
1205
1206 bool isExists = false;
1207 bool isOverSize = false;
1208 errCode = osAccountControl_->CheckConstraintsList(constraints, isExists, isOverSize);
1209 if (errCode != ERR_OK || !isExists || isOverSize) {
1210 ACCOUNT_LOGE("input constraints not in constraints list or is oversize!");
1211 return ERR_ACCOUNT_COMMON_INVALID_PARAMETER;
1212 }
1213
1214 osAccountControl_->UpdateGlobalOAConstraints(std::to_string(enforcerId), constraints, enable);
1215
1216 errCode = DealWithDeviceOwnerId(isDeviceOwner, enforcerId);
1217 if (errCode != ERR_OK) {
1218 ACCOUNT_LOGE("deal with device owner id error");
1219 return errCode;
1220 }
1221 return ERR_OK;
1222 }
1223
1224 ErrCode IInnerOsAccountManager::SetSpecificOsAccountConstraints(const std::vector<std::string> &constraints,
1225 const bool enable, const int32_t targetId, const int32_t enforcerId, const bool isDeviceOwner)
1226 {
1227 OsAccountInfo enforcerOsAccountInfo;
1228 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(enforcerId, enforcerOsAccountInfo);
1229 if (errCode != ERR_OK) {
1230 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1231 }
1232
1233 OsAccountInfo targetOsAccountInfo;
1234 errCode = osAccountControl_->GetOsAccountInfoById(targetId, targetOsAccountInfo);
1235 if (errCode != ERR_OK) {
1236 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1237 }
1238 if (targetOsAccountInfo.GetToBeRemoved() || enforcerOsAccountInfo.GetToBeRemoved()) {
1239 ACCOUNT_LOGE("account %{public}d or %{public}d will be removed, cannot change constraints!",
1240 enforcerId, targetId);
1241 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_TO_BE_REMOVED_ERROR;
1242 }
1243
1244 bool isExists = false;
1245 bool isOverSize = false;
1246 errCode = osAccountControl_->CheckConstraintsList(constraints, isExists, isOverSize);
1247 if (errCode != ERR_OK || !isExists || isOverSize) {
1248 ACCOUNT_LOGE("input constraints not in constraints list or is oversize!");
1249 return ERR_ACCOUNT_COMMON_INVALID_PARAMETER;
1250 }
1251
1252 osAccountControl_->UpdateSpecificOAConstraints(
1253 std::to_string(enforcerId), std::to_string(targetId), constraints, enable);
1254
1255 errCode = DealWithDeviceOwnerId(isDeviceOwner, enforcerId);
1256 if (errCode != ERR_OK) {
1257 ACCOUNT_LOGE("deal with device owner id error");
1258 return errCode;
1259 }
1260 return ERR_OK;
1261 }
1262
1263 ErrCode IInnerOsAccountManager::QueryAllCreatedOsAccounts(std::vector<OsAccountInfo> &createdOsAccounts)
1264 {
1265 std::vector<OsAccountInfo> allOsAccounts;
1266 ErrCode errCode = osAccountControl_->GetOsAccountList(allOsAccounts);
1267 if (errCode != ERR_OK) {
1268 ACCOUNT_LOGE("get osaccount info list error, errCode %{public}d.", errCode);
1269 return errCode;
1270 }
1271 for (auto osAccountInfo : allOsAccounts) {
1272 if (osAccountInfo.GetIsCreateCompleted() && !osAccountInfo.GetToBeRemoved()) {
1273 createdOsAccounts.push_back(osAccountInfo);
1274 }
1275 }
1276 return ERR_OK;
1277 }
1278
1279 ErrCode IInnerOsAccountManager::DealWithDeviceOwnerId(const bool isDeviceOwner, const int32_t localId)
1280 {
1281 ACCOUNT_LOGD("enter.");
1282 if (isDeviceOwner && localId != deviceOwnerId_) {
1283 ACCOUNT_LOGI("this device owner os account id is changed!");
1284 deviceOwnerId_ = localId;
1285 return osAccountControl_->UpdateDeviceOwnerId(localId);
1286 }
1287 if (isDeviceOwner == false && localId == deviceOwnerId_) {
1288 deviceOwnerId_ = -1;
1289 return osAccountControl_->UpdateDeviceOwnerId(-1);
1290 }
1291 return ERR_OK;
1292 }
1293
1294 int32_t IInnerOsAccountManager::CleanGarbageOsAccounts(int32_t excludeId)
1295 {
1296 ACCOUNT_LOGI("enter");
1297 std::vector<int32_t> idList;
1298 if (osAccountControl_->GetOsAccountIdList(idList) != ERR_OK) {
1299 ACCOUNT_LOGI("GetOsAccountIdList failed.");
1300 return 0;
1301 }
1302
1303 int32_t removeNum = 0;
1304
1305 for (auto id : idList) {
1306 if (id == Constants::START_USER_ID || id == Constants::ADMIN_LOCAL_ID || id == excludeId) {
1307 continue;
1308 }
1309 if (!CheckAndAddLocalIdOperating(id)) {
1310 ACCOUNT_LOGI("Account id = %{public}d already in operating", id);
1311 continue;
1312 }
1313 OsAccountInfo osAccountInfo;
1314 ErrCode ret = osAccountControl_->GetOsAccountInfoById(id, osAccountInfo);
1315 if (ret != ERR_OK && ret != ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR) {
1316 continue;
1317 }
1318 osAccountInfo.SetLocalId(id);
1319
1320 if (!osAccountInfo.GetToBeRemoved() && osAccountInfo.GetIsCreateCompleted()) {
1321 RemoveLocalIdToOperating(id);
1322 continue;
1323 }
1324 ErrCode errCode = RemoveOsAccountOperate(id, osAccountInfo, true);
1325 RemoveLocalIdToOperating(id);
1326 if (errCode != ERR_OK) {
1327 ACCOUNT_LOGE("remove account %{public}d failed! errCode %{public}d.", id, errCode);
1328 } else {
1329 ACCOUNT_LOGI("remove account %{public}d succeed!", id);
1330 removeNum++;
1331 }
1332 }
1333 ACCOUNT_LOGI("finished.");
1334 return removeNum;
1335 }
1336
1337 bool IInnerOsAccountManager::IsSameAccount(
1338 const DomainAccountInfo &domainInfoSrc, const DomainAccountInfo &domainInfoTar)
1339 {
1340 return (((!domainInfoSrc.accountId_.empty()) && (domainInfoSrc.accountId_ == domainInfoTar.accountId_)) ||
1341 ((!domainInfoSrc.accountName_.empty()) && (domainInfoSrc.accountName_ == domainInfoTar.accountName_) &&
1342 (!domainInfoSrc.domain_.empty()) && (domainInfoSrc.domain_ == domainInfoTar.domain_)));
1343 }
1344
1345 ErrCode IInnerOsAccountManager::GetOsAccountLocalIdFromDomain(const DomainAccountInfo &domainInfo, int &id)
1346 {
1347 if (domainInfo.domain_.size() > Constants::DOMAIN_NAME_MAX_SIZE) {
1348 ACCOUNT_LOGE("invalid domain name length %{public}zu.", domainInfo.domain_.size());
1349 return ERR_ACCOUNT_COMMON_INVALID_PARAMETER;
1350 }
1351
1352 if (domainInfo.accountName_.size() > Constants::LOCAL_NAME_MAX_SIZE) {
1353 ACCOUNT_LOGE("invalid domain account name length %{public}zu.", domainInfo.accountName_.size());
1354 return ERR_ACCOUNT_COMMON_INVALID_PARAMETER;
1355 }
1356
1357 id = -1;
1358 std::vector<OsAccountInfo> osAccountInfos;
1359 ErrCode errCode = osAccountControl_->GetOsAccountList(osAccountInfos);
1360 if (errCode != ERR_OK) {
1361 return errCode;
1362 }
1363
1364 DomainAccountInfo curDomainInfo;
1365 for (auto osAccountInfosPtr = osAccountInfos.begin(); osAccountInfosPtr != osAccountInfos.end();
1366 ++osAccountInfosPtr) {
1367 osAccountInfosPtr->GetDomainInfo(curDomainInfo);
1368 if (IsSameAccount(curDomainInfo, domainInfo)) {
1369 id = osAccountInfosPtr->GetLocalId();
1370 return ERR_OK;
1371 }
1372 }
1373 return ERR_DOMAIN_ACCOUNT_SERVICE_NOT_DOMAIN_ACCOUNT;
1374 }
1375
1376 ErrCode IInnerOsAccountManager::GetOsAccountShortName(const int id, std::string &shortName)
1377 {
1378 OsAccountInfo osAccountInfo;
1379 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(id, osAccountInfo);
1380 if (errCode != ERR_OK) {
1381 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1382 }
1383 shortName = osAccountInfo.GetShortName();
1384 return ERR_OK;
1385 }
1386
1387 ErrCode IInnerOsAccountManager::GetOsAccountName(const int id, std::string &name)
1388 {
1389 OsAccountInfo osAccountInfo;
1390 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(id, osAccountInfo);
1391 if (errCode != ERR_OK) {
1392 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1393 }
1394 name = osAccountInfo.GetLocalName();
1395 return ERR_OK;
1396 }
1397
1398 ErrCode IInnerOsAccountManager::QueryOsAccountById(const int id, OsAccountInfo &osAccountInfo)
1399 {
1400 ErrCode errCode = GetRealOsAccountInfoById(id, osAccountInfo);
1401 if (errCode != ERR_OK) {
1402 ACCOUNT_LOGE("get osaccount info error, errCode %{public}d.", errCode);
1403 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1404 }
1405
1406 if (osAccountInfo.GetPhoto() != "") {
1407 std::string photo = osAccountInfo.GetPhoto();
1408 errCode = osAccountControl_->GetPhotoById(osAccountInfo.GetLocalId(), photo);
1409 if (errCode != ERR_OK) {
1410 ACCOUNT_LOGE("get osaccount photo error, errCode %{public}d.", errCode);
1411 return errCode;
1412 }
1413 osAccountInfo.SetPhoto(photo);
1414 }
1415 return ERR_OK;
1416 }
1417
1418 ErrCode IInnerOsAccountManager::GetOsAccountType(const int id, OsAccountType &type)
1419 {
1420 OsAccountInfo osAccountInfo;
1421 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(id, osAccountInfo);
1422 if (errCode != ERR_OK) {
1423 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1424 }
1425 type = osAccountInfo.GetType();
1426 return ERR_OK;
1427 }
1428
1429 ErrCode IInnerOsAccountManager::GetOsAccountProfilePhoto(const int id, std::string &photo)
1430 {
1431 OsAccountInfo osAccountInfo;
1432 ErrCode errCode = QueryOsAccountById(id, osAccountInfo);
1433 if (errCode != ERR_OK) {
1434 ACCOUNT_LOGE("QueryOsAccountById return error, errCode %{public}d.", errCode);
1435 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1436 }
1437 photo = osAccountInfo.GetPhoto();
1438 return ERR_OK;
1439 }
1440
1441 ErrCode IInnerOsAccountManager::IsMultiOsAccountEnable(bool &isMultiOsAccountEnable)
1442 {
1443 #ifdef ENABLE_MULTIPLE_OS_ACCOUNTS
1444 ErrCode errCode = osAccountControl_->GetIsMultiOsAccountEnable(isMultiOsAccountEnable);
1445 if (errCode != ERR_OK) {
1446 ACCOUNT_LOGE("GetIsMultiOsAccountEnable error, errCode %{public}d.", errCode);
1447 return errCode;
1448 }
1449 #else
1450 isMultiOsAccountEnable = false;
1451 #endif // ENABLE_MULTIPLE_OS_ACCOUNTS
1452 return ERR_OK;
1453 }
1454
1455 ErrCode IInnerOsAccountManager::SetOsAccountName(const int id, const std::string &name)
1456 {
1457 OsAccountInfo osAccountInfo;
1458 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(id, osAccountInfo);
1459 if (errCode != ERR_OK) {
1460 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1461 }
1462
1463 // to be removed, cannot change any thing
1464 if (osAccountInfo.GetToBeRemoved()) {
1465 ACCOUNT_LOGE("account %{public}d will be removed, cannot change name!", id);
1466 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_TO_BE_REMOVED_ERROR;
1467 }
1468
1469 std::string localName = osAccountInfo.GetLocalName();
1470 if (localName == name) {
1471 return ERR_OK;
1472 }
1473
1474 osAccountInfo.SetLocalName(name);
1475 errCode = ValidateOsAccount(osAccountInfo);
1476 if (errCode != ERR_OK) {
1477 ACCOUNT_LOGE("account name already exist, errCode %{public}d.", errCode);
1478 return errCode;
1479 }
1480
1481 errCode = osAccountControl_->UpdateOsAccount(osAccountInfo);
1482 if (errCode != ERR_OK) {
1483 ACCOUNT_LOGE("update osaccount info error %{public}d, id: %{public}d", errCode, osAccountInfo.GetLocalId());
1484 return ERR_OSACCOUNT_SERVICE_INNER_UPDATE_ACCOUNT_ERROR;
1485 }
1486 osAccountControl_->UpdateAccountIndex(osAccountInfo, false);
1487 OsAccountInterface::PublishCommonEvent(
1488 osAccountInfo, OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_USER_INFO_UPDATED, Constants::OPERATION_UPDATE);
1489 return ERR_OK;
1490 }
1491
1492 ErrCode IInnerOsAccountManager::SetOsAccountConstraints(
1493 const int id, const std::vector<std::string> &constraints, const bool enable)
1494 {
1495 OsAccountInfo osAccountInfo;
1496 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(id, osAccountInfo);
1497 if (errCode != ERR_OK) {
1498 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1499 }
1500
1501 // to be removed, cannot change any thing
1502 if (osAccountInfo.GetToBeRemoved()) {
1503 ACCOUNT_LOGE("account %{public}d will be removed, cannot change constraints!", id);
1504 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_TO_BE_REMOVED_ERROR;
1505 }
1506
1507 bool isExists = false;
1508 bool isOverSize = false;
1509 errCode = osAccountControl_->CheckConstraintsList(constraints, isExists, isOverSize);
1510 if (errCode != ERR_OK || !isExists || isOverSize) {
1511 ACCOUNT_LOGE("input constraints not in constraints list or is oversize!");
1512 return ERR_ACCOUNT_COMMON_INVALID_PARAMETER;
1513 }
1514 std::vector<std::string> oldConstraints = osAccountInfo.GetConstraints();
1515 for (auto it = constraints.begin(); it != constraints.end(); it++) {
1516 if (enable) {
1517 if (std::find(oldConstraints.begin(), oldConstraints.end(), *it) == oldConstraints.end()) {
1518 oldConstraints.push_back(*it);
1519 }
1520 } else {
1521 oldConstraints.erase(
1522 std::remove(oldConstraints.begin(), oldConstraints.end(), *it), oldConstraints.end());
1523 }
1524 }
1525 osAccountInfo.SetConstraints(oldConstraints);
1526 errCode = osAccountControl_->UpdateOsAccount(osAccountInfo);
1527 if (errCode != ERR_OK) {
1528 ACCOUNT_LOGE("update osaccount info error %{public}d, id: %{public}d", errCode, osAccountInfo.GetLocalId());
1529 return ERR_OSACCOUNT_SERVICE_INNER_UPDATE_ACCOUNT_ERROR;
1530 }
1531 return ERR_OK;
1532 }
1533
1534 ErrCode IInnerOsAccountManager::SetOsAccountProfilePhoto(const int id, const std::string &photo)
1535 {
1536 OsAccountInfo osAccountInfo;
1537 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(id, osAccountInfo);
1538 if (errCode != ERR_OK) {
1539 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1540 }
1541
1542 // to be removed, cannot change any thing
1543 if (osAccountInfo.GetToBeRemoved()) {
1544 ACCOUNT_LOGE("account %{public}d will be removed, cannot change photo!", id);
1545 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_TO_BE_REMOVED_ERROR;
1546 }
1547
1548 if (osAccountInfo.GetPhoto() == photo) {
1549 return ERR_OK;
1550 }
1551 errCode = osAccountControl_->SetPhotoById(id, photo);
1552 if (errCode != ERR_OK) {
1553 ACCOUNT_LOGE("Set photo error, code=%{public}d, id=%{public}d.", errCode, id);
1554 return errCode;
1555 }
1556 osAccountInfo.SetPhoto(Constants::USER_PHOTO_FILE_TXT_NAME);
1557 errCode = osAccountControl_->UpdateOsAccount(osAccountInfo);
1558 if (errCode != ERR_OK) {
1559 ACCOUNT_LOGE("Update osaccount info faile code=%{public}d, id=%{public}d", errCode, osAccountInfo.GetLocalId());
1560 return ERR_OSACCOUNT_SERVICE_INNER_UPDATE_ACCOUNT_ERROR;
1561 }
1562 OsAccountInterface::PublishCommonEvent(
1563 osAccountInfo, OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_USER_INFO_UPDATED, Constants::OPERATION_UPDATE);
1564 return ERR_OK;
1565 }
1566
1567 ErrCode IInnerOsAccountManager::DeactivateOsAccountByInfo(OsAccountInfo &osAccountInfo)
1568 {
1569 int localId = osAccountInfo.GetLocalId();
1570 loggedInAccounts_.Erase(localId);
1571 verifiedAccounts_.Erase(localId);
1572 int32_t foregroundId = -1;
1573 if (foregroundAccountMap_.Find(Constants::DEFAULT_DISPALY_ID, foregroundId) && foregroundId == localId) {
1574 foregroundAccountMap_.Erase(Constants::DEFAULT_DISPALY_ID);
1575 }
1576 EraseIdFromActiveList(localId);
1577
1578 osAccountInfo.SetIsActived(false);
1579 osAccountInfo.SetIsVerified(false);
1580 osAccountInfo.SetIsForeground(false);
1581 osAccountInfo.SetDisplayId(Constants::INVALID_DISPALY_ID);
1582 osAccountInfo.SetIsLoggedIn(false);
1583 DomainAccountInfo domainAccountInfo;
1584 osAccountInfo.GetDomainInfo(domainAccountInfo);
1585 domainAccountInfo.status_ = DomainAccountStatus::LOGOUT;
1586 osAccountInfo.SetDomainInfo(domainAccountInfo);
1587 ErrCode errCode = osAccountControl_->UpdateOsAccount(osAccountInfo);
1588 if (errCode != ERR_OK && errCode != ERR_ACCOUNT_COMMON_DATA_NO_SPACE) {
1589 ACCOUNT_LOGE("Update account failed, id=%{public}d, errCode=%{public}d.", osAccountInfo.GetLocalId(), errCode);
1590 return ERR_OSACCOUNT_SERVICE_INNER_UPDATE_ACCOUNT_ERROR;
1591 }
1592
1593 AccountInfoReport::ReportSecurityInfo(osAccountInfo.GetLocalName(), localId,
1594 ReportEvent::EVENT_LOGOUT, 0);
1595 return ERR_OK;
1596 }
1597
1598 ErrCode IInnerOsAccountManager::DeactivateOsAccountById(const int id)
1599 {
1600 OsAccountInfo osAccountInfo;
1601 ErrCode errCode = GetRealOsAccountInfoById(id, osAccountInfo);
1602 if (errCode != ERR_OK) {
1603 ACCOUNT_LOGE("cannot get os account %{public}d info. error %{public}d.",
1604 id, errCode);
1605 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1606 }
1607 return DeactivateOsAccountByInfo(osAccountInfo);
1608 }
1609
1610 ErrCode IInnerOsAccountManager::ActivateOsAccount(const int id, const bool startStorage, const uint64_t displayId)
1611 {
1612 if (!CheckAndAddLocalIdOperating(id)) {
1613 ACCOUNT_LOGE("the %{public}d already in operating", id);
1614 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_OPERATING_ERROR;
1615 }
1616 std::lock_guard<std::mutex> lock(*GetOrInsertUpdateLock(id));
1617 // get information
1618 OsAccountInfo osAccountInfo;
1619 ErrCode errCode = GetRealOsAccountInfoById(id, osAccountInfo);
1620 if (errCode != ERR_OK) {
1621 RemoveLocalIdToOperating(id);
1622 ACCOUNT_LOGE("cannot find os account info by id:%{public}d, errCode %{public}d.", id, errCode);
1623 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1624 }
1625
1626 int32_t foregroundId = -1;
1627 if (foregroundAccountMap_.Find(displayId, foregroundId) && (foregroundId == id) && osAccountInfo.GetIsVerified()) {
1628 ACCOUNT_LOGI("Account %{public}d already is foreground", id);
1629 RemoveLocalIdToOperating(id);
1630 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_ALREADY_ACTIVE_ERROR;
1631 }
1632
1633 errCode = IsValidOsAccount(osAccountInfo);
1634 if (errCode != ERR_OK) {
1635 RemoveLocalIdToOperating(id);
1636 return errCode;
1637 }
1638
1639 if (!osAccountInfo.GetIsActived() &&
1640 (static_cast<uint32_t>(loggedInAccounts_.Size()) >= config_.maxLoggedInOsAccountNum)) {
1641 RemoveLocalIdToOperating(id);
1642 ACCOUNT_LOGE("The number of logged in account reaches the upper limit, maxLoggedInNum: %{public}d",
1643 config_.maxLoggedInOsAccountNum);
1644 return ERR_OSACCOUNT_SERVICE_LOGGED_IN_ACCOUNTS_OVERSIZE;
1645 }
1646
1647 subscribeManager_.Publish(id, OS_ACCOUNT_SUBSCRIBE_TYPE::ACTIVATING);
1648 errCode = SendMsgForAccountActivate(osAccountInfo, startStorage);
1649 RemoveLocalIdToOperating(id);
1650 if (errCode != ERR_OK) {
1651 return errCode;
1652 }
1653
1654 DomainAccountInfo domainInfo;
1655 osAccountInfo.GetDomainInfo(domainInfo);
1656 if (domainInfo.accountId_.empty() && (osAccountInfo.GetCredentialId() == 0)) {
1657 AccountInfoReport::ReportSecurityInfo(
1658 osAccountInfo.GetLocalName(), osAccountInfo.GetLocalId(), ReportEvent::EVENT_LOGIN, 0);
1659 }
1660 ACCOUNT_LOGI("IInnerOsAccountManager ActivateOsAccount end");
1661 return ERR_OK;
1662 }
1663
1664 ErrCode IInnerOsAccountManager::DeactivateOsAccount(const int id, bool isStopStorage)
1665 {
1666 if (!CheckAndAddLocalIdOperating(id)) {
1667 ACCOUNT_LOGW("the %{public}d already in operating", id);
1668 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_OPERATING_ERROR;
1669 }
1670 std::lock_guard<std::mutex> lock(*GetOrInsertUpdateLock(id));
1671 OsAccountInfo osAccountInfo;
1672 ErrCode errCode = GetRealOsAccountInfoById(id, osAccountInfo);
1673 if (errCode != ERR_OK) {
1674 RemoveLocalIdToOperating(id);
1675 ACCOUNT_LOGW("cannot find os account info by id:%{public}d, errCode %{public}d.", id, errCode);
1676 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1677 }
1678
1679 if ((!osAccountInfo.GetIsActived()) && (!osAccountInfo.GetIsVerified())) {
1680 RemoveLocalIdToOperating(id);
1681 ACCOUNT_LOGW("account %{public}d is neither active nor verified, don't need to deactivate!", id);
1682 return ERR_OK;
1683 }
1684 errCode = IsValidOsAccount(osAccountInfo);
1685 if (errCode != ERR_OK) {
1686 RemoveLocalIdToOperating(id);
1687 return errCode;
1688 }
1689
1690 OsAccountInterface::PublishCommonEvent(
1691 osAccountInfo, OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_USER_STOPPING, Constants::OPERATION_STOP);
1692 subscribeManager_.Publish(id, OS_ACCOUNT_SUBSCRIBE_TYPE::STOPPING);
1693
1694 errCode = SendMsgForAccountDeactivate(osAccountInfo, isStopStorage);
1695 if (errCode != ERR_OK) {
1696 RemoveLocalIdToOperating(id);
1697 ReportOsAccountOperationFail(id, "deactivate", errCode, "deactivate os account failed");
1698 return errCode;
1699 }
1700
1701 OsAccountInterface::PublishCommonEvent(osAccountInfo, OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_USER_STOPPED,
1702 Constants::OPERATION_STOP);
1703 subscribeManager_.Publish(id, OS_ACCOUNT_SUBSCRIBE_TYPE::STOPPED);
1704 ReportOsAccountLifeCycle(id, Constants::OPERATION_STOP);
1705
1706 RemoveLocalIdToOperating(id);
1707 ACCOUNT_LOGI("IInnerOsAccountManager DeactivateOsAccount end");
1708 return ERR_OK;
1709 }
1710
1711 ErrCode IInnerOsAccountManager::SendMsgForAccountActivate(OsAccountInfo &osAccountInfo, const bool startStorage,
1712 const uint64_t displayId)
1713 {
1714 // activate
1715 int32_t oldId = -1;
1716 bool oldIdExist = foregroundAccountMap_.Find(displayId, oldId);
1717 int32_t localId = static_cast<int32_t>(osAccountInfo.GetLocalId());
1718 bool preActivated = osAccountInfo.GetIsActived();
1719 subscribeManager_.Publish(localId, oldId, OS_ACCOUNT_SUBSCRIBE_TYPE::SWITCHING);
1720
1721 if (startStorage) {
1722 ErrCode errCode = SendToStorageAccountStart(osAccountInfo);
1723 if (errCode != ERR_OK) {
1724 return errCode;
1725 }
1726 }
1727 ErrCode errCode = SendToAMSAccountStart(osAccountInfo, displayId);
1728 if (errCode != ERR_OK) {
1729 return errCode;
1730 }
1731 if (oldId != localId) {
1732 OsAccountInterface::PublishCommonEvent(osAccountInfo,
1733 OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_USER_FOREGROUND, Constants::OPERATION_SWITCH);
1734 }
1735 errCode = UpdateAccountToForeground(displayId, osAccountInfo);
1736 if (errCode != ERR_OK) {
1737 return errCode;
1738 }
1739
1740 if (oldIdExist && (oldId != localId)) {
1741 errCode = UpdateAccountToBackground(oldId);
1742 if (errCode != ERR_OK) {
1743 return errCode;
1744 }
1745 }
1746
1747 OsAccountInterface::SendToCESAccountSwitched(localId, oldId);
1748 subscribeManager_.Publish(localId, OS_ACCOUNT_SUBSCRIBE_TYPE::ACTIVED);
1749 subscribeManager_.Publish(localId, oldId, OS_ACCOUNT_SUBSCRIBE_TYPE::SWITCHED);
1750 if (!preActivated) {
1751 ReportOsAccountLifeCycle(defaultActivatedId_, Constants::OPERATION_ACTIVATE);
1752 }
1753 ACCOUNT_LOGI("SendMsgForAccountActivate ok");
1754 ReportOsAccountSwitch(localId, oldId);
1755 return errCode;
1756 }
1757
1758 ErrCode IInnerOsAccountManager::SendToStorageAccountStart(OsAccountInfo &osAccountInfo)
1759 {
1760 bool preVerified = osAccountInfo.GetIsVerified();
1761 int32_t localId = osAccountInfo.GetLocalId();
1762 ErrCode err = OsAccountInterface::SendToStorageAccountStart(osAccountInfo);
1763 if (err != ERR_OK) {
1764 ACCOUNT_LOGE("Failed to SendToStorageAccountStart, localId %{public}d, error: %{public}d.", localId, err);
1765 return ERR_ACCOUNT_COMMON_GET_SYSTEM_ABILITY_MANAGER;
1766 }
1767 if (osAccountInfo.GetIsVerified()) {
1768 verifiedAccounts_.EnsureInsert(osAccountInfo.GetLocalId(), true);
1769 }
1770 if (osAccountInfo.GetIsLoggedIn()) {
1771 loggedInAccounts_.EnsureInsert(osAccountInfo.GetLocalId(), true);
1772 }
1773
1774 if (!preVerified && osAccountInfo.GetIsVerified()) {
1775 OsAccountInterface::PublishCommonEvent(osAccountInfo,
1776 OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED, Constants::OPERATION_UNLOCK);
1777 subscribeManager_.Publish(localId, OS_ACCOUNT_SUBSCRIBE_TYPE::UNLOCKED);
1778 ReportOsAccountLifeCycle(localId, Constants::OPERATION_UNLOCK);
1779
1780 auto task = [] { IInnerOsAccountManager::GetInstance().CleanGarbageOsAccounts(); };
1781 std::thread cleanThread(task);
1782 pthread_setname_np(cleanThread.native_handle(), "CleanGarbageOsAccounts");
1783 cleanThread.detach();
1784 }
1785 return ERR_OK;
1786 }
1787
1788 ErrCode IInnerOsAccountManager::SendToAMSAccountStart(OsAccountInfo &osAccountInfo,
1789 uint64_t displayId)
1790 {
1791 OsAccountStartCallbackFunc callbackFunc = [this, displayId](int32_t localId) {
1792 this->PushIdIntoActiveList(localId);
1793 this->foregroundAccountMap_.EnsureInsert(displayId, localId);
1794 };
1795 ErrCode errCode = OsAccountInterface::SendToAMSAccountStart(osAccountInfo, callbackFunc);
1796 if (errCode != ERR_OK) {
1797 ACCOUNT_LOGE("Failed to call SendToAMSAccountStart, localId: %{public}d, error: %{public}d.",
1798 osAccountInfo.GetLocalId(), errCode);
1799 return errCode;
1800 }
1801
1802 return ERR_OK;
1803 }
1804
1805 ErrCode IInnerOsAccountManager::StartOsAccount(const int id)
1806 {
1807 return ERR_OK;
1808 }
1809
1810 ErrCode IInnerOsAccountManager::GetOsAccountLocalIdBySerialNumber(const int64_t serialNumber, int &id)
1811 {
1812 if (serialNumber ==
1813 Constants::CARRY_NUM * Constants::SERIAL_NUMBER_NUM_START_FOR_ADMIN + Constants::ADMIN_LOCAL_ID) {
1814 id = Constants::ADMIN_LOCAL_ID;
1815 return ERR_OK;
1816 }
1817 std::vector<OsAccountInfo> osAccountInfos;
1818 id = -1;
1819 ErrCode errCode = osAccountControl_->GetOsAccountList(osAccountInfos);
1820 if (errCode != ERR_OK) {
1821 ACCOUNT_LOGE("get osaccount info list error");
1822 return errCode;
1823 }
1824 for (auto it = osAccountInfos.begin(); it != osAccountInfos.end(); it++) {
1825 if (serialNumber == it->GetSerialNumber()) {
1826 id = it->GetLocalId();
1827 break;
1828 }
1829 }
1830 if (id == -1) {
1831 ACCOUNT_LOGE("cannot find id by serialNumber");
1832 return ERR_OSACCOUNT_SERVICE_INNER_SELECT_ERROR;
1833 }
1834 return ERR_OK;
1835 }
1836
1837 ErrCode IInnerOsAccountManager::GetOsAccountInfoById(const int id, OsAccountInfo &osAccountInfo)
1838 {
1839 ErrCode errCode = GetRealOsAccountInfoById(id, osAccountInfo);
1840 if (errCode != ERR_OK) {
1841 ACCOUNT_LOGE("get osaccount info error, errCode %{public}d.", errCode);
1842 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1843 }
1844 return ERR_OK;
1845 }
1846
1847 ErrCode IInnerOsAccountManager::GetSerialNumberByOsAccountLocalId(const int &id, int64_t &serialNumber)
1848 {
1849 OsAccountInfo osAccountInfo;
1850 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(id, osAccountInfo);
1851 if (errCode != ERR_OK) {
1852 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1853 }
1854 serialNumber = osAccountInfo.GetSerialNumber();
1855 return ERR_OK;
1856 }
1857
1858 ErrCode IInnerOsAccountManager::SubscribeOsAccount(
1859 const OsAccountSubscribeInfo &subscribeInfo, const sptr<IRemoteObject> &eventListener)
1860 {
1861 auto subscribeInfoPtr = std::make_shared<OsAccountSubscribeInfo>(subscribeInfo);
1862 if (subscribeInfoPtr == nullptr) {
1863 ACCOUNT_LOGE("subscribeInfoPtr is nullptr");
1864 }
1865 return subscribeManager_.SubscribeOsAccount(subscribeInfoPtr, eventListener);
1866 }
1867
1868 ErrCode IInnerOsAccountManager::UnsubscribeOsAccount(const sptr<IRemoteObject> &eventListener)
1869 {
1870 return subscribeManager_.UnsubscribeOsAccount(eventListener);
1871 }
1872
1873 const std::shared_ptr<OsAccountSubscribeInfo> IInnerOsAccountManager::GetSubscribeRecordInfo(
1874 const sptr<IRemoteObject> &eventListener)
1875 {
1876 return subscribeManager_.GetSubscribeRecordInfo(eventListener);
1877 }
1878
1879 OS_ACCOUNT_SWITCH_MOD IInnerOsAccountManager::GetOsAccountSwitchMod()
1880 {
1881 return Constants::NOW_OS_ACCOUNT_SWITCH_MOD;
1882 }
1883
1884 ErrCode IInnerOsAccountManager::IsOsAccountCompleted(const int id, bool &isOsAccountCompleted)
1885 {
1886 OsAccountInfo osAccountInfo;
1887 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(id, osAccountInfo);
1888 if (errCode != ERR_OK) {
1889 return errCode;
1890 }
1891 isOsAccountCompleted = osAccountInfo.GetIsCreateCompleted();
1892 return ERR_OK;
1893 }
1894
1895 ErrCode IInnerOsAccountManager::SetOsAccountIsVerified(const int id, const bool isVerified)
1896 {
1897 std::lock_guard<std::mutex> lock(*GetOrInsertUpdateLock(id));
1898 OsAccountInfo osAccountInfo;
1899 ErrCode errCode = GetRealOsAccountInfoById(id, osAccountInfo);
1900 if (errCode != ERR_OK) {
1901 ACCOUNT_LOGE("get osaccount info error, errCode %{public}d.", errCode);
1902 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1903 }
1904
1905 // to be removed, cannot change any thing
1906 if (osAccountInfo.GetToBeRemoved()) {
1907 ACCOUNT_LOGE("account %{public}d will be removed, cannot change verify state!", id);
1908 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_TO_BE_REMOVED_ERROR;
1909 }
1910 bool preVerified = osAccountInfo.GetIsVerified();
1911
1912 osAccountInfo.SetIsVerified(isVerified);
1913 if (isVerified) {
1914 verifiedAccounts_.EnsureInsert(id, true);
1915 } else {
1916 verifiedAccounts_.Erase(id);
1917 }
1918 errCode = osAccountControl_->UpdateOsAccount(osAccountInfo);
1919 if (errCode != ERR_OK && errCode != ERR_ACCOUNT_COMMON_DATA_NO_SPACE) {
1920 ACCOUNT_LOGE("update osaccount info error %{public}d, id: %{public}d",
1921 errCode, osAccountInfo.GetLocalId());
1922 return ERR_OSACCOUNT_SERVICE_INNER_UPDATE_ACCOUNT_ERROR;
1923 }
1924 if (isVerified && !preVerified) {
1925 OsAccountInterface::PublishCommonEvent(osAccountInfo,
1926 OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED, Constants::OPERATION_UNLOCK);
1927 subscribeManager_.Publish(id, OS_ACCOUNT_SUBSCRIBE_TYPE::UNLOCKED);
1928 ReportOsAccountLifeCycle(id, Constants::OPERATION_UNLOCK);
1929
1930 auto task = [] { IInnerOsAccountManager::GetInstance().CleanGarbageOsAccounts(); };
1931 std::thread cleanThread(task);
1932 pthread_setname_np(cleanThread.native_handle(), "CleanGarbageOsAccounts");
1933 cleanThread.detach();
1934 }
1935 return ERR_OK;
1936 }
1937
1938 ErrCode IInnerOsAccountManager::SetOsAccountIsLoggedIn(const int32_t id, const bool isLoggedIn)
1939 {
1940 std::lock_guard<std::mutex> lock(*GetOrInsertUpdateLock(id));
1941 OsAccountInfo osAccountInfo;
1942 ErrCode errCode = GetRealOsAccountInfoById(id, osAccountInfo);
1943 if (errCode != ERR_OK) {
1944 ACCOUNT_LOGE("get osaccount info error, errCode %{public}d.", errCode);
1945 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1946 }
1947 if (osAccountInfo.GetToBeRemoved()) {
1948 ACCOUNT_LOGE("account %{public}d will be removed, cannot change verify state!", id);
1949 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_TO_BE_REMOVED_ERROR;
1950 }
1951 if (isLoggedIn) {
1952 loggedInAccounts_.EnsureInsert(id, true);
1953 } else {
1954 loggedInAccounts_.Erase(id);
1955 }
1956 if (!osAccountInfo.GetIsLoggedIn()) {
1957 #ifdef ACTIVATE_LAST_LOGGED_IN_ACCOUNT
1958 osAccountControl_->SetDefaultActivatedOsAccount(id);
1959 #endif
1960 osAccountInfo.SetIsLoggedIn(isLoggedIn);
1961 osAccountInfo.SetLastLoginTime(std::chrono::duration_cast<std::chrono::seconds>(
1962 std::chrono::system_clock::now().time_since_epoch()).count());
1963 }
1964 errCode = osAccountControl_->UpdateOsAccount(osAccountInfo);
1965 if (errCode != ERR_OK && errCode != ERR_ACCOUNT_COMMON_DATA_NO_SPACE) {
1966 ACCOUNT_LOGE("Update account info failed, errCode: %{public}d, id: %{public}d", errCode, id);
1967 return ERR_OSACCOUNT_SERVICE_INNER_UPDATE_ACCOUNT_ERROR;
1968 }
1969 return ERR_OK;
1970 }
1971
1972 ErrCode IInnerOsAccountManager::GetOsAccountCredentialId(const int id, uint64_t &credentialId)
1973 {
1974 credentialId = 0;
1975 OsAccountInfo osAccountInfo;
1976 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(id, osAccountInfo);
1977 if (errCode == ERR_OK) {
1978 credentialId = osAccountInfo.GetCredentialId();
1979 }
1980 return errCode;
1981 }
1982
1983 ErrCode IInnerOsAccountManager::SetOsAccountCredentialId(const int id, uint64_t credentialId)
1984 {
1985 OsAccountInfo osAccountInfo;
1986 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(id, osAccountInfo);
1987 if (errCode != ERR_OK) {
1988 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
1989 }
1990
1991 osAccountInfo.SetCredentialId(credentialId);
1992 errCode = osAccountControl_->UpdateOsAccount(osAccountInfo);
1993 if (errCode != ERR_OK) {
1994 ACCOUNT_LOGE("update osaccount info error %{public}d, id: %{public}d",
1995 errCode, osAccountInfo.GetLocalId());
1996 return ERR_OSACCOUNT_SERVICE_INNER_UPDATE_ACCOUNT_ERROR;
1997 }
1998 return ERR_OK;
1999 }
2000
2001 ErrCode IInnerOsAccountManager::SetDefaultActivatedOsAccount(const int32_t id)
2002 {
2003 std::lock_guard<std::mutex> lock(operatingMutex_);
2004 if (id == defaultActivatedId_) {
2005 ACCOUNT_LOGW("no need to repeat set initial start id %{public}d", id);
2006 return ERR_OK;
2007 }
2008 OsAccountInfo osAccountInfo;
2009 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(id, osAccountInfo);
2010 if (errCode != ERR_OK) {
2011 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
2012 }
2013
2014 errCode = IsValidOsAccount(osAccountInfo);
2015 if (errCode != ERR_OK) {
2016 return errCode;
2017 }
2018 errCode = osAccountControl_->SetDefaultActivatedOsAccount(id);
2019 if (errCode != ERR_OK) {
2020 ACCOUNT_LOGE("set default activated account id error %{public}d, id: %{public}d", errCode, id);
2021 return errCode;
2022 }
2023 defaultActivatedId_ = id;
2024 return ERR_OK;
2025 }
2026
2027 ErrCode IInnerOsAccountManager::IsOsAccountForeground(const int32_t localId, const uint64_t displayId,
2028 bool &isForeground)
2029 {
2030 int32_t id;
2031 if (!foregroundAccountMap_.Find(displayId, id)) {
2032 ACCOUNT_LOGE("No foreground account in displayId %{public}llu.", static_cast<unsigned long long>(displayId));
2033 return ERR_ACCOUNT_COMMON_ACCOUNT_IN_DISPLAY_ID_NOT_FOUND_ERROR;
2034 }
2035 isForeground = (id == localId);
2036 return ERR_OK;
2037 }
2038
2039 ErrCode IInnerOsAccountManager::GetForegroundOsAccountLocalId(const uint64_t displayId, int32_t &localId)
2040 {
2041 if (!foregroundAccountMap_.Find(displayId, localId)) {
2042 ACCOUNT_LOGE("No foreground account in displayId %{public}llu.", static_cast<unsigned long long>(displayId));
2043 return ERR_ACCOUNT_COMMON_ACCOUNT_IN_DISPLAY_ID_NOT_FOUND_ERROR;
2044 }
2045 return ERR_OK;
2046 }
2047
2048 ErrCode IInnerOsAccountManager::GetForegroundOsAccounts(std::vector<ForegroundOsAccount> &accounts)
2049 {
2050 accounts.clear();
2051 auto it = [&](uint64_t displayId, int32_t localId) {
2052 ForegroundOsAccount foregroundOsAccount;
2053 foregroundOsAccount.displayId = displayId;
2054 foregroundOsAccount.localId = localId;
2055 accounts.emplace_back(foregroundOsAccount);
2056 };
2057 foregroundAccountMap_.Iterate(it);
2058 ACCOUNT_LOGI("Get foreground list successful, total=%{public}zu.", accounts.size());
2059 return ERR_OK;
2060 }
2061
2062 ErrCode IInnerOsAccountManager::GetBackgroundOsAccountLocalIds(std::vector<int32_t> &localIds)
2063 {
2064 localIds.clear();
2065 std::vector<int32_t> activatedIds;
2066 CopyFromActiveList(activatedIds);
2067
2068 std::vector<int32_t> foregroundIds;
2069 auto it = [&](uint64_t displayId, int32_t localId) {
2070 foregroundIds.emplace_back(localId);
2071 };
2072 foregroundAccountMap_.Iterate(it);
2073 std::unordered_set<int32_t> foregroundSet(foregroundIds.begin(), foregroundIds.end());
2074 for (const auto &id : activatedIds) {
2075 if (foregroundSet.find(id) == foregroundSet.end()) {
2076 localIds.emplace_back(id);
2077 }
2078 }
2079 ACCOUNT_LOGI("Get background list successful, total=%{public}zu.", localIds.size());
2080 return ERR_OK;
2081 }
2082
2083 ErrCode IInnerOsAccountManager::GetDefaultActivatedOsAccount(int32_t &id)
2084 {
2085 std::lock_guard<std::mutex> lock(operatingMutex_);
2086 id = defaultActivatedId_;
2087 return ERR_OK;
2088 }
2089
2090 ErrCode IInnerOsAccountManager::IsAllowedCreateAdmin(bool &isAllowedCreateAdmin)
2091 {
2092 return osAccountControl_->IsAllowedCreateAdmin(isAllowedCreateAdmin);
2093 }
2094
2095 ErrCode IInnerOsAccountManager::GetCreatedOsAccountNumFromDatabase(const std::string& storeID,
2096 int &createdOsAccountNum)
2097 {
2098 return osAccountControl_->GetCreatedOsAccountNumFromDatabase(storeID, createdOsAccountNum);
2099 }
2100
2101 ErrCode IInnerOsAccountManager::GetSerialNumberFromDatabase(const std::string& storeID,
2102 int64_t &serialNumber)
2103 {
2104 return osAccountControl_->GetSerialNumberFromDatabase(storeID, serialNumber);
2105 }
2106
2107 ErrCode IInnerOsAccountManager::GetMaxAllowCreateIdFromDatabase(const std::string& storeID, int &id)
2108 {
2109 #ifdef ENABLE_MULTIPLE_OS_ACCOUNTS
2110 return osAccountControl_->GetMaxAllowCreateIdFromDatabase(storeID, id);
2111 #else
2112 id = Constants::START_USER_ID;
2113 return ERR_OK;
2114 #endif // ENABLE_MULTIPLE_OS_ACCOUNTS
2115 }
2116
2117 ErrCode IInnerOsAccountManager::GetOsAccountFromDatabase(const std::string& storeID, const int id,
2118 OsAccountInfo &osAccountInfo)
2119 {
2120 return osAccountControl_->GetOsAccountFromDatabase(storeID, id, osAccountInfo);
2121 }
2122
2123 ErrCode IInnerOsAccountManager::GetOsAccountListFromDatabase(const std::string& storeID,
2124 std::vector<OsAccountInfo> &osAccountList)
2125 {
2126 return osAccountControl_->GetOsAccountListFromDatabase(storeID, osAccountList);
2127 }
2128
2129 void IInnerOsAccountManager::RemoveLocalIdToOperating(int32_t localId)
2130 {
2131 std::lock_guard<std::mutex> lock(operatingMutex_);
2132 auto it = std::find(operatingId_.begin(), operatingId_.end(), localId);
2133 if (it != operatingId_.end()) {
2134 operatingId_.erase(it);
2135 }
2136 }
2137
2138 bool IInnerOsAccountManager::CheckAndAddLocalIdOperating(int32_t localId)
2139 {
2140 std::lock_guard<std::mutex> lock(operatingMutex_);
2141 if (std::find(operatingId_.begin(), operatingId_.end(), localId) != operatingId_.end()) {
2142 return false;
2143 }
2144 operatingId_.push_back(localId);
2145 return true;
2146 }
2147
2148 ErrCode IInnerOsAccountManager::QueryActiveOsAccountIds(std::vector<int32_t>& ids)
2149 {
2150 CopyFromActiveList(ids);
2151 return ERR_OK;
2152 }
2153
2154 void IInnerOsAccountManager::PushIdIntoActiveList(int32_t id)
2155 {
2156 std::lock_guard<std::mutex> lock(ativeMutex_);
2157 if (std::find(activeAccountId_.begin(), activeAccountId_.end(), id) == activeAccountId_.end()) {
2158 CountTraceAdapter("activeId", (int64_t)id);
2159 }
2160 #ifndef ENABLE_MULTIPLE_ACTIVE_ACCOUNTS
2161 activeAccountId_.clear();
2162 #else
2163 activeAccountId_.erase(std::remove(activeAccountId_.begin(), activeAccountId_.end(), id), activeAccountId_.end());
2164 #endif
2165 //Compatible with the QueryActiveOsAccountIds
2166 activeAccountId_.insert(activeAccountId_.begin(), id);
2167 return;
2168 }
2169
2170 void IInnerOsAccountManager::EraseIdFromActiveList(int32_t id)
2171 {
2172 std::lock_guard<std::mutex> lock(ativeMutex_);
2173 if (std::find(activeAccountId_.begin(), activeAccountId_.end(), id) != activeAccountId_.end()) {
2174 ACCOUNT_LOGE("EraseIdFromActiveList enter0");
2175 activeAccountId_.erase(
2176 std::remove(activeAccountId_.begin(), activeAccountId_.end(), id), activeAccountId_.end());
2177 } else {
2178 ACCOUNT_LOGI("os account is not in active list, no need to erase!");
2179 }
2180 CountTraceAdapter("deActiveId", (int64_t)id);
2181 }
2182
2183 bool IInnerOsAccountManager::IsOsAccountIDInActiveList(int32_t id)
2184 {
2185 std::lock_guard<std::mutex> lock(ativeMutex_);
2186 auto it = std::find(activeAccountId_.begin(), activeAccountId_.end(), id);
2187 return (it != activeAccountId_.end());
2188 }
2189
2190 void IInnerOsAccountManager::CopyFromActiveList(std::vector<int32_t>& idList)
2191 {
2192 idList.clear();
2193 std::lock_guard<std::mutex> lock(ativeMutex_);
2194 for (auto it = activeAccountId_.begin(); it != activeAccountId_.end(); it++) {
2195 idList.push_back(*it);
2196 }
2197 }
2198
2199 ErrCode IInnerOsAccountManager::UpdateAccountInfoByDomainAccountInfo(
2200 int32_t userId, const DomainAccountInfo &newDomainAccountInfo)
2201 {
2202 if (!CheckAndAddLocalIdOperating(userId)) {
2203 ACCOUNT_LOGW("Account id = %{public}d already in operating", userId);
2204 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_OPERATING_ERROR;
2205 }
2206 OsAccountInfo accountInfo;
2207 ErrCode result = osAccountControl_->GetOsAccountInfoById(userId, accountInfo);
2208 if (result != ERR_OK) {
2209 RemoveLocalIdToOperating(userId);
2210 return result;
2211 }
2212 DomainAccountInfo oldDomainAccountInfo;
2213 accountInfo.GetDomainInfo(oldDomainAccountInfo);
2214 if (!newDomainAccountInfo.accountName_.empty()) {
2215 oldDomainAccountInfo.accountName_ = newDomainAccountInfo.accountName_;
2216 }
2217 if (!newDomainAccountInfo.accountId_.empty()) {
2218 oldDomainAccountInfo.accountId_ = newDomainAccountInfo.accountId_;
2219 }
2220 accountInfo.SetDomainInfo(oldDomainAccountInfo);
2221 accountInfo.SetLocalName(newDomainAccountInfo.domain_ + "/" + newDomainAccountInfo.accountName_);
2222 result = osAccountControl_->UpdateOsAccount(accountInfo);
2223 if (result != ERR_OK) {
2224 ACCOUNT_LOGE("Update account info failed, result = %{public}d", result);
2225 ReportOsAccountOperationFail(userId, Constants::OPERATION_UPDATE, result,
2226 "Failed to update domain account info");
2227 RemoveLocalIdToOperating(userId);
2228 return result;
2229 }
2230 RemoveLocalIdToOperating(userId);
2231 #ifdef HAS_CES_PART
2232 AccountEventProvider::EventPublish(EventFwk::CommonEventSupport::COMMON_EVENT_USER_INFO_UPDATED,
2233 userId, nullptr);
2234 #endif // HAS_CES_PART
2235 return ERR_OK;
2236 }
2237
2238 ErrCode IInnerOsAccountManager::UpdateAccountToForeground(const uint64_t displayId, OsAccountInfo &osAccountInfo)
2239 {
2240 int32_t localId = osAccountInfo.GetLocalId();
2241 osAccountInfo.SetIsActived(true);
2242 osAccountInfo.SetDisplayId(displayId);
2243 osAccountInfo.SetIsForeground(true);
2244 if (osAccountInfo.GetIsLoggedIn()) {
2245 #ifdef ACTIVATE_LAST_LOGGED_IN_ACCOUNT
2246 osAccountControl_->SetDefaultActivatedOsAccount(localId);
2247 #endif
2248 }
2249 ErrCode errCode = osAccountControl_->UpdateOsAccount(osAccountInfo);
2250 if (errCode != ERR_OK && errCode != ERR_ACCOUNT_COMMON_DATA_NO_SPACE) {
2251 ACCOUNT_LOGE("Update account failed, localId=%{public}d, errCode=%{public}d.",
2252 localId, errCode);
2253 }
2254 return ERR_OK;
2255 }
2256
2257 ErrCode IInnerOsAccountManager::UpdateAccountToBackground(int32_t oldId)
2258 {
2259 OsAccountInfo oldOsAccountInfo;
2260 {
2261 std::lock_guard<std::mutex> lock(*GetOrInsertUpdateLock(oldId));
2262 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(oldId, oldOsAccountInfo);
2263 if (errCode != ERR_OK) {
2264 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
2265 }
2266 oldOsAccountInfo.SetIsForeground(false);
2267 oldOsAccountInfo.SetDisplayId(Constants::INVALID_DISPALY_ID);
2268 errCode = osAccountControl_->UpdateOsAccount(oldOsAccountInfo);
2269 if (errCode != ERR_OK && errCode != ERR_ACCOUNT_COMMON_DATA_NO_SPACE) {
2270 ACCOUNT_LOGE("Update osaccount failed, errCode=%{public}d, id=%{public}d",
2271 errCode, oldOsAccountInfo.GetLocalId());
2272 }
2273 }
2274 OsAccountInterface::PublishCommonEvent(oldOsAccountInfo,
2275 OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_USER_BACKGROUND, Constants::OPERATION_SWITCH);
2276
2277 #ifdef ENABLE_MULTIPLE_ACTIVE_ACCOUNTS
2278 #ifndef SUPPORT_STOP_MAIN_OS_ACCOUNT
2279 if (oldId == Constants::START_USER_ID) {
2280 return ERR_OK;
2281 }
2282 #endif
2283 bool isLoggedIn = false;
2284 if ((oldOsAccountInfo.GetType() != OsAccountType::PRIVATE) && (!loggedInAccounts_.Find(oldId, isLoggedIn))) {
2285 DeactivateOsAccount(oldId, false);
2286 }
2287 #else
2288 DeactivateOsAccountByInfo(oldOsAccountInfo);
2289 #endif // ENABLE_MULTIPLE_ACTIVE_ACCOUNTS
2290 return ERR_OK;
2291 }
2292
2293 std::shared_ptr<std::mutex> IInnerOsAccountManager::GetOrInsertUpdateLock(int32_t id)
2294 {
2295 std::lock_guard<std::mutex> lock(updateLockMutex_);
2296 auto it = updateLocks_.find(id);
2297 if (it == updateLocks_.end()) {
2298 auto mutexPtr = std::make_shared<std::mutex>();
2299 updateLocks_.insert(std::make_pair(id, mutexPtr));
2300 return mutexPtr;
2301 } else {
2302 return it->second;
2303 }
2304 }
2305
2306 ErrCode IInnerOsAccountManager::SetOsAccountToBeRemoved(int32_t localId, bool toBeRemoved)
2307 {
2308 if (!CheckAndAddLocalIdOperating(localId)) {
2309 ACCOUNT_LOGE("The account %{public}d already in operating", localId);
2310 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_OPERATING_ERROR;
2311 }
2312 OsAccountInfo osAccountInfo;
2313 ErrCode errCode = osAccountControl_->GetOsAccountInfoById(localId, osAccountInfo);
2314 if (errCode != ERR_OK) {
2315 RemoveLocalIdToOperating(localId);
2316 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
2317 }
2318 osAccountInfo.SetToBeRemoved(toBeRemoved);
2319 errCode = osAccountControl_->UpdateOsAccount(osAccountInfo);
2320 RemoveLocalIdToOperating(localId);
2321 return errCode;
2322 }
2323
2324 ErrCode IInnerOsAccountManager::IsValidOsAccount(const OsAccountInfo &osAccountInfo)
2325 {
2326 if (!osAccountInfo.GetIsCreateCompleted()) {
2327 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_IS_UNCOMPLETED_ERROR;
2328 }
2329
2330 if (osAccountInfo.GetToBeRemoved()) {
2331 return ERR_OSACCOUNT_SERVICE_INNER_ACCOUNT_TO_BE_REMOVED_ERROR;
2332 }
2333 return ERR_OK;
2334 }
2335 } // namespace AccountSA
2336 } // namespace OHOS