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