1 /*
2 * Copyright (c) 2021-2025 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 "os_account_control_file_manager.h"
16 #include <dirent.h>
17 #include <string>
18 #include <pthread.h>
19 #include <securec.h>
20 #include <sstream>
21 #include <sys/types.h>
22 #include <thread>
23 #include <unistd.h>
24
25 #include "account_log_wrapper.h"
26 #include "account_hisysevent_adapter.h"
27 #ifdef HAS_CONFIG_POLICY_PART
28 #include "config_policy_utils.h"
29 #endif
30 #include "string_ex.h"
31 #include "os_account_constants.h"
32 #include "os_account_info_json_parser.h"
33 #include "parameters.h"
34
35 namespace OHOS {
36 namespace AccountSA {
37 namespace {
38 const char DEFAULT_ACTIVATED_ACCOUNT_ID[] = "DefaultActivatedAccountID";
39 const std::string OS_ACCOUNT_STORE_ID = "os_account_info";
40 #ifdef ENABLE_FILE_WATCHER
41 constexpr uint32_t ALG_COMMON_SIZE = 32;
42 const char DISTRIBUTED_ACCOUNT_FILE_NAME[] = "/account.json";
43 #endif // ENABLE_FILE_WATCHER
44 #ifndef ACCOUNT_TEST
45 const std::string ACCOUNT_CFG_DIR_ROOT_PATH = "/data/service/el1/public/account/";
46 const std::string DEFAULT_OS_ACCOUNT_CONFIG_FILE = "/system/etc/account/os_account_config.json";
47 #else
48 const std::string ACCOUNT_CFG_DIR_ROOT_PATH = "/data/service/el1/public/account/test/";
49 const std::string DEFAULT_OS_ACCOUNT_CONFIG_FILE = ACCOUNT_CFG_DIR_ROOT_PATH + "os_account_config.json";
50 #endif // ACCOUNT_TEST
51 #ifdef HAS_CONFIG_POLICY_PART
52 const char OS_ACCOUNT_CONFIG_FILE[] = "etc/os_account/os_account_config.json";
53 #endif // HAS_CONFIG_POLICY_PART
54 const char MAX_OS_ACCOUNT_NUM[] = "maxOsAccountNum";
55 const char MAX_LOGGED_IN_OS_ACCOUNT_NUM[] = "maxLoggedInOsAccountNum";
56 #ifdef ENABLE_U1_ACCOUNT
57 const char SYSTEM_ACCOUNTS_CONFIG[] = "systemAccounts";
58 const char U1_CONFIG[] = "1";
59 const char SYSTEM_ACCOUNT_TYPE[] = "type";
60 const char SYSTEM_ACCOUNT_NAME[] = "name";
61 const char SYSTEM_ACCOUNT_BLOCK_BOOT[] = "canBlockBoot";
62 #endif // ENABLE_U1_ACCOUNT
63 const char DEVELOPER_MODE_STATE[] = "const.security.developermode.state";
64 const char DEVELOPER_MODE[] = "developerMode";
65 const char USER_PHOTO_FILE_PNG_NAME[] = "fase.png";
66 const char USER_PHOTO_FILE_JPG_NAME[] = "fase.jpg";
67 const char USER_PHOTO_BASE_JPG_HEAD[] = "data:image/jpeg;base64,";
68 const char USER_PHOTO_BASE_PNG_HEAD[] = "data:image/png;base64,";
69 const char START_USER_STRING_ID[] = "100";
70 const char DEVICE_OWNER_ID[] = "deviceOwnerId";
71 const char NEXT_LOCAL_ID[] = "NextLocalId";
72 const char IS_SERIAL_NUMBER_FULL[] = "isSerialNumberFull";
73 }
74
GetValidAccountID(const std::string & dirName,std::int32_t & accountID)75 bool GetValidAccountID(const std::string& dirName, std::int32_t& accountID)
76 {
77 // check length first
78 if (dirName.empty() || dirName.size() > Constants::MAX_USER_ID_LENGTH) {
79 return false;
80 }
81
82 auto iter = std::any_of(dirName.begin(), dirName.end(),
83 [dirName](char c) {
84 return (c < '0' || c > '9');
85 });
86 if (iter) {
87 return false;
88 }
89
90 // convert to osaccount id
91 std::stringstream sstream;
92 sstream << dirName;
93 sstream >> accountID;
94 return (accountID >= Constants::ADMIN_LOCAL_ID && accountID <= Constants::MAX_USER_ID);
95 }
96
97 #ifdef ENABLE_U1_ACCOUNT
GetU1Config(const CJsonUnique & configJson,OsAccountConfig & config)98 void OsAccountControlFileManager::GetU1Config(const CJsonUnique &configJson, OsAccountConfig &config)
99 {
100 CJson *systemAccountsJson = nullptr;
101 bool ret = GetDataByType<CJson *>(configJson, SYSTEM_ACCOUNTS_CONFIG, systemAccountsJson);
102 if (!ret) {
103 ACCOUNT_LOGE("Failed to parse %{public}s", SYSTEM_ACCOUNTS_CONFIG);
104 return;
105 }
106 CJson *u1Json = nullptr;
107 ret = GetDataByType<CJson *>(systemAccountsJson, U1_CONFIG, u1Json);
108 if (!ret) {
109 ACCOUNT_LOGE("Failed to parse %{public}s", U1_CONFIG);
110 return;
111 }
112 config.isU1Enable = true;
113 int32_t type = -1;
114 GetDataByType<std::int32_t>(u1Json, SYSTEM_ACCOUNT_TYPE, type);
115 if (type != static_cast<int32_t>(OsAccountType::ADMIN) &&
116 type != static_cast<int32_t>(OsAccountType::NORMAL) &&
117 type != static_cast<int32_t>(OsAccountType::GUEST) &&
118 type != static_cast<int32_t>(OsAccountType::PRIVATE)) {
119 ACCOUNT_LOGE("Fail to get type:%{public}d from config.", type);
120 config.u1AccountType = OsAccountType::ADMIN;
121 } else {
122 config.u1AccountType = static_cast<OsAccountType>(type);
123 }
124 GetDataByType<std::string>(u1Json, SYSTEM_ACCOUNT_NAME, config.u1AccountName);
125 if (config.u1AccountName.length() > Constants::LOCAL_NAME_MAX_SIZE) {
126 ACCOUNT_LOGE("Fail to get name:%{public}s from config.", config.u1AccountName.c_str());
127 config.u1AccountName = "";
128 }
129 GetDataByType<bool>(u1Json, SYSTEM_ACCOUNT_BLOCK_BOOT, config.isBlockBoot);
130 }
131 #endif // ENABLE_U1_ACCOUNT
132
GetOsAccountConfig(OsAccountConfig & config)133 ErrCode OsAccountControlFileManager::GetOsAccountConfig(OsAccountConfig &config)
134 {
135 std::string cfgPath = DEFAULT_OS_ACCOUNT_CONFIG_FILE;
136 #ifdef HAS_CONFIG_POLICY_PART
137 char buf[MAX_PATH_LEN];
138 char *path = GetOneCfgFile(OS_ACCOUNT_CONFIG_FILE, buf, MAX_PATH_LEN);
139 if (path != nullptr && *path != '\0') {
140 cfgPath = path;
141 }
142 #endif
143 std::string configStr;
144 ErrCode errCode = accountFileOperator_->GetFileContentByPath(cfgPath, configStr);
145 if (errCode != ERR_OK) {
146 ACCOUNT_LOGE("Get content from file %{public}s failed!", cfgPath.c_str());
147 return errCode;
148 }
149 auto configJson = CreateJsonFromString(configStr);
150 if (configJson == nullptr) {
151 ACCOUNT_LOGE("Parse os account info json data failed");
152 return ERR_ACCOUNT_COMMON_BAD_JSON_FORMAT_ERROR;
153 }
154
155 int32_t maxOsAccountNum = -1;
156 GetDataByType<int32_t>(configJson, MAX_OS_ACCOUNT_NUM, maxOsAccountNum);
157 if (maxOsAccountNum > 0) {
158 config.maxOsAccountNum = static_cast<uint32_t>(maxOsAccountNum);
159 }
160 GetDataByType<uint32_t>(configJson, MAX_LOGGED_IN_OS_ACCOUNT_NUM, config.maxLoggedInOsAccountNum);
161 #ifdef ENABLE_U1_ACCOUNT
162 GetU1Config(configJson, config);
163 #endif // ENABLE_U1_ACCOUNT
164 bool isDeveloperMode = OHOS::system::GetBoolParameter(DEVELOPER_MODE_STATE, false);
165 if (isDeveloperMode && IsKeyExist(configJson, DEVELOPER_MODE)) {
166 auto modeJson = GetItemFromJson(configJson, DEVELOPER_MODE);
167 GetDataByType<uint32_t>(modeJson, MAX_LOGGED_IN_OS_ACCOUNT_NUM, config.maxLoggedInOsAccountNum);
168 }
169 if ((config.maxLoggedInOsAccountNum > config.maxOsAccountNum) ||
170 (config.maxLoggedInOsAccountNum <= 0)) {
171 config.maxLoggedInOsAccountNum = config.maxOsAccountNum;
172 }
173 return ERR_OK;
174 }
175
176 #ifdef ENABLE_FILE_WATCHER
RecoverAccountData(const std::string & fileName,const int32_t id)177 bool OsAccountControlFileManager::RecoverAccountData(const std::string &fileName, const int32_t id)
178 {
179 #if defined(HAS_KV_STORE_PART) && defined(DISTRIBUTED_FEATURE_ENABLED)
180 std::string recoverDataStr;
181 if (fileName == Constants::ACCOUNT_LIST_FILE_JSON_PATH) {
182 CJsonUnique accountListJson = nullptr;
183 osAccountDataBaseOperator_->GetAccountListFromStoreID(OS_ACCOUNT_STORE_ID, accountListJson);
184 recoverDataStr = PackJsonToString(accountListJson);
185 if (recoverDataStr.empty()) {
186 ACCOUNT_LOGE("failed to dump json object");
187 return false;
188 }
189 } else if (id >= Constants::START_USER_ID) {
190 OsAccountInfo osAccountInfo;
191 if (GetOsAccountFromDatabase(OS_ACCOUNT_STORE_ID, id, osAccountInfo) != ERR_OK) {
192 ACCOUNT_LOGW("Failed to get osaccount from database");
193 return false;
194 }
195 recoverDataStr = osAccountInfo.ToString();
196 } else {
197 ACCOUNT_LOGW("Failed to parse parameters");
198 return false;
199 }
200 if (recoverDataStr.empty()) {
201 ACCOUNT_LOGW("Get empty recover file data");
202 return false;
203 }
204 // recover data
205 ErrCode result = accountFileOperator_->InputFileByPathAndContent(fileName, recoverDataStr);
206 if (result != ERR_OK) {
207 ACCOUNT_LOGE("Recover local file data failed, err = %{public}d", result);
208 return false;
209 }
210 // update local digest
211 if (accountFileWatcherMgr_.AddAccountInfoDigest(recoverDataStr, fileName) != ERR_OK) {
212 ACCOUNT_LOGE("Failed to update local digest");
213 return false;
214 }
215 #endif // defined(HAS_KV_STORE_PART) && defined(DISTRIBUTED_FEATURE_ENABLED)
216 return true;
217 }
218
DealWithFileModifyEvent(const std::string & fileName,const int32_t id)219 bool OsAccountControlFileManager::DealWithFileModifyEvent(const std::string &fileName, const int32_t id)
220 {
221 ACCOUNT_LOGI("Enter");
222 {
223 std::unique_lock<std::shared_timed_mutex> lock(accountFileOperator_->fileLock_);
224 if (accountFileOperator_->GetValidModifyFileOperationFlag(fileName)) {
225 ACCOUNT_LOGD("This is valid service operate, no need to deal with it.");
226 accountFileOperator_->SetValidModifyFileOperationFlag(fileName, false);
227 return true;
228 }
229 }
230 std::lock_guard<std::mutex> lock(accountInfoFileLock_);
231 std::string fileInfoStr;
232 if (accountFileOperator_->GetFileContentByPath(fileName, fileInfoStr) != ERR_OK) {
233 ACCOUNT_LOGE("Get content from file %{public}s failed!", fileName.c_str());
234 return false;
235 }
236 uint8_t localDigestData[ALG_COMMON_SIZE] = {0};
237 accountFileWatcherMgr_.GetAccountInfoDigestFromFile(fileName, localDigestData, ALG_COMMON_SIZE);
238 #ifdef HAS_HUKS_PART
239 uint8_t newDigestData[ALG_COMMON_SIZE] = {0};
240 GenerateAccountInfoDigest(fileInfoStr, newDigestData, ALG_COMMON_SIZE);
241
242 if (memcmp(localDigestData, newDigestData, ALG_COMMON_SIZE) == EOK) {
243 ACCOUNT_LOGD("No need to recover local file data.");
244 return true;
245 }
246 #endif // HAS_HUKS_PART
247 ReportOsAccountDataTampered(id, fileName, "OS_ACCOUNT_INFO");
248 ACCOUNT_LOGW("Local file data has been changed");
249 return RecoverAccountData(fileName, id);
250 }
251
DealWithFileDeleteEvent(const std::string & fileName,const int32_t id)252 bool OsAccountControlFileManager::DealWithFileDeleteEvent(const std::string &fileName, const int32_t id)
253 {
254 ACCOUNT_LOGI("Enter");
255 {
256 std::unique_lock<std::shared_timed_mutex> lock(accountFileOperator_->fileLock_);
257 if (accountFileOperator_->GetValidDeleteFileOperationFlag(fileName)) {
258 ACCOUNT_LOGD("This is valid service operate, no need to deal with it.");
259 accountFileOperator_->SetValidDeleteFileOperationFlag(fileName, false);
260 accountFileWatcherMgr_.RemoveFileWatcher(id, fileName);
261 return true;
262 }
263 }
264 ReportOsAccountDataTampered(id, fileName, "OS_ACCOUNT_INFO");
265 std::lock_guard<std::mutex> lock(accountInfoFileLock_);
266 if (!RecoverAccountData(fileName, id)) {
267 ACCOUNT_LOGE("Recover account data failed.");
268 }
269 accountFileWatcherMgr_.AddFileWatcher(id, eventCallbackFunc_, fileName);
270 return true;
271 }
272
DealWithFileMoveEvent(const std::string & fileName,const int32_t id)273 bool OsAccountControlFileManager::DealWithFileMoveEvent(const std::string &fileName, const int32_t id)
274 {
275 ACCOUNT_LOGI("Enter");
276 // delete old file watcher
277 accountFileWatcherMgr_.RemoveFileWatcher(id, fileName);
278 ReportOsAccountDataTampered(id, fileName, "OS_ACCOUNT_INFO");
279 std::lock_guard<std::mutex> lock(accountInfoFileLock_);
280 if (!RecoverAccountData(fileName, id)) {
281 ACCOUNT_LOGE("Recover account data failed.");
282 }
283 accountFileWatcherMgr_.AddFileWatcher(id, eventCallbackFunc_, fileName);
284 return true;
285 }
286 #endif // ENABLE_FILE_WATCHER
287
288 #ifdef ENABLE_FILE_WATCHER
OsAccountControlFileManager()289 OsAccountControlFileManager::OsAccountControlFileManager()
290 : accountFileWatcherMgr_(AccountFileWatcherMgr::GetInstance())
291 {
292 accountFileOperator_ = accountFileWatcherMgr_.accountFileOperator_;
293 #if defined(HAS_KV_STORE_PART) && defined(DISTRIBUTED_FEATURE_ENABLED)
294 osAccountDataBaseOperator_ = std::make_shared<OsAccountDatabaseOperator>();
295 #endif // defined(HAS_KV_STORE_PART) && defined(DISTRIBUTED_FEATURE_ENABLED)
296 osAccountFileOperator_ = std::make_shared<OsAccountFileOperator>();
297 osAccountPhotoOperator_ = std::make_shared<OsAccountPhotoOperator>();
298 eventCallbackFunc_ = [this](const std::string &fileName, int32_t id, uint32_t event) {
299 ACCOUNT_LOGI("Inotify event = %{public}d, fileName = %{public}s", event, fileName.c_str());
300 switch (event) {
301 case IN_MODIFY: {
302 return DealWithFileModifyEvent(fileName, id);
303 }
304 case IN_MOVE_SELF: {
305 return DealWithFileMoveEvent(fileName, id);
306 }
307 case IN_DELETE_SELF: {
308 return DealWithFileDeleteEvent(fileName, id);
309 }
310 default: {
311 ACCOUNT_LOGW("Get event invalid!");
312 return false;
313 }
314 }
315 };
316 }
317 #else
OsAccountControlFileManager()318 OsAccountControlFileManager::OsAccountControlFileManager()
319 {
320 accountFileOperator_ = std::make_shared<AccountFileOperator>();
321 #if defined(HAS_KV_STORE_PART) && defined(DISTRIBUTED_FEATURE_ENABLED)
322 osAccountDataBaseOperator_ = std::make_shared<OsAccountDatabaseOperator>();
323 #endif // HAS_KV_STORE_PART && defined(DISTRIBUTED_FEATURE_ENABLED)
324 osAccountFileOperator_ = std::make_shared<OsAccountFileOperator>();
325 osAccountPhotoOperator_ = std::make_shared<OsAccountPhotoOperator>();
326 }
327 #endif // ENABLE_FILE_WATCHER
~OsAccountControlFileManager()328 OsAccountControlFileManager::~OsAccountControlFileManager()
329 {}
330
Init()331 void OsAccountControlFileManager::Init()
332 {
333 FileInit();
334 CJsonUnique accountListJson = nullptr;
335 ErrCode result = GetAccountListFromFile(accountListJson);
336 if (result != ERR_OK) {
337 return;
338 }
339 std::vector<std::string> accountIdList;
340 GetDataByType<std::vector<std::string>>(accountListJson, Constants::ACCOUNT_LIST, accountIdList);
341
342 #ifdef ENABLE_FILE_WATCHER
343 if (!accountIdList.empty()) {
344 InitFileWatcherInfo(accountIdList);
345 }
346 #endif // ENABLE_FILE_WATCHER
347 ACCOUNT_LOGI("OsAccountControlFileManager Init end");
348 }
349
FileInit()350 void OsAccountControlFileManager::FileInit()
351 {
352 if (!accountFileOperator_->IsJsonFileReady(Constants::ACCOUNT_LIST_FILE_JSON_PATH)) {
353 ACCOUNT_LOGI("OsAccountControlFileManager there is not have valid account list, create!");
354 RecoverAccountListJsonFile();
355 }
356 #ifdef ENABLE_FILE_WATCHER
357 if (!accountFileOperator_->IsJsonFileReady(Constants::ACCOUNT_INFO_DIGEST_FILE_PATH)) {
358 ACCOUNT_LOGI("OsAccountControlFileManager there is not have valid account info digest file, create!");
359 RecoverAccountInfoDigestJsonFile();
360 }
361 #endif // ENABLE_FILE_WATCHER
362 // -1 is special refers to conmon account data file.
363 #ifdef ENABLE_FILE_WATCHER
364 accountFileWatcherMgr_.AddFileWatcher(-1, eventCallbackFunc_, Constants::ACCOUNT_LIST_FILE_JSON_PATH);
365 #endif // ENABLE_FILE_WATCHER
366 if (!accountFileOperator_->IsJsonFileReady(Constants::ACCOUNT_INDEX_JSON_PATH)) {
367 ACCOUNT_LOGI("OsAccountControlFileManager there is not have valid account index file, create!");
368 BuildAndSaveOsAccountIndexJsonFile();
369 }
370 #ifdef ENABLE_FILE_WATCHER
371 accountFileWatcherMgr_.AddFileWatcher(-1, eventCallbackFunc_, Constants::ACCOUNT_INDEX_JSON_PATH);
372 #endif // ENABLE_FILE_WATCHER
373 if (!accountFileOperator_->IsJsonFileReady(Constants::BASE_OSACCOUNT_CONSTRAINTS_JSON_PATH)) {
374 ACCOUNT_LOGI("OsAccountControlFileManager there is not have valid account list, create!");
375 BuildAndSaveBaseOAConstraintsJsonFile();
376 }
377 #ifdef ENABLE_FILE_WATCHER
378 accountFileWatcherMgr_.AddFileWatcher(-1, eventCallbackFunc_, Constants::BASE_OSACCOUNT_CONSTRAINTS_JSON_PATH);
379 #endif // ENABLE_FILE_WATCHER
380 if (!accountFileOperator_->IsJsonFileReady(Constants::GLOBAL_OSACCOUNT_CONSTRAINTS_JSON_PATH)) {
381 ACCOUNT_LOGI("OsAccountControlFileManager there is not have valid account list, create!");
382 BuildAndSaveGlobalOAConstraintsJsonFile();
383 }
384 #ifdef ENABLE_FILE_WATCHER
385 accountFileWatcherMgr_.AddFileWatcher(-1, eventCallbackFunc_, Constants::GLOBAL_OSACCOUNT_CONSTRAINTS_JSON_PATH);
386 #endif // ENABLE_FILE_WATCHER
387 if (!accountFileOperator_->IsJsonFileReady(Constants::SPECIFIC_OSACCOUNT_CONSTRAINTS_JSON_PATH)) {
388 ACCOUNT_LOGI("OsAccountControlFileManager there is not have valid account list, create!");
389 BuildAndSaveSpecificOAConstraintsJsonFile();
390 }
391 #ifdef ENABLE_FILE_WATCHER
392 accountFileWatcherMgr_.AddFileWatcher(-1, eventCallbackFunc_, Constants::SPECIFIC_OSACCOUNT_CONSTRAINTS_JSON_PATH);
393 #endif // ENABLE_FILE_WATCHER
394 }
395
396 #ifdef ENABLE_FILE_WATCHER
InitFileWatcherInfo(std::vector<std::string> & accountIdList)397 void OsAccountControlFileManager::InitFileWatcherInfo(std::vector<std::string> &accountIdList)
398 {
399 for (std::string i : accountIdList) {
400 int32_t id = 0;
401 if (!StrToInt(i, id)) {
402 ACCOUNT_LOGE("Convert localId failed");
403 continue;
404 }
405 accountFileWatcherMgr_.AddFileWatcher(id, eventCallbackFunc_);
406 }
407 }
408 #endif // ENABLE_FILE_WATCHER
409
BuildAndSaveAccountListJsonFile(const std::vector<std::string> & accounts)410 void OsAccountControlFileManager::BuildAndSaveAccountListJsonFile(const std::vector<std::string>& accounts)
411 {
412 ACCOUNT_LOGD("Enter.");
413 std::lock_guard<std::mutex> lock(accountInfoFileLock_);
414 auto accountList = CreateJson();
415 AddVectorStringToJson(accountList, Constants::ACCOUNT_LIST, accounts);
416 AddIntToJson(accountList, Constants::COUNT_ACCOUNT_NUM, accounts.size());
417 AddIntToJson(accountList, DEFAULT_ACTIVATED_ACCOUNT_ID, Constants::START_USER_ID);
418 AddIntToJson(accountList, Constants::MAX_ALLOW_CREATE_ACCOUNT_ID, Constants::MAX_USER_ID);
419 AddInt64ToJson(accountList, Constants::SERIAL_NUMBER_NUM, Constants::SERIAL_NUMBER_NUM_START);
420 AddBoolToJson(accountList, IS_SERIAL_NUMBER_FULL, Constants::IS_SERIAL_NUMBER_FULL_INIT_VALUE);
421 AddIntToJson(accountList, NEXT_LOCAL_ID, Constants::START_USER_ID + 1);
422
423 SaveAccountListToFile(accountList);
424 }
425
BuildAndSaveBaseOAConstraintsJsonFile()426 void OsAccountControlFileManager::BuildAndSaveBaseOAConstraintsJsonFile()
427 {
428 ACCOUNT_LOGI("Enter.");
429 std::lock_guard<std::mutex> lock(accountInfoFileLock_);
430 std::vector<std::string> baseOAConstraints;
431 if (osAccountFileOperator_->GetConstraintsByType(OsAccountType::ADMIN, baseOAConstraints) != ERR_OK) {
432 ACCOUNT_LOGE("Get %{public}d base os account constraints failed.", Constants::START_USER_ID);
433 return;
434 }
435 auto baseOsAccountConstraints = CreateJson();
436 AddVectorStringToJson(baseOsAccountConstraints, START_USER_STRING_ID, baseOAConstraints);
437 SaveBaseOAConstraintsToFile(baseOsAccountConstraints);
438 }
439
BuildAndSaveGlobalOAConstraintsJsonFile()440 void OsAccountControlFileManager::BuildAndSaveGlobalOAConstraintsJsonFile()
441 {
442 ACCOUNT_LOGI("Enter.");
443 std::lock_guard<std::mutex> lock(accountInfoFileLock_);
444 auto globalOsAccountConstraints = CreateJson();
445 AddIntToJson(globalOsAccountConstraints, DEVICE_OWNER_ID, -1);
446 auto allGlobalConstraints = CreateJsonNull();
447 AddObjToJson(globalOsAccountConstraints, Constants::ALL_GLOBAL_CONSTRAINTS, allGlobalConstraints);
448 SaveGlobalOAConstraintsToFile(globalOsAccountConstraints);
449 }
450
BuildAndSaveSpecificOAConstraintsJsonFile()451 void OsAccountControlFileManager::BuildAndSaveSpecificOAConstraintsJsonFile()
452 {
453 std::lock_guard<std::mutex> lock(accountInfoFileLock_);
454 auto allGlobalConstraints = CreateJsonNull();
455 auto osAccountConstraintsList = CreateJson();
456 AddObjToJson(osAccountConstraintsList, Constants::ALL_SPECIFIC_CONSTRAINTS, allGlobalConstraints);
457 auto specificOsAccountConstraints = CreateJson();
458 AddObjToJson(specificOsAccountConstraints, START_USER_STRING_ID, osAccountConstraintsList);
459 SaveSpecificOAConstraintsToFile(specificOsAccountConstraints);
460 }
461
BuildAndSaveOsAccountIndexJsonFile()462 void OsAccountControlFileManager::BuildAndSaveOsAccountIndexJsonFile()
463 {
464 std::string accountIndex;
465 ErrCode result = GetAccountIndexInfo(accountIndex);
466 if (result != ERR_OK) {
467 ACCOUNT_LOGE("Get account index info error code %{public}d.", result);
468 return;
469 }
470 std::lock_guard<std::mutex> lock(accountInfoFileLock_);
471 result = accountFileOperator_->InputFileByPathAndContent(Constants::ACCOUNT_INDEX_JSON_PATH, accountIndex);
472 if (result != ERR_OK) {
473 ACCOUNT_LOGE("Failed to input account index info to file!");
474 }
475 return;
476 }
477
RecoverAccountInfoDigestJsonFile()478 void OsAccountControlFileManager::RecoverAccountInfoDigestJsonFile()
479 {
480 std::string listInfoStr;
481 accountFileOperator_->GetFileContentByPath(Constants::ACCOUNT_LIST_FILE_JSON_PATH, listInfoStr);
482 #ifdef HAS_HUKS_PART
483 uint8_t digestOutData[ALG_COMMON_SIZE] = {0};
484 GenerateAccountInfoDigest(listInfoStr, digestOutData, ALG_COMMON_SIZE);
485 auto digestJsonData = CreateJson();
486 AddVectorUint8ToJson(digestJsonData, Constants::ACCOUNT_LIST_FILE_JSON_PATH,
487 std::vector<uint8_t>(digestOutData, digestOutData + ALG_COMMON_SIZE));
488 std::string strValue = PackJsonToString(digestJsonData);
489 accountFileOperator_->InputFileByPathAndContent(Constants::ACCOUNT_INFO_DIGEST_FILE_PATH, strValue);
490 #endif // HAS_HUKS_PART
491 return;
492 }
493
RecoverAccountListJsonFile()494 void OsAccountControlFileManager::RecoverAccountListJsonFile()
495 {
496 // get account list
497 std::vector<std::string> accounts;
498 DIR* rootDir = opendir(Constants::USER_INFO_BASE.c_str());
499 if (rootDir == nullptr) {
500 accounts.push_back(std::to_string(Constants::START_USER_ID)); // account 100 always exists
501 BuildAndSaveAccountListJsonFile(accounts);
502 ACCOUNT_LOGE("Cannot open dir %{public}s, err %{public}d.", Constants::USER_INFO_BASE.c_str(), errno);
503 return;
504 }
505
506 struct dirent* curDir = nullptr;
507 while ((curDir = readdir(rootDir)) != nullptr) {
508 std::string curDirName(curDir->d_name);
509 if (curDirName == "." || curDirName == ".." || curDir->d_type != DT_DIR) {
510 continue;
511 }
512
513 // get and check os account id
514 std::int32_t accountID = Constants::INVALID_OS_ACCOUNT_ID;
515 if (!GetValidAccountID(curDirName, accountID)) {
516 ACCOUNT_LOGE("Invalid account id %{public}s detected in %{public}s.", curDirName.c_str(),
517 Constants::USER_INFO_BASE.c_str());
518 continue;
519 }
520
521 // check repeat
522 bool sameAccountID = false;
523 std::string curAccountIDStr = std::to_string(accountID);
524 for (size_t i = 0; i < accounts.size(); ++i) {
525 if (accounts[i] == curAccountIDStr) {
526 ACCOUNT_LOGE("Repeated account id %{public}s detected in %{public}s.", curAccountIDStr.c_str(),
527 Constants::USER_INFO_BASE.c_str());
528 sameAccountID = true;
529 break;
530 }
531 }
532
533 if (!sameAccountID && accountID >= Constants::START_USER_ID) {
534 accounts.push_back(curAccountIDStr);
535 }
536 }
537
538 if (closedir(rootDir) != 0) {
539 ACCOUNT_LOGE("Cannot closedir dir %{public}s, err %{public}d.", Constants::USER_INFO_BASE.c_str(), errno);
540 }
541 BuildAndSaveAccountListJsonFile(accounts);
542 }
543
GetOsAccountIdList(std::vector<int32_t> & idList)544 ErrCode OsAccountControlFileManager::GetOsAccountIdList(std::vector<int32_t> &idList)
545 {
546 idList.clear();
547 CJsonUnique accountListJson = nullptr;
548 ErrCode errCode = GetAccountListFromFile(accountListJson);
549 if (errCode != ERR_OK) {
550 return errCode;
551 }
552 std::vector<std::string> idStrList;
553 GetDataByType<std::vector<std::string>>(accountListJson, Constants::ACCOUNT_LIST, idStrList);
554 for (const auto &idStr : idStrList) {
555 int32_t id = 0;
556 if (!StrToInt(idStr, id)) {
557 ACCOUNT_LOGE("Convert localId failed");
558 continue;
559 }
560 idList.emplace_back(id);
561 }
562 return errCode;
563 }
564
GetOsAccountList(std::vector<OsAccountInfo> & osAccountList)565 ErrCode OsAccountControlFileManager::GetOsAccountList(std::vector<OsAccountInfo> &osAccountList)
566 {
567 osAccountList.clear();
568 CJsonUnique accountListJson = nullptr;
569 ErrCode result = GetAccountListFromFile(accountListJson);
570 if (result != ERR_OK) {
571 ACCOUNT_LOGE("GetAccountListFromFile failed!");
572 #if defined(HAS_KV_STORE_PART) && defined(DISTRIBUTED_FEATURE_ENABLED)
573 if (osAccountDataBaseOperator_->GetAccountListFromStoreID("", accountListJson) == ERR_OK) {
574 SaveAccountListToFile(accountListJson);
575 } else {
576 return result;
577 }
578 #else
579 return result;
580 #endif // defined(HAS_KV_STORE_PART) && defined(DISTRIBUTED_FEATURE_ENABLED)
581 }
582 std::vector<std::string> idList;
583 GetDataByType<std::vector<std::string>>(accountListJson, Constants::ACCOUNT_LIST, idList);
584
585 for (const auto& it : idList) {
586 OsAccountInfo osAccountInfo;
587 int32_t id = 0;
588 if (!StrToInt(it, id)) {
589 ACCOUNT_LOGE("Convert localId failed");
590 continue;
591 }
592 if (GetOsAccountInfoById(id, osAccountInfo) == ERR_OK) {
593 if (osAccountInfo.GetPhoto() != "") {
594 std::string photo = osAccountInfo.GetPhoto();
595 GetPhotoById(osAccountInfo.GetLocalId(), photo);
596 osAccountInfo.SetPhoto(photo);
597 }
598 osAccountList.push_back(osAccountInfo);
599 }
600 }
601 return ERR_OK;
602 }
603
GetOsAccountInfoById(const int id,OsAccountInfo & osAccountInfo)604 ErrCode OsAccountControlFileManager::GetOsAccountInfoById(const int id, OsAccountInfo &osAccountInfo)
605 {
606 std::string path = Constants::USER_INFO_BASE + Constants::PATH_SEPARATOR + std::to_string(id) +
607 Constants::PATH_SEPARATOR + Constants::USER_INFO_FILE_NAME;
608 ErrCode err = accountFileOperator_->CheckFileExistence(path);
609 if (err != ERR_OK) {
610 ACCOUNT_LOGE("File %{public}s does not exist err, errcode=%{public}d", path.c_str(), err);
611 if (GetOsAccountFromDatabase("", id, osAccountInfo) == ERR_OK) {
612 InsertOsAccount(osAccountInfo);
613 return ERR_OK;
614 }
615 return err == ERR_ACCOUNT_COMMON_FILE_NOT_EXIST ?
616 ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR : ERR_ACCOUNT_COMMON_FILE_READ_FAILED;
617 }
618 std::string accountInfoStr;
619 if (accountFileOperator_->GetFileContentByPath(path, accountInfoStr) != ERR_OK) {
620 ACCOUNT_LOGE("Get content from file %{public}s failed!", path.c_str());
621 if (GetOsAccountFromDatabase("", id, osAccountInfo) == ERR_OK) {
622 return ERR_OK;
623 }
624 return ERR_ACCOUNT_COMMON_FILE_READ_FAILED;
625 }
626 auto osAccountInfoJson = CreateJsonFromString(accountInfoStr);
627 if (osAccountInfoJson == nullptr || !FromJson(osAccountInfoJson.get(), osAccountInfo)) {
628 ACCOUNT_LOGE("Parse os account info json for %{public}d failed", id);
629 if (GetOsAccountFromDatabase("", id, osAccountInfo) != ERR_OK) {
630 ACCOUNT_LOGE("GetOsAccountFromDatabase failed id=%{public}d", id);
631 return ERR_ACCOUNT_COMMON_ACCOUNT_NOT_EXIST_ERROR;
632 }
633 }
634 return ERR_OK;
635 }
636
GetConstraintsByType(const OsAccountType type,std::vector<std::string> & constraints)637 ErrCode OsAccountControlFileManager::GetConstraintsByType(
638 const OsAccountType type, std::vector<std::string> &constraints)
639 {
640 int typeInit = static_cast<int>(type);
641 return osAccountFileOperator_->GetConstraintsByType(typeInit, constraints);
642 }
643
UpdateBaseOAConstraints(const std::string & idStr,const std::vector<std::string> & ConstraintStr,bool isAdd)644 ErrCode OsAccountControlFileManager::UpdateBaseOAConstraints(const std::string& idStr,
645 const std::vector<std::string>& ConstraintStr, bool isAdd)
646 {
647 std::lock_guard<std::mutex> lock(accountInfoFileLock_);
648 CJsonUnique baseOAConstraintsJson = nullptr;
649 ErrCode result = GetBaseOAConstraintsFromFile(baseOAConstraintsJson);
650 if (result != ERR_OK) {
651 ACCOUNT_LOGE("Get baseOAConstraints from json file failed!");
652 return result;
653 }
654 if (!IsKeyExist(baseOAConstraintsJson, idStr)) {
655 if (!isAdd) {
656 return ERR_OK;
657 }
658 AddVectorStringToJson(baseOAConstraintsJson, idStr, ConstraintStr);
659 } else {
660 std::vector<std::string> baseOAConstraints;
661 GetDataByType<std::vector<std::string>>(baseOAConstraintsJson, idStr, baseOAConstraints);
662 for (auto it = ConstraintStr.begin(); it != ConstraintStr.end(); it++) {
663 if (!isAdd) {
664 baseOAConstraints.erase(std::remove(baseOAConstraints.begin(), baseOAConstraints.end(), *it),
665 baseOAConstraints.end());
666 continue;
667 }
668 if (std::find(baseOAConstraints.begin(), baseOAConstraints.end(), *it) == baseOAConstraints.end()) {
669 baseOAConstraints.emplace_back(*it);
670 }
671 }
672 AddVectorStringToJson(baseOAConstraintsJson, idStr, baseOAConstraints);
673 }
674 return SaveBaseOAConstraintsToFile(baseOAConstraintsJson);
675 }
676
UpdateGlobalOAConstraints(const std::string & idStr,const std::vector<std::string> & ConstraintStr,bool isAdd)677 ErrCode OsAccountControlFileManager::UpdateGlobalOAConstraints(
678 const std::string& idStr, const std::vector<std::string>& ConstraintStr, bool isAdd)
679 {
680 std::lock_guard<std::mutex> lock(accountInfoFileLock_);
681 CJsonUnique globalOAConstraintsJson = nullptr;
682 ErrCode result = GetGlobalOAConstraintsFromFile(globalOAConstraintsJson);
683 if (result != ERR_OK) {
684 ACCOUNT_LOGE("Get globalOAConstraints from file failed!");
685 return result;
686 }
687 GlobalConstraintsDataOperate(idStr, ConstraintStr, isAdd, globalOAConstraintsJson);
688 return SaveGlobalOAConstraintsToFile(globalOAConstraintsJson);
689 }
690
GlobalConstraintsDataOperate(const std::string & idStr,const std::vector<std::string> & ConstraintStr,bool isAdd,CJsonUnique & globalOAConstraintsJson)691 void OsAccountControlFileManager::GlobalConstraintsDataOperate(const std::string& idStr,
692 const std::vector<std::string>& ConstraintStr, bool isAdd, CJsonUnique &globalOAConstraintsJson)
693 {
694 std::vector<std::string> globalOAConstraintsList;
695 GetDataByType<std::vector<std::string>>(globalOAConstraintsJson, Constants::ALL_GLOBAL_CONSTRAINTS,
696 globalOAConstraintsList);
697 std::vector<std::string> waitForErase;
698 for (auto it = ConstraintStr.begin(); it != ConstraintStr.end(); it++) {
699 if (!isAdd) {
700 if (std::find(globalOAConstraintsList.begin(),
701 globalOAConstraintsList.end(), *it) == globalOAConstraintsList.end()) {
702 continue;
703 }
704 std::vector<std::string> constraintSourceList;
705 GetDataByType<std::vector<std::string>>(globalOAConstraintsJson, *it, constraintSourceList);
706 constraintSourceList.erase(std::remove(constraintSourceList.begin(), constraintSourceList.end(), idStr),
707 constraintSourceList.end());
708 if (constraintSourceList.size() == 0) {
709 globalOAConstraintsList.erase(std::remove(globalOAConstraintsList.begin(),
710 globalOAConstraintsList.end(), *it), globalOAConstraintsList.end());
711 AddVectorStringToJson(globalOAConstraintsJson, Constants::ALL_GLOBAL_CONSTRAINTS,
712 globalOAConstraintsList);
713 waitForErase.push_back(*it);
714 } else {
715 AddVectorStringToJson(globalOAConstraintsJson, *it, constraintSourceList);
716 }
717 continue;
718 }
719 if (std::find(globalOAConstraintsList.begin(),
720 globalOAConstraintsList.end(), *it) != globalOAConstraintsList.end()) {
721 std::vector<std::string> constraintSourceList;
722 GetDataByType<std::vector<std::string>>(globalOAConstraintsJson, *it, constraintSourceList);
723 if (std::find(constraintSourceList.begin(),
724 constraintSourceList.end(), idStr) == constraintSourceList.end()) {
725 constraintSourceList.emplace_back(idStr);
726 AddVectorStringToJson(globalOAConstraintsJson, *it, constraintSourceList);
727 }
728 continue;
729 }
730 std::vector<std::string> constraintSourceList;
731 constraintSourceList.emplace_back(idStr);
732 globalOAConstraintsList.emplace_back(*it);
733 AddVectorStringToJson(globalOAConstraintsJson, *it, constraintSourceList);
734 AddVectorStringToJson(globalOAConstraintsJson, Constants::ALL_GLOBAL_CONSTRAINTS, globalOAConstraintsList);
735 }
736 for (auto keyStr : waitForErase) {
737 DeleteItemFromJson(globalOAConstraintsJson, keyStr);
738 }
739 }
740
UpdateSpecificOAConstraints(const std::string & idStr,const std::string & targetIdStr,const std::vector<std::string> & ConstraintStr,bool isAdd)741 ErrCode OsAccountControlFileManager::UpdateSpecificOAConstraints(
742 const std::string& idStr, const std::string& targetIdStr, const std::vector<std::string>& ConstraintStr, bool isAdd)
743 {
744 std::lock_guard<std::mutex> lock(accountInfoFileLock_);
745 CJsonUnique specificOAConstraintsJson = nullptr;
746 ErrCode result = GetSpecificOAConstraintsFromFile(specificOAConstraintsJson);
747 if (result != ERR_OK) {
748 ACCOUNT_LOGE("Get specificOAConstraints from file failed!");
749 return result;
750 }
751 if (!IsKeyExist(specificOAConstraintsJson, targetIdStr)) {
752 if (!isAdd) {
753 return ERR_OK;
754 }
755 auto accountList = CreateJsonNull();
756 auto osAccountConstraintsList = CreateJson();
757 AddObjToJson(osAccountConstraintsList, Constants::ALL_SPECIFIC_CONSTRAINTS, accountList);
758 AddObjToJson(specificOAConstraintsJson, targetIdStr, osAccountConstraintsList);
759 }
760 cJSON *userPrivateConstraintsDataJson = GetItemFromJson(specificOAConstraintsJson, targetIdStr);
761 SpecificConstraintsDataOperate(idStr, targetIdStr, ConstraintStr, isAdd, userPrivateConstraintsDataJson);
762 AddObjToJson(specificOAConstraintsJson.get(), targetIdStr, userPrivateConstraintsDataJson);
763 return SaveSpecificOAConstraintsToFile(specificOAConstraintsJson);
764 }
765
SpecificConstraintsDataOperate(const std::string & idStr,const std::string & targetIdStr,const std::vector<std::string> & ConstraintStr,bool isAdd,cJSON * userPrivateConstraintsDataJson)766 void OsAccountControlFileManager::SpecificConstraintsDataOperate(
767 const std::string& idStr, const std::string& targetIdStr, const std::vector<std::string>& ConstraintStr,
768 bool isAdd, cJSON *userPrivateConstraintsDataJson)
769 {
770 std::vector<std::string> specificOAConstraintsList;
771 GetDataByType<std::vector<std::string>>(userPrivateConstraintsDataJson, Constants::ALL_SPECIFIC_CONSTRAINTS,
772 specificOAConstraintsList);
773
774 std::vector<std::string> waitForErase;
775 for (auto it = ConstraintStr.begin(); it != ConstraintStr.end(); it++) {
776 if (!isAdd) {
777 if (!IsKeyExist(userPrivateConstraintsDataJson, *it)) {
778 continue;
779 }
780 std::vector<std::string> constraintSourceList;
781 GetDataByType<std::vector<std::string>>(userPrivateConstraintsDataJson, *it, constraintSourceList);
782 constraintSourceList.erase(std::remove(constraintSourceList.begin(), constraintSourceList.end(), idStr),
783 constraintSourceList.end());
784 if (constraintSourceList.size() == 0) {
785 specificOAConstraintsList.erase(std::remove(specificOAConstraintsList.begin(),
786 specificOAConstraintsList.end(), *it), specificOAConstraintsList.end());
787 AddVectorStringToJson(userPrivateConstraintsDataJson, Constants::ALL_SPECIFIC_CONSTRAINTS,
788 specificOAConstraintsList);
789 waitForErase.push_back(*it);
790 } else {
791 AddVectorStringToJson(userPrivateConstraintsDataJson, *it, constraintSourceList);
792 }
793 continue;
794 }
795 if (std::find(specificOAConstraintsList.begin(),
796 specificOAConstraintsList.end(), *it) != specificOAConstraintsList.end()) {
797 std::vector<std::string> constraintSourceList;
798 GetDataByType<std::vector<std::string>>(userPrivateConstraintsDataJson, *it, constraintSourceList);
799 if (std::find(constraintSourceList.begin(),
800 constraintSourceList.end(), idStr) == constraintSourceList.end()) {
801 constraintSourceList.emplace_back(idStr);
802 AddVectorStringToJson(userPrivateConstraintsDataJson, *it, constraintSourceList);
803 }
804 continue;
805 }
806 std::vector<std::string> constraintSourceList;
807 constraintSourceList.emplace_back(idStr);
808 specificOAConstraintsList.emplace_back(*it);
809 AddVectorStringToJson(userPrivateConstraintsDataJson, *it, constraintSourceList);
810 AddVectorStringToJson(userPrivateConstraintsDataJson, Constants::ALL_SPECIFIC_CONSTRAINTS,
811 specificOAConstraintsList);
812 }
813 for (auto keyStr : waitForErase) {
814 DeleteItemFromJson(userPrivateConstraintsDataJson, keyStr);
815 }
816 }
817
RemoveOAConstraintsInfo(const int32_t id)818 ErrCode OsAccountControlFileManager::RemoveOAConstraintsInfo(const int32_t id)
819 {
820 ErrCode errCode = RemoveOABaseConstraintsInfo(id);
821 if (errCode != ERR_OK) {
822 ACCOUNT_LOGE("Remove os account %{public}d base constraints info failed!", id);
823 return errCode;
824 }
825 errCode = RemoveOAGlobalConstraintsInfo(id);
826 if (errCode != ERR_OK) {
827 ACCOUNT_LOGE("Remove os account %{public}d global constraints info failed!", id);
828 return errCode;
829 }
830 errCode = RemoveOASpecificConstraintsInfo(id);
831 if (errCode != ERR_OK) {
832 ACCOUNT_LOGE("Remove os account %{public}d specific constraints info failed!", id);
833 return errCode;
834 }
835 return ERR_OK;
836 }
837
RemoveOABaseConstraintsInfo(const int32_t id)838 ErrCode OsAccountControlFileManager::RemoveOABaseConstraintsInfo(const int32_t id)
839 {
840 std::lock_guard<std::mutex> lock(accountInfoFileLock_);
841 CJsonUnique baseOAConstraintsJson = nullptr;
842 ErrCode result = GetBaseOAConstraintsFromFile(baseOAConstraintsJson);
843 if (result != ERR_OK) {
844 ACCOUNT_LOGE("Get baseOAConstraints from file failed!");
845 return result;
846 }
847 DeleteItemFromJson(baseOAConstraintsJson, std::to_string(id));
848 result = SaveBaseOAConstraintsToFile(baseOAConstraintsJson);
849 if (result != ERR_OK) {
850 ACCOUNT_LOGE("SaveBaseOAConstraintsToFile failed!");
851 return result;
852 }
853 return ERR_OK;
854 }
855
RemoveOAGlobalConstraintsInfo(const int32_t id)856 ErrCode OsAccountControlFileManager::RemoveOAGlobalConstraintsInfo(const int32_t id)
857 {
858 std::lock_guard<std::mutex> lock(accountInfoFileLock_);
859 CJsonUnique globalOAConstraintsJson = nullptr;
860 ErrCode result = GetGlobalOAConstraintsFromFile(globalOAConstraintsJson);
861 if (result != ERR_OK) {
862 ACCOUNT_LOGE("Get globalOAConstraints from file failed!");
863 return result;
864 }
865 std::vector<std::string> waitForErase;
866 std::vector<cJSON *> globalOAConstraintsJsonLists;
867 cJSON* item = nullptr;
868 cJSON_ArrayForEach(item, globalOAConstraintsJson.get()) {
869 globalOAConstraintsJsonLists.emplace_back(item);
870 }
871 for (const auto &it : globalOAConstraintsJsonLists) {
872 std::string key(it->string);
873 if (key != Constants::ALL_GLOBAL_CONSTRAINTS && key != DEVICE_OWNER_ID) {
874 std::vector<std::string> sourceList;
875 GetDataByType<std::vector<std::string>>(globalOAConstraintsJson, key, sourceList);
876 sourceList.erase(std::remove(sourceList.begin(), sourceList.end(), std::to_string(id)), sourceList.end());
877 if (sourceList.size() == 0) {
878 std::vector<std::string> allGlobalConstraints;
879 GetDataByType<std::vector<std::string>>(globalOAConstraintsJson, Constants::ALL_GLOBAL_CONSTRAINTS,
880 allGlobalConstraints);
881 allGlobalConstraints.erase(std::remove(allGlobalConstraints.begin(),
882 allGlobalConstraints.end(), key), allGlobalConstraints.end());
883 AddVectorStringToJson(globalOAConstraintsJson, Constants::ALL_GLOBAL_CONSTRAINTS, allGlobalConstraints);
884 waitForErase.push_back(key);
885 } else {
886 AddVectorStringToJson(globalOAConstraintsJson, key, sourceList);
887 }
888 }
889 }
890 for (auto keyStr : waitForErase) {
891 DeleteItemFromJson(globalOAConstraintsJson, keyStr);
892 }
893 return SaveGlobalOAConstraintsToFile(globalOAConstraintsJson);
894 }
895
RemoveOASpecificConstraintsInfo(const int32_t id)896 ErrCode OsAccountControlFileManager::RemoveOASpecificConstraintsInfo(const int32_t id)
897 {
898 std::lock_guard<std::mutex> lock(accountInfoFileLock_);
899 CJsonUnique specificOAConstraintsJson = nullptr;
900 ErrCode result = GetSpecificOAConstraintsFromFile(specificOAConstraintsJson);
901 if (result != ERR_OK) {
902 ACCOUNT_LOGE("Get specificOAConstraints from file failed!");
903 return result;
904 }
905 if (IsKeyExist(specificOAConstraintsJson, std::to_string(id))) {
906 DeleteItemFromJson(specificOAConstraintsJson, std::to_string(id));
907 }
908
909 RemoveAllUsersConstraintsInfo(specificOAConstraintsJson, id);
910
911 return SaveSpecificOAConstraintsToFile(specificOAConstraintsJson);
912 }
913
RemoveAllUsersConstraintsInfo(CJsonUnique & specificOAConstraintsJson,const int32_t id)914 void OsAccountControlFileManager::RemoveAllUsersConstraintsInfo(CJsonUnique &specificOAConstraintsJson,
915 const int32_t id)
916 {
917 std::vector<cJSON *> specificJsonObjLists;
918 cJSON* specificJsonObj = nullptr;
919 cJSON_ArrayForEach(specificJsonObj, specificOAConstraintsJson.get()) {
920 specificJsonObjLists.emplace_back(specificJsonObj);
921 }
922 for (const auto &it : specificJsonObjLists) {
923 std::vector<std::string> waitForErase;
924 cJSON *userPrivateConstraintsJson = nullptr;
925 GetDataByType<CJson *>(specificOAConstraintsJson, it->string, userPrivateConstraintsJson);
926 std::vector<std::string> allSpecificConstraints;
927 GetDataByType<std::vector<std::string>>(userPrivateConstraintsJson, Constants::ALL_SPECIFIC_CONSTRAINTS,
928 allSpecificConstraints);
929 if (allSpecificConstraints.size() == 0) {
930 continue;
931 }
932 std::vector<cJSON *> userJsonObjLists;
933 cJSON* userJsonObj = nullptr;
934 cJSON_ArrayForEach(userJsonObj, userPrivateConstraintsJson) {
935 userJsonObjLists.emplace_back(userJsonObj);
936 }
937 for (const auto &item : userJsonObjLists) {
938 if (std::string(item->string) == Constants::ALL_SPECIFIC_CONSTRAINTS) {
939 continue;
940 }
941 std::vector<std::string> sourceList;
942 GetDataByType<std::vector<std::string>>(userPrivateConstraintsJson, item->string, sourceList);
943 sourceList.erase(std::remove(sourceList.begin(),
944 sourceList.end(), std::to_string(id)), sourceList.end());
945 if (sourceList.size() == 0) {
946 allSpecificConstraints.erase(std::remove(allSpecificConstraints.begin(),
947 allSpecificConstraints.end(), item->string), allSpecificConstraints.end());
948 AddVectorStringToJson(userPrivateConstraintsJson, Constants::ALL_SPECIFIC_CONSTRAINTS,
949 allSpecificConstraints);
950 waitForErase.push_back(item->string);
951 } else {
952 AddVectorStringToJson(userPrivateConstraintsJson, item->string, sourceList);
953 }
954 }
955 for (auto keyStr : waitForErase) {
956 DeleteItemFromJson(userPrivateConstraintsJson, keyStr);
957 }
958 AddObjToJson(specificOAConstraintsJson.get(), it->string, userPrivateConstraintsJson);
959 }
960 }
961
UpdateAccountList(const std::string & idStr,bool isAdd)962 ErrCode OsAccountControlFileManager::UpdateAccountList(const std::string& idStr, bool isAdd)
963 {
964 CJsonUnique accountListJson = nullptr;
965 ErrCode result = GetAccountListFromFile(accountListJson);
966 if (result != ERR_OK) {
967 ACCOUNT_LOGE("Get account list failed!");
968 return result;
969 }
970
971 std::vector<std::string> accountIdList;
972 GetDataByType<std::vector<std::string>>(accountListJson, Constants::ACCOUNT_LIST, accountIdList);
973 if (isAdd) {
974 // check repeat
975 if (std::find(accountIdList.begin(), accountIdList.end(), idStr) != accountIdList.end()) {
976 return ERR_OK; // already exist, no need to add.
977 }
978 accountIdList.emplace_back(idStr);
979 } else {
980 accountIdList.erase(std::remove(accountIdList.begin(), accountIdList.end(), idStr), accountIdList.end());
981 }
982 AddVectorStringToJson(accountListJson, Constants::ACCOUNT_LIST, accountIdList);
983 AddIntToJson(accountListJson, Constants::COUNT_ACCOUNT_NUM, accountIdList.size());
984 return SaveAccountListToFileAndDataBase(accountListJson);
985 }
986
UpdateAccountIndex(const OsAccountInfo & osAccountInfo,const bool isDelete)987 ErrCode OsAccountControlFileManager::UpdateAccountIndex(const OsAccountInfo &osAccountInfo, const bool isDelete)
988 {
989 // private type account not write index to index file, don't check name in ValidateOsAccount
990 if (osAccountInfo.GetType() == OsAccountType::PRIVATE) {
991 return ERR_OK;
992 }
993 std::lock_guard<std::mutex> lock(accountInfoFileLock_);
994 CJsonUnique accountIndexJson = nullptr;
995 ErrCode result = GetAccountIndexFromFile(accountIndexJson);
996 if (result != ERR_OK) {
997 ACCOUNT_LOGE("Get account index failed!");
998 return result;
999 }
1000 std::string localIdStr = std::to_string(osAccountInfo.GetLocalId());
1001 if (isDelete) {
1002 if (!IsObject(accountIndexJson)) {
1003 ACCOUNT_LOGE("Get os account index json data failed");
1004 return ERR_ACCOUNT_COMMON_BAD_JSON_FORMAT_ERROR;
1005 }
1006 DeleteItemFromJson(accountIndexJson, localIdStr);
1007 } else {
1008 auto accountBaseInfo = CreateJson();
1009 AddStringToJson(accountBaseInfo, Constants::LOCAL_NAME, osAccountInfo.GetLocalName());
1010 AddStringToJson(accountBaseInfo, Constants::SHORT_NAME, osAccountInfo.GetShortName());
1011 AddObjToJson(accountIndexJson, localIdStr, accountBaseInfo);
1012 }
1013 std::string lastAccountIndexStr = PackJsonToString(accountIndexJson);
1014 result = accountFileOperator_->InputFileByPathAndContent(Constants::ACCOUNT_INDEX_JSON_PATH, lastAccountIndexStr);
1015 if (result != ERR_OK) {
1016 ACCOUNT_LOGE("Failed to input account index info to file!");
1017 return result;
1018 }
1019 #ifdef ENABLE_FILE_WATCHER
1020 accountFileWatcherMgr_.AddAccountInfoDigest(lastAccountIndexStr, Constants::ACCOUNT_INDEX_JSON_PATH);
1021 #endif // ENABLE_FILE_WATCHER
1022 return ERR_OK;
1023 }
1024
SetNextLocalId(const int32_t & nextLocalId)1025 ErrCode OsAccountControlFileManager::SetNextLocalId(const int32_t &nextLocalId)
1026 {
1027 std::lock_guard<std::mutex> lock(operatingIdMutex_);
1028 CJsonUnique accountListJson = nullptr;
1029 ErrCode result = GetAccountListFromFile(accountListJson);
1030 if (result != ERR_OK) {
1031 ACCOUNT_LOGE("SetNextLocalId get accountList error.");
1032 return result;
1033 }
1034 int32_t nextLocalIdJson = -1;
1035 if (!GetDataByType<std::int32_t>(accountListJson, NEXT_LOCAL_ID, nextLocalIdJson)) {
1036 ACCOUNT_LOGW("SetNextLocalId get next localId failed");
1037 nextLocalIdJson = Constants::START_USER_ID + 1;
1038 }
1039 AddIntToJson(accountListJson, NEXT_LOCAL_ID, std::max(nextLocalId, nextLocalIdJson));
1040 result = SaveAccountListToFileAndDataBase(accountListJson);
1041 if (result != ERR_OK) {
1042 ACCOUNT_LOGE("SetNextLocalId save accountListJson error.");
1043 }
1044 return result;
1045 }
1046
RemoveAccountIndex(const int32_t id)1047 ErrCode OsAccountControlFileManager::RemoveAccountIndex(const int32_t id)
1048 {
1049 CJsonUnique accountIndexJson = nullptr;
1050 ErrCode result = GetAccountIndexFromFile(accountIndexJson);
1051 if (result != ERR_OK) {
1052 ACCOUNT_LOGE("Get account index failed!");
1053 return result;
1054 }
1055 std::string localIdStr = std::to_string(id);
1056 if (!IsObject(accountIndexJson)) {
1057 ACCOUNT_LOGE("Get os account index data failed");
1058 return ERR_ACCOUNT_COMMON_BAD_JSON_FORMAT_ERROR;
1059 }
1060 DeleteItemFromJson(accountIndexJson, localIdStr);
1061 std::string lastAccountIndexStr = PackJsonToString(accountIndexJson);
1062 result = accountFileOperator_->InputFileByPathAndContent(Constants::ACCOUNT_INDEX_JSON_PATH, lastAccountIndexStr);
1063 if (result != ERR_OK) {
1064 ACCOUNT_LOGE("Failed to input account index info to file!");
1065 return result;
1066 }
1067 #ifdef ENABLE_FILE_WATCHER
1068 accountFileWatcherMgr_.AddAccountInfoDigest(lastAccountIndexStr, Constants::ACCOUNT_INDEX_JSON_PATH);
1069 #endif // ENABLE_FILE_WATCHER
1070 return ERR_OK;
1071 }
1072
InsertOsAccount(OsAccountInfo & osAccountInfo)1073 ErrCode OsAccountControlFileManager::InsertOsAccount(OsAccountInfo &osAccountInfo)
1074 {
1075 ACCOUNT_LOGI("Enter");
1076 if (osAccountInfo.GetLocalId() < Constants::ADMIN_LOCAL_ID) {
1077 ACCOUNT_LOGE("Error id %{public}d cannot insert", osAccountInfo.GetLocalId());
1078 return ERR_OSACCOUNT_SERVICE_CONTROL_ID_CANNOT_CREATE_ERROR;
1079 }
1080
1081 std::string path = Constants::USER_INFO_BASE + Constants::PATH_SEPARATOR + osAccountInfo.GetPrimeKey() +
1082 Constants::PATH_SEPARATOR + Constants::USER_INFO_FILE_NAME;
1083 if (accountFileOperator_->IsExistFile(path) && accountFileOperator_->IsJsonFormat(path)) {
1084 ACCOUNT_LOGE("Account %{public}d already exists", osAccountInfo.GetLocalId());
1085 return ERR_OSACCOUNT_SERVICE_CONTROL_INSERT_FILE_EXISTS_ERROR;
1086 }
1087
1088 std::string accountInfoStr = osAccountInfo.ToString();
1089 if (accountInfoStr.empty()) {
1090 ACCOUNT_LOGE("Os account info is empty! maybe some illegal characters caused exception!");
1091 return ERR_OSACCOUNT_SERVICE_ACCOUNT_INFO_EMPTY_ERROR;
1092 }
1093 std::lock_guard<std::mutex> lock(accountInfoFileLock_);
1094 if (osAccountInfo.GetLocalId() >= Constants::START_USER_ID) {
1095 ErrCode updateRet = UpdateAccountList(osAccountInfo.GetPrimeKey(), true);
1096 if (updateRet != ERR_OK) {
1097 ACCOUNT_LOGE("Update account list failed, errCode: %{public}d", updateRet);
1098 return updateRet;
1099 }
1100 }
1101 ErrCode result = accountFileOperator_->InputFileByPathAndContent(path, accountInfoStr);
1102 if (result != ERR_OK) {
1103 ACCOUNT_LOGE("InputFileByPathAndContent failed! path %{public}s.", path.c_str());
1104 return result;
1105 }
1106 #if defined(HAS_KV_STORE_PART) && defined(DISTRIBUTED_FEATURE_ENABLED)
1107 osAccountDataBaseOperator_->InsertOsAccountIntoDataBase(osAccountInfo);
1108 #endif // defined(HAS_KV_STORE_PART) && defined(DISTRIBUTED_FEATURE_ENABLED)
1109
1110 #ifdef ENABLE_FILE_WATCHER
1111 if (osAccountInfo.GetLocalId() >= Constants::START_USER_ID || osAccountInfo.GetLocalId() == Constants::U1_ID) {
1112 accountFileWatcherMgr_.AddAccountInfoDigest(accountInfoStr, path);
1113 accountFileWatcherMgr_.AddFileWatcher(osAccountInfo.GetLocalId(), eventCallbackFunc_);
1114 }
1115 #endif // ENABLE_FILE_WATCHER
1116 ACCOUNT_LOGI("End");
1117 return ERR_OK;
1118 }
1119
DelOsAccount(const int id)1120 ErrCode OsAccountControlFileManager::DelOsAccount(const int id)
1121 {
1122 ACCOUNT_LOGD("Enter");
1123 if (id <= Constants::START_USER_ID || id > Constants::MAX_USER_ID) {
1124 ACCOUNT_LOGE("Ivalid input id %{public}d to delete!", id);
1125 return ERR_OSACCOUNT_SERVICE_CONTROL_CANNOT_DELETE_ID_ERROR;
1126 }
1127 std::lock_guard<std::mutex> lock(accountInfoFileLock_);
1128 std::string path = Constants::USER_INFO_BASE + Constants::PATH_SEPARATOR + std::to_string(id);
1129 ErrCode result = accountFileOperator_->DeleteDirOrFile(path);
1130 if (result != ERR_OK) {
1131 ACCOUNT_LOGE("DeleteDirOrFile failed! path %{public}s.", path.c_str());
1132 return result;
1133 }
1134 #if defined(HAS_KV_STORE_PART) && defined(DISTRIBUTED_FEATURE_ENABLED)
1135 osAccountDataBaseOperator_->DelOsAccountFromDatabase(id);
1136 #endif // defined(HAS_KV_STORE_PART) && defined(DISTRIBUTED_FEATURE_ENABLED)
1137 #ifdef ENABLE_FILE_WATCHER
1138 path += Constants::PATH_SEPARATOR + Constants::USER_INFO_FILE_NAME;
1139 accountFileWatcherMgr_.DeleteAccountInfoDigest(path);
1140 std::string distributedDataPath =
1141 Constants::USER_INFO_BASE + Constants::PATH_SEPARATOR + std::to_string(id) + DISTRIBUTED_ACCOUNT_FILE_NAME;
1142 accountFileWatcherMgr_.DeleteAccountInfoDigest(distributedDataPath);
1143 #endif // ENABLE_FILE_WATCHER
1144 RemoveAccountIndex(id);
1145 return UpdateAccountList(std::to_string(id), false);
1146 }
1147
1148
UpdateOsAccount(OsAccountInfo & osAccountInfo)1149 ErrCode OsAccountControlFileManager::UpdateOsAccount(OsAccountInfo &osAccountInfo)
1150 {
1151 ACCOUNT_LOGD("Start");
1152 std::string path = Constants::USER_INFO_BASE + Constants::PATH_SEPARATOR + osAccountInfo.GetPrimeKey() +
1153 Constants::PATH_SEPARATOR + Constants::USER_INFO_FILE_NAME;
1154 if (!accountFileOperator_->IsExistFile(path)) {
1155 ACCOUNT_LOGE("Path %{public}s does not exist!", path.c_str());
1156 return ERR_OSACCOUNT_SERVICE_CONTROL_UPDATE_FILE_NOT_EXISTS_ERROR;
1157 }
1158
1159 std::string accountInfoStr = osAccountInfo.ToString();
1160 if (accountInfoStr.empty()) {
1161 ACCOUNT_LOGE("Account info str is empty!");
1162 return ERR_OSACCOUNT_SERVICE_ACCOUNT_INFO_EMPTY_ERROR;
1163 }
1164 std::lock_guard<std::mutex> lock(accountInfoFileLock_);
1165 ErrCode result = accountFileOperator_->InputFileByPathAndContent(path, accountInfoStr);
1166 if (result != ERR_OK) {
1167 return result;
1168 }
1169
1170 #if defined(HAS_KV_STORE_PART) && defined(DISTRIBUTED_FEATURE_ENABLED)
1171 // update in database
1172 if (osAccountInfo.GetLocalId() >= Constants::START_USER_ID || osAccountInfo.GetLocalId() == Constants::U1_ID) {
1173 osAccountDataBaseOperator_->UpdateOsAccountInDatabase(osAccountInfo);
1174 }
1175 #else // DISTRIBUTED_FEATURE_ENABLED
1176 ACCOUNT_LOGI("No distributed feature!");
1177 #endif // defined(HAS_KV_STORE_PART) && defined(DISTRIBUTED_FEATURE_ENABLED)
1178 #ifdef ENABLE_FILE_WATCHER
1179 accountFileWatcherMgr_.AddAccountInfoDigest(accountInfoStr, path);
1180 #endif // ENABLE_FILE_WATCHER
1181 ACCOUNT_LOGD("End");
1182 return ERR_OK;
1183 }
1184
AccountExistsWithSerialNumber(const std::vector<OsAccountInfo> & osAccountInfos,int serialNumber)1185 bool AccountExistsWithSerialNumber(const std::vector<OsAccountInfo>& osAccountInfos, int serialNumber)
1186 {
1187 const auto targetSerialNumber = Constants::SERIAL_NUMBER_NUM_START_FOR_ADMIN * Constants::CARRY_NUM + serialNumber;
1188 return std::any_of(osAccountInfos.begin(), osAccountInfos.end(),
1189 [&targetSerialNumber](const OsAccountInfo& accountInfo) {
1190 return accountInfo.GetSerialNumber() == targetSerialNumber;
1191 });
1192 }
1193
GetSerialNumber(int64_t & serialNumber)1194 ErrCode OsAccountControlFileManager::GetSerialNumber(int64_t &serialNumber)
1195 {
1196 std::lock_guard<std::mutex> lock(accountInfoFileLock_);
1197 CJsonUnique accountListJson = nullptr;
1198 ErrCode result = GetAccountListFromFile(accountListJson);
1199 if (result != ERR_OK) {
1200 ACCOUNT_LOGE("GetSerialNumber get accountList error");
1201 return result;
1202 }
1203 GetDataByType<int64_t>(accountListJson, Constants::SERIAL_NUMBER_NUM, serialNumber);
1204 if (serialNumber == Constants::CARRY_NUM) {
1205 AddBoolToJson(accountListJson, IS_SERIAL_NUMBER_FULL, true);
1206 serialNumber = Constants::SERIAL_NUMBER_NUM_START;
1207 }
1208 bool isSerialNumberFull = false;
1209 GetDataByType<bool>(accountListJson, IS_SERIAL_NUMBER_FULL, isSerialNumberFull);
1210 if (isSerialNumberFull) {
1211 std::vector<OsAccountInfo> osAccountInfos;
1212 result = GetOsAccountList(osAccountInfos);
1213 if (result != ERR_OK) {
1214 ACCOUNT_LOGE("GetSerialNumber get accountList error");
1215 return result;
1216 }
1217 while (serialNumber < Constants::CARRY_NUM) {
1218 bool exists = false;
1219 exists = AccountExistsWithSerialNumber(osAccountInfos, serialNumber);
1220 if (!exists) {
1221 break;
1222 }
1223 serialNumber++;
1224 serialNumber = (serialNumber == Constants::CARRY_NUM) ? Constants::SERIAL_NUMBER_NUM_START : serialNumber;
1225 }
1226 }
1227 AddInt64ToJson(accountListJson, Constants::SERIAL_NUMBER_NUM, serialNumber + 1);
1228 result = SaveAccountListToFileAndDataBase(accountListJson);
1229 if (result != ERR_OK) {
1230 return result;
1231 }
1232 serialNumber = serialNumber + Constants::SERIAL_NUMBER_NUM_START_FOR_ADMIN * Constants::CARRY_NUM;
1233 return ERR_OK;
1234 }
1235
GetNextLocalId(const std::vector<std::string> & accountIdList,int32_t startId)1236 int32_t OsAccountControlFileManager::GetNextLocalId(const std::vector<std::string> &accountIdList, int32_t startId)
1237 {
1238 if ((startId <= Constants::START_USER_ID) || (startId > Constants::MAX_CREATABLE_USER_ID)) {
1239 startId = Constants::START_USER_ID + 1;
1240 }
1241 int32_t searchCount = 0;
1242 int32_t totalRange = Constants::MAX_CREATABLE_USER_ID - Constants::START_USER_ID;
1243
1244 do {
1245 if (std::find(accountIdList.begin(), accountIdList.end(), std::to_string(startId)) ==
1246 accountIdList.end()) {
1247 return startId;
1248 }
1249 ++startId;
1250 ++searchCount;
1251 if (startId > Constants::MAX_CREATABLE_USER_ID) {
1252 startId = Constants::START_USER_ID + 1;
1253 }
1254 if (searchCount >= totalRange) {
1255 ACCOUNT_LOGE("No available account id in range %{public}d - %{public}d",
1256 Constants::START_USER_ID + 1, Constants::MAX_CREATABLE_USER_ID);
1257 return Constants::MAX_CREATABLE_USER_ID + 1;
1258 }
1259 } while (true);
1260 }
1261
GetAllowCreateId(int & id)1262 ErrCode OsAccountControlFileManager::GetAllowCreateId(int &id)
1263 {
1264 std::lock_guard<std::mutex> lock(operatingIdMutex_);
1265 CJsonUnique accountListJson = nullptr;
1266 ErrCode result = GetAccountListFromFile(accountListJson);
1267 if (result != ERR_OK) {
1268 ACCOUNT_LOGE("GetAllowCreateId get accountList error.");
1269 return result;
1270 }
1271 std::vector<std::string> accountIdList;
1272 int32_t nextLocalId = -1;
1273 if (!GetDataByType<std::vector<std::string>>(accountListJson, Constants::ACCOUNT_LIST, accountIdList)) {
1274 ACCOUNT_LOGE("GetAllowCreateId get accountIdList error");
1275 return ERR_ACCOUNT_COMMON_BAD_JSON_FORMAT_ERROR;
1276 }
1277 if (!GetDataByType<int32_t>(accountListJson, NEXT_LOCAL_ID, nextLocalId)) {
1278 ACCOUNT_LOGW("Get next localId failed");
1279 int32_t lastLocalId = -1;
1280 if (!accountIdList.empty() && StrToInt(accountIdList[accountIdList.size() - 1], lastLocalId)) {
1281 nextLocalId = lastLocalId + 1;
1282 } else {
1283 nextLocalId = Constants::START_USER_ID + 1;
1284 ACCOUNT_LOGW("Convert last item in accountIdList to string failed.");
1285 }
1286 }
1287 id = GetNextLocalId(accountIdList, nextLocalId);
1288 if (id > Constants::MAX_CREATABLE_USER_ID) {
1289 ACCOUNT_LOGE("No available account id in range 0 - %{public}d, next id would be %{public}d",
1290 Constants::MAX_CREATABLE_USER_ID, id);
1291 return ERR_OSACCOUNT_SERVICE_CONTROL_MAX_CAN_CREATE_ERROR;
1292 }
1293 AddIntToJson(accountListJson, NEXT_LOCAL_ID, id + 1);
1294 result = SaveAccountListToFileAndDataBase(accountListJson);
1295 if (result != ERR_OK) {
1296 ACCOUNT_LOGE("GetAllowCreateId save accountListJson error, errCode %{public}d.", result);
1297 }
1298 return result;
1299 }
1300
GetAccountListFromFile(CJsonUnique & accountListJson)1301 ErrCode OsAccountControlFileManager::GetAccountListFromFile(CJsonUnique &accountListJson)
1302 {
1303 ACCOUNT_LOGD("Enter");
1304 std::string accountList;
1305 std::lock_guard<std::mutex> lock(accountListFileLock_);
1306 ErrCode errCode = accountFileOperator_->GetFileContentByPath(Constants::ACCOUNT_LIST_FILE_JSON_PATH,
1307 accountList);
1308 if (errCode != ERR_OK) {
1309 ACCOUNT_LOGE("GetFileContentByPath failed! error code %{public}d.", errCode);
1310 return errCode;
1311 }
1312 accountListJson = CreateJsonFromString(accountList);
1313 if (accountListJson == nullptr) {
1314 ACCOUNT_LOGE("AccountListFile does not comply with the json format.");
1315 #if defined(HAS_KV_STORE_PART) && defined(DISTRIBUTED_FEATURE_ENABLED)
1316 return osAccountDataBaseOperator_->GetAccountListFromStoreID(OS_ACCOUNT_STORE_ID, accountListJson);
1317 #else
1318 return ERR_ACCOUNT_COMMON_BAD_JSON_FORMAT_ERROR;
1319 #endif // defined(HAS_KV_STORE_PART) && defined(DISTRIBUTED_FEATURE_ENABLED)
1320 }
1321 ACCOUNT_LOGD("End");
1322 return ERR_OK;
1323 }
1324
GetAccountIndexFromFile(CJsonUnique & accountIndexJson)1325 ErrCode OsAccountControlFileManager::GetAccountIndexFromFile(CJsonUnique &accountIndexJson)
1326 {
1327 std::string accountIndex;
1328 if (!accountFileOperator_->IsJsonFileReady(Constants::ACCOUNT_INDEX_JSON_PATH)) {
1329 ErrCode result = GetAccountIndexInfo(accountIndex);
1330 if (result != ERR_OK) {
1331 ACCOUNT_LOGE("GetAccountIndexInfo error code %{public}d.", result);
1332 return result;
1333 }
1334 } else {
1335 ErrCode errCode = accountFileOperator_->GetFileContentByPath(Constants::ACCOUNT_INDEX_JSON_PATH, accountIndex);
1336 if (errCode != ERR_OK) {
1337 ACCOUNT_LOGE("GetFileContentByPath failed! error code %{public}d.", errCode);
1338 return errCode;
1339 }
1340 }
1341 accountIndexJson = CreateJsonFromString(accountIndex);
1342 if (accountIndexJson == nullptr) {
1343 ACCOUNT_LOGE("parse os account info json data failed");
1344 return ERR_ACCOUNT_COMMON_BAD_JSON_FORMAT_ERROR;
1345 }
1346 return ERR_OK;
1347 }
1348
GetAccountIndexInfo(std::string & accountIndexInfo)1349 ErrCode OsAccountControlFileManager::GetAccountIndexInfo(std::string &accountIndexInfo)
1350 {
1351 std::vector<OsAccountInfo> osAccountInfos;
1352 ErrCode result = GetOsAccountList(osAccountInfos);
1353 if (result != ERR_OK) {
1354 return result;
1355 }
1356 auto accountIndexJson = osAccountInfos.empty() ? CreateJsonNull() : CreateJson();
1357 for (auto account = osAccountInfos.begin(); account != osAccountInfos.end(); account++) {
1358 // private account don't check name
1359 if (account->GetType() == OsAccountType::PRIVATE) {
1360 continue;
1361 }
1362 std::string localIdStr = std::to_string(account->GetLocalId());
1363 auto accountIndexElement = CreateJson();
1364 AddStringToJson(accountIndexElement, Constants::LOCAL_NAME, account->GetLocalName());
1365 AddStringToJson(accountIndexElement, Constants::SHORT_NAME, account->GetShortName());
1366 AddObjToJson(accountIndexJson, localIdStr, accountIndexElement);
1367 }
1368 accountIndexInfo = PackJsonToString(accountIndexJson);
1369 return ERR_OK;
1370 }
1371
GetBaseOAConstraintsFromFile(CJsonUnique & baseOAConstraintsJson)1372 ErrCode OsAccountControlFileManager::GetBaseOAConstraintsFromFile(CJsonUnique &baseOAConstraintsJson)
1373 {
1374 std::string baseOAConstraints;
1375 std::lock_guard<std::mutex> lock(baseOAConstraintsFileLock_);
1376 ErrCode errCode = accountFileOperator_->GetFileContentByPath(
1377 Constants::BASE_OSACCOUNT_CONSTRAINTS_JSON_PATH, baseOAConstraints);
1378 if (errCode != ERR_OK) {
1379 ACCOUNT_LOGE("GetFileContentByPath failed! error code %{public}d.", errCode);
1380 return errCode;
1381 }
1382 baseOAConstraintsJson = CreateJsonFromString(baseOAConstraints);
1383 if (baseOAConstraintsJson == nullptr || !IsObject(baseOAConstraintsJson)) {
1384 ACCOUNT_LOGE("Base constraints json data parse failed code.");
1385 return errCode;
1386 }
1387
1388 return ERR_OK;
1389 }
1390
GetGlobalOAConstraintsFromFile(CJsonUnique & globalOAConstraintsJson)1391 ErrCode OsAccountControlFileManager::GetGlobalOAConstraintsFromFile(CJsonUnique &globalOAConstraintsJson)
1392 {
1393 std::string globalOAConstraints;
1394 std::lock_guard<std::mutex> lock(globalOAConstraintsFileLock_);
1395 ErrCode errCode = accountFileOperator_->GetFileContentByPath(
1396 Constants::GLOBAL_OSACCOUNT_CONSTRAINTS_JSON_PATH, globalOAConstraints);
1397 if (errCode != ERR_OK) {
1398 ACCOUNT_LOGE("GetFileContentByPath failed! error code %{public}d.", errCode);
1399 return errCode;
1400 }
1401 globalOAConstraintsJson = CreateJsonFromString(globalOAConstraints);
1402 if (globalOAConstraintsJson == nullptr || !IsObject(globalOAConstraintsJson)) {
1403 ACCOUNT_LOGE("Global constraints json data parse failed code.");
1404 return errCode;
1405 }
1406
1407 return ERR_OK;
1408 }
1409
GetSpecificOAConstraintsFromFile(CJsonUnique & specificOAConstraintsJson)1410 ErrCode OsAccountControlFileManager::GetSpecificOAConstraintsFromFile(CJsonUnique &specificOAConstraintsJson)
1411 {
1412 std::string specificOAConstraints;
1413 std::lock_guard<std::mutex> lock(specificOAConstraintsFileLock_);
1414 ErrCode errCode = accountFileOperator_->GetFileContentByPath(
1415 Constants::SPECIFIC_OSACCOUNT_CONSTRAINTS_JSON_PATH, specificOAConstraints);
1416 if (errCode != ERR_OK) {
1417 ACCOUNT_LOGE("GetFileContentByPath failed! error code %{public}d.", errCode);
1418 return errCode;
1419 }
1420 specificOAConstraintsJson = CreateJsonFromString(specificOAConstraints);
1421 if (specificOAConstraintsJson == nullptr || !IsObject(specificOAConstraintsJson)) {
1422 ACCOUNT_LOGE("Specific constraints json data parse failed code.");
1423 return errCode;
1424 }
1425
1426 return ERR_OK;
1427 }
1428
IsFromBaseOAConstraintsList(const int32_t id,const std::string constraint,bool & isExist)1429 ErrCode OsAccountControlFileManager::IsFromBaseOAConstraintsList(
1430 const int32_t id, const std::string constraint, bool &isExist)
1431 {
1432 isExist = false;
1433 std::vector<std::string> constraintsList;
1434 std::lock_guard<std::mutex> lock(baseOAConstraintsFileLock_);
1435 ErrCode errCode = osAccountFileOperator_->GetBaseOAConstraintsList(id, constraintsList);
1436 if (errCode != ERR_OK) {
1437 ACCOUNT_LOGE("GetBaseOAConstraintsList failed! error code %{public}d.", errCode);
1438 return errCode;
1439 }
1440
1441 if (std::find(constraintsList.begin(), constraintsList.end(), constraint) != constraintsList.end()) {
1442 isExist = true;
1443 }
1444
1445 return ERR_OK;
1446 }
1447
IsFromGlobalOAConstraintsList(const int32_t id,const int32_t deviceOwnerId,const std::string constraint,std::vector<ConstraintSourceTypeInfo> & globalSourceList)1448 ErrCode OsAccountControlFileManager::IsFromGlobalOAConstraintsList(const int32_t id, const int32_t deviceOwnerId,
1449 const std::string constraint, std::vector<ConstraintSourceTypeInfo> &globalSourceList)
1450 {
1451 globalSourceList.clear();
1452 std::vector<std::string> constraintsList;
1453 ErrCode errCode = ERR_OK;
1454 {
1455 std::lock_guard<std::mutex> lock(globalOAConstraintsFileLock_);
1456 errCode = osAccountFileOperator_->GetGlobalOAConstraintsList(constraintsList);
1457 }
1458 if (errCode != ERR_OK) {
1459 ACCOUNT_LOGE("GetGlobalOAConstraintsList failed! error code %{public}d.", errCode);
1460 return errCode;
1461 }
1462 if (constraintsList.size() == 0) {
1463 return ERR_OK;
1464 }
1465 if (std::find(constraintsList.begin(), constraintsList.end(), constraint) != constraintsList.end()) {
1466 CJsonUnique globalOAConstraintsJson = nullptr;
1467 errCode = GetGlobalOAConstraintsFromFile(globalOAConstraintsJson);
1468 if (errCode != ERR_OK) {
1469 ACCOUNT_LOGE("Get globalOAConstraints from file failed!");
1470 return errCode;
1471 }
1472 std::vector<std::string> globalOAConstraintsList;
1473 GetDataByType<std::vector<std::string>>(globalOAConstraintsJson, constraint, globalOAConstraintsList);
1474
1475 ConstraintSourceTypeInfo constraintSourceTypeInfo;
1476 for (auto it = globalOAConstraintsList.begin(); it != globalOAConstraintsList.end(); it++) {
1477 int32_t localId = 0;
1478 if (!StrToInt(*it, localId)) {
1479 ACCOUNT_LOGE("Convert localId failed");
1480 continue;
1481 }
1482 if (localId == deviceOwnerId) {
1483 constraintSourceTypeInfo.localId = localId;
1484 constraintSourceTypeInfo.typeInfo = ConstraintSourceType::CONSTRAINT_TYPE_DEVICE_OWNER;
1485 globalSourceList.push_back(constraintSourceTypeInfo);
1486 } else {
1487 constraintSourceTypeInfo.localId = localId;
1488 constraintSourceTypeInfo.typeInfo = ConstraintSourceType::CONSTRAINT_TYPE_PROFILE_OWNER;
1489 globalSourceList.push_back(constraintSourceTypeInfo);
1490 }
1491 }
1492 }
1493 return ERR_OK;
1494 }
1495
IsFromSpecificOAConstraintsList(const int32_t id,const int32_t deviceOwnerId,const std::string constraint,std::vector<ConstraintSourceTypeInfo> & specificSourceList)1496 ErrCode OsAccountControlFileManager::IsFromSpecificOAConstraintsList(const int32_t id, const int32_t deviceOwnerId,
1497 const std::string constraint, std::vector<ConstraintSourceTypeInfo> &specificSourceList)
1498 {
1499 specificSourceList.clear();
1500 std::vector<std::string> constraintsList;
1501 ErrCode errCode = ERR_OK;
1502 {
1503 std::lock_guard<std::mutex> lock(specificOAConstraintsFileLock_);
1504 errCode = osAccountFileOperator_->GetSpecificOAConstraintsList(id, constraintsList);
1505 }
1506 if (errCode != ERR_OK) {
1507 ACCOUNT_LOGE("GetSpecificOAConstraintsList failed! error code %{public}d.", errCode);
1508 return errCode;
1509 }
1510
1511 if (std::find(constraintsList.begin(), constraintsList.end(), constraint) != constraintsList.end()) {
1512 CJsonUnique specificOAConstraintsJson = nullptr;
1513 errCode = GetSpecificOAConstraintsFromFile(specificOAConstraintsJson);
1514 if (errCode != ERR_OK) {
1515 ACCOUNT_LOGE("Get specificOAConstraints from file failed!");
1516 return errCode;
1517 }
1518 cJSON *specificOAConstraintsInfo = nullptr;
1519 GetDataByType<CJson *>(specificOAConstraintsJson, std::to_string(id), specificOAConstraintsInfo);
1520 std::vector<std::string> specificConstraintSource;
1521 GetDataByType<std::vector<std::string>>(specificOAConstraintsInfo, constraint, specificConstraintSource);
1522 ConstraintSourceTypeInfo constraintSourceTypeInfo;
1523 for (auto it = specificConstraintSource.begin(); it != specificConstraintSource.end(); it++) {
1524 int32_t localId = 0;
1525 if (!StrToInt(*it, localId)) {
1526 ACCOUNT_LOGE("Convert localId failed");
1527 continue;
1528 }
1529 if (localId == deviceOwnerId) {
1530 constraintSourceTypeInfo.localId = localId;
1531 constraintSourceTypeInfo.typeInfo = ConstraintSourceType::CONSTRAINT_TYPE_DEVICE_OWNER;
1532 specificSourceList.push_back(constraintSourceTypeInfo);
1533 } else {
1534 constraintSourceTypeInfo.localId = localId;
1535 constraintSourceTypeInfo.typeInfo = ConstraintSourceType::CONSTRAINT_TYPE_PROFILE_OWNER;
1536 specificSourceList.push_back(constraintSourceTypeInfo);
1537 }
1538 }
1539 }
1540 return ERR_OK;
1541 }
1542
SaveAccountListToFile(const CJsonUnique & accountListJson)1543 ErrCode OsAccountControlFileManager::SaveAccountListToFile(const CJsonUnique &accountListJson)
1544 {
1545 std::lock_guard<std::mutex> lock(accountListFileLock_);
1546 std::string strValue = PackJsonToString(accountListJson);
1547 ErrCode result =
1548 accountFileOperator_->InputFileByPathAndContent(Constants::ACCOUNT_LIST_FILE_JSON_PATH, strValue);
1549 if (result != ERR_OK) {
1550 ACCOUNT_LOGE("Cannot save save account list file content!");
1551 return result;
1552 }
1553 #ifdef ENABLE_FILE_WATCHER
1554 accountFileWatcherMgr_.AddAccountInfoDigest(strValue, Constants::ACCOUNT_LIST_FILE_JSON_PATH);
1555 #endif // ENABLE_FILE_WATCHER
1556 ACCOUNT_LOGD("Save account list file succeed!");
1557 return ERR_OK;
1558 }
1559
SaveBaseOAConstraintsToFile(const CJsonUnique & baseOAConstraints)1560 ErrCode OsAccountControlFileManager::SaveBaseOAConstraintsToFile(const CJsonUnique &baseOAConstraints)
1561 {
1562 std::lock_guard<std::mutex> lock(baseOAConstraintsFileLock_);
1563 std::string strValue = PackJsonToString(baseOAConstraints);
1564 ErrCode result = accountFileOperator_->InputFileByPathAndContent(
1565 Constants::BASE_OSACCOUNT_CONSTRAINTS_JSON_PATH, strValue);
1566 if (result != ERR_OK) {
1567 ACCOUNT_LOGE("Cannot save base osaccount constraints file content!");
1568 return result;
1569 }
1570 #ifdef ENABLE_FILE_WATCHER
1571 accountFileWatcherMgr_.AddAccountInfoDigest(
1572 strValue, Constants::BASE_OSACCOUNT_CONSTRAINTS_JSON_PATH);
1573 #endif // ENABLE_FILE_WATCHER
1574 return ERR_OK;
1575 }
1576
SaveGlobalOAConstraintsToFile(const CJsonUnique & globalOAConstraints)1577 ErrCode OsAccountControlFileManager::SaveGlobalOAConstraintsToFile(const CJsonUnique &globalOAConstraints)
1578 {
1579 std::lock_guard<std::mutex> lock(globalOAConstraintsFileLock_);
1580 std::string strValue = PackJsonToString(globalOAConstraints);
1581 ErrCode result = accountFileOperator_->InputFileByPathAndContent(
1582 Constants::GLOBAL_OSACCOUNT_CONSTRAINTS_JSON_PATH, strValue);
1583 if (result != ERR_OK) {
1584 ACCOUNT_LOGE("Cannot save global osAccount constraints file content!");
1585 return result;
1586 }
1587 #ifdef ENABLE_FILE_WATCHER
1588 accountFileWatcherMgr_.AddAccountInfoDigest(
1589 strValue, Constants::GLOBAL_OSACCOUNT_CONSTRAINTS_JSON_PATH);
1590 #endif // ENABLE_FILE_WATCHER
1591 return ERR_OK;
1592 }
1593
SaveSpecificOAConstraintsToFile(const CJsonUnique & specificOAConstraints)1594 ErrCode OsAccountControlFileManager::SaveSpecificOAConstraintsToFile(const CJsonUnique &specificOAConstraints)
1595 {
1596 std::lock_guard<std::mutex> lock(specificOAConstraintsFileLock_);
1597 std::string strValue = PackJsonToString(specificOAConstraints);
1598 ErrCode result = accountFileOperator_->InputFileByPathAndContent(
1599 Constants::SPECIFIC_OSACCOUNT_CONSTRAINTS_JSON_PATH, strValue);
1600 if (result != ERR_OK) {
1601 ACCOUNT_LOGE("Cannot save specific osAccount constraints file content!");
1602 return result;
1603 }
1604 #ifdef ENABLE_FILE_WATCHER
1605 accountFileWatcherMgr_.AddAccountInfoDigest(
1606 strValue, Constants::SPECIFIC_OSACCOUNT_CONSTRAINTS_JSON_PATH);
1607 #endif // ENABLE_FILE_WATCHER
1608 return ERR_OK;
1609 }
1610
GetDeviceOwnerId(int & deviceOwnerId)1611 ErrCode OsAccountControlFileManager::GetDeviceOwnerId(int &deviceOwnerId)
1612 {
1613 CJsonUnique globalOAConstraintsJson = nullptr;
1614 ErrCode result = GetGlobalOAConstraintsFromFile(globalOAConstraintsJson);
1615 if (result != ERR_OK) {
1616 ACCOUNT_LOGE("Get global json data from file failed!");
1617 return result;
1618 }
1619 GetDataByType<int>(globalOAConstraintsJson, DEVICE_OWNER_ID, deviceOwnerId);
1620 return ERR_OK;
1621 }
1622
UpdateDeviceOwnerId(const int deviceOwnerId)1623 ErrCode OsAccountControlFileManager::UpdateDeviceOwnerId(const int deviceOwnerId)
1624 {
1625 std::lock_guard<std::mutex> lock(accountInfoFileLock_);
1626 CJsonUnique globalOAConstraintsJson = nullptr;
1627 ErrCode result = GetGlobalOAConstraintsFromFile(globalOAConstraintsJson);
1628 if (result != ERR_OK) {
1629 ACCOUNT_LOGE("Get global json data from file failed!");
1630 return result;
1631 }
1632 AddIntToJson(globalOAConstraintsJson, DEVICE_OWNER_ID, deviceOwnerId);
1633 return SaveGlobalOAConstraintsToFile(globalOAConstraintsJson);
1634 }
1635
SetDefaultActivatedOsAccount(const int32_t id)1636 ErrCode OsAccountControlFileManager::SetDefaultActivatedOsAccount(const int32_t id)
1637 {
1638 std::lock_guard<std::mutex> lock(accountInfoFileLock_);
1639 CJsonUnique accountListJson = nullptr;
1640 ErrCode result = GetAccountListFromFile(accountListJson);
1641 if (result != ERR_OK) {
1642 ACCOUNT_LOGE("Get account list failed!");
1643 return result;
1644 }
1645 AddIntToJson(accountListJson, DEFAULT_ACTIVATED_ACCOUNT_ID, id);
1646 return SaveAccountListToFileAndDataBase(accountListJson);
1647 }
1648
GetDefaultActivatedOsAccount(int32_t & id)1649 ErrCode OsAccountControlFileManager::GetDefaultActivatedOsAccount(int32_t &id)
1650 {
1651 CJsonUnique accountListJsonData = nullptr;
1652 ErrCode result = GetAccountListFromFile(accountListJsonData);
1653 if (result != ERR_OK) {
1654 return result;
1655 }
1656 GetDataByType<int>(accountListJsonData, DEFAULT_ACTIVATED_ACCOUNT_ID, id);
1657 return ERR_OK;
1658 }
1659
SaveAccountListToFileAndDataBase(const CJsonUnique & accountListJson)1660 ErrCode OsAccountControlFileManager::SaveAccountListToFileAndDataBase(const CJsonUnique &accountListJson)
1661 {
1662 #if defined(HAS_KV_STORE_PART) && defined(DISTRIBUTED_FEATURE_ENABLED)
1663 osAccountDataBaseOperator_->UpdateOsAccountIDListInDatabase(accountListJson);
1664 #endif // defined(HAS_KV_STORE_PART) && defined(DISTRIBUTED_FEATURE_ENABLED)
1665 return SaveAccountListToFile(accountListJson);
1666 }
1667
IsOsAccountExists(const int id,bool & isExists)1668 ErrCode OsAccountControlFileManager::IsOsAccountExists(const int id, bool &isExists)
1669 {
1670 isExists = false;
1671 std::string path = Constants::USER_INFO_BASE + Constants::PATH_SEPARATOR + std::to_string(id) +
1672 Constants::PATH_SEPARATOR + Constants::USER_INFO_FILE_NAME;
1673 // check exist
1674 if (!accountFileOperator_->IsExistFile(path)) {
1675 ACCOUNT_LOGI("IsOsAccountExists path %{public}s does not exist!", path.c_str());
1676 return ERR_OK;
1677 }
1678
1679 // check format
1680 if (!accountFileOperator_->IsJsonFormat(path)) {
1681 ACCOUNT_LOGI("IsOsAccountExists path %{public}s wrong format!", path.c_str());
1682 return ERR_OK;
1683 }
1684
1685 isExists = true;
1686 return ERR_OK;
1687 }
1688
GetPhotoById(const int id,std::string & photo)1689 ErrCode OsAccountControlFileManager::GetPhotoById(const int id, std::string &photo)
1690 {
1691 if ((photo != USER_PHOTO_FILE_JPG_NAME) && (photo != USER_PHOTO_FILE_PNG_NAME)
1692 && (photo != Constants::USER_PHOTO_FILE_TXT_NAME)) {
1693 return ERR_OK;
1694 }
1695 std::string path =
1696 Constants::USER_INFO_BASE + Constants::PATH_SEPARATOR + std::to_string(id) + Constants::PATH_SEPARATOR + photo;
1697 std::string byteStr = "";
1698 ErrCode errCode = accountFileOperator_->GetFileContentByPath(path, byteStr);
1699 if (errCode != ERR_OK) {
1700 ACCOUNT_LOGE("GetPhotoById cannot find photo file error");
1701 return errCode;
1702 }
1703 if (photo == Constants::USER_PHOTO_FILE_TXT_NAME) {
1704 photo = byteStr;
1705 return ERR_OK;
1706 }
1707 // USER_PHOTO_FILE_JPG_NAME and USER_PHOTO_FILE_PNG_NAME are compatible with previous data
1708 if (photo == USER_PHOTO_FILE_JPG_NAME) {
1709 photo = USER_PHOTO_BASE_JPG_HEAD + osAccountPhotoOperator_->EnCode(byteStr.c_str(), byteStr.length());
1710 } else {
1711 photo = USER_PHOTO_BASE_PNG_HEAD + osAccountPhotoOperator_->EnCode(byteStr.c_str(), byteStr.length());
1712 }
1713 std::string substr = "\r\n";
1714 while (photo.find(substr) != std::string::npos) {
1715 photo.erase(photo.find(substr), substr.length());
1716 }
1717 return ERR_OK;
1718 }
1719
SetPhotoById(const int id,const std::string & photo)1720 ErrCode OsAccountControlFileManager::SetPhotoById(const int id, const std::string &photo)
1721 {
1722 std::string path = Constants::USER_INFO_BASE + Constants::PATH_SEPARATOR + std::to_string(id)
1723 + Constants::PATH_SEPARATOR + Constants::USER_PHOTO_FILE_TXT_NAME;
1724 ErrCode errCode = accountFileOperator_->InputFileByPathAndContentWithTransaction(path, photo);
1725 if (errCode != ERR_OK) {
1726 return errCode;
1727 }
1728 return ERR_OK;
1729 }
1730
GetGlobalOAConstraintsList(std::vector<std::string> & constraintsList)1731 ErrCode OsAccountControlFileManager::GetGlobalOAConstraintsList(std::vector<std::string> &constraintsList)
1732 {
1733 std::lock_guard<std::mutex> lock(globalOAConstraintsFileLock_);
1734 return osAccountFileOperator_->GetGlobalOAConstraintsList(constraintsList);
1735 }
1736
GetSpecificOAConstraintsList(const int32_t id,std::vector<std::string> & constraintsList)1737 ErrCode OsAccountControlFileManager::GetSpecificOAConstraintsList(
1738 const int32_t id, std::vector<std::string> &constraintsList)
1739 {
1740 std::lock_guard<std::mutex> lock(specificOAConstraintsFileLock_);
1741 return osAccountFileOperator_->GetSpecificOAConstraintsList(id, constraintsList);
1742 }
1743
GetIsMultiOsAccountEnable(bool & isMultiOsAccountEnable)1744 ErrCode OsAccountControlFileManager::GetIsMultiOsAccountEnable(bool &isMultiOsAccountEnable)
1745 {
1746 return osAccountFileOperator_->GetIsMultiOsAccountEnable(isMultiOsAccountEnable);
1747 }
1748
CheckConstraints(const std::vector<std::string> & constraints)1749 bool OsAccountControlFileManager::CheckConstraints(const std::vector<std::string> &constraints)
1750 {
1751 return osAccountFileOperator_->CheckConstraints(constraints);
1752 }
1753
IsAllowedCreateAdmin(bool & isAllowedCreateAdmin)1754 ErrCode OsAccountControlFileManager::IsAllowedCreateAdmin(bool &isAllowedCreateAdmin)
1755 {
1756 return osAccountFileOperator_->IsAllowedCreateAdmin(isAllowedCreateAdmin);
1757 }
1758
GetCreatedOsAccountNumFromDatabase(const std::string & storeID,int & createdOsAccountNum)1759 ErrCode OsAccountControlFileManager::GetCreatedOsAccountNumFromDatabase(const std::string& storeID,
1760 int &createdOsAccountNum)
1761 {
1762 #if defined(HAS_KV_STORE_PART) && defined(DISTRIBUTED_FEATURE_ENABLED)
1763 return osAccountDataBaseOperator_->GetCreatedOsAccountNumFromDatabase(storeID, createdOsAccountNum);
1764 #else
1765 return ERR_ACCOUNT_COMMON_INTERFACE_NOT_SUPPORT_ERROR;
1766 #endif // defined(HAS_KV_STORE_PART) && defined(DISTRIBUTED_FEATURE_ENABLED)
1767 }
1768
GetSerialNumberFromDatabase(const std::string & storeID,int64_t & serialNumber)1769 ErrCode OsAccountControlFileManager::GetSerialNumberFromDatabase(const std::string& storeID,
1770 int64_t &serialNumber)
1771 {
1772 #if defined(HAS_KV_STORE_PART) && defined(DISTRIBUTED_FEATURE_ENABLED)
1773 return osAccountDataBaseOperator_->GetSerialNumberFromDatabase(storeID, serialNumber);
1774 #else
1775 return ERR_ACCOUNT_COMMON_INTERFACE_NOT_SUPPORT_ERROR;
1776 #endif // defined(HAS_KV_STORE_PART) && defined(DISTRIBUTED_FEATURE_ENABLED)
1777 }
1778
GetMaxAllowCreateIdFromDatabase(const std::string & storeID,int & id)1779 ErrCode OsAccountControlFileManager::GetMaxAllowCreateIdFromDatabase(const std::string& storeID,
1780 int &id)
1781 {
1782 #if defined(HAS_KV_STORE_PART) && defined(DISTRIBUTED_FEATURE_ENABLED)
1783 return osAccountDataBaseOperator_->GetMaxAllowCreateIdFromDatabase(storeID, id);
1784 #else
1785 return ERR_ACCOUNT_COMMON_INTERFACE_NOT_SUPPORT_ERROR;
1786 #endif // defined(HAS_KV_STORE_PART) && defined(DISTRIBUTED_FEATURE_ENABLED)
1787 }
1788
GetOsAccountFromDatabase(const std::string & storeID,const int id,OsAccountInfo & osAccountInfo)1789 ErrCode OsAccountControlFileManager::GetOsAccountFromDatabase(const std::string& storeID,
1790 const int id, OsAccountInfo &osAccountInfo)
1791 {
1792 #if defined(HAS_KV_STORE_PART) && defined(DISTRIBUTED_FEATURE_ENABLED)
1793 return osAccountDataBaseOperator_->GetOsAccountFromDatabase(storeID, id, osAccountInfo);
1794 #else
1795 return ERR_ACCOUNT_COMMON_INTERFACE_NOT_SUPPORT_ERROR;
1796 #endif // defined(HAS_KV_STORE_PART) && defined(DISTRIBUTED_FEATURE_ENABLED)
1797 }
1798
GetOsAccountListFromDatabase(const std::string & storeID,std::vector<OsAccountInfo> & osAccountList)1799 ErrCode OsAccountControlFileManager::GetOsAccountListFromDatabase(const std::string& storeID,
1800 std::vector<OsAccountInfo> &osAccountList)
1801 {
1802 #if defined(HAS_KV_STORE_PART) && defined(DISTRIBUTED_FEATURE_ENABLED)
1803 return osAccountDataBaseOperator_->GetOsAccountListFromDatabase(storeID, osAccountList);
1804 #else
1805 return ERR_ACCOUNT_COMMON_INTERFACE_NOT_SUPPORT_ERROR;
1806 #endif // defined(HAS_KV_STORE_PART) && defined(DISTRIBUTED_FEATURE_ENABLED)
1807 }
1808
GetDomainBoundFlagPath(const int32_t localId)1809 static std::string GetDomainBoundFlagPath(const int32_t localId)
1810 {
1811 return Constants::USER_INFO_BASE + Constants::PATH_SEPARATOR + std::to_string(localId) + Constants::PATH_SEPARATOR +
1812 Constants::IS_DOMAIN_BOUND_COMPLETED_FILE_NAME;
1813 }
1814
SetDomainBoundFlag(const int32_t localId,const bool isBoundCompleted,const DomainAccountInfo domainInfo)1815 ErrCode OsAccountControlFileManager::SetDomainBoundFlag(
1816 const int32_t localId, const bool isBoundCompleted, const DomainAccountInfo domainInfo)
1817 {
1818 std::string flagFilePath = GetDomainBoundFlagPath(localId);
1819 if (isBoundCompleted) {
1820 return accountFileOperator_->DeleteFile(flagFilePath);
1821 }
1822 auto jsonObj = ToJson(domainInfo);
1823 if (!jsonObj) {
1824 ACCOUNT_LOGE("Domain account info to json failed.");
1825 return ERR_ACCOUNT_COMMON_INSUFFICIENT_MEMORY_ERROR;
1826 }
1827 std::string jsonStr = PackJsonToString(jsonObj);
1828 ErrCode ret = accountFileOperator_->InputFileByPathAndContent(flagFilePath, jsonStr);
1829 if (ret != ERR_OK) {
1830 accountFileOperator_->DeleteFile(flagFilePath);
1831 ACCOUNT_LOGE("Set domain bound completed flag failed, ret = %{public}d.", ret);
1832 }
1833 return ret;
1834 }
1835
GetDomainBoundFlag(const int32_t localId,bool & isBoundCompleted,DomainAccountInfo & domainInfo)1836 ErrCode OsAccountControlFileManager::GetDomainBoundFlag(
1837 const int32_t localId, bool &isBoundCompleted, DomainAccountInfo &domainInfo)
1838 {
1839 isBoundCompleted = false;
1840 domainInfo.Clear();
1841 std::string flagFilePath = GetDomainBoundFlagPath(localId);
1842 std::string jsonStr;
1843 ErrCode ret = accountFileOperator_->GetFileContentByPath(flagFilePath, jsonStr);
1844 if (ret == ERR_OSACCOUNT_SERVICE_FILE_FIND_FILE_ERROR) {
1845 isBoundCompleted = true;
1846 return ERR_OK;
1847 } else if (ret != ERR_OK) {
1848 ACCOUNT_LOGE("Get domain bound completed flag failed, ret = %{public}d.", ret);
1849 return ret;
1850 }
1851 auto jsonObj = CreateJsonFromString(jsonStr);
1852 if (!jsonObj) {
1853 ACCOUNT_LOGE("Get domain account info from json failed.");
1854 return ERR_ACCOUNT_COMMON_BAD_JSON_FORMAT_ERROR;
1855 }
1856 FromJson(jsonObj.get(), domainInfo);
1857 return ERR_OK;
1858 }
1859 } // namespace AccountSA
1860 } // namespace OHOS
1861