• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023-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 
16 #include "profile_utils.h"
17 
18 #include <codecvt>
19 #include <locale>
20 #include <regex>
21 #include <unordered_set>
22 
23 #include "dm_device_info.h"
24 #include "rdb_errno.h"
25 
26 #include "content_sensor_manager_utils.h"
27 #include "distributed_device_profile_constants.h"
28 #include "distributed_device_profile_enums.h"
29 #include "distributed_device_profile_errors.h"
30 #include "distributed_device_profile_log.h"
31 
32 namespace OHOS {
33 namespace DistributedDeviceProfile {
34 using namespace OHOS::DistributedHardware;
35 
36 namespace {
37     const std::string TAG = "ProfileUtils";
38     const std::unordered_set<std::string> NEED_ADD_OH_SUFFIX_DEV_PROFILES { OS_TYPE, OS_VERSION };
39     const std::unordered_set<std::string> NEED_ADD_OH_SUFFIX_SVR_NAMES { "DistributeModemService",
40         "multiScreenAssistantService", "appInfo" };
41 }
42 
GetDbKeyAnonyString(const std::string & dbKey)43 std::string ProfileUtils::GetDbKeyAnonyString(const std::string& dbKey)
44 {
45     constexpr size_t DEVICE_ID_INDEX = 1;
46     std::vector<std::string> splitKeys;
47     if (ProfileUtils::SplitString(dbKey, SEPARATOR, splitKeys) != DP_SUCCESS ||
48         splitKeys.size() <= DEVICE_ID_INDEX) {
49         return GetAnonyString(dbKey);
50     }
51     for (size_t i = DEVICE_ID_INDEX; i < splitKeys.size(); i++) {
52         splitKeys[i] = GetAnonyString(splitKeys[i]);
53     }
54     return JoinString(splitKeys, SEPARATOR);
55 }
56 
GetAnonyString(const std::string & value)57 std::string ProfileUtils::GetAnonyString(const std::string& value)
58 {
59     constexpr size_t INT32_SHORT_ID_LENGTH = 10;
60     constexpr size_t INT32_PLAINTEXT_LENGTH = 4;
61     constexpr size_t INT32_MIN_ID_LENGTH = 3;
62     std::string res;
63     std::string tmpStr("***");
64     size_t strLen = value.length();
65     if (strLen < INT32_MIN_ID_LENGTH) {
66         return tmpStr;
67     }
68 
69     if (strLen <= INT32_SHORT_ID_LENGTH) {
70         res += value[0];
71         res += tmpStr;
72         res += value[strLen - 1];
73     } else {
74         res.append(value, 0, INT32_PLAINTEXT_LENGTH);
75         res += tmpStr;
76         res.append(value, strLen - INT32_PLAINTEXT_LENGTH, INT32_PLAINTEXT_LENGTH);
77     }
78     return res;
79 }
80 
GetAnonyInt32(const int32_t value)81 std::string ProfileUtils::GetAnonyInt32(const int32_t value)
82 {
83     std::string tempString = std::to_string(value);
84     size_t length = tempString.length();
85     if (length == 0x01) {
86         tempString[0] = '*';
87         return tempString;
88     }
89     for (size_t i = 1; i < length - 1; i++) {
90         tempString[i] = '*';
91     }
92     return tempString;
93 }
94 
IsP2p(const int32_t authForm)95 bool ProfileUtils::IsP2p(const int32_t authForm)
96 {
97     if (authForm == static_cast<int32_t>(DistributedHardware::DmAuthForm::INVALID_TYPE) ||
98         authForm == static_cast<int32_t>(DistributedHardware::DmAuthForm::IDENTICAL_ACCOUNT)) {
99         HILOGD("authForm: %{public}d!", authForm);
100         return false;
101     }
102     return true;
103 }
104 
GetProfileType(const std::string & key)105 ProfileType ProfileUtils::GetProfileType(const std::string& key)
106 {
107     if (key.length() == 0 || key.length() > MAX_STRING_LEN) {
108         HILOGE("This key is invalid, value: %{public}s!", GetAnonyString(key).c_str());
109         return ProfileType::PROFILE_TYPE_MIN;
110     }
111     ProfileType profileType = ProfileType::PROFILE_TYPE_MIN;
112     if (StartsWith(key, DEV_PREFIX)) {
113         profileType = ProfileType::DEVICE_PROFILE;
114     }
115     if (StartsWith(key, SVR_PREFIX)) {
116         profileType = ProfileType::SERVICE_PROFILE;
117     }
118     if (StartsWith(key, CHAR_PREFIX)) {
119         profileType = ProfileType::CHAR_PROFILE;
120     }
121     return profileType;
122 }
123 
StartsWith(const std::string & str,const std::string & prefix)124 bool ProfileUtils::StartsWith(const std::string& str, const std::string& prefix)
125 {
126     return (str.find(prefix, 0) == 0);
127 }
128 
EndsWith(const std::string & str,const std::string & suffix)129 bool ProfileUtils::EndsWith(const std::string& str, const std::string& suffix)
130 {
131     if (str.length() < suffix.length()) {
132         return false;
133     }
134     return str.substr(str.length() - suffix.length()).compare(suffix) == 0;
135 }
136 
GetProfileKey(const std::string & dbKey)137 std::string ProfileUtils::GetProfileKey(const std::string& dbKey)
138 {
139     if (dbKey.length() == 0 || dbKey.length() > MAX_STRING_LEN) {
140         return "";
141     }
142     std::size_t pos = dbKey.find_last_of("#");
143     return dbKey.substr(0, pos);
144 }
145 
GetDeviceIdByDBKey(const std::string & dbKey)146 std::string ProfileUtils::GetDeviceIdByDBKey(const std::string& dbKey)
147 {
148     if (dbKey.length() == 0 || dbKey.length() > MAX_STRING_LEN) {
149         return "";
150     }
151     std::vector<std::string> res;
152     if (SplitString(dbKey, SEPARATOR, res) != DP_SUCCESS) {
153         return "";
154     }
155     if (res.size() < NUM_1) {
156         return "";
157     }
158     return res[NUM_1];
159 }
160 
GetServiceNameByDBKey(const std::string & dbKey)161 std::string ProfileUtils::GetServiceNameByDBKey(const std::string& dbKey)
162 {
163     if (dbKey.length() == 0 || dbKey.length() > MAX_STRING_LEN) {
164         return "";
165     }
166     std::vector<std::string> res;
167     if (SplitString(dbKey, SEPARATOR, res) != DP_SUCCESS) {
168         return "";
169     }
170     if (res.size() < NUM_2) {
171         return "";
172     }
173     return res[NUM_2];
174 }
175 
GetNonOhSuffixServiceNameByDBKey(const std::string & dbKey)176 std::string ProfileUtils::GetNonOhSuffixServiceNameByDBKey(const std::string& dbKey)
177 {
178     std::string serviceName = GetServiceNameByDBKey(dbKey);
179     if (serviceName.empty()) {
180         return "";
181     }
182     return CheckAndRemoveOhSuffix(serviceName);
183 }
184 
IsNeedAddOhSuffix(const std::string & profileName,bool isSvr)185 bool ProfileUtils::IsNeedAddOhSuffix(const std::string& profileName, bool isSvr)
186 {
187     if (profileName.length() == 0 || profileName.length() > MAX_STRING_LEN) {
188         return false;
189     }
190     if (isSvr && NEED_ADD_OH_SUFFIX_SVR_NAMES.count(profileName) > 0) {
191         return true;
192     }
193     if (!isSvr && NEED_ADD_OH_SUFFIX_DEV_PROFILES.count(profileName) > 0) {
194         return true;
195     }
196     return false;
197 }
198 
CheckAndAddOhSuffix(const std::string & profileName,bool isSvr)199 std::string ProfileUtils::CheckAndAddOhSuffix(const std::string& profileName, bool isSvr)
200 {
201     std::string str = profileName;
202     if (IsNeedAddOhSuffix(str, isSvr)) {
203         str = str + OH_PROFILE_SUFFIX;
204     }
205     return str;
206 }
207 
CheckAndRemoveOhSuffix(const std::string & profileName)208 std::string ProfileUtils::CheckAndRemoveOhSuffix(const std::string& profileName)
209 {
210     std::string str = profileName;
211     if (EndsWith(str, OH_PROFILE_SUFFIX)) {
212         str = str.erase(str.length() - OH_PROFILE_SUFFIX.length());
213     }
214     return str;
215 }
216 
GetCharKeyByDBKey(const std::string & dbKey)217 std::string ProfileUtils::GetCharKeyByDBKey(const std::string& dbKey)
218 {
219     if (dbKey.length() == 0 || dbKey.length() > MAX_STRING_LEN) {
220         return "";
221     }
222     std::vector<std::string> res;
223     if (SplitString(dbKey, SEPARATOR, res) != DP_SUCCESS) {
224         return "";
225     }
226     if (res.size() < NUM_3) {
227         return "";
228     }
229     return res[NUM_3];
230 }
231 
SplitString(const std::string & str,const std::string & splits,std::vector<std::string> & res)232 int32_t ProfileUtils::SplitString(const std::string& str, const std::string& splits, std::vector<std::string>& res)
233 {
234     if (str == "") {
235         return DP_INVALID_PARAMS;
236     }
237     std::string strs = str + splits;
238     size_t pos = strs.find(splits);
239     int32_t step = splits.size();
240 
241     while (pos != strs.npos) {
242         std::string temp = strs.substr(0, pos);
243         res.push_back(temp);
244         strs = strs.substr(pos + step, strs.size());
245         pos = strs.find(splits);
246     }
247     return DP_SUCCESS;
248 }
249 
JoinString(const std::vector<std::string> & strs,const std::string & delimiter)250 std::string ProfileUtils::JoinString(const std::vector<std::string>& strs, const std::string& delimiter)
251 {
252     std::string res = EMPTY_STRING;
253     if (strs.empty()) {
254         return res;
255     }
256     for (size_t i = 0; i < strs.size(); i++) {
257         res += strs[i];
258         if (i != strs.size() - 1) {
259             res += delimiter;
260         }
261     }
262     return res;
263 }
264 
IsKeyValid(const std::string & key)265 bool ProfileUtils::IsKeyValid(const std::string& key)
266 {
267     if (key.length() == 0 || key.length() > MAX_STRING_LEN) {
268         return false;
269     }
270     size_t found = key.find(SEPARATOR);
271     if (found != std::string::npos) {
272         return false;
273     }
274     return true;
275 }
276 
IsLocalUdid(const std::string & udid)277 bool ProfileUtils::IsLocalUdid(const std::string& udid)
278 {
279     if (udid.length() == 0 || udid.length() > MAX_STRING_LEN) {
280         return false;
281     }
282     std::string localUdid = ContentSensorManagerUtils::GetInstance().ObtainLocalUdid();
283     return localUdid == udid;
284 }
285 
IsDevProfileValid(const DeviceProfile & devProfile)286 bool ProfileUtils::IsDevProfileValid(const DeviceProfile& devProfile)
287 {
288     return IsKeyValid(devProfile.GetDeviceId()) && IsLocalUdid(devProfile.GetDeviceId());
289 }
290 
IsSvrProfileValid(const ServiceProfile & svrProfile)291 bool ProfileUtils::IsSvrProfileValid(const ServiceProfile& svrProfile)
292 {
293     return IsKeyValid(svrProfile.GetDeviceId()) && IsLocalUdid(svrProfile.GetDeviceId()) &&
294         IsKeyValid(svrProfile.GetServiceName());
295 }
296 
IsCharProfileValid(const CharacteristicProfile & charProfile)297 bool ProfileUtils::IsCharProfileValid(const CharacteristicProfile& charProfile)
298 {
299     return IsKeyValid(charProfile.GetDeviceId()) && IsLocalUdid(charProfile.GetDeviceId()) &&
300         IsKeyValid(charProfile.GetServiceName()) && IsKeyValid(charProfile.GetCharacteristicKey());
301 }
302 
IsDeviceProfileValid(const DeviceProfile & devProfile)303 bool ProfileUtils::IsDeviceProfileValid(const DeviceProfile& devProfile)
304 {
305     if (devProfile.GetOsVersion().empty() || devProfile.GetOsType() == MIN_OS_TYPE) {
306         return false;
307     }
308     return true;
309 }
310 
IsServiceProfileValid(const ServiceProfile & svrProfile)311 bool ProfileUtils::IsServiceProfileValid(const ServiceProfile& svrProfile)
312 {
313     if (svrProfile.GetServiceName().empty() || svrProfile.GetServiceType().empty()) {
314         return false;
315     }
316     return true;
317 }
318 
IsCharacteristicProfileValid(const CharacteristicProfile & charProfile)319 bool ProfileUtils::IsCharacteristicProfileValid(const CharacteristicProfile& charProfile)
320 {
321     if (charProfile.GetCharacteristicKey().empty() || charProfile.GetCharacteristicValue().empty()) {
322         return false;
323     }
324     return true;
325 }
326 
GenerateDeviceProfileKey(const std::string & deviceId)327 std::string ProfileUtils::GenerateDeviceProfileKey(const std::string& deviceId)
328 {
329     return DEV_PREFIX + SEPARATOR + deviceId;
330 }
331 
GenerateServiceProfileKey(const std::string & deviceId,const std::string & serviceName)332 std::string ProfileUtils::GenerateServiceProfileKey(const std::string& deviceId, const std::string& serviceName)
333 {
334     return SVR_PREFIX + SEPARATOR + deviceId + SEPARATOR + serviceName;
335 }
336 
GenerateCharProfileKey(const std::string & deviceId,const std::string & serviceName,const std::string & charKey)337 std::string ProfileUtils::GenerateCharProfileKey(const std::string& deviceId, const std::string& serviceName,
338     const std::string& charKey)
339 {
340     return CHAR_PREFIX + SEPARATOR + deviceId + SEPARATOR + serviceName + SEPARATOR + charKey;
341 }
342 
TrustDeviceProfileToEntries(const TrustDeviceProfile & profile,ValuesBucket & values)343 int32_t ProfileUtils::TrustDeviceProfileToEntries(const TrustDeviceProfile& profile, ValuesBucket& values)
344 {
345     values.PutString(DEVICE_ID, profile.GetDeviceId());
346     values.PutInt(DEVICE_ID_TYPE, profile.GetDeviceIdType());
347     values.PutString(DEVICE_ID_HASH, profile.GetDeviceIdHash());
348     values.PutInt(STATUS, profile.GetStatus());
349     return DP_SUCCESS;
350 }
351 
AccessControlProfileToEntries(const AccessControlProfile & profile,ValuesBucket & values)352 int32_t ProfileUtils::AccessControlProfileToEntries(const AccessControlProfile& profile, ValuesBucket& values)
353 {
354     values.PutLong(ACCESS_CONTROL_ID, profile.GetAccessControlId());
355     values.PutLong(ACCESSER_ID, profile.GetAccesserId());
356     values.PutLong(ACCESSEE_ID, profile.GetAccesseeId());
357     values.PutString(TRUST_DEVICE_ID, profile.GetTrustDeviceId());
358     values.PutInt(AUTHENTICATION_TYPE, profile.GetAuthenticationType());
359     values.PutInt(DEVICE_ID_TYPE, profile.GetDeviceIdType());
360     values.PutString(DEVICE_ID_HASH, profile.GetDeviceIdHash());
361     values.PutInt(BIND_TYPE, profile.GetBindType());
362     values.PutString(SESSION_KEY, profile.GetSessionKey());
363     values.PutLong(LAST_AUTH_TIME, profile.GetLastAuthTime());
364     values.PutLong(VALID_PERIOD, profile.GetValidPeriod());
365     values.PutInt(STATUS, profile.GetStatus());
366     values.PutInt(BIND_LEVEL, profile.GetBindLevel());
367     values.PutString(EXTRA_DATA, profile.GetExtraData());
368     return DP_SUCCESS;
369 }
370 
AccesserToEntries(const AccessControlProfile & aclProfile,ValuesBucket & values)371 int32_t ProfileUtils::AccesserToEntries(const AccessControlProfile& aclProfile, ValuesBucket& values)
372 {
373     Accesser accesser = aclProfile.GetAccesser();
374     values.PutLong(ACCESSER_ID, accesser.GetAccesserId());
375     values.PutString(ACCESSER_DEVICE_ID, accesser.GetAccesserDeviceId());
376     values.PutInt(ACCESSER_USER_ID, accesser.GetAccesserUserId());
377     values.PutString(ACCESSER_ACCOUNT_ID, accesser.GetAccesserAccountId());
378     values.PutLong(ACCESSER_TOKEN_ID, accesser.GetAccesserTokenId());
379     values.PutString(ACCESSER_BUNDLE_NAME, accesser.GetAccesserBundleName());
380     values.PutString(ACCESSER_HAP_SIGNATURE, accesser.GetAccesserHapSignature());
381     values.PutInt(ACCESSER_BIND_LEVEL, accesser.GetAccesserBindLevel());
382     values.PutString(ACCESSER_DEVICE_NAME, accesser.GetAccesserDeviceName());
383     values.PutString(ACCESSER_SERVICE_NAME, accesser.GetAccesserServiceName());
384     values.PutInt(ACCESSER_CREDENTIAL_ID, accesser.GetAccesserCredentialId());
385     values.PutString(ACCESSER_CREDENTIAL_ID_STR, accesser.GetAccesserCredentialIdStr());
386     values.PutInt(ACCESSER_STATUS, accesser.GetAccesserStatus());
387     values.PutInt(ACCESSER_SESSION_KEY_ID, accesser.GetAccesserSessionKeyId());
388     values.PutLong(ACCESSER_SESSION_KEY_TIMESTAMP, accesser.GetAccesserSKTimeStamp());
389     values.PutString(ACCESSER_EXTRA_DATA, accesser.GetAccesserExtraData());
390     return DP_SUCCESS;
391 }
392 
AccesseeToEntries(const AccessControlProfile & aclProfile,ValuesBucket & values)393 int32_t ProfileUtils::AccesseeToEntries(const AccessControlProfile& aclProfile, ValuesBucket& values)
394 {
395     Accessee accessee = aclProfile.GetAccessee();
396     values.PutLong(ACCESSEE_ID, accessee.GetAccesseeId());
397     values.PutString(ACCESSEE_DEVICE_ID, accessee.GetAccesseeDeviceId());
398     values.PutInt(ACCESSEE_USER_ID, accessee.GetAccesseeUserId());
399     values.PutString(ACCESSEE_ACCOUNT_ID, accessee.GetAccesseeAccountId());
400     values.PutLong(ACCESSEE_TOKEN_ID, accessee.GetAccesseeTokenId());
401     values.PutString(ACCESSEE_BUNDLE_NAME, accessee.GetAccesseeBundleName());
402     values.PutString(ACCESSEE_HAP_SIGNATURE, accessee.GetAccesseeHapSignature());
403     values.PutInt(ACCESSEE_BIND_LEVEL, accessee.GetAccesseeBindLevel());
404     values.PutString(ACCESSEE_DEVICE_NAME, accessee.GetAccesseeDeviceName());
405     values.PutString(ACCESSEE_SERVICE_NAME, accessee.GetAccesseeServiceName());
406     values.PutInt(ACCESSEE_CREDENTIAL_ID, accessee.GetAccesseeCredentialId());
407     values.PutString(ACCESSEE_CREDENTIAL_ID_STR, accessee.GetAccesseeCredentialIdStr());
408     values.PutInt(ACCESSEE_STATUS, accessee.GetAccesseeStatus());
409     values.PutInt(ACCESSEE_SESSION_KEY_ID, accessee.GetAccesseeSessionKeyId());
410     values.PutLong(ACCESSEE_SESSION_KEY_TIMESTAMP, accessee.GetAccesseeSKTimeStamp());
411     values.PutString(ACCESSEE_EXTRA_DATA, accessee.GetAccesseeExtraData());
412     return DP_SUCCESS;
413 }
414 
DeviceProfileToEntries(const DeviceProfile & profile,std::map<std::string,std::string> & values,bool isMultiUser)415 int32_t ProfileUtils::DeviceProfileToEntries(const DeviceProfile& profile, std::map<std::string, std::string>& values,
416     bool isMultiUser)
417 {
418     std::string deviceProfileKey = GenerateDeviceProfileKey(profile.GetDeviceId());
419     if (isMultiUser) {
420         values[GenerateDBKey(deviceProfileKey, OS_SYS_CAPACITY, profile.GetUserId())] = profile.GetOsSysCap();
421         values[GenerateDBKey(deviceProfileKey, OS_VERSION, profile.GetUserId())] = profile.GetOsVersion();
422         values[GenerateDBKey(deviceProfileKey, OS_TYPE, profile.GetUserId())] = std::to_string(profile.GetOsType());
423         values[GenerateDBKey(deviceProfileKey, OS_VERSION + OH_PROFILE_SUFFIX, profile.GetUserId())] =
424             profile.GetOsVersion();
425         values[GenerateDBKey(deviceProfileKey, OS_TYPE + OH_PROFILE_SUFFIX, profile.GetUserId())] =
426             std::to_string(profile.GetOsType());
427     } else {
428         values[GenerateDBKey(deviceProfileKey, OS_SYS_CAPACITY)] = profile.GetOsSysCap();
429         values[GenerateDBKey(deviceProfileKey, OS_VERSION)] = profile.GetOsVersion();
430         values[GenerateDBKey(deviceProfileKey, OS_TYPE)] = std::to_string(profile.GetOsType());
431         values[GenerateDBKey(deviceProfileKey, OS_VERSION + OH_PROFILE_SUFFIX)] = profile.GetOsVersion();
432         values[GenerateDBKey(deviceProfileKey, OS_TYPE + OH_PROFILE_SUFFIX)] = std::to_string(profile.GetOsType());
433     }
434     return DP_SUCCESS;
435 }
436 
ServiceProfileToEntries(const ServiceProfile & profile,std::map<std::string,std::string> & values,bool isMultiUser)437 int32_t ProfileUtils::ServiceProfileToEntries(const ServiceProfile& profile, std::map<std::string,
438     std::string>& values, bool isMultiUser)
439 {
440     std::string serviceName = CheckAndAddOhSuffix(profile.GetServiceName(), true);
441     std::string serviceProfileKey = GenerateServiceProfileKey(profile.GetDeviceId(), serviceName);
442     // value not need add OH suffix
443     if (isMultiUser) {
444         values[GenerateDBKey(serviceProfileKey, SERVICE_NAME, profile.GetUserId())] = profile.GetServiceName();
445         values[GenerateDBKey(serviceProfileKey, SERVICE_TYPE, profile.GetUserId())] = profile.GetServiceType();
446     } else {
447         values[GenerateDBKey(serviceProfileKey, SERVICE_NAME)] = profile.GetServiceName();
448         values[GenerateDBKey(serviceProfileKey, SERVICE_TYPE)] = profile.GetServiceType();
449     }
450     return DP_SUCCESS;
451 }
452 
CharacteristicProfileToEntries(const CharacteristicProfile & profile,std::map<std::string,std::string> & values,bool isMultiUser)453 int32_t ProfileUtils::CharacteristicProfileToEntries(const CharacteristicProfile& profile,
454     std::map<std::string, std::string>& values, bool isMultiUser)
455 {
456     std::string serviceName = CheckAndAddOhSuffix(profile.GetServiceName(), true);
457     std::string charProfileKey = GenerateCharProfileKey(profile.GetDeviceId(), serviceName,
458         profile.GetCharacteristicKey());
459     if (isMultiUser) {
460         values[GenerateDBKey(charProfileKey, CHARACTERISTIC_KEY, profile.GetUserId())] =
461             profile.GetCharacteristicKey();
462         values[GenerateDBKey(charProfileKey, CHARACTERISTIC_VALUE, profile.GetUserId())] =
463             profile.GetCharacteristicValue();
464     } else {
465         values[GenerateDBKey(charProfileKey, CHARACTERISTIC_KEY)] = profile.GetCharacteristicKey();
466         values[GenerateDBKey(charProfileKey, CHARACTERISTIC_VALUE)] = profile.GetCharacteristicValue();
467     }
468     return DP_SUCCESS;
469 }
470 
EntriesToTrustDeviceProfile(const ValuesBucket & values,TrustDeviceProfile & profile)471 int32_t ProfileUtils::EntriesToTrustDeviceProfile(const ValuesBucket& values, TrustDeviceProfile& profile)
472 {
473     ValueObject valueObject;
474     std::string strValue = "";
475     int32_t intValue = 0;
476     if (values.GetObject(DEVICE_ID, valueObject) && valueObject.GetString(strValue) == NativeRdb::E_OK) {
477         profile.SetDeviceId(strValue);
478     }
479     if (values.GetObject(DEVICE_ID_HASH, valueObject) && valueObject.GetString(strValue) == NativeRdb::E_OK) {
480         profile.SetDeviceIdHash(strValue);
481     }
482     if (values.GetObject(DEVICE_TYPE_ID, valueObject) && valueObject.GetInt(intValue) == NativeRdb::E_OK) {
483         profile.SetDeviceIdType(intValue);
484     }
485     if (values.GetObject(STATUS, valueObject) && valueObject.GetInt(intValue) == NativeRdb::E_OK) {
486         profile.SetStatus(intValue);
487     }
488     return DP_SUCCESS;
489 }
490 
EntriesToAccessControlProfile(const ValuesBucket & values,AccessControlProfile & profile)491 int32_t ProfileUtils::EntriesToAccessControlProfile(const ValuesBucket& values, AccessControlProfile& profile)
492 {
493     std::string strValue = "";
494     int32_t intValue = 0;
495     int64_t int64Value = 0;
496     if (GetLongValue(values, ACCESS_CONTROL_ID, int64Value)) {
497         profile.SetAccessControlId(int64Value);
498     }
499     if (GetLongValue(values, ACCESSER_ID, int64Value)) {
500         profile.SetAccesserId(int64Value);
501     }
502     if (GetLongValue(values, ACCESSEE_ID, int64Value)) {
503         profile.SetAccesseeId(int64Value);
504     }
505     if (GetStringValue(values, SESSION_KEY, strValue)) {
506         profile.SetSessionKey(strValue);
507     }
508     if (GetIntValue(values, BIND_TYPE, intValue)) {
509         profile.SetBindType(intValue);
510     }
511     if (GetIntValue(values, AUTHENTICATION_TYPE, intValue)) {
512         profile.SetAuthenticationType(intValue);
513     }
514     if (GetIntValue(values, BIND_LEVEL, intValue)) {
515         profile.SetBindLevel(intValue);
516     }
517     if (GetIntValue(values, STATUS, intValue)) {
518         profile.SetStatus(intValue);
519     }
520     if (GetLongValue(values, VALID_PERIOD, int64Value)) {
521         profile.SetValidPeriod(int64Value);
522     }
523     if (GetLongValue(values, LAST_AUTH_TIME, int64Value)) {
524         profile.SetLastAuthTime(int64Value);
525     }
526     if (GetStringValue(values, TRUST_DEVICE_ID, strValue)) {
527         profile.SetTrustDeviceId(strValue);
528     }
529     if (GetIntValue(values, DEVICE_TYPE_ID, intValue)) {
530         profile.SetDeviceIdType(intValue);
531     }
532     if (GetStringValue(values, DEVICE_ID_HASH, strValue)) {
533         profile.SetDeviceIdHash(strValue);
534     }
535     if (GetStringValue(values, EXTRA_DATA, strValue)) {
536         profile.SetExtraData(strValue);
537     }
538     return DP_SUCCESS;
539 }
540 
EntriesToAccesser(const ValuesBucket & values,Accesser & accesser)541 int32_t ProfileUtils::EntriesToAccesser(const ValuesBucket& values, Accesser& accesser)
542 {
543     ValueObject valueObject;
544     std::string strValue = "";
545     int32_t intValue = 0;
546     int64_t int64Value = 0;
547     if (values.GetObject(ACCESSER_ID, valueObject) && valueObject.GetLong(int64Value) == NativeRdb::E_OK) {
548         accesser.SetAccesserId(int64Value);
549     }
550     if (values.GetObject(ACCESSER_DEVICE_ID, valueObject) && valueObject.GetString(strValue) == NativeRdb::E_OK) {
551         accesser.SetAccesserDeviceId(strValue);
552     }
553     if (values.GetObject(ACCESSER_USER_ID, valueObject) && valueObject.GetInt(intValue) == NativeRdb::E_OK) {
554         accesser.SetAccesserUserId(intValue);
555     }
556     if (values.GetObject(ACCESSER_ACCOUNT_ID, valueObject) && valueObject.GetString(strValue) == NativeRdb::E_OK) {
557         accesser.SetAccesserAccountId(strValue);
558     }
559     if (values.GetObject(ACCESSER_TOKEN_ID, valueObject) && valueObject.GetLong(int64Value) == NativeRdb::E_OK) {
560         accesser.SetAccesserTokenId(int64Value);
561     }
562     if (values.GetObject(ACCESSER_BUNDLE_NAME, valueObject) && valueObject.GetString(strValue) == NativeRdb::E_OK) {
563         accesser.SetAccesserBundleName(strValue);
564     }
565     if (values.GetObject(ACCESSER_BIND_LEVEL, valueObject) && valueObject.GetInt(intValue) == NativeRdb::E_OK) {
566         accesser.SetAccesserBindLevel(intValue);
567     }
568     EntriesToAccesserExt(values, accesser);
569     return DP_SUCCESS;
570 }
571 
EntriesToAccessee(const ValuesBucket & values,Accessee & accessee)572 int32_t ProfileUtils::EntriesToAccessee(const ValuesBucket& values, Accessee& accessee)
573 {
574     ValueObject valueObject;
575     std::string strValue = "";
576     int32_t intValue = 0;
577     int64_t int64Value = 0;
578     if (values.GetObject(ACCESSEE_ID, valueObject) && valueObject.GetLong(int64Value) == NativeRdb::E_OK) {
579         accessee.SetAccesseeId(int64Value);
580     }
581     if (values.GetObject(ACCESSEE_DEVICE_ID, valueObject) && valueObject.GetString(strValue) == NativeRdb::E_OK) {
582         accessee.SetAccesseeDeviceId(strValue);
583     }
584     if (values.GetObject(ACCESSEE_USER_ID, valueObject) && valueObject.GetInt(intValue) == NativeRdb::E_OK) {
585         accessee.SetAccesseeUserId(intValue);
586     }
587     if (values.GetObject(ACCESSEE_ACCOUNT_ID, valueObject) && valueObject.GetString(strValue) == NativeRdb::E_OK) {
588         accessee.SetAccesseeAccountId(strValue);
589     }
590     if (values.GetObject(ACCESSEE_TOKEN_ID, valueObject) && valueObject.GetLong(int64Value) == NativeRdb::E_OK) {
591         accessee.SetAccesseeTokenId(int64Value);
592     }
593     if (values.GetObject(ACCESSEE_BUNDLE_NAME, valueObject) && valueObject.GetString(strValue) == NativeRdb::E_OK) {
594         accessee.SetAccesseeBundleName(strValue);
595     }
596     if (values.GetObject(ACCESSEE_BIND_LEVEL, valueObject) && valueObject.GetInt(intValue) == NativeRdb::E_OK) {
597         accessee.SetAccesseeBindLevel(intValue);
598     }
599     EntriesToAccesseeExt(values, accessee);
600     return DP_SUCCESS;
601 }
602 
EntriesToAccesserExt(const ValuesBucket & values,Accesser & accesser)603 int32_t ProfileUtils::EntriesToAccesserExt(const ValuesBucket &values, Accesser &accesser)
604 {
605     ValueObject valueObject;
606     std::string strValue = "";
607     int32_t intValue = 0;
608     int64_t int64Value = 0;
609     if (values.GetObject(ACCESSER_DEVICE_NAME, valueObject) && valueObject.GetString(strValue) == NativeRdb::E_OK) {
610         accesser.SetAccesserDeviceName(strValue);
611     }
612     if (values.GetObject(ACCESSER_SERVICE_NAME, valueObject) && valueObject.GetString(strValue) == NativeRdb::E_OK) {
613         accesser.SetAccesserServiceName(strValue);
614     }
615     if (values.GetObject(ACCESSER_CREDENTIAL_ID, valueObject) && valueObject.GetInt(intValue) == NativeRdb::E_OK) {
616         accesser.SetAccesserCredentialId(intValue);
617     }
618     if (values.GetObject(ACCESSER_CREDENTIAL_ID_STR, valueObject) &&
619         valueObject.GetString(strValue) == NativeRdb::E_OK) {
620         accesser.SetAccesserCredentialIdStr(strValue);
621     }
622     if (values.GetObject(ACCESSER_STATUS, valueObject) && valueObject.GetInt(intValue) == NativeRdb::E_OK) {
623         accesser.SetAccesserStatus(intValue);
624     }
625     if (values.GetObject(ACCESSER_SESSION_KEY_ID, valueObject) && valueObject.GetInt(intValue) == NativeRdb::E_OK) {
626         accesser.SetAccesserSessionKeyId(intValue);
627     }
628     if (values.GetObject(ACCESSER_SESSION_KEY_TIMESTAMP, valueObject) &&
629         valueObject.GetLong(int64Value) == NativeRdb::E_OK) {
630         accesser.SetAccesserSKTimeStamp(int64Value);
631     }
632     if (values.GetObject(ACCESSER_EXTRA_DATA, valueObject) && valueObject.GetString(strValue) == NativeRdb::E_OK) {
633         accesser.SetAccesserExtraData(strValue);
634     }
635     return DP_SUCCESS;
636 }
637 
EntriesToAccesseeExt(const ValuesBucket & values,Accessee & accessee)638 int32_t ProfileUtils::EntriesToAccesseeExt(const ValuesBucket &values, Accessee &accessee)
639 {
640     ValueObject valueObject;
641     std::string strValue = "";
642     int32_t intValue = 0;
643     int64_t int64Value = 0;
644     if (values.GetObject(ACCESSEE_DEVICE_NAME, valueObject) && valueObject.GetString(strValue) == NativeRdb::E_OK) {
645         accessee.SetAccesseeDeviceName(strValue);
646     }
647     if (values.GetObject(ACCESSEE_SERVICE_NAME, valueObject) && valueObject.GetString(strValue) == NativeRdb::E_OK) {
648         accessee.SetAccesseeServiceName(strValue);
649     }
650     if (values.GetObject(ACCESSEE_CREDENTIAL_ID, valueObject) && valueObject.GetInt(intValue) == NativeRdb::E_OK) {
651         accessee.SetAccesseeCredentialId(intValue);
652     }
653     if (values.GetObject(ACCESSEE_CREDENTIAL_ID_STR, valueObject) &&
654         valueObject.GetString(strValue) == NativeRdb::E_OK) {
655         accessee.SetAccesseeCredentialIdStr(strValue);
656     }
657     if (values.GetObject(ACCESSEE_STATUS, valueObject) && valueObject.GetInt(intValue) == NativeRdb::E_OK) {
658         accessee.SetAccesseeStatus(intValue);
659     }
660     if (values.GetObject(ACCESSEE_SESSION_KEY_ID, valueObject) && valueObject.GetInt(intValue) == NativeRdb::E_OK) {
661         accessee.SetAccesseeSessionKeyId(intValue);
662     }
663     if (values.GetObject(ACCESSEE_SESSION_KEY_TIMESTAMP, valueObject) &&
664         valueObject.GetLong(int64Value) == NativeRdb::E_OK) {
665         accessee.SetAccesseeSKTimeStamp(int64Value);
666     }
667     if (values.GetObject(ACCESSEE_EXTRA_DATA, valueObject) && valueObject.GetString(strValue) == NativeRdb::E_OK) {
668         accessee.SetAccesseeExtraData(strValue);
669     }
670     return DP_SUCCESS;
671 }
672 
EntriesToDeviceProfile(std::map<std::string,std::string> values,DeviceProfile & profile)673 int32_t ProfileUtils::EntriesToDeviceProfile(std::map<std::string, std::string> values, DeviceProfile& profile)
674 {
675     if (values.empty() || values.size() > MAX_DB_RECORD_SIZE) {
676         HILOGI("Entries size is invalid!size: %{public}zu!", values.size());
677         return DP_INVALID_PARAMS;
678     }
679     auto propertiesMap = GetProfilePropertiesMap(values, profile.GetUserId());
680     if (IsPropertyValid(propertiesMap, OS_SYS_CAPACITY, MAX_STRING_LEN)) {
681         profile.SetOsSysCap(propertiesMap[OS_SYS_CAPACITY]);
682     }
683     if (IsPropertyValid(propertiesMap, OS_VERSION, MAX_STRING_LEN)) {
684         profile.SetOsVersion(propertiesMap[OS_VERSION]);
685     }
686     if (IsPropertyValid(propertiesMap, OS_VERSION + OH_PROFILE_SUFFIX, MAX_STRING_LEN)) {
687         profile.SetOsVersion(propertiesMap[OS_VERSION + OH_PROFILE_SUFFIX]);
688     }
689     if (IsPropertyValid(propertiesMap, OS_TYPE, MIN_OS_TYPE, MAX_OS_TYPE)) {
690         int32_t osType = std::atoi(propertiesMap[OS_TYPE].c_str());
691         profile.SetOsType(osType);
692     }
693     if (IsPropertyValid(propertiesMap, OS_TYPE + OH_PROFILE_SUFFIX, MIN_OS_TYPE, MAX_OS_TYPE)) {
694         int32_t osType = std::atoi(propertiesMap[OS_TYPE + OH_PROFILE_SUFFIX].c_str());
695         profile.SetOsType(osType);
696     }
697     return DP_SUCCESS;
698 }
699 
EntriesToServiceProfile(std::map<std::string,std::string> values,ServiceProfile & profile)700 int32_t ProfileUtils::EntriesToServiceProfile(std::map<std::string, std::string> values, ServiceProfile& profile)
701 {
702     if (values.empty() || values.size() > MAX_DB_RECORD_SIZE) {
703         HILOGI("Entries size is invalid!size: %{public}zu!", values.size());
704         return DP_INVALID_PARAMS;
705     }
706     auto iter = values.begin();
707     profile.SetDeviceId(GetDeviceIdByDBKey(iter->first));
708     auto propertiesMap = GetProfilePropertiesMap(values, profile.GetUserId());
709     if (propertiesMap.count(SERVICE_NAME) != 0 && 0 < propertiesMap[SERVICE_NAME].length() &&
710         propertiesMap[SERVICE_NAME].length() < MAX_STRING_LEN) {
711         profile.SetServiceName(CheckAndRemoveOhSuffix(propertiesMap[SERVICE_NAME]));
712     }
713     if (propertiesMap.count(SERVICE_TYPE) != 0 && 0 < propertiesMap[SERVICE_TYPE].length() &&
714         propertiesMap[SERVICE_TYPE].length() < MAX_STRING_LEN) {
715         profile.SetServiceType(propertiesMap[SERVICE_TYPE]);
716     }
717     return DP_SUCCESS;
718 }
719 
EntriesToCharProfile(std::map<std::string,std::string> values,CharacteristicProfile & profile)720 int32_t ProfileUtils::EntriesToCharProfile(std::map<std::string, std::string> values, CharacteristicProfile& profile)
721 {
722     if (values.empty() || values.size() > MAX_DB_RECORD_SIZE) {
723         HILOGI("Entries size is invalid!size : %{public}zu", values.size());
724         return DP_INVALID_PARAMS;
725     }
726     auto iter = values.begin();
727     profile.SetDeviceId(GetDeviceIdByDBKey(iter->first));
728     profile.SetServiceName(GetNonOhSuffixServiceNameByDBKey(iter->first));
729     auto propertiesMap = GetProfilePropertiesMap(values, profile.GetUserId());
730     if (propertiesMap.count(CHARACTERISTIC_KEY) != 0 && 0 < propertiesMap[CHARACTERISTIC_KEY].length() &&
731         propertiesMap[CHARACTERISTIC_KEY].length() < MAX_STRING_LEN) {
732         profile.SetCharacteristicKey(propertiesMap[CHARACTERISTIC_KEY]);
733     }
734     if (propertiesMap.count(CHARACTERISTIC_VALUE) != 0 && 0 < propertiesMap[CHARACTERISTIC_VALUE].length() &&
735         propertiesMap[CHARACTERISTIC_VALUE].length() < MAX_STRING_LEN) {
736         profile.SetCharacteristicValue(propertiesMap[CHARACTERISTIC_VALUE]);
737     }
738     return DP_SUCCESS;
739 }
740 
GenerateDBKey(const std::string & profileKey,const std::string & profileProperty,int32_t userId)741 std::string ProfileUtils::GenerateDBKey(const std::string& profileKey, const std::string& profileProperty,
742     int32_t userId)
743 {
744     std::string DBKey = "";
745     if (userId != DEFAULT_USER_ID) {
746         DBKey = profileKey + SEPARATOR + profileProperty + SEPARATOR + std::to_string(userId);
747     } else {
748         DBKey = profileKey + SEPARATOR + profileProperty;
749     }
750     return DBKey;
751 }
752 
GetProfileProperty(const std::string & dbKey,int32_t userId)753 std::string ProfileUtils::GetProfileProperty(const std::string& dbKey, int32_t userId)
754 {
755     if (dbKey.length() == 0 || dbKey.length() > MAX_STRING_LEN) {
756         return "";
757     }
758     int32_t getUserId = GetUserIdFromDbKey(dbKey);
759     std::vector<std::string> splitKeys;
760     if (SplitString(dbKey, SEPARATOR, splitKeys) != DP_SUCCESS || splitKeys.size() < NUM_3) {
761         HILOGE("GetProfileProperty SplitString fail");
762         return "";
763     }
764 
765     if (splitKeys[0] == DEV_PREFIX) {
766         if (userId != DEFAULT_USER_ID && getUserId == DEFAULT_USER_ID) {
767             return splitKeys[NUM_2];
768         }
769         return (userId == getUserId) ? splitKeys[NUM_2] : "";
770     }
771     if (splitKeys[0] == SVR_PREFIX && splitKeys.size() >= NUM_4) {
772         if (userId != DEFAULT_USER_ID && getUserId == DEFAULT_USER_ID) {
773             return splitKeys[NUM_3];
774         }
775         return (userId == getUserId) ? splitKeys[NUM_3] : "";
776     }
777     if (splitKeys[0] == CHAR_PREFIX && splitKeys.size() >= NUM_5) {
778         if (userId != DEFAULT_USER_ID && getUserId == DEFAULT_USER_ID) {
779             return splitKeys[NUM_4];
780         }
781         return (userId == getUserId) ? splitKeys[NUM_4] : "";
782     }
783 
784     HILOGE("dbKey has wrong prefix");
785     return "";
786 }
787 
GetProfilePropertiesMap(std::map<std::string,std::string> dbEntries,int32_t userId)788 std::map<std::string, std::string> ProfileUtils::GetProfilePropertiesMap(std::map<std::string, std::string> dbEntries,
789     int32_t userId)
790 {
791     std::map<std::string, std::string> propertiesWithoutUserId;
792     std::map<std::string, std::string> propertiesWithUserId;
793     if (userId <= 0 && userId != DEFAULT_USER_ID) {
794         HILOGE("userId is invalid, userId: %{public}s", GetAnonyInt32(userId).c_str());
795         return propertiesWithoutUserId;
796     }
797     for (const auto& item : dbEntries) {
798         std::string profileProperty = GetProfileProperty(item.first, userId);
799         if (profileProperty.empty()) {
800             HILOGE("GetProfileProperty fail, %{public}s!", GetDbKeyAnonyString(item.first).c_str());
801             continue;
802         }
803         if (GetUserIdFromDbKey(item.first) == DEFAULT_USER_ID) {
804             propertiesWithoutUserId[profileProperty] = item.second;
805             continue;
806         }
807         propertiesWithUserId[profileProperty] = item.second;
808     }
809 
810     if (userId != DEFAULT_USER_ID && !propertiesWithUserId.empty()) {
811         HILOGI("GetProfile with multi-user");
812         return propertiesWithUserId;
813     }
814 
815     //1. Get profile without multi-user;
816     //2. Get profile with multi-user, but remote device without multi-user;
817     //3. Get profile with multi-user, but can't find in DB;
818     return propertiesWithoutUserId;
819 }
820 
toString(const std::u16string & str16)821 std::string ProfileUtils::toString(const std::u16string& str16)
822 {
823     return std::wstring_convert< std::codecvt_utf8_utf16<char16_t>, char16_t >{}.to_bytes(str16);
824 }
825 
IsPropertyValid(const std::map<std::string,std::string> & propertyMap,const std::string & property,int32_t maxValue)826 bool ProfileUtils::IsPropertyValid(const std::map<std::string, std::string>& propertyMap, const std::string& property,
827     int32_t maxValue)
828 {
829     if (propertyMap.count(property) != 0 && 0 < propertyMap.at(property).length() &&
830         (static_cast<int32_t>(propertyMap.at(property).length())) < maxValue) {
831         return true;
832     }
833     HILOGE("property is valid, property : %{public}s", property.c_str());
834     return false;
835 }
836 
IsPropertyValid(const std::map<std::string,std::string> & propertyMap,const std::string & property,int32_t minValue,int32_t maxValue)837 bool ProfileUtils::IsPropertyValid(const std::map<std::string, std::string>& propertyMap, const std::string& property,
838     int32_t minValue, int32_t maxValue)
839 {
840     if (property.empty() || propertyMap.find(property) == propertyMap.end()) {
841         return false;
842     }
843     std::string propertyValue = propertyMap.at(property);
844     if (!IsNumStr(propertyValue)) {
845         HILOGE("%{public}s is not numeric string", GetAnonyString(propertyValue).c_str());
846         return false;
847     }
848     if (minValue < std::atoi(propertyValue.c_str()) && std::atoi(propertyValue.c_str()) < maxValue) {
849         return true;
850     }
851     return false;
852 }
853 
IsPropertyValidInt64(const std::map<std::string,std::string> & propertyMap,const std::string & property)854 bool ProfileUtils::IsPropertyValidInt64(const std::map<std::string,
855     std::string>& propertyMap, const std::string& property)
856 {
857     if (property.empty() || propertyMap.find(property) == propertyMap.end()) {
858         return false;
859     }
860     std::string propertyValue = propertyMap.at(property);
861     if (!IsNumStr(propertyValue)) {
862         HILOGE("%{public}s is not numeric string", GetAnonyString(propertyValue).c_str());
863         return false;
864     }
865     if (INT64_MIN < std::atoll(propertyValue.c_str()) && std::atoll(propertyValue.c_str()) < INT64_MAX) {
866         return true;
867     }
868     return false;
869 }
870 
IsNumStr(const std::string & inString)871 bool ProfileUtils::IsNumStr(const std::string& inString)
872 {
873     if (inString.empty()) {
874         HILOGE("inString is empty");
875         return false;
876     }
877     std::regex isNumStrRule(IS_NUMSTRING_RULES);
878     return std::regex_match(inString, isNumStrRule);
879 }
880 
GetIntValue(const ValuesBucket & values,const std::string & property,int32_t & value)881 bool ProfileUtils::GetIntValue(const ValuesBucket& values, const std::string& property, int32_t& value)
882 {
883     ValueObject valueObject;
884     if (values.GetObject(property, valueObject) && valueObject.GetInt(value) == NativeRdb::E_OK) {
885         return true;
886     }
887     return false;
888 }
889 
GetStringValue(const ValuesBucket & values,const std::string & property,std::string & value)890 bool ProfileUtils::GetStringValue(const ValuesBucket& values, const std::string& property, std::string& value)
891 {
892     ValueObject valueObject;
893     if (values.GetObject(property, valueObject) && valueObject.GetString(value) == NativeRdb::E_OK) {
894         return true;
895     }
896     return false;
897 }
898 
GetLongValue(const ValuesBucket & values,const std::string & property,int64_t & value)899 bool ProfileUtils::GetLongValue(const ValuesBucket& values, const std::string& property, int64_t& value)
900 {
901     ValueObject valueObject;
902     if (values.GetObject(property, valueObject) && valueObject.GetLong(value) == NativeRdb::E_OK) {
903         return true;
904     }
905     return false;
906 }
907 
GetDbKeyByProfile(const CharacteristicProfile & profile)908 std::string ProfileUtils::GetDbKeyByProfile(const CharacteristicProfile& profile)
909 {
910     if (profile.GetDeviceId().empty() ||
911         profile.GetServiceName().empty() ||
912         profile.GetCharacteristicKey().empty()) {
913         HILOGE("GetDbKeyByProfile fail");
914         return "";
915     }
916     std::string serviceName = CheckAndAddOhSuffix(profile.GetServiceName(), true);
917     std::string dbKey = CHAR_PREFIX + SEPARATOR + profile.GetDeviceId() + SEPARATOR + serviceName +
918         SEPARATOR + profile.GetCharacteristicKey() + SEPARATOR + CHARACTERISTIC_VALUE;
919     return dbKey;
920 }
921 
GetUserIdFromDbKey(const std::string & dbKey)922 int32_t ProfileUtils::GetUserIdFromDbKey(const std::string& dbKey)
923 {
924     int32_t userId = DEFAULT_USER_ID;
925     std::vector<std::string> splitKeys;
926     if (SplitString(dbKey, SEPARATOR, splitKeys) != DP_SUCCESS || splitKeys.size() < NUM_3) {
927         HILOGE("SplitString fail");
928         return userId;
929     }
930     if (splitKeys[0] == DEV_PREFIX && splitKeys.size() > NUM_3 && IsNumStr(splitKeys[NUM_3])) {
931         userId = std::atoi(splitKeys[NUM_3].c_str());
932     }
933     if (splitKeys[0] == SVR_PREFIX && splitKeys.size() > NUM_4 && IsNumStr(splitKeys[NUM_4])) {
934         userId = std::atoi(splitKeys[NUM_4].c_str());
935     }
936     if (splitKeys[0] == CHAR_PREFIX && splitKeys.size() > NUM_5 && IsNumStr(splitKeys[NUM_5])) {
937         userId = std::atoi(splitKeys[NUM_5].c_str());
938     }
939     return userId;
940 }
941 
RemoveUserIdFromDbKey(const std::string & dbKey)942 std::string ProfileUtils::RemoveUserIdFromDbKey(const std::string& dbKey)
943 {
944     std::vector<std::string> splitKeys;
945     if (SplitString(dbKey, SEPARATOR, splitKeys) != DP_SUCCESS || splitKeys.size() < NUM_3) {
946         HILOGE("SplitString fail");
947         return EMPTY_STRING;
948     }
949     if (splitKeys[0] == DEV_PREFIX && splitKeys.size() > NUM_3 && IsNumStr(splitKeys[NUM_3])) {
950         splitKeys.erase(splitKeys.begin() + NUM_3);
951     }
952     if (splitKeys[0] == SVR_PREFIX && splitKeys.size() > NUM_4 && IsNumStr(splitKeys[NUM_4])) {
953         splitKeys.erase(splitKeys.begin() + NUM_4);
954     }
955     if (splitKeys[0] == CHAR_PREFIX && splitKeys.size() > NUM_5 && IsNumStr(splitKeys[NUM_5])) {
956         splitKeys.erase(splitKeys.begin() + NUM_5);
957     }
958     std::string dbKeyWithoutUserId = JoinString(splitKeys, SEPARATOR);
959     if (dbKeyWithoutUserId.empty()) {
960         HILOGE("JoinString fail");
961         return EMPTY_STRING;
962     }
963     return dbKeyWithoutUserId;
964 }
965 
GenerateServiceDBkeys(const std::string & deviceId,const std::string & serviceName,std::vector<std::string> & dbKeys,bool isMultiUser,int32_t userId)966 int32_t ProfileUtils::GenerateServiceDBkeys(const std::string& deviceId, const std::string& serviceName,
967     std::vector<std::string>& dbKeys, bool isMultiUser, int32_t userId)
968 {
969     std::string localServiceName = CheckAndAddOhSuffix(serviceName, true);
970     std::string serviceProfileKey = GenerateServiceProfileKey(deviceId, localServiceName);
971     // value not need add OH suffix
972     if (isMultiUser) {
973         dbKeys.emplace_back(GenerateDBKey(serviceProfileKey, SERVICE_NAME, userId));
974         dbKeys.emplace_back(GenerateDBKey(serviceProfileKey, SERVICE_TYPE, userId));
975     } else {
976         dbKeys.emplace_back(GenerateDBKey(serviceProfileKey, SERVICE_NAME));
977         dbKeys.emplace_back(GenerateDBKey(serviceProfileKey, SERVICE_TYPE));
978     }
979     return DP_SUCCESS;
980 }
981 
GenerateCharacteristicDBkeys(const std::string & deviceId,const std::string & serviceName,const std::string & characteristicKey,std::vector<std::string> & dbKeys,bool isMultiUser,int32_t userId)982 int32_t ProfileUtils::GenerateCharacteristicDBkeys(const std::string& deviceId, const std::string& serviceName,
983     const std::string& characteristicKey, std::vector<std::string>& dbKeys, bool isMultiUser, int32_t userId)
984 {
985     std::string localServiceName = CheckAndAddOhSuffix(serviceName, true);
986     std::string charProfileKey = GenerateCharProfileKey(deviceId, localServiceName, characteristicKey);
987     if (isMultiUser) {
988         dbKeys.emplace_back(GenerateDBKey(charProfileKey, CHARACTERISTIC_KEY, userId));
989         dbKeys.emplace_back(GenerateDBKey(charProfileKey, CHARACTERISTIC_VALUE, userId));
990     } else {
991         dbKeys.emplace_back(GenerateDBKey(charProfileKey, CHARACTERISTIC_KEY));
992         dbKeys.emplace_back(GenerateDBKey(charProfileKey, CHARACTERISTIC_VALUE));
993     }
994     return DP_SUCCESS;
995 }
996 
ConvertToTrustDeviceProfile(const AccessControlProfile & accessControlProfile,TrustDeviceProfile & trustDeviceProfile)997 int32_t ProfileUtils::ConvertToTrustDeviceProfile(
998     const AccessControlProfile& accessControlProfile, TrustDeviceProfile& trustDeviceProfile)
999 {
1000     trustDeviceProfile.SetDeviceId(accessControlProfile.GetTrustDeviceId());
1001     trustDeviceProfile.SetDeviceIdType(accessControlProfile.GetDeviceIdType());
1002     trustDeviceProfile.SetDeviceIdHash(accessControlProfile.GetDeviceIdHash());
1003     trustDeviceProfile.SetStatus(accessControlProfile.GetStatus());
1004     trustDeviceProfile.SetBindType(accessControlProfile.GetBindType());
1005     std::string peerDeviceId = accessControlProfile.GetTrustDeviceId();
1006     int32_t peerUserId = accessControlProfile.GetAccesser().GetAccesserUserId();
1007     int32_t localUserId = accessControlProfile.GetAccessee().GetAccesseeUserId();
1008     if (accessControlProfile.GetAccessee().GetAccesseeDeviceId() == peerDeviceId) {
1009         peerUserId = accessControlProfile.GetAccessee().GetAccesseeUserId();
1010         localUserId = accessControlProfile.GetAccesser().GetAccesserUserId();
1011     }
1012     trustDeviceProfile.SetPeerUserId(peerUserId);
1013     trustDeviceProfile.SetLocalUserId(localUserId);
1014     return DP_SUCCESS;
1015 }
1016 
ConvertToAccessControlProfiles(std::shared_ptr<ResultSet> resultSet,std::shared_ptr<ResultSet> accesserResultSet,std::shared_ptr<ResultSet> accesseeResultSet,std::vector<AccessControlProfile> & profile)1017 int32_t ProfileUtils::ConvertToAccessControlProfiles(std::shared_ptr<ResultSet> resultSet,
1018     std::shared_ptr<ResultSet> accesserResultSet, std::shared_ptr<ResultSet> accesseeResultSet,
1019     std::vector<AccessControlProfile>& profile)
1020 {
1021     if (accesserResultSet == nullptr) {
1022         HILOGE("accesserResultSet is nullptr");
1023         return DP_GET_RESULTSET_FAIL;
1024     }
1025     if (accesseeResultSet == nullptr) {
1026         HILOGE("accesseeResultSet is nullptr");
1027         return DP_GET_RESULTSET_FAIL;
1028     }
1029     Accesser accesser;
1030     accesserResultSet->GoToNextRow();
1031     ConvertToAccesser(accesserResultSet, accesser);
1032     Accessee accessee;
1033     accesseeResultSet->GoToNextRow();
1034     ConvertToAccessee(accesseeResultSet, accessee);
1035     if (resultSet == nullptr) {
1036         HILOGE("resultSet is nullptr");
1037         return DP_GET_RESULTSET_FAIL;
1038     }
1039     AccessControlProfile accessControlProfile;
1040     ConvertToAccessControlProfile(resultSet, accessControlProfile);
1041 
1042     accessControlProfile.SetAccesser(accesser);
1043     accessControlProfile.SetAccessee(accessee);
1044     profile.push_back(accessControlProfile);
1045     return DP_SUCCESS;
1046 }
1047 
ConvertToTrustDeviceProfile(std::shared_ptr<ResultSet> trustResultSet,TrustDeviceProfile & trustDeviceProfile)1048 int32_t ProfileUtils::ConvertToTrustDeviceProfile(
1049     std::shared_ptr<ResultSet> trustResultSet, TrustDeviceProfile& trustDeviceProfile)
1050 {
1051     if (trustResultSet == nullptr) {
1052         HILOGE("trustResultSet is nullptr");
1053         return DP_GET_RESULTSET_FAIL;
1054     }
1055     RowEntity rowEntity;
1056     if (trustResultSet->GetRow(rowEntity) != DP_SUCCESS) {
1057         HILOGE("get trustResultSet failed");
1058         return DP_GET_RESULTSET_FAIL;
1059     }
1060     std::string deviceId = rowEntity.Get(DEVICE_ID);
1061     int32_t deviceIdType = rowEntity.Get(DEVICE_ID_TYPE);
1062     std::string deviceIdHash = rowEntity.Get(DEVICE_ID_HASH);
1063     int32_t status = rowEntity.Get(STATUS);
1064 
1065     trustDeviceProfile.SetDeviceId(deviceId);
1066     trustDeviceProfile.SetDeviceIdType(deviceIdType);
1067     trustDeviceProfile.SetDeviceIdHash(deviceIdHash);
1068     trustDeviceProfile.SetStatus(status);
1069     return DP_SUCCESS;
1070 }
1071 
ConvertToAccesser(std::shared_ptr<ResultSet> accesserResultSet,Accesser & accesser)1072 int32_t ProfileUtils::ConvertToAccesser(std::shared_ptr<ResultSet> accesserResultSet,
1073     Accesser& accesser)
1074 {
1075     if (accesserResultSet == nullptr) {
1076         HILOGE("accesserResultSet is nullptr");
1077         return DP_GET_RESULTSET_FAIL;
1078     }
1079     RowEntity rowEntity;
1080     if (accesserResultSet->GetRow(rowEntity) != DP_SUCCESS) {
1081         HILOGE("get accesserResultSet failed");
1082         return DP_GET_RESULTSET_FAIL;
1083     }
1084     int64_t accesserId = rowEntity.Get(ACCESSER_ID);
1085     std::string accesserDeviceId = rowEntity.Get(ACCESSER_DEVICE_ID);
1086     int32_t accesserUserId = rowEntity.Get(ACCESSER_USER_ID);
1087     std::string accesserAccountId = rowEntity.Get(ACCESSER_ACCOUNT_ID);
1088     int64_t accesserTokenId = rowEntity.Get(ACCESSER_TOKEN_ID);
1089     std::string accesserBundleName = rowEntity.Get(ACCESSER_BUNDLE_NAME);
1090     std::string accesserHapSignature = rowEntity.Get(ACCESSER_HAP_SIGNATURE);
1091     int32_t accesserBindLevel = rowEntity.Get(ACCESSER_BIND_LEVEL);
1092     std::string accesserDeviceName = rowEntity.Get(ACCESSER_DEVICE_NAME);
1093     std::string accesserServiceName = rowEntity.Get(ACCESSER_SERVICE_NAME);
1094     int32_t accesserCredentialId = rowEntity.Get(ACCESSER_CREDENTIAL_ID);
1095     std::string accesserCredentialIdStr = rowEntity.Get(ACCESSER_CREDENTIAL_ID_STR);
1096     int32_t accesserStatus = rowEntity.Get(ACCESSER_STATUS);
1097     int32_t accesserSessionKeyId = rowEntity.Get(ACCESSER_SESSION_KEY_ID);
1098     int64_t accesserSKTimeStamp = rowEntity.Get(ACCESSER_SESSION_KEY_TIMESTAMP);
1099     std::string accesserExtraData = rowEntity.Get(ACCESSER_EXTRA_DATA);
1100 
1101     accesser.SetAccesserId(accesserId);
1102     accesser.SetAccesserDeviceId(accesserDeviceId);
1103     accesser.SetAccesserUserId(accesserUserId);
1104     accesser.SetAccesserAccountId(accesserAccountId);
1105     accesser.SetAccesserTokenId(accesserTokenId);
1106     accesser.SetAccesserBundleName(accesserBundleName);
1107     accesser.SetAccesserHapSignature(accesserHapSignature);
1108     accesser.SetAccesserBindLevel(accesserBindLevel);
1109     accesser.SetAccesserDeviceName(accesserDeviceName);
1110     accesser.SetAccesserServiceName(accesserServiceName);
1111     accesser.SetAccesserCredentialId(accesserCredentialId);
1112     accesser.SetAccesserCredentialIdStr(accesserCredentialIdStr);
1113     accesser.SetAccesserStatus(accesserStatus);
1114     accesser.SetAccesserSessionKeyId(accesserSessionKeyId);
1115     accesser.SetAccesserSKTimeStamp(accesserSKTimeStamp);
1116     accesser.SetAccesserExtraData(accesserExtraData);
1117     return DP_SUCCESS;
1118 }
1119 
ConvertToAccessee(std::shared_ptr<ResultSet> accesseeResultSet,Accessee & accessee)1120 int32_t ProfileUtils::ConvertToAccessee(std::shared_ptr<ResultSet> accesseeResultSet,
1121     Accessee& accessee)
1122 {
1123     if (accesseeResultSet == nullptr) {
1124         HILOGE("accesseeResultSet is nullptr");
1125         return DP_GET_RESULTSET_FAIL;
1126     }
1127     RowEntity rowEntity;
1128     if (accesseeResultSet->GetRow(rowEntity) != DP_SUCCESS) {
1129         HILOGE("get accesseeResultSet failed");
1130         return DP_GET_RESULTSET_FAIL;
1131     }
1132     int64_t accesseeId = rowEntity.Get(ACCESSEE_ID);
1133     std::string accesseeDeviceId = rowEntity.Get(ACCESSEE_DEVICE_ID);
1134     int32_t accesseeUserId = rowEntity.Get(ACCESSEE_USER_ID);
1135     std::string accesseeAccountId = rowEntity.Get(ACCESSEE_ACCOUNT_ID);
1136     int64_t accesseeTokenId = rowEntity.Get(ACCESSEE_TOKEN_ID);
1137     std::string accesseeBundleName = rowEntity.Get(ACCESSEE_BUNDLE_NAME);
1138     std::string accesseeHapSignature = rowEntity.Get(ACCESSEE_HAP_SIGNATURE);
1139     int32_t accesseeBindLevel = rowEntity.Get(ACCESSEE_BIND_LEVEL);
1140     std::string accesseeDeviceName = rowEntity.Get(ACCESSEE_DEVICE_NAME);
1141     std::string accesseeServiceName = rowEntity.Get(ACCESSEE_SERVICE_NAME);
1142     int32_t accesseeCredentialId = rowEntity.Get(ACCESSEE_CREDENTIAL_ID);
1143     std::string accesseeCredentialIdStr = rowEntity.Get(ACCESSEE_CREDENTIAL_ID_STR);
1144     int32_t accesseeStatus = rowEntity.Get(ACCESSEE_STATUS);
1145     int32_t accesseeSessionKeyId = rowEntity.Get(ACCESSEE_SESSION_KEY_ID);
1146     int64_t accesseeSKTimeStamp = rowEntity.Get(ACCESSEE_SESSION_KEY_TIMESTAMP);
1147     std::string accesseeExtraData = rowEntity.Get(ACCESSEE_EXTRA_DATA);
1148 
1149     accessee.SetAccesseeId(accesseeId);
1150     accessee.SetAccesseeDeviceId(accesseeDeviceId);
1151     accessee.SetAccesseeUserId(accesseeUserId);
1152     accessee.SetAccesseeAccountId(accesseeAccountId);
1153     accessee.SetAccesseeTokenId(accesseeTokenId);
1154     accessee.SetAccesseeBundleName(accesseeBundleName);
1155     accessee.SetAccesseeHapSignature(accesseeHapSignature);
1156     accessee.SetAccesseeBindLevel(accesseeBindLevel);
1157     accessee.SetAccesseeDeviceName(accesseeDeviceName);
1158     accessee.SetAccesseeServiceName(accesseeServiceName);
1159     accessee.SetAccesseeCredentialId(accesseeCredentialId);
1160     accessee.SetAccesseeCredentialIdStr(accesseeCredentialIdStr);
1161     accessee.SetAccesseeStatus(accesseeStatus);
1162     accessee.SetAccesseeSessionKeyId(accesseeSessionKeyId);
1163     accessee.SetAccesseeSKTimeStamp(accesseeSKTimeStamp);
1164     accessee.SetAccesseeExtraData(accesseeExtraData);
1165     return DP_SUCCESS;
1166 }
1167 
ConvertToAccessControlProfile(std::shared_ptr<ResultSet> accessControlResultSet,AccessControlProfile & accessControlProfile)1168 int32_t ProfileUtils::ConvertToAccessControlProfile(
1169     std::shared_ptr<ResultSet> accessControlResultSet, AccessControlProfile& accessControlProfile)
1170 {
1171     if (accessControlResultSet == nullptr) {
1172         HILOGE("accessControlResultSet is nullptr");
1173         return DP_GET_RESULTSET_FAIL;
1174     }
1175     RowEntity rowEntity;
1176     if (accessControlResultSet->GetRow(rowEntity) != DP_SUCCESS) {
1177         HILOGE("get accessControlResultSet failed");
1178         return DP_GET_RESULTSET_FAIL;
1179     }
1180     int64_t accessControlId = rowEntity.Get(ACCESS_CONTROL_ID);
1181     int64_t accesserId = rowEntity.Get(ACCESSER_ID);
1182     int64_t accesseeId = rowEntity.Get(ACCESSEE_ID);
1183     std::string trustDeviceId = rowEntity.Get(TRUST_DEVICE_ID);
1184     std::string sessionKey = rowEntity.Get(SESSION_KEY);
1185     int32_t bindType = rowEntity.Get(BIND_TYPE);
1186     int32_t authenticationType = rowEntity.Get(AUTHENTICATION_TYPE);
1187     int32_t deviceIdType = rowEntity.Get(DEVICE_ID_TYPE);
1188     std::string deviceIdHash = rowEntity.Get(DEVICE_ID_HASH);
1189     int32_t status = rowEntity.Get(STATUS);
1190     int64_t validPeriod = rowEntity.Get(VALID_PERIOD);
1191     int64_t lastAuthTime = rowEntity.Get(LAST_AUTH_TIME);
1192     int32_t bindLevel = rowEntity.Get(BIND_LEVEL);
1193     std::string extraData = rowEntity.Get(EXTRA_DATA);
1194 
1195     accessControlProfile.SetAccessControlId(accessControlId);
1196     accessControlProfile.SetAccesserId(accesserId);
1197     accessControlProfile.SetAccesseeId(accesseeId);
1198     accessControlProfile.SetTrustDeviceId(trustDeviceId);
1199     accessControlProfile.SetSessionKey(sessionKey);
1200     accessControlProfile.SetBindType(bindType);
1201     accessControlProfile.SetAuthenticationType(authenticationType);
1202     accessControlProfile.SetDeviceIdType(deviceIdType);
1203     accessControlProfile.SetDeviceIdHash(deviceIdHash);
1204     accessControlProfile.SetStatus(status);
1205     accessControlProfile.SetValidPeriod(validPeriod);
1206     accessControlProfile.SetLastAuthTime(lastAuthTime);
1207     accessControlProfile.SetBindLevel(bindLevel);
1208     accessControlProfile.SetExtraData(extraData);
1209     return DP_SUCCESS;
1210 }
1211 
IsExistColumn(RdbStore & store,const std::string & tabName,const std::string & colName,const std::string & colType,int32_t & errCode)1212 bool ProfileUtils::IsExistColumn(RdbStore& store, const std::string &tabName, const std::string &colName,
1213     const std::string &colType, int32_t &errCode)
1214 {
1215     std::vector<ValueObject> args {tabName, colName, colType};
1216     std::shared_ptr<ResultSet> resultSet = nullptr;
1217     resultSet = store.QuerySql(TABLE_EXIST_COLUMN_SQL, args);
1218     if (resultSet == nullptr) {
1219         HILOGE("resultSet is nullptr");
1220         errCode = DP_GET_RESULTSET_FAIL;
1221         return false;
1222     }
1223     int32_t rowCount = ROWCOUNT_INIT;
1224     if (resultSet->GetRowCount(rowCount) != DP_SUCCESS) {
1225         HILOGE("GetRowCount failed");
1226         resultSet->Close();
1227         errCode = DP_GET_RESULTSET_FAIL;
1228         return false;
1229     }
1230     if (rowCount == 0) {
1231         HILOGE("by condition not find data");
1232         resultSet->Close();
1233         errCode = DP_NOT_FIND_DATA;
1234         return false;
1235     }
1236     if (resultSet->GoToNextRow() != DP_SUCCESS) {
1237         HILOGE("GoToNextRow failed");
1238         resultSet->Close();
1239         errCode = DP_GET_RESULTSET_FAIL;
1240         return false;
1241     }
1242     RowEntity rowEntity;
1243     if (resultSet->GetRow(rowEntity) != DP_SUCCESS) {
1244         HILOGE("GetRow failed");
1245         resultSet->Close();
1246         errCode = DP_GET_RESULTSET_FAIL;
1247         return false;
1248     }
1249     int32_t result = rowEntity.Get(RESULT);
1250     if (result != 0 && result != 1) {
1251         HILOGE("select exists sql failed");
1252         resultSet->Close();
1253         errCode = DP_INVALID_SQL_RESULT;
1254         return false;
1255     }
1256     resultSet->Close();
1257     errCode = DP_SUCCESS;
1258     return result == 1;
1259 }
1260 } // namespace DistributedDeviceProfile
1261 } // namespace OHOS
1262