diff --git a/frameworks/common/BUILD.gn b/frameworks/common/BUILD.gn index e4c4118eb251c8e65509996ee390761a3725dcc9..e3629cf62ad1aefdbaee32ab0776fac06d21ea19 100644 --- a/frameworks/common/BUILD.gn +++ b/frameworks/common/BUILD.gn @@ -32,6 +32,7 @@ ohos_shared_library("accesstoken_common_cxx") { ] sources = [ + "src/constant_common.cpp", "src/data_validator.cpp", "src/random_mbedtls.cpp", ] @@ -40,7 +41,10 @@ ohos_shared_library("accesstoken_common_cxx") { "//third_party/mbedtls:mbedtls_shared", "//utils/native/base:utils", ] - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "startup_l2:syspara", + ] cflags_cc = [ "-DHILOG_ENABLE" ] } diff --git a/frameworks/common/include/constant_common.h b/frameworks/common/include/constant_common.h new file mode 100644 index 0000000000000000000000000000000000000000..f520054fc8476c804a310f20e67990b830265643 --- /dev/null +++ b/frameworks/common/include/constant_common.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef FRAMEWORK_CONSTANT_COMMON_H +#define FRAMEWORK_CONSTANT_COMMON_H + +#include +#include + +namespace OHOS { +namespace Security { +namespace AccessToken { +class ConstantCommon { +public: + /** + * Device id length. + */ + const static int32_t DEVICE_UUID_LENGTH = 65; + static constexpr int32_t MINDEVICEIDLEN = 8; + static constexpr int32_t ENCRYPTLEN = 4; + static constexpr int32_t ENCRYPTBEGIN = 0; + static constexpr int32_t ENCRYPTEND = 3; + static std::string EncryptDevId(std::string deviceId); + + /** + * GetLocalDeviceId + */ + static std::string GetLocalDeviceId(); +}; +} +} +} +#endif \ No newline at end of file diff --git a/frameworks/common/src/constant_common.cpp b/frameworks/common/src/constant_common.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1ecf48f55b4d0a9e24696629053b0e273254b5c7 --- /dev/null +++ b/frameworks/common/src/constant_common.cpp @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "constant_common.h" +#include "parameter.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static const std::string REPLACE_TARGET = "****"; +} // namespace +std::string ConstantCommon::EncryptDevId(std::string deviceId) +{ + std::string result = deviceId; + if (deviceId.size() > MINDEVICEIDLEN) { + result.replace(ENCRYPTBEGIN + ENCRYPTLEN, deviceId.size() - MINDEVICEIDLEN, REPLACE_TARGET); + } else { + result.replace(ENCRYPTBEGIN, deviceId.size(), REPLACE_TARGET); + } + return result; +} + +std::string ConstantCommon::GetLocalDeviceId() +{ + static std::string localDeviceId; + if (!localDeviceId.empty()) { + return localDeviceId; + } + const int32_t DEVICE_UUID_LENGTH = 65; + char udid[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(udid, DEVICE_UUID_LENGTH); + localDeviceId = udid; + return localDeviceId; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/accesstoken/src/accesstoken_kit.cpp b/interfaces/innerkits/accesstoken/src/accesstoken_kit.cpp index 66ca1dadc2d7f84bbcee6cb2c91b09579e128c7c..7359e5d9f97e1534d947c0d0672a062c6246c141 100644 --- a/interfaces/innerkits/accesstoken/src/accesstoken_kit.cpp +++ b/interfaces/innerkits/accesstoken/src/accesstoken_kit.cpp @@ -1,368 +1,370 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "accesstoken_kit.h" - -#include -#include - -#include "accesstoken_log.h" -#include "accesstoken_manager_client.h" -#include "data_validator.h" - -namespace OHOS { -namespace Security { -namespace AccessToken { -namespace { -static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "AccessTokenKit"}; -} // namespace - -AccessTokenIDEx AccessTokenKit::AllocHapToken(const HapInfoParams& info, const HapPolicyParams& policy) -{ - AccessTokenIDEx res = {0}; - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); - if ((!DataValidator::IsUserIdValid(info.userID)) || !DataValidator::IsAppIDDescValid(info.appIDDesc) || - !DataValidator::IsBundleNameValid(info.bundleName) || !DataValidator::IsAplNumValid(policy.apl) || - !DataValidator::IsDomainValid(policy.domain) || !DataValidator::IsDlpTypeValid(info.dlpType)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "input param failed"); - return res; - } - - return AccessTokenManagerClient::GetInstance().AllocHapToken(info, policy); -} - -AccessTokenID AccessTokenKit::AllocLocalTokenID(const std::string& remoteDeviceID, AccessTokenID remoteTokenID) -{ - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{private}s tokenID=%{public}d", - __func__, remoteDeviceID.c_str(), remoteTokenID); -#ifdef DEBUG_API_PERFORMANCE - ACCESSTOKEN_LOG_INFO(LABEL, "api_performance:start call"); - AccessTokenID resID = AccessTokenManagerClient::GetInstance().AllocLocalTokenID(remoteDeviceID, remoteTokenID); - ACCESSTOKEN_LOG_INFO(LABEL, "api_performance:end call"); - return resID; -#else - return AccessTokenManagerClient::GetInstance().AllocLocalTokenID(remoteDeviceID, remoteTokenID); -#endif -} - -int AccessTokenKit::UpdateHapToken(AccessTokenID tokenID, const std::string& appIDDesc, const HapPolicyParams& policy) -{ - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); - if ((tokenID == 0) || (!DataValidator::IsAppIDDescValid(appIDDesc)) || - (!DataValidator::IsAplNumValid(policy.apl))) { - ACCESSTOKEN_LOG_ERROR(LABEL, "input param failed"); - return RET_FAILED; - } - return AccessTokenManagerClient::GetInstance().UpdateHapToken(tokenID, appIDDesc, policy); -} - -int AccessTokenKit::DeleteToken(AccessTokenID tokenID) -{ - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); - if (tokenID == 0) { - ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); - return RET_FAILED; - } - ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); - return AccessTokenManagerClient::GetInstance().DeleteToken(tokenID); -} - -ATokenTypeEnum AccessTokenKit::GetTokenType(AccessTokenID tokenID) -{ - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); - if (tokenID == 0) { - ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); - return TOKEN_INVALID; - } - ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); - return AccessTokenManagerClient::GetInstance().GetTokenType(tokenID); -} - -ATokenTypeEnum AccessTokenKit::GetTokenTypeFlag(AccessTokenID tokenID) -{ - if (tokenID == 0) { - return TOKEN_INVALID; - } - AccessTokenIDInner *idInner = reinterpret_cast(&tokenID); - return (ATokenTypeEnum)(idInner->type); -} - -int AccessTokenKit::CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap) -{ - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); - if (tokenID == 0) { - ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); - return RET_FAILED; - } - if (!DataValidator::IsDcapValid(dcap)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "dcap is invalid"); - return RET_FAILED; - } - ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, dcap=%{public}s", tokenID, dcap.c_str()); - return AccessTokenManagerClient::GetInstance().CheckNativeDCap(tokenID, dcap); -} - -AccessTokenID AccessTokenKit::GetHapTokenID(int userID, const std::string& bundleName, int instIndex) -{ - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); - if (!DataValidator::IsUserIdValid(userID) || !DataValidator::IsBundleNameValid(bundleName)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "hap token param failed"); - return 0; - } - ACCESSTOKEN_LOG_INFO(LABEL, "int userID=%{public}d, bundleName=%{public}s, instIndex=%{public}d", - userID, bundleName.c_str(), instIndex); - return AccessTokenManagerClient::GetInstance().GetHapTokenID(userID, bundleName, instIndex); -} - -int AccessTokenKit::GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfo& hapTokenInfoRes) -{ - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); - if (tokenID == 0) { - ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); - return RET_FAILED; - } - ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); - - return AccessTokenManagerClient::GetInstance().GetHapTokenInfo(tokenID, hapTokenInfoRes); -} - -int AccessTokenKit::GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfo& nativeTokenInfoRes) -{ - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); - ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); - - return AccessTokenManagerClient::GetInstance().GetNativeTokenInfo(tokenID, nativeTokenInfoRes); -} - -PermissionOper AccessTokenKit::GetSelfPermissionsState(std::vector& permList) -{ - ACCESSTOKEN_LOG_INFO(LABEL, "called."); - return AccessTokenManagerClient::GetInstance().GetSelfPermissionsState(permList); -} - -int AccessTokenKit::VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName) -{ - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); - if (tokenID == 0) { - ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); - return PERMISSION_DENIED; - } - if (!DataValidator::IsPermissionNameValid(permissionName)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "permissionName is invalid"); - return PERMISSION_DENIED; - } - ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, permissionName=%{public}s", tokenID, permissionName.c_str()); - return AccessTokenManagerClient::GetInstance().VerifyAccessToken(tokenID, permissionName); -} - -int AccessTokenKit::VerifyAccessToken( - AccessTokenID callerTokenID, AccessTokenID firstTokenID, const std::string& permissionName) -{ - int ret = AccessTokenKit::VerifyAccessToken(callerTokenID, permissionName); - if (ret != PERMISSION_GRANTED) { - return ret; - } - if (firstTokenID == FIRSTCALLER_TOKENID_DEFAULT) { - return ret; - } - return AccessTokenKit::VerifyAccessToken(firstTokenID, permissionName); -} - -int AccessTokenKit::VerifyNativeToken(AccessTokenID tokenID, const std::string& permissionName) -{ - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); - if (tokenID == 0) { - ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID=%{public}d is invalid", tokenID); - return PERMISSION_DENIED; - } - if (!DataValidator::IsPermissionNameValid(permissionName)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "permissionName is invalid"); - return PERMISSION_DENIED; - } - ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, permissionName=%{public}s", tokenID, permissionName.c_str()); - return AccessTokenManagerClient::GetInstance().VerifyNativeToken(tokenID, permissionName); -} - -int AccessTokenKit::GetDefPermission(const std::string& permissionName, PermissionDef& permissionDefResult) -{ - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); - if (!DataValidator::IsPermissionNameValid(permissionName)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "permissionName is invalid"); - return RET_FAILED; - } - ACCESSTOKEN_LOG_INFO(LABEL, "permissionName=%{public}s", permissionName.c_str()); - - int ret = AccessTokenManagerClient::GetInstance().GetDefPermission(permissionName, permissionDefResult); - ACCESSTOKEN_LOG_INFO(LABEL, "GetDefPermission bundleName = %{public}s", permissionDefResult.bundleName.c_str()); - - return ret; -} - -int AccessTokenKit::GetDefPermissions(AccessTokenID tokenID, std::vector& permDefList) -{ - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); - if (tokenID == 0) { - ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); - return RET_FAILED; - } - ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); - - return AccessTokenManagerClient::GetInstance().GetDefPermissions(tokenID, permDefList); -} - -int AccessTokenKit::GetReqPermissions( - AccessTokenID tokenID, std::vector& reqPermList, bool isSystemGrant) -{ - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); - if (tokenID == 0) { - ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); - return RET_FAILED; - } - ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, isSystemGrant=%{public}d", tokenID, isSystemGrant); - - return AccessTokenManagerClient::GetInstance().GetReqPermissions(tokenID, reqPermList, isSystemGrant); -} - -int AccessTokenKit::GetPermissionFlag(AccessTokenID tokenID, const std::string& permissionName) -{ - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); - if (tokenID == 0) { - ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); - return PERMISSION_DEFAULT_FLAG; - } - if (!DataValidator::IsPermissionNameValid(permissionName)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "permissionName is invalid"); - return PERMISSION_DEFAULT_FLAG; - } - ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, permissionName=%{public}s", tokenID, permissionName.c_str()); - return AccessTokenManagerClient::GetInstance().GetPermissionFlag(tokenID, permissionName); -} - -int AccessTokenKit::GrantPermission(AccessTokenID tokenID, const std::string& permissionName, int flag) -{ - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); - if (tokenID == 0) { - ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); - return RET_FAILED; - } - if (!DataValidator::IsPermissionNameValid(permissionName)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "permissionName is invalid"); - return RET_FAILED; - } - if (!DataValidator::IsPermissionFlagValid(flag)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "flag is invalid"); - return RET_FAILED; - } - ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, permissionName=%{public}s, flag=%{public}d", - tokenID, permissionName.c_str(), flag); - return AccessTokenManagerClient::GetInstance().GrantPermission(tokenID, permissionName, flag); -} - -int AccessTokenKit::RevokePermission(AccessTokenID tokenID, const std::string& permissionName, int flag) -{ - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); - if (tokenID == 0) { - ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); - return RET_FAILED; - } - if (!DataValidator::IsPermissionNameValid(permissionName)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "permissionName is invalid"); - return RET_FAILED; - } - if (!DataValidator::IsPermissionFlagValid(flag)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "flag is invalid"); - return RET_FAILED; - } - ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, permissionName=%{public}s, flag=%{public}d", - tokenID, permissionName.c_str(), flag); - return AccessTokenManagerClient::GetInstance().RevokePermission(tokenID, permissionName, flag); -} - -int AccessTokenKit::ClearUserGrantedPermissionState(AccessTokenID tokenID) -{ - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); - if (tokenID == 0) { - ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); - return RET_FAILED; - } - ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); - return AccessTokenManagerClient::GetInstance().ClearUserGrantedPermissionState(tokenID); -} - -#ifdef TOKEN_SYNC_ENABLE -int AccessTokenKit::GetHapTokenInfoFromRemote(AccessTokenID tokenID, HapTokenInfoForSync& hapSync) -{ - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); - if (tokenID == 0) { - ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); - return RET_FAILED; - } - ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); - - return AccessTokenManagerClient::GetInstance().GetHapTokenInfoFromRemote(tokenID, hapSync); -} - -int AccessTokenKit::GetAllNativeTokenInfo(std::vector& nativeTokenInfosRes) -{ - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); - - return AccessTokenManagerClient::GetInstance().GetAllNativeTokenInfo(nativeTokenInfosRes); -} - -int AccessTokenKit::SetRemoteHapTokenInfo(const std::string& deviceID, - const HapTokenInfoForSync& hapSync) -{ - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{private}s tokenID=%{public}d", - __func__, deviceID.c_str(), hapSync.baseInfo.tokenID); - return AccessTokenManagerClient::GetInstance().SetRemoteHapTokenInfo(deviceID, hapSync); -} - -int AccessTokenKit::SetRemoteNativeTokenInfo(const std::string& deviceID, - std::vector& nativeTokenInfoList) -{ - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{private}s", __func__, deviceID.c_str()); - return AccessTokenManagerClient::GetInstance() - .SetRemoteNativeTokenInfo(deviceID, nativeTokenInfoList); -} - -int AccessTokenKit::DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID) -{ - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{private}s tokenID=%{public}d", - __func__, deviceID.c_str(), tokenID); - return AccessTokenManagerClient::GetInstance().DeleteRemoteToken(deviceID, tokenID); -} - -int AccessTokenKit::DeleteRemoteDeviceTokens(const std::string& deviceID) -{ - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{private}s", __func__, deviceID.c_str()); - return AccessTokenManagerClient::GetInstance().DeleteRemoteDeviceTokens(deviceID); -} - -AccessTokenID AccessTokenKit::GetRemoteNativeTokenID(const std::string& deviceID, AccessTokenID tokenID) -{ - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{private}s tokenID=%{public}d", - __func__, deviceID.c_str(), tokenID); - return AccessTokenManagerClient::GetInstance().GetRemoteNativeTokenID(deviceID, tokenID); -} -#endif - -void AccessTokenKit::DumpTokenInfo(std::string& dumpInfo) -{ - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); - AccessTokenManagerClient::GetInstance().DumpTokenInfo(dumpInfo); -} -} // namespace AccessToken -} // namespace Security -} // namespace OHOS +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "accesstoken_kit.h" + +#include +#include + +#include "accesstoken_log.h" +#include "accesstoken_manager_client.h" +#include "constant_common.h" +#include "data_validator.h" +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "AccessTokenKit"}; +} // namespace + +AccessTokenIDEx AccessTokenKit::AllocHapToken(const HapInfoParams& info, const HapPolicyParams& policy) +{ + AccessTokenIDEx res = {0}; + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + if ((!DataValidator::IsUserIdValid(info.userID)) || !DataValidator::IsAppIDDescValid(info.appIDDesc) || + !DataValidator::IsBundleNameValid(info.bundleName) || !DataValidator::IsAplNumValid(policy.apl) || + !DataValidator::IsDomainValid(policy.domain) || !DataValidator::IsDlpTypeValid(info.dlpType)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "input param failed"); + return res; + } + + return AccessTokenManagerClient::GetInstance().AllocHapToken(info, policy); +} + +AccessTokenID AccessTokenKit::AllocLocalTokenID(const std::string& remoteDeviceID, AccessTokenID remoteTokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{public}s tokenID=%{public}d", + __func__, ConstantCommon::EncryptDevId(remoteDeviceID).c_str(), remoteTokenID); +#ifdef DEBUG_API_PERFORMANCE + ACCESSTOKEN_LOG_INFO(LABEL, "api_performance:start call"); + AccessTokenID resID = AccessTokenManagerClient::GetInstance().AllocLocalTokenID(remoteDeviceID, remoteTokenID); + ACCESSTOKEN_LOG_INFO(LABEL, "api_performance:end call"); + return resID; +#else + return AccessTokenManagerClient::GetInstance().AllocLocalTokenID(remoteDeviceID, remoteTokenID); +#endif +} + +int AccessTokenKit::UpdateHapToken(AccessTokenID tokenID, const std::string& appIDDesc, const HapPolicyParams& policy) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + if ((tokenID == 0) || (!DataValidator::IsAppIDDescValid(appIDDesc)) || + (!DataValidator::IsAplNumValid(policy.apl))) { + ACCESSTOKEN_LOG_ERROR(LABEL, "input param failed"); + return RET_FAILED; + } + return AccessTokenManagerClient::GetInstance().UpdateHapToken(tokenID, appIDDesc, policy); +} + +int AccessTokenKit::DeleteToken(AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + if (tokenID == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); + return RET_FAILED; + } + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); + return AccessTokenManagerClient::GetInstance().DeleteToken(tokenID); +} + +ATokenTypeEnum AccessTokenKit::GetTokenType(AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + if (tokenID == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); + return TOKEN_INVALID; + } + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); + return AccessTokenManagerClient::GetInstance().GetTokenType(tokenID); +} + +ATokenTypeEnum AccessTokenKit::GetTokenTypeFlag(AccessTokenID tokenID) +{ + if (tokenID == 0) { + return TOKEN_INVALID; + } + AccessTokenIDInner *idInner = reinterpret_cast(&tokenID); + return (ATokenTypeEnum)(idInner->type); +} + +int AccessTokenKit::CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + if (tokenID == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); + return RET_FAILED; + } + if (!DataValidator::IsDcapValid(dcap)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "dcap is invalid"); + return RET_FAILED; + } + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, dcap=%{public}s", tokenID, dcap.c_str()); + return AccessTokenManagerClient::GetInstance().CheckNativeDCap(tokenID, dcap); +} + +AccessTokenID AccessTokenKit::GetHapTokenID(int userID, const std::string& bundleName, int instIndex) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + if (!DataValidator::IsUserIdValid(userID) || !DataValidator::IsBundleNameValid(bundleName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "hap token param failed"); + return 0; + } + ACCESSTOKEN_LOG_INFO(LABEL, "int userID=%{public}d, bundleName=%{public}s, instIndex=%{public}d", + userID, bundleName.c_str(), instIndex); + return AccessTokenManagerClient::GetInstance().GetHapTokenID(userID, bundleName, instIndex); +} + +int AccessTokenKit::GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfo& hapTokenInfoRes) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + if (tokenID == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); + return RET_FAILED; + } + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); + + return AccessTokenManagerClient::GetInstance().GetHapTokenInfo(tokenID, hapTokenInfoRes); +} + +int AccessTokenKit::GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfo& nativeTokenInfoRes) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); + + return AccessTokenManagerClient::GetInstance().GetNativeTokenInfo(tokenID, nativeTokenInfoRes); +} + +PermissionOper AccessTokenKit::GetSelfPermissionsState(std::vector& permList) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called."); + return AccessTokenManagerClient::GetInstance().GetSelfPermissionsState(permList); +} + +int AccessTokenKit::VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + if (tokenID == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); + return PERMISSION_DENIED; + } + if (!DataValidator::IsPermissionNameValid(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "permissionName is invalid"); + return PERMISSION_DENIED; + } + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, permissionName=%{public}s", tokenID, permissionName.c_str()); + return AccessTokenManagerClient::GetInstance().VerifyAccessToken(tokenID, permissionName); +} + +int AccessTokenKit::VerifyAccessToken( + AccessTokenID callerTokenID, AccessTokenID firstTokenID, const std::string& permissionName) +{ + int ret = AccessTokenKit::VerifyAccessToken(callerTokenID, permissionName); + if (ret != PERMISSION_GRANTED) { + return ret; + } + if (firstTokenID == FIRSTCALLER_TOKENID_DEFAULT) { + return ret; + } + return AccessTokenKit::VerifyAccessToken(firstTokenID, permissionName); +} + +int AccessTokenKit::VerifyNativeToken(AccessTokenID tokenID, const std::string& permissionName) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + if (tokenID == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID=%{public}d is invalid", tokenID); + return PERMISSION_DENIED; + } + if (!DataValidator::IsPermissionNameValid(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "permissionName is invalid"); + return PERMISSION_DENIED; + } + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, permissionName=%{public}s", tokenID, permissionName.c_str()); + return AccessTokenManagerClient::GetInstance().VerifyNativeToken(tokenID, permissionName); +} + +int AccessTokenKit::GetDefPermission(const std::string& permissionName, PermissionDef& permissionDefResult) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + if (!DataValidator::IsPermissionNameValid(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "permissionName is invalid"); + return RET_FAILED; + } + ACCESSTOKEN_LOG_INFO(LABEL, "permissionName=%{public}s", permissionName.c_str()); + + int ret = AccessTokenManagerClient::GetInstance().GetDefPermission(permissionName, permissionDefResult); + ACCESSTOKEN_LOG_INFO(LABEL, "GetDefPermission bundleName = %{public}s", permissionDefResult.bundleName.c_str()); + + return ret; +} + +int AccessTokenKit::GetDefPermissions(AccessTokenID tokenID, std::vector& permDefList) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + if (tokenID == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); + return RET_FAILED; + } + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); + + return AccessTokenManagerClient::GetInstance().GetDefPermissions(tokenID, permDefList); +} + +int AccessTokenKit::GetReqPermissions( + AccessTokenID tokenID, std::vector& reqPermList, bool isSystemGrant) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + if (tokenID == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); + return RET_FAILED; + } + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, isSystemGrant=%{public}d", tokenID, isSystemGrant); + + return AccessTokenManagerClient::GetInstance().GetReqPermissions(tokenID, reqPermList, isSystemGrant); +} + +int AccessTokenKit::GetPermissionFlag(AccessTokenID tokenID, const std::string& permissionName) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + if (tokenID == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); + return PERMISSION_DEFAULT_FLAG; + } + if (!DataValidator::IsPermissionNameValid(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "permissionName is invalid"); + return PERMISSION_DEFAULT_FLAG; + } + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, permissionName=%{public}s", tokenID, permissionName.c_str()); + return AccessTokenManagerClient::GetInstance().GetPermissionFlag(tokenID, permissionName); +} + +int AccessTokenKit::GrantPermission(AccessTokenID tokenID, const std::string& permissionName, int flag) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + if (tokenID == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); + return RET_FAILED; + } + if (!DataValidator::IsPermissionNameValid(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "permissionName is invalid"); + return RET_FAILED; + } + if (!DataValidator::IsPermissionFlagValid(flag)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "flag is invalid"); + return RET_FAILED; + } + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, permissionName=%{public}s, flag=%{public}d", + tokenID, permissionName.c_str(), flag); + return AccessTokenManagerClient::GetInstance().GrantPermission(tokenID, permissionName, flag); +} + +int AccessTokenKit::RevokePermission(AccessTokenID tokenID, const std::string& permissionName, int flag) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + if (tokenID == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); + return RET_FAILED; + } + if (!DataValidator::IsPermissionNameValid(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "permissionName is invalid"); + return RET_FAILED; + } + if (!DataValidator::IsPermissionFlagValid(flag)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "flag is invalid"); + return RET_FAILED; + } + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, permissionName=%{public}s, flag=%{public}d", + tokenID, permissionName.c_str(), flag); + return AccessTokenManagerClient::GetInstance().RevokePermission(tokenID, permissionName, flag); +} + +int AccessTokenKit::ClearUserGrantedPermissionState(AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + if (tokenID == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); + return RET_FAILED; + } + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); + return AccessTokenManagerClient::GetInstance().ClearUserGrantedPermissionState(tokenID); +} + +#ifdef TOKEN_SYNC_ENABLE +int AccessTokenKit::GetHapTokenInfoFromRemote(AccessTokenID tokenID, HapTokenInfoForSync& hapSync) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + if (tokenID == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); + return RET_FAILED; + } + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); + + return AccessTokenManagerClient::GetInstance().GetHapTokenInfoFromRemote(tokenID, hapSync); +} + +int AccessTokenKit::GetAllNativeTokenInfo(std::vector& nativeTokenInfosRes) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + + return AccessTokenManagerClient::GetInstance().GetAllNativeTokenInfo(nativeTokenInfosRes); +} + +int AccessTokenKit::SetRemoteHapTokenInfo(const std::string& deviceID, + const HapTokenInfoForSync& hapSync) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{public}s tokenID=%{public}d", + __func__, ConstantCommon::EncryptDevId(deviceID).c_str(), hapSync.baseInfo.tokenID); + return AccessTokenManagerClient::GetInstance().SetRemoteHapTokenInfo(deviceID, hapSync); +} + +int AccessTokenKit::SetRemoteNativeTokenInfo(const std::string& deviceID, + std::vector& nativeTokenInfoList) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{public}s", __func__, + ConstantCommon::EncryptDevId(deviceID).c_str()); + return AccessTokenManagerClient::GetInstance() + .SetRemoteNativeTokenInfo(deviceID, nativeTokenInfoList); +} + +int AccessTokenKit::DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{public}s tokenID=%{public}d", + __func__, ConstantCommon::EncryptDevId(deviceID).c_str(), tokenID); + return AccessTokenManagerClient::GetInstance().DeleteRemoteToken(deviceID, tokenID); +} + +int AccessTokenKit::DeleteRemoteDeviceTokens(const std::string& deviceID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{public}s", __func__, + ConstantCommon::EncryptDevId(deviceID).c_str()); + return AccessTokenManagerClient::GetInstance().DeleteRemoteDeviceTokens(deviceID); +} + +AccessTokenID AccessTokenKit::GetRemoteNativeTokenID(const std::string& deviceID, AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{public}s tokenID=%{public}d", + __func__, ConstantCommon::EncryptDevId(deviceID).c_str(), tokenID); + return AccessTokenManagerClient::GetInstance().GetRemoteNativeTokenID(deviceID, tokenID); +} +#endif + +void AccessTokenKit::DumpTokenInfo(std::string& dumpInfo) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + AccessTokenManagerClient::GetInstance().DumpTokenInfo(dumpInfo); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/interfaces/innerkits/privacy/src/privacy_kit.cpp b/interfaces/innerkits/privacy/src/privacy_kit.cpp index 1693faa03ee60896845a5fb1dde52001700bdda7..0b9557bdd38c5d61acc97c2fb206349b3b8894fc 100644 --- a/interfaces/innerkits/privacy/src/privacy_kit.cpp +++ b/interfaces/innerkits/privacy/src/privacy_kit.cpp @@ -19,6 +19,7 @@ #include #include "accesstoken_log.h" +#include "constant_common.h" #include "privacy_manager_client.h" namespace OHOS { @@ -53,8 +54,8 @@ int32_t PrivacyKit::StopUsingPermission(AccessTokenID tokenID, const std::string int32_t PrivacyKit::RemovePermissionUsedRecords(AccessTokenID tokenID, const std::string& deviceID) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "Entry, tokenID=0x%{public}x, deviceID=%{private}s", - tokenID, deviceID.c_str()); + ACCESSTOKEN_LOG_DEBUG(LABEL, "Entry, tokenID=0x%{public}x, deviceID=%{public}s", + tokenID, ConstantCommon::EncryptDevId(deviceID).c_str()); return PrivacyManagerClient::GetInstance().RemovePermissionUsedRecords(tokenID, deviceID); } diff --git a/interfaces/innerkits/tokensync/BUILD.gn b/interfaces/innerkits/tokensync/BUILD.gn index 991849b9f095fb2d92e41997d8f0458255c96462..c595ead52fb640f2e89d5536bc20ec998d7a43a6 100644 --- a/interfaces/innerkits/tokensync/BUILD.gn +++ b/interfaces/innerkits/tokensync/BUILD.gn @@ -49,6 +49,7 @@ ohos_shared_library("libtokensync_sdk") { deps = [ "//base/security/access_token/frameworks/accesstoken:accesstoken_communication_adapter_cxx", + "//base/security/access_token/frameworks/common:accesstoken_common_cxx", "//utils/native/base:utils", ] diff --git a/interfaces/innerkits/tokensync/src/token_sync_kit.cpp b/interfaces/innerkits/tokensync/src/token_sync_kit.cpp index 415cf1f0f5c2b1def15b6cfebdc0d0399d93a86c..4a3493ef393bae8350caa144f750fb25f041caf4 100644 --- a/interfaces/innerkits/tokensync/src/token_sync_kit.cpp +++ b/interfaces/innerkits/tokensync/src/token_sync_kit.cpp @@ -1,53 +1,53 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "token_sync_kit.h" - -#include -#include - -#include "accesstoken_log.h" -#include "token_sync_manager_client.h" - -namespace OHOS { -namespace Security { -namespace AccessToken { -using namespace std; - -namespace { -static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "TokenSyncKit"}; -} // namespace - -int TokenSyncKit::GetRemoteHapTokenInfo(const std::string& deviceID, AccessTokenID tokenID) -{ - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{private}s tokenID=%{public}d", - __func__, deviceID.c_str(), tokenID); - return TokenSyncManagerClient::GetInstance().GetRemoteHapTokenInfo(deviceID, tokenID); -} - -int TokenSyncKit::DeleteRemoteHapTokenInfo(AccessTokenID tokenID) -{ - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, tokenID=%{public}d", __func__, tokenID); - return TokenSyncManagerClient::GetInstance().DeleteRemoteHapTokenInfo(tokenID); -} - -int TokenSyncKit::UpdateRemoteHapTokenInfo(const HapTokenInfoForSync& tokenInfo) -{ - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called tokenID=%{public}d", __func__, tokenInfo.baseInfo.tokenID); - return TokenSyncManagerClient::GetInstance().UpdateRemoteHapTokenInfo(tokenInfo); -} -} // namespace AccessToken -} // namespace Security -} // namespace OHOS +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "token_sync_kit.h" + +#include +#include + +#include "accesstoken_log.h" +#include "constant_common.h" +#include "token_sync_manager_client.h" +namespace OHOS { +namespace Security { +namespace AccessToken { +using namespace std; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "TokenSyncKit"}; +} // namespace + +int TokenSyncKit::GetRemoteHapTokenInfo(const std::string& deviceID, AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{public}s tokenID=%{public}d", + __func__, ConstantCommon::EncryptDevId(deviceID).c_str(), tokenID); + return TokenSyncManagerClient::GetInstance().GetRemoteHapTokenInfo(deviceID, tokenID); +} + +int TokenSyncKit::DeleteRemoteHapTokenInfo(AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, tokenID=%{public}d", __func__, tokenID); + return TokenSyncManagerClient::GetInstance().DeleteRemoteHapTokenInfo(tokenID); +} + +int TokenSyncKit::UpdateRemoteHapTokenInfo(const HapTokenInfoForSync& tokenInfo) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called tokenID=%{public}d", __func__, tokenInfo.baseInfo.tokenID); + return TokenSyncManagerClient::GetInstance().UpdateRemoteHapTokenInfo(tokenInfo); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_service.cpp b/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_service.cpp index b55f467d23a52bd25bb75c36144429e2f68b3c5a..017468bd75c0c937efc12c84eb7c6fb35fd636e6 100644 --- a/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_service.cpp +++ b/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_service.cpp @@ -25,6 +25,7 @@ #include "atm_device_state_callback.h" #include "device_manager.h" #endif +#include "constant_common.h" #include "hap_token_info.h" #include "hap_token_info_inner.h" #include "ipc_skeleton.h" @@ -247,8 +248,8 @@ AccessTokenID AccessTokenManagerService::GetHapTokenID(int userID, const std::st AccessTokenID AccessTokenManagerService::AllocLocalTokenID( const std::string& remoteDeviceID, AccessTokenID remoteTokenID) { - ACCESSTOKEN_LOG_INFO(LABEL, "called, remoteDeviceID: %{private}s, remoteTokenID: %{public}d", - remoteDeviceID.c_str(), remoteTokenID); + ACCESSTOKEN_LOG_INFO(LABEL, "called, remoteDeviceID: %{public}s, remoteTokenID: %{public}d", + ConstantCommon::EncryptDevId(remoteDeviceID).c_str(), remoteTokenID); return AccessTokenInfoManager::GetInstance().AllocLocalTokenID(remoteDeviceID, remoteTokenID); } @@ -303,7 +304,7 @@ int AccessTokenManagerService::GetAllNativeTokenInfo(std::vector& nativeTokenInfoForSyncParcel) { - ACCESSTOKEN_LOG_INFO(LABEL, "called, deviceID: %{private}s", deviceID.c_str()); + ACCESSTOKEN_LOG_INFO(LABEL, "called, deviceID: %{public}s", ConstantCommon::EncryptDevId(deviceID).c_str()); std::vector nativeList; @@ -325,8 +326,8 @@ int AccessTokenManagerService::SetRemoteNativeTokenInfo(const std::string& devic int AccessTokenManagerService::DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID) { - ACCESSTOKEN_LOG_INFO(LABEL, "called, deviceID: %{private}s, token id %{public}d", - deviceID.c_str(), tokenID); + ACCESSTOKEN_LOG_INFO(LABEL, "called, deviceID: %{public}s, token id %{public}d", + ConstantCommon::EncryptDevId(deviceID).c_str(), tokenID); return AccessTokenInfoManager::GetInstance().DeleteRemoteToken(deviceID, tokenID); } @@ -334,15 +335,15 @@ int AccessTokenManagerService::DeleteRemoteToken(const std::string& deviceID, Ac AccessTokenID AccessTokenManagerService::GetRemoteNativeTokenID(const std::string& deviceID, AccessTokenID tokenID) { - ACCESSTOKEN_LOG_INFO(LABEL, "called, deviceID: %{private}s, token id %{public}d", - deviceID.c_str(), tokenID); + ACCESSTOKEN_LOG_INFO(LABEL, "called, deviceID: %{public}s, token id %{public}d", + ConstantCommon::EncryptDevId(deviceID).c_str(), tokenID); return AccessTokenInfoManager::GetInstance().GetRemoteNativeTokenID(deviceID, tokenID); } int AccessTokenManagerService::DeleteRemoteDeviceTokens(const std::string& deviceID) { - ACCESSTOKEN_LOG_INFO(LABEL, "called, deviceID: %{private}s", deviceID.c_str()); + ACCESSTOKEN_LOG_INFO(LABEL, "called, deviceID: %{public}s", ConstantCommon::EncryptDevId(deviceID).c_str()); return AccessTokenInfoManager::GetInstance().DeleteRemoteDeviceTokens(deviceID); } diff --git a/services/accesstokenmanager/main/cpp/src/token/accesstoken_info_manager.cpp b/services/accesstokenmanager/main/cpp/src/token/accesstoken_info_manager.cpp index 10bfcdd93887b8db034415828f4360965ff4caf8..c5f21ccd57e82fac93a8fa4af9b23b660105f060 100644 --- a/services/accesstokenmanager/main/cpp/src/token/accesstoken_info_manager.cpp +++ b/services/accesstokenmanager/main/cpp/src/token/accesstoken_info_manager.cpp @@ -19,6 +19,7 @@ #include "accesstoken_id_manager.h" #include "accesstoken_log.h" #include "accesstoken_remote_token_manager.h" +#include "constant_common.h" #include "data_storage.h" #include "data_translator.h" #include "data_validator.h" @@ -647,15 +648,15 @@ int AccessTokenInfoManager::SetRemoteHapTokenInfo(const std::string& deviceID, H || !DataValidator::IsDlpTypeValid(hapSync.baseInfo.dlpType) || hapSync.baseInfo.ver != DEFAULT_TOKEN_VERSION || AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(hapSync.baseInfo.tokenID) != TOKEN_HAP) { - ACCESSTOKEN_LOG_ERROR(LABEL, "device %{private}s parms invalid", deviceID.c_str()); + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s parms invalid", ConstantCommon::EncryptDevId(deviceID).c_str()); return RET_FAILED; } AccessTokenID remoteID = hapSync.baseInfo.tokenID; AccessTokenID mapID = AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(deviceID, remoteID); if (mapID != 0) { - ACCESSTOKEN_LOG_INFO(LABEL, "device %{private}s token %{public}u update exist remote hap token %{public}u.", - deviceID.c_str(), remoteID, mapID); + ACCESSTOKEN_LOG_INFO(LABEL, "device %{public}s token %{public}u update exist remote hap token %{public}u.", + ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID, mapID); // update remote token mapping id hapSync.baseInfo.tokenID = mapID; hapSync.baseInfo.deviceID = deviceID; @@ -664,8 +665,8 @@ int AccessTokenInfoManager::SetRemoteHapTokenInfo(const std::string& deviceID, H mapID = AccessTokenRemoteTokenManager::GetInstance().MapRemoteDeviceTokenToLocal(deviceID, remoteID); if (mapID == 0) { - ACCESSTOKEN_LOG_ERROR( - LABEL, "device %{private}s token %{public}u map failed.", deviceID.c_str(), remoteID); + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s token %{public}u map failed.", + ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID); return RET_FAILED; } @@ -675,12 +676,12 @@ int AccessTokenInfoManager::SetRemoteHapTokenInfo(const std::string& deviceID, H if (CreateRemoteHapTokenInfo(mapID, hapSync) == RET_FAILED) { AccessTokenRemoteTokenManager::GetInstance().RemoveDeviceMappingTokenID(deviceID, mapID); - ACCESSTOKEN_LOG_INFO(LABEL, "device %{private}s token %{public}u map to local token %{public}u failed.", - deviceID.c_str(), remoteID, mapID); + ACCESSTOKEN_LOG_INFO(LABEL, "device %{public}s token %{public}u map to local token %{public}u failed.", + ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID, mapID); return RET_FAILED; } - ACCESSTOKEN_LOG_INFO(LABEL, "device %{private}s token %{public}u map to local token %{public}u success.", - deviceID.c_str(), remoteID, mapID); + ACCESSTOKEN_LOG_INFO(LABEL, "device %{public}s token %{public}u map to local token %{public}u success.", + ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID, mapID); return RET_SUCCESS; } @@ -688,7 +689,7 @@ int AccessTokenInfoManager::SetRemoteNativeTokenInfo(const std::string& deviceID std::vector& nativeTokenInfoList) { if (!DataValidator::IsDeviceIdValid(deviceID)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "device %{private}s parms invalid", deviceID.c_str()); + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s parms invalid", ConstantCommon::EncryptDevId(deviceID).c_str()); return RET_FAILED; } @@ -699,8 +700,8 @@ int AccessTokenInfoManager::SetRemoteNativeTokenInfo(const std::string& deviceID nativeToken.baseInfo.dcap.size() <= 0 || AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(nativeToken.baseInfo.tokenID) != TOKEN_NATIVE) { ACCESSTOKEN_LOG_ERROR( - LABEL, "device %{private}s token %{public}u is invalid.", - deviceID.c_str(), nativeToken.baseInfo.tokenID); + LABEL, "device %{public}s token %{public}u is invalid.", + ConstantCommon::EncryptDevId(deviceID).c_str(), nativeToken.baseInfo.tokenID); continue; } @@ -708,8 +709,8 @@ int AccessTokenInfoManager::SetRemoteNativeTokenInfo(const std::string& deviceID AccessTokenID mapID = AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(deviceID, remoteID); if (mapID != 0) { ACCESSTOKEN_LOG_ERROR( - LABEL, "device %{private}s token %{public}u has maped, no need update it.", - deviceID.c_str(), nativeToken.baseInfo.tokenID); + LABEL, "device %{public}s token %{public}u has maped, no need update it.", + ConstantCommon::EncryptDevId(deviceID).c_str(), nativeToken.baseInfo.tokenID); continue; } @@ -717,32 +718,32 @@ int AccessTokenInfoManager::SetRemoteNativeTokenInfo(const std::string& deviceID if (mapID == 0) { AccessTokenRemoteTokenManager::GetInstance().RemoveDeviceMappingTokenID(deviceID, mapID); ACCESSTOKEN_LOG_ERROR( - LABEL, "device %{private}s token %{public}u map failed.", - deviceID.c_str(), remoteID); + LABEL, "device %{public}s token %{public}u map failed.", + ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID); continue; } nativeToken.baseInfo.tokenID = mapID; - ACCESSTOKEN_LOG_INFO(LABEL, "device %{private}s token %{public}u map to local token %{public}u.", - deviceID.c_str(), remoteID, mapID); + ACCESSTOKEN_LOG_INFO(LABEL, "device %{public}s token %{public}u map to local token %{public}u.", + ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID, mapID); std::shared_ptr nativePtr = std::make_shared(nativeToken.baseInfo, nativeToken.permStateList); if (nativePtr == nullptr) { AccessTokenRemoteTokenManager::GetInstance().RemoveDeviceMappingTokenID(deviceID, mapID); - ACCESSTOKEN_LOG_ERROR(LABEL, "device %{private}s tokenId %{public}u alloc local token failed.", - deviceID.c_str(), remoteID); + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s tokenId %{public}u alloc local token failed.", + ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID); continue; } nativePtr->SetRemote(true); int ret = AddNativeTokenInfo(nativePtr); if (ret != RET_SUCCESS) { AccessTokenRemoteTokenManager::GetInstance().RemoveDeviceMappingTokenID(deviceID, mapID); - ACCESSTOKEN_LOG_ERROR(LABEL, "device %{private}s tokenId %{public}u add local token failed.", - deviceID.c_str(), remoteID); + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s tokenId %{public}u add local token failed.", + ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID); continue; } - ACCESSTOKEN_LOG_INFO(LABEL, "device %{private}s token %{public}u map token %{public}u add success.", - deviceID.c_str(), remoteID, mapID); + ACCESSTOKEN_LOG_INFO(LABEL, "device %{public}s token %{public}u map token %{public}u add success.", + ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID, mapID); } return RET_SUCCESS; @@ -751,13 +752,13 @@ int AccessTokenInfoManager::SetRemoteNativeTokenInfo(const std::string& deviceID int AccessTokenInfoManager::DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID) { if (!DataValidator::IsDeviceIdValid(deviceID)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "device %{private}s parms invalid", deviceID.c_str()); + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s parms invalid", ConstantCommon::EncryptDevId(deviceID).c_str()); return RET_FAILED; } AccessTokenID mapID = AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(deviceID, tokenID); if (mapID == 0) { - ACCESSTOKEN_LOG_ERROR(LABEL, "device %{private}s tokenId %{public}u is not mapped", - deviceID.c_str(), tokenID); + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s tokenId %{public}u is not mapped", + ConstantCommon::EncryptDevId(deviceID).c_str(), tokenID); return RET_FAILED; } @@ -788,7 +789,7 @@ AccessTokenID AccessTokenInfoManager::GetRemoteNativeTokenID(const std::string& { if (!DataValidator::IsDeviceIdValid(deviceID) || AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(tokenID) != TOKEN_NATIVE) { - ACCESSTOKEN_LOG_ERROR(LABEL, "device %{private}s parms invalid", deviceID.c_str()); + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s parms invalid", ConstantCommon::EncryptDevId(deviceID).c_str()); return 0; } return AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(deviceID, tokenID); @@ -797,13 +798,14 @@ AccessTokenID AccessTokenInfoManager::GetRemoteNativeTokenID(const std::string& int AccessTokenInfoManager::DeleteRemoteDeviceTokens(const std::string& deviceID) { if (!DataValidator::IsDeviceIdValid(deviceID)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "device %{private}s parms invalid", deviceID.c_str()); + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s parms invalid", ConstantCommon::EncryptDevId(deviceID).c_str()); return RET_FAILED; } std::vector remoteTokens; int ret = AccessTokenRemoteTokenManager::GetInstance().GetDeviceAllRemoteTokenID(deviceID, remoteTokens); if (ret == RET_FAILED) { - ACCESSTOKEN_LOG_ERROR(LABEL, "device %{private}s have no remote token", deviceID.c_str()); + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s have no remote token", + ConstantCommon::EncryptDevId(deviceID).c_str()); return RET_FAILED; } for (AccessTokenID remoteID : remoteTokens) { @@ -830,11 +832,12 @@ AccessTokenID AccessTokenInfoManager::AllocLocalTokenID(const std::string& remot AccessTokenID remoteTokenID) { if (!DataValidator::IsDeviceIdValid(remoteDeviceID)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "device %{private}s parms invalid", remoteDeviceID.c_str()); + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s parms invalid", + ConstantCommon::EncryptDevId(remoteDeviceID).c_str()); return 0; } std::string remoteUdid = GetUdidByNodeId(remoteDeviceID); - ACCESSTOKEN_LOG_ERROR(LABEL, "device %{private}s remoteUdid", remoteUdid.c_str()); + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s remoteUdid", ConstantCommon::EncryptDevId(remoteUdid).c_str()); AccessTokenID mapID = AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(remoteUdid, remoteTokenID); if (mapID != 0) { @@ -842,8 +845,8 @@ AccessTokenID AccessTokenInfoManager::AllocLocalTokenID(const std::string& remot } int ret = TokenSyncKit::GetRemoteHapTokenInfo(remoteUdid, remoteTokenID); if (ret != RET_SUCCESS) { - ACCESSTOKEN_LOG_ERROR(LABEL, "device %{private}s token %{public}u sync failed", - remoteUdid.c_str(), remoteTokenID); + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s token %{public}u sync failed", + ConstantCommon::EncryptDevId(remoteUdid).c_str(), remoteTokenID); return 0; } diff --git a/services/accesstokenmanager/main/cpp/src/token/accesstoken_remote_token_manager.cpp b/services/accesstokenmanager/main/cpp/src/token/accesstoken_remote_token_manager.cpp index 9ac41f88c6efd6915af6e798cc5774636306af8c..d2240dfe5fc7127dde5b9c3cb1a4c59ad207fc20 100644 --- a/services/accesstokenmanager/main/cpp/src/token/accesstoken_remote_token_manager.cpp +++ b/services/accesstokenmanager/main/cpp/src/token/accesstoken_remote_token_manager.cpp @@ -18,7 +18,7 @@ #include "accesstoken_id_manager.h" #include "accesstoken_log.h" #include "data_validator.h" - +#include "constant_common.h" namespace OHOS { namespace Security { namespace AccessToken { @@ -43,8 +43,8 @@ AccessTokenID AccessTokenRemoteTokenManager::MapRemoteDeviceTokenToLocal(const s AccessTokenID remoteID) { if (!DataValidator::IsDeviceIdValid(deviceID) || !DataValidator::IsTokenIDValid(remoteID)) { - ACCESSTOKEN_LOG_ERROR( - LABEL, "device %{private}s or token %{public}x is invalid.", deviceID.c_str(), remoteID); + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s or token %{public}x is invalid.", + ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID); return 0; } ATokenTypeEnum tokeType = AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(remoteID); @@ -63,8 +63,8 @@ AccessTokenID AccessTokenRemoteTokenManager::MapRemoteDeviceTokenToLocal(const s if (device.MappingTokenIDPairMap_.count(remoteID) > 0) { mapID = device.MappingTokenIDPairMap_[remoteID]; ACCESSTOKEN_LOG_ERROR( - LABEL, "device %{private}s token %{public}x has already mapped, maptokenID is %{public}x.", - deviceID.c_str(), remoteID, mapID); + LABEL, "device %{public}s token %{public}x has already mapped, maptokenID is %{public}x.", + ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID, mapID); return mapID; } mapPtr = &device.MappingTokenIDPairMap_; @@ -78,8 +78,8 @@ AccessTokenID AccessTokenRemoteTokenManager::MapRemoteDeviceTokenToLocal(const s mapID = AccessTokenIDManager::GetInstance().CreateAndRegisterTokenId(tokeType, dlpType); if (mapID == 0) { ACCESSTOKEN_LOG_ERROR( - LABEL, "device %{private}s token %{public}x map local Token failed.", - deviceID.c_str(), remoteID); + LABEL, "device %{public}s token %{public}x map local Token failed.", + ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID); return 0; } mapPtr->insert(std::pair(remoteID, mapID)); @@ -90,12 +90,13 @@ int AccessTokenRemoteTokenManager::GetDeviceAllRemoteTokenID(const std::string& std::vector& remoteIDs) { if (!DataValidator::IsDeviceIdValid(deviceID)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "device %{private}s is valid.", deviceID.c_str()); + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s is valid.", ConstantCommon::EncryptDevId(deviceID).c_str()); return RET_FAILED; } Utils::UniqueReadGuard infoGuard(this->remoteDeviceLock_); if (remoteDeviceMap_.count(deviceID) < 1) { - ACCESSTOKEN_LOG_ERROR(LABEL, "device %{private}s has not mapping.", deviceID.c_str()); + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s has not mapping.", + ConstantCommon::EncryptDevId(deviceID).c_str()); return RET_FAILED; } @@ -109,15 +110,16 @@ AccessTokenID AccessTokenRemoteTokenManager::GetDeviceMappingTokenID(const std:: AccessTokenID remoteID) { if (!DataValidator::IsDeviceIdValid(deviceID) || !DataValidator::IsTokenIDValid(remoteID)) { - ACCESSTOKEN_LOG_ERROR( - LABEL, "device %{private}s or token %{public}x is invalid.", deviceID.c_str(), remoteID); + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s or token %{public}x is invalid.", + ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID); return 0; } Utils::UniqueReadGuard infoGuard(this->remoteDeviceLock_); if (remoteDeviceMap_.count(deviceID) < 1 || remoteDeviceMap_[deviceID].MappingTokenIDPairMap_.count(remoteID) < 1) { - ACCESSTOKEN_LOG_ERROR(LABEL, "device %{private}s has not mapping.", deviceID.c_str()); + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s has not mapping.", + ConstantCommon::EncryptDevId(deviceID).c_str()); return 0; } @@ -128,15 +130,16 @@ int AccessTokenRemoteTokenManager::RemoveDeviceMappingTokenID(const std::string& AccessTokenID remoteID) { if (!DataValidator::IsDeviceIdValid(deviceID) || !DataValidator::IsTokenIDValid(remoteID)) { - ACCESSTOKEN_LOG_ERROR( - LABEL, "device %{private}s or token %{public}x is invalid.", deviceID.c_str(), remoteID); + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s or token %{public}x is invalid.", + ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID); return RET_FAILED; } Utils::UniqueWriteGuard infoGuard(this->remoteDeviceLock_); if (remoteDeviceMap_.count(deviceID) < 1 || remoteDeviceMap_[deviceID].MappingTokenIDPairMap_.count(remoteID) < 1) { - ACCESSTOKEN_LOG_ERROR(LABEL, "device %{private}s has not mapping.", deviceID.c_str()); + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s has not mapping.", + ConstantCommon::EncryptDevId(deviceID).c_str()); return RET_FAILED; } diff --git a/services/accesstokenmanager/main/cpp/src/token/native_token_info_inner.cpp b/services/accesstokenmanager/main/cpp/src/token/native_token_info_inner.cpp index 00c656f841e46cd69233a124ef9ec2e5534fb222..2ad119e8b7a5964de2d2e9283ba4a7f6a6ca5d61 100644 --- a/services/accesstokenmanager/main/cpp/src/token/native_token_info_inner.cpp +++ b/services/accesstokenmanager/main/cpp/src/token/native_token_info_inner.cpp @@ -65,7 +65,7 @@ int NativeTokenInfoInner::Init(AccessTokenID id, const std::string& processName, tokenInfoBasic_.processName = processName; if (!DataValidator::IsAplNumValid(apl)) { ACCESSTOKEN_LOG_ERROR(LABEL, - "tokenID: %{public}u init failed, apl %{public}d is invalid", + "tokenID: %{public}u init failed, apl %d is invalid", tokenInfoBasic_.tokenID, apl); return RET_FAILED; } @@ -128,7 +128,7 @@ int NativeTokenInfoInner::RestoreNativeTokenInfo(AccessTokenID tokenId, const Ge int aplNum = inGenericValues.GetInt(FIELD_APL); if (!DataValidator::IsAplNumValid(aplNum)) { ACCESSTOKEN_LOG_ERROR(LABEL, - "tokenID: %{public}u apl is error, value %{public}d", + "tokenID: %{public}u apl is error, value %d", tokenInfoBasic_.tokenID, aplNum); return RET_FAILED; } @@ -136,7 +136,7 @@ int NativeTokenInfoInner::RestoreNativeTokenInfo(AccessTokenID tokenId, const Ge tokenInfoBasic_.ver = (char)inGenericValues.GetInt(FIELD_TOKEN_VERSION); if (tokenInfoBasic_.ver != DEFAULT_TOKEN_VERSION) { ACCESSTOKEN_LOG_ERROR(LABEL, - "tokenID: %{public}u version is error, version %{public}d", + "tokenID: %{public}u version is error, version %d", tokenInfoBasic_.tokenID, tokenInfoBasic_.ver); return RET_FAILED; } diff --git a/services/accesstokenmanager/main/cpp/src/token/native_token_receptor.cpp b/services/accesstokenmanager/main/cpp/src/token/native_token_receptor.cpp index f948fb3720dbc9d44cf64ad147958899d536db38..0c99a143e24fff4089932674db27717d4f3ef241 100644 --- a/services/accesstokenmanager/main/cpp/src/token/native_token_receptor.cpp +++ b/services/accesstokenmanager/main/cpp/src/token/native_token_receptor.cpp @@ -151,7 +151,7 @@ int NativeTokenReceptor::ReadCfgFile(std::string& nativeRawData) { int32_t fd = open(NATIVE_TOKEN_CONFIG_FILE.c_str(), O_RDONLY); if (fd < 0) { - ACCESSTOKEN_LOG_ERROR(LABEL, "open failed errno %{public}d.", errno); + ACCESSTOKEN_LOG_ERROR(LABEL, "open failed errno %d.", errno); return RET_FAILED; } struct stat statBuffer; diff --git a/services/privacymanager/include/common/constant.h b/services/privacymanager/include/common/constant.h index 5a7a0de70d17b628983c55d46e2ba723f4442709..6e3602ac6997e3bb12487543d7179de4991567ad 100644 --- a/services/privacymanager/include/common/constant.h +++ b/services/privacymanager/include/common/constant.h @@ -67,8 +67,6 @@ public: public: static bool TransferPermissionToOpcode(const std::string& permissionName, int32_t& opCode); static bool TransferOpcodeToPermission(int32_t opCode, std::string& permissionName); - - static std::string GetLocalDeviceUdid(); }; } // namespace AccessToken } // namespace Security diff --git a/services/privacymanager/src/common/constant.cpp b/services/privacymanager/src/common/constant.cpp index 1f3bc55f1215651a1fa49e5d34efa947a4122c9b..34fda467f258b1d64a42f07a37f98c7203b51854 100644 --- a/services/privacymanager/src/common/constant.cpp +++ b/services/privacymanager/src/common/constant.cpp @@ -14,7 +14,6 @@ */ #include "constant.h" -#include "parameter.h" namespace OHOS { namespace Security { @@ -70,19 +69,6 @@ bool Constant::TransferOpcodeToPermission(int32_t opCode, std::string& permissio permissionName = iter->first; return true; } - -std::string Constant::GetLocalDeviceUdid() -{ - static std::string localDeviceId; - if (!localDeviceId.empty()) { - return localDeviceId; - } - const int32_t DEVICE_UUID_LENGTH = 65; - char udid[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(udid, DEVICE_UUID_LENGTH); - localDeviceId = udid; - return localDeviceId; -} } // namespace AccessToken } // namespace Security } // namespace OHOS \ No newline at end of file diff --git a/services/privacymanager/src/record/permission_record_manager.cpp b/services/privacymanager/src/record/permission_record_manager.cpp index a852f57f418ee3359b486f76ae76bd7acef7f522..024790c7d1f230b01a13fe4c1ca016359d66253c 100644 --- a/services/privacymanager/src/record/permission_record_manager.cpp +++ b/services/privacymanager/src/record/permission_record_manager.cpp @@ -18,6 +18,7 @@ #include "accesstoken_kit.h" #include "accesstoken_log.h" #include "constant.h" +#include "constant_common.h" #include "data_translator.h" #include "field_const.h" #include "permission_record_repository.h" @@ -89,7 +90,7 @@ bool PermissionRecordManager::GetPermissionVisitor(AccessTokenID tokenID, Permis visitor.userId = tokenInfo.userID; visitor.bundleName = tokenInfo.bundleName; if (IsLocalDevice(tokenInfo.deviceID)) { - visitor.deviceId = Constant::GetLocalDeviceUdid(); + visitor.deviceId = ConstantCommon::GetLocalDeviceId(); visitor.isRemoteDevice = false; visitor.tokenId = tokenID; } diff --git a/services/privacymanager/src/service/privacy_manager_service.cpp b/services/privacymanager/src/service/privacy_manager_service.cpp index 0f1d28343c7673bbbcb4a55911d10c4ac18a6d0e..1f9cecd49093288fff571c590dc68b9b9acf3184 100644 --- a/services/privacymanager/src/service/privacy_manager_service.cpp +++ b/services/privacymanager/src/service/privacy_manager_service.cpp @@ -16,6 +16,7 @@ #include "privacy_manager_service.h" #include "accesstoken_log.h" +#include "constant_common.h" #include "constant.h" #include "ipc_skeleton.h" #include "permission_record_manager.h" @@ -94,7 +95,8 @@ int32_t PrivacyManagerService::StopUsingPermission(AccessTokenID tokenID, const int32_t PrivacyManagerService::RemovePermissionUsedRecords(AccessTokenID tokenID, const std::string& deviceID) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "Entry, tokenID: 0x%{public}x, deviceID: %{private}s", tokenID, deviceID.c_str()); + ACCESSTOKEN_LOG_DEBUG(LABEL, "Entry, tokenID: 0x%{public}x, deviceID: %{public}s", + tokenID, ConstantCommon::EncryptDevId(deviceID).c_str()); PermissionRecordManager::GetInstance().RemovePermissionUsedRecords(tokenID, deviceID); return Constant::SUCCESS; } diff --git a/services/tokensyncmanager/include/common/constant.h b/services/tokensyncmanager/include/common/constant.h index 3a7d0d5e60b3ca60022fbfc79d6352e6dc0a15d4..391c686586c4929799ccbed25c243e40fb9c73b6 100644 --- a/services/tokensyncmanager/include/common/constant.h +++ b/services/tokensyncmanager/include/common/constant.h @@ -68,26 +68,7 @@ public: * Command result string, indicates failed. */ static const std::string COMMAND_RESULT_FAILED; - - /** - * Device id length. - */ - const static int32_t DEVICE_UUID_LENGTH = 65; - - /** - * Command status code, indicate a status of command before RPC call. - */ const static int32_t DELAY_SYNC_TOKEN_MS = 3000; - - static constexpr int32_t ENCRYPTLEN = 4; - static constexpr int32_t ENCRYPTBEGIN = 0; - static constexpr int32_t ENCRYPTEND = 3; - static std::string EncryptDevId(std::string deviceId); - - /** - * GetLocalDeviceId - */ - static std::string GetLocalDeviceId(); }; } // namespace AccessToken } // namespace Security diff --git a/services/tokensyncmanager/src/command/delete_remote_token_command.cpp b/services/tokensyncmanager/src/command/delete_remote_token_command.cpp index f09bb04c91560e7fcc30a9f17a78c5478e43d2a2..a0043c0e9351270baaafc6dd6f0b7153cd9d777e 100644 --- a/services/tokensyncmanager/src/command/delete_remote_token_command.cpp +++ b/services/tokensyncmanager/src/command/delete_remote_token_command.cpp @@ -18,6 +18,8 @@ #include "accesstoken_kit.h" #include "accesstoken_log.h" #include "base_remote_command.h" +#include "constant_common.h" +#include "constant.h" #include "device_info.h" #include "device_info_manager.h" @@ -73,7 +75,7 @@ void DeleteRemoteTokenCommand::Prepare() void DeleteRemoteTokenCommand::Execute() { ACCESSTOKEN_LOG_INFO(LABEL, "execute: start as: DeleteRemoteTokenCommand"); - remoteProtocol_.responseDeviceId = Constant::GetLocalDeviceId(); + remoteProtocol_.responseDeviceId = ConstantCommon::GetLocalDeviceId(); remoteProtocol_.responseVersion = Constant::DISTRIBUTED_ACCESS_TOKEN_SERVICE_VERSION; DeviceInfo devInfo; diff --git a/services/tokensyncmanager/src/command/sync_remote_hap_token_command.cpp b/services/tokensyncmanager/src/command/sync_remote_hap_token_command.cpp index 65d0ef836fd31716f4b76927a2f1c292ae79b247..dc12d829b9ac3243e93529832d3d1d9acdf78554 100644 --- a/services/tokensyncmanager/src/command/sync_remote_hap_token_command.cpp +++ b/services/tokensyncmanager/src/command/sync_remote_hap_token_command.cpp @@ -17,6 +17,8 @@ #include "accesstoken_kit.h" #include "accesstoken_log.h" +#include "constant_common.h" +#include "constant.h" #include "base_remote_command.h" namespace OHOS { @@ -92,7 +94,7 @@ void SyncRemoteHapTokenCommand::Prepare() void SyncRemoteHapTokenCommand::Execute() { ACCESSTOKEN_LOG_INFO(LABEL, "execute: start as: SyncRemoteHapTokenCommand"); - remoteProtocol_.responseDeviceId = Constant::GetLocalDeviceId(); + remoteProtocol_.responseDeviceId = ConstantCommon::GetLocalDeviceId(); remoteProtocol_.responseVersion = Constant::DISTRIBUTED_ACCESS_TOKEN_SERVICE_VERSION; int ret = AccessTokenKit::GetHapTokenInfoFromRemote(requestTokenId_, hapTokenInfo_); diff --git a/services/tokensyncmanager/src/command/sync_remote_native_token_command.cpp b/services/tokensyncmanager/src/command/sync_remote_native_token_command.cpp index e61d6f618c79e85cd1df2aaa723552aca7e5fdd1..80c52de868a23347aac3eb73cd05dcde4a560126 100644 --- a/services/tokensyncmanager/src/command/sync_remote_native_token_command.cpp +++ b/services/tokensyncmanager/src/command/sync_remote_native_token_command.cpp @@ -18,6 +18,8 @@ #include "accesstoken_kit.h" #include "accesstoken_log.h" #include "base_remote_command.h" +#include "constant_common.h" +#include "constant.h" #include "device_info_manager.h" namespace OHOS { @@ -76,7 +78,7 @@ void SyncRemoteNativeTokenCommand::Prepare() void SyncRemoteNativeTokenCommand::Execute() { ACCESSTOKEN_LOG_INFO(LABEL, "execute: start as: SyncRemoteNativeTokenCommand"); - remoteProtocol_.responseDeviceId = Constant::GetLocalDeviceId(); + remoteProtocol_.responseDeviceId = ConstantCommon::GetLocalDeviceId(); remoteProtocol_.responseVersion = Constant::DISTRIBUTED_ACCESS_TOKEN_SERVICE_VERSION; int ret = AccessTokenKit::GetAllNativeTokenInfo(nativeTokenInfo_); diff --git a/services/tokensyncmanager/src/command/update_remote_hap_token_command.cpp b/services/tokensyncmanager/src/command/update_remote_hap_token_command.cpp index 0d6dfe6e6bdb452daf2c0e2c5011c9729cbb669c..78865714e6a0167ac6956e7a456547d97b9072f3 100644 --- a/services/tokensyncmanager/src/command/update_remote_hap_token_command.cpp +++ b/services/tokensyncmanager/src/command/update_remote_hap_token_command.cpp @@ -18,6 +18,8 @@ #include "accesstoken_kit.h" #include "accesstoken_log.h" #include "base_remote_command.h" +#include "constant_common.h" +#include "constant.h" #include "device_info_manager.h" namespace OHOS { @@ -69,7 +71,7 @@ void UpdateRemoteHapTokenCommand::Execute() { ACCESSTOKEN_LOG_INFO(LABEL, "execute: start as: UpdateRemoteHapTokenCommand"); - remoteProtocol_.responseDeviceId = Constant::GetLocalDeviceId(); + remoteProtocol_.responseDeviceId = ConstantCommon::GetLocalDeviceId(); remoteProtocol_.responseVersion = Constant::DISTRIBUTED_ACCESS_TOKEN_SERVICE_VERSION; DeviceInfo devInfo; diff --git a/services/tokensyncmanager/src/common/constant.cpp b/services/tokensyncmanager/src/common/constant.cpp index a20a7cc052547f48bc296da132c9ec33cb4c1711..7de4ff1875c7b4d030bad6818fd21e8175b1ce24 100644 --- a/services/tokensyncmanager/src/common/constant.cpp +++ b/services/tokensyncmanager/src/common/constant.cpp @@ -23,24 +23,6 @@ static const std::string REPLACE_TARGET = "****"; } // namespace const std::string Constant::COMMAND_RESULT_SUCCESS = "success"; const std::string Constant::COMMAND_RESULT_FAILED = "execute command failed"; - -std::string Constant::EncryptDevId(std::string deviceId) -{ - std::string result = deviceId; - if (deviceId.size() >= ENCRYPTLEN) { - result.replace(ENCRYPTBEGIN, ENCRYPTEND, REPLACE_TARGET); - } else { - result.replace(ENCRYPTBEGIN, result.size() - 1, REPLACE_TARGET); - } - return result; -} - -std::string Constant::GetLocalDeviceId() -{ - char deviceIdCharArray[Constant::DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(deviceIdCharArray, Constant::DEVICE_UUID_LENGTH); - return deviceIdCharArray; -} } // namespace AccessToken } // namespace Security } // namespace OHOS diff --git a/services/tokensyncmanager/src/device/device_info_manager.cpp b/services/tokensyncmanager/src/device/device_info_manager.cpp index dfe35aa9a36e3a42a26dd1bb3acfc9c428d863af..9c6723618b8aebf9a3e0544271fe9a5b9d08bb2f 100644 --- a/services/tokensyncmanager/src/device/device_info_manager.cpp +++ b/services/tokensyncmanager/src/device/device_info_manager.cpp @@ -14,6 +14,7 @@ */ #include "device_info_manager.h" +#include "constant_common.h" namespace OHOS { namespace Security { @@ -54,11 +55,11 @@ void DeviceInfoManager::AddDeviceInfo(const std::string &networkId, const std::s void DeviceInfoManager::RemoveAllRemoteDeviceInfo() { - char deviceIdCharArray[Constant::DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(deviceIdCharArray, Constant::DEVICE_UUID_LENGTH); + std::string localDevice = ConstantCommon::GetLocalDeviceId(); + DeviceInfo localDeviceInfoOpt; if (DeviceInfoRepository::GetInstance().FindDeviceInfo( - deviceIdCharArray, DeviceIdType::UNIQUE_DISABILITY_ID, localDeviceInfoOpt)) { + localDevice, DeviceIdType::UNIQUE_DISABILITY_ID, localDeviceInfoOpt)) { DeviceInfoRepository::GetInstance().DeleteAllDeviceInfoExceptOne(localDeviceInfoOpt); } } @@ -69,10 +70,9 @@ void DeviceInfoManager::RemoveRemoteDeviceInfo(const std::string &nodeId, Device ACCESSTOKEN_LOG_ERROR(LABEL, "removeDeviceInfoByNetworkId: nodeId is invalid"); } else { DeviceInfo deviceInfo; - char deviceIdCharArray[Constant::DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(deviceIdCharArray, Constant::DEVICE_UUID_LENGTH); + std::string localDevice = ConstantCommon::GetLocalDeviceId(); if (DeviceInfoRepository::GetInstance().FindDeviceInfo(nodeId, deviceIdType, deviceInfo)) { - if (deviceInfo.deviceId.uniqueDeviceId != deviceIdCharArray) { + if (deviceInfo.deviceId.uniqueDeviceId != localDevice) { DeviceInfoRepository::GetInstance().DeleteDeviceInfo(nodeId, deviceIdType); } } @@ -119,17 +119,18 @@ std::string DeviceInfoManager::ConvertToUniqueDeviceIdOrFetch(const std::string } else { ACCESSTOKEN_LOG_DEBUG(LABEL, "FindDeviceInfo succeed, udid and local udid is empty, nodeId(%{public}s)", - Constant::EncryptDevId(nodeId).c_str()); + ConstantCommon::EncryptDevId(nodeId).c_str()); } } else { ACCESSTOKEN_LOG_DEBUG(LABEL, "FindDeviceInfo succeed, udid is empty, nodeId(%{public}s) ", - Constant::EncryptDevId(nodeId).c_str()); + ConstantCommon::EncryptDevId(nodeId).c_str()); result = uniqueDeviceId; } } else { ACCESSTOKEN_LOG_DEBUG( - LABEL, "FindDeviceInfo failed, nodeId(%{public}s)", Constant::EncryptDevId(nodeId).c_str()); + LABEL, "FindDeviceInfo failed, nodeId(%{public}s)", + ConstantCommon::EncryptDevId(nodeId).c_str()); auto list = DeviceInfoRepository::GetInstance().ListDeviceInfo(); auto iter = list.begin(); for (; iter != list.end(); iter++) { @@ -140,7 +141,7 @@ std::string DeviceInfoManager::ConvertToUniqueDeviceIdOrFetch(const std::string LABEL, ">>> DeviceInfoRepository device type: %{public}s", info.deviceType.c_str()); ACCESSTOKEN_LOG_DEBUG(LABEL, ">>> DeviceInfoRepository device network id: %{public}s", - Constant::EncryptDevId(info.deviceId.networkId).c_str()); + ConstantCommon::EncryptDevId(info.deviceId.networkId).c_str()); } } return result; diff --git a/services/tokensyncmanager/src/remote/remote_command_executor.cpp b/services/tokensyncmanager/src/remote/remote_command_executor.cpp index 74029f95f4f39ef2dc3af1e15cb09b09ae1f5e8b..659a8acf321b800c5e0e7c922eb2adf3209748f5 100644 --- a/services/tokensyncmanager/src/remote/remote_command_executor.cpp +++ b/services/tokensyncmanager/src/remote/remote_command_executor.cpp @@ -1,332 +1,331 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "remote_command_executor.h" - -#include "device_info_manager.h" -#include "parameter.h" -#include "singleton.h" -#include "soft_bus_channel.h" -#include "token_sync_event_handler.h" -#include "token_sync_manager_service.h" - -namespace OHOS { -namespace Security { -namespace AccessToken { -namespace { -static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "RemoteCommandExecutor"}; -static const std::string TASK_NAME = "RemoteCommandExecutor::ProcessBufferedCommandsWithThread"; -} // namespace -RemoteCommandExecutor::RemoteCommandExecutor(const std::string &targetNodeId) - : targetNodeId_(targetNodeId), ptrChannel_(nullptr), mutex_(), commands_(), running_(false) -{ - ACCESSTOKEN_LOG_DEBUG(LABEL, "RemoteCommandExecutor()"); -} - -RemoteCommandExecutor::~RemoteCommandExecutor() -{ - ACCESSTOKEN_LOG_DEBUG(LABEL, "~RemoteCommandExecutor() begin"); - running_ = false; -} - -const std::shared_ptr RemoteCommandExecutor::CreateChannel(const std::string &targetNodeId) -{ - ACCESSTOKEN_LOG_DEBUG(LABEL, "CreateChannel: targetNodeId=%{public}s", targetNodeId.c_str()); - // only consider SoftBusChannel - std::shared_ptr ptrChannel = std::make_shared(targetNodeId); - if (ptrChannel == nullptr) { - ACCESSTOKEN_LOG_INFO( - LABEL, "CreateChannel: create channel failed, targetNodeId=%{public}s", targetNodeId.c_str()); - } - return ptrChannel; -} - -/* - * called by RemoteCommandExecutor, RemoteCommandManager - */ -int RemoteCommandExecutor::ProcessOneCommand(const std::shared_ptr &ptrCommand) -{ - if (ptrCommand == nullptr) { - ACCESSTOKEN_LOG_WARN( - LABEL, "targetNodeId %{public}s, attempt to process on null command.", targetNodeId_.c_str()); - return Constant::SUCCESS; - } - const std::string uniqueId = ptrCommand->remoteProtocol_.uniqueId; - ACCESSTOKEN_LOG_INFO(LABEL, - "targetNodeId %{public}s, process one command start, uniqueId: %{public}s", - targetNodeId_.c_str(), - uniqueId.c_str()); - - ptrCommand->Prepare(); - int status = ptrCommand->remoteProtocol_.statusCode; - if (status != Constant::SUCCESS) { - ACCESSTOKEN_LOG_ERROR(LABEL, - "targetNodeId %{public}s, process one command error, uniqueId: %{public}s, message: " - "prepare failure code %{public}d", - targetNodeId_.c_str(), - uniqueId.c_str(), - status); - return status; - } - - char localUdid[Constant::DEVICE_UUID_LENGTH] = {0}; - ::GetDevUdid(localUdid, Constant::DEVICE_UUID_LENGTH); - if (targetNodeId_ == localUdid) { - return ExecuteRemoteCommand(ptrCommand, false); - } - - // otherwise a remote device - CreateChannelIfNeeded(); - if (ptrChannel_ == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "targetNodeId %{public}s, channel is null.", targetNodeId_.c_str()); - return Constant::FAILURE; - } - if (ptrChannel_->BuildConnection() != Constant::SUCCESS) { - ACCESSTOKEN_LOG_ERROR(LABEL, "targetNodeId %{public}s, channel is not ready.", targetNodeId_.c_str()); - return Constant::FAILURE; - } - - return ExecuteRemoteCommand(ptrCommand, true); -} - -/* - * called by RemoteCommandManager - */ -int RemoteCommandExecutor::AddCommand(const std::shared_ptr &ptrCommand) -{ - if (ptrCommand == nullptr) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "targetNodeId %{public}s, attempt to add an empty command.", - targetNodeId_.c_str()); - return Constant::INVALID_COMMAND; - } - - const std::string uniqueId = ptrCommand->remoteProtocol_.uniqueId; - ACCESSTOKEN_LOG_DEBUG( - LABEL, "targetNodeId %{public}s, add uniqueId %{public}s", targetNodeId_.c_str(), uniqueId.c_str()); - - std::unique_lock lock(mutex_); - - // make sure do not have the same command in the command buffer - for (const auto& bufferedCommand : commands_) { - if (bufferedCommand->remoteProtocol_.uniqueId == uniqueId) { - ACCESSTOKEN_LOG_WARN(LABEL, - "targetNodeId %{public}s, add uniqueId %{public}s, already exist in the buffer, skip", - targetNodeId_.c_str(), - uniqueId.c_str()); - return Constant::SUCCESS; - } - } - - commands_.push_back(ptrCommand); - return Constant::SUCCESS; -} - -/* - * called by RemoteCommandExecutor.ProcessCommandThread, RemoteCommandManager - */ -int RemoteCommandExecutor::ProcessBufferedCommands(bool standalone) -{ - ACCESSTOKEN_LOG_INFO( - LABEL, "begin, targetNodeId: %{public}s, standalone: %{public}d", targetNodeId_.c_str(), standalone); - - std::unique_lock lock(mutex_); - - if (commands_.empty()) { - ACCESSTOKEN_LOG_WARN(LABEL, "no command, targetNodeId %{public}s", targetNodeId_.c_str()); - running_ = false; - return Constant::SUCCESS; - } - - running_ = true; - while (true) { - // interrupt - if (!running_) { - ACCESSTOKEN_LOG_INFO( - LABEL, "end with running flag == false, targetNodeId: %{public}s", targetNodeId_.c_str()); - return Constant::FAILURE; - } - // end - if (commands_.empty()) { - running_ = false; - ACCESSTOKEN_LOG_INFO(LABEL, "end, no command left, targetNodeId: %{public}s", targetNodeId_.c_str()); - return Constant::SUCCESS; - } - - // consume queue to execute - const std::shared_ptr bufferedCommand = commands_.front(); - int status = ProcessOneCommand(bufferedCommand); - if (status == Constant::SUCCESS) { - commands_.pop_front(); - continue; - } else if (status == Constant::FAILURE_BUT_CAN_RETRY) { - ACCESSTOKEN_LOG_WARN(LABEL, - "execute failed and wait to retry, targetNodeId: %{public}s, message: %{public}s, and will retry ", - targetNodeId_.c_str(), - bufferedCommand->remoteProtocol_.message.c_str()); - - // now, the retry at once will have no effective because the network problem - // so if the before the step, one command is added, and run this function - // it should also not need to restart to process the commands buffer at once. - running_ = false; - return Constant::FAILURE; - } else { - // this command failed, move on to execute next command - commands_.pop_front(); - ACCESSTOKEN_LOG_ERROR(LABEL, - "execute failed, targetNodeId: %{public}s, commandName: %{public}s, message: %{public}s", - targetNodeId_.c_str(), - bufferedCommand->remoteProtocol_.commandName.c_str(), - bufferedCommand->remoteProtocol_.message.c_str()); - } - } -} - -/* - * called by RemoteCommandManager - */ -void RemoteCommandExecutor::ProcessBufferedCommandsWithThread() -{ - ACCESSTOKEN_LOG_INFO(LABEL, "begin, targetNodeId: %{public}s", targetNodeId_.c_str()); - - std::unique_lock lock(mutex_); - - if (commands_.empty()) { - ACCESSTOKEN_LOG_INFO(LABEL, "No buffered commands. targetNodeId: %{public}s", targetNodeId_.c_str()); - return; - } - if (running_) { - // task is running, do not need to start one more - ACCESSTOKEN_LOG_WARN(LABEL, "task busy. targetNodeId: %{public}s", targetNodeId_.c_str()); - return; - } - - running_ = true; - const std::function runner = std::bind(&RemoteCommandExecutor::ProcessBufferedCommands, this, true); - - std::shared_ptr handler = - DelayedSingleton::GetInstance()->GetSendEventHandler(); - if (handler == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "fail to get EventHandler"); - return; - } - bool result = handler->ProxyPostTask(runner, TASK_NAME); - if (!result) { - ACCESSTOKEN_LOG_ERROR(LABEL, "post task failed, targetNodeId: %{public}s", targetNodeId_.c_str()); - } - ACCESSTOKEN_LOG_INFO(LABEL, - "post task succeed, targetNodeId: %{public}s, taskName: %{public}s", - targetNodeId_.c_str(), - TASK_NAME.c_str()); -} - -int RemoteCommandExecutor::ExecuteRemoteCommand( - const std::shared_ptr &ptrCommand, const bool isRemote) -{ - std::string uniqueId = ptrCommand->remoteProtocol_.uniqueId; - ACCESSTOKEN_LOG_INFO(LABEL, - "targetNodeId %{public}s, uniqueId %{public}s, remote %{public}d: start to execute", - targetNodeId_.c_str(), - uniqueId.c_str(), - isRemote); - - ptrCommand->remoteProtocol_.statusCode = Constant::STATUS_CODE_BEFORE_RPC; - - if (!isRemote) { - // Local device, play myself. - ptrCommand->Execute(); - int code = ClientProcessResult(ptrCommand); - ACCESSTOKEN_LOG_DEBUG(LABEL, - "command finished with status: %{public}d, message: %{public}s", - ptrCommand->remoteProtocol_.statusCode, - ptrCommand->remoteProtocol_.message.c_str()); - return code; - } - - std::string responseString = - ptrChannel_->ExecuteCommand(ptrCommand->remoteProtocol_.commandName, ptrCommand->ToJsonPayload()); - ACCESSTOKEN_LOG_INFO(LABEL, "command executed uniqueId %{public}s", uniqueId.c_str()); - if (responseString.empty()) { - ACCESSTOKEN_LOG_WARN(LABEL, - "targetNodeId %{public}s, uniqueId %{public}s, execute remote command error, response is empty.", - targetNodeId_.c_str(), - uniqueId.c_str()); - // if command send failed, also try to close session - if (commands_.empty()) { - ptrChannel_->CloseConnection(); - } - return Constant::FAILURE; - } - - std::shared_ptr ptrResponseCommand = - RemoteCommandFactory::GetInstance().NewRemoteCommandFromJson( - ptrCommand->remoteProtocol_.commandName, responseString); - if (ptrResponseCommand == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "targetNodeId %{public}s, get null response command!", targetNodeId_.c_str()); - return Constant::FAILURE; - } - int32_t result = ClientProcessResult(ptrResponseCommand); - if (commands_.empty()) { - ptrChannel_->CloseConnection(); - } - ACCESSTOKEN_LOG_DEBUG(LABEL, - "command finished with status: %{public}d, message: %{public}s", - ptrResponseCommand->remoteProtocol_.statusCode, - ptrResponseCommand->remoteProtocol_.message.c_str()); - return result; -} - -void RemoteCommandExecutor::CreateChannelIfNeeded() -{ - std::unique_lock lock(mutex_); - if (ptrChannel_ != nullptr) { - ACCESSTOKEN_LOG_INFO(LABEL, "targetNodeId %{public}s, channel is exist.", targetNodeId_.c_str()); - return; - } - - ptrChannel_ = CreateChannel(targetNodeId_); -} - -int RemoteCommandExecutor::ClientProcessResult(const std::shared_ptr &ptrCommand) -{ - std::string uniqueId = ptrCommand->remoteProtocol_.uniqueId; - if (ptrCommand->remoteProtocol_.statusCode == Constant::STATUS_CODE_BEFORE_RPC) { - ACCESSTOKEN_LOG_ERROR(LABEL, - "targetNodeId %{public}s, uniqueId %{public}s, status code after RPC is same as before, the remote side " - "may not " - "support this command", - targetNodeId_.c_str(), - uniqueId.c_str()); - return Constant::FAILURE; - } - - ptrCommand->Finish(); - int status = ptrCommand->remoteProtocol_.statusCode; - if (status != Constant::SUCCESS) { - ACCESSTOKEN_LOG_ERROR(LABEL, - "targetNodeId %{public}s, uniqueId %{public}s, execute failed, message: %{public}s", - targetNodeId_.c_str(), - uniqueId.c_str(), - ptrCommand->remoteProtocol_.message.c_str()); - } else { - ACCESSTOKEN_LOG_INFO(LABEL, - "targetNodeId %{public}s, uniqueId %{public}s, execute succeed.", - targetNodeId_.c_str(), - uniqueId.c_str()); - } - return status; -} -} // namespace AccessToken -} // namespace Security -} // namespace OHOS +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "remote_command_executor.h" +#include "constant_common.h" +#include "device_info_manager.h" +#include "parameter.h" +#include "singleton.h" +#include "soft_bus_channel.h" +#include "token_sync_event_handler.h" +#include "token_sync_manager_service.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "RemoteCommandExecutor"}; +static const std::string TASK_NAME = "RemoteCommandExecutor::ProcessBufferedCommandsWithThread"; +} // namespace +RemoteCommandExecutor::RemoteCommandExecutor(const std::string &targetNodeId) + : targetNodeId_(targetNodeId), ptrChannel_(nullptr), mutex_(), commands_(), running_(false) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "RemoteCommandExecutor()"); +} + +RemoteCommandExecutor::~RemoteCommandExecutor() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "~RemoteCommandExecutor() begin"); + running_ = false; +} + +const std::shared_ptr RemoteCommandExecutor::CreateChannel(const std::string &targetNodeId) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "CreateChannel: targetNodeId=%{public}s", targetNodeId.c_str()); + // only consider SoftBusChannel + std::shared_ptr ptrChannel = std::make_shared(targetNodeId); + if (ptrChannel == nullptr) { + ACCESSTOKEN_LOG_INFO( + LABEL, "CreateChannel: create channel failed, targetNodeId=%{public}s", targetNodeId.c_str()); + } + return ptrChannel; +} + +/* + * called by RemoteCommandExecutor, RemoteCommandManager + */ +int RemoteCommandExecutor::ProcessOneCommand(const std::shared_ptr &ptrCommand) +{ + if (ptrCommand == nullptr) { + ACCESSTOKEN_LOG_WARN( + LABEL, "targetNodeId %{public}s, attempt to process on null command.", targetNodeId_.c_str()); + return Constant::SUCCESS; + } + const std::string uniqueId = ptrCommand->remoteProtocol_.uniqueId; + ACCESSTOKEN_LOG_INFO(LABEL, + "targetNodeId %{public}s, process one command start, uniqueId: %{public}s", + targetNodeId_.c_str(), + uniqueId.c_str()); + + ptrCommand->Prepare(); + int status = ptrCommand->remoteProtocol_.statusCode; + if (status != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, + "targetNodeId %{public}s, process one command error, uniqueId: %{public}s, message: " + "prepare failure code %{public}d", + targetNodeId_.c_str(), + uniqueId.c_str(), + status); + return status; + } + + std::string localUdid = ConstantCommon::GetLocalDeviceId(); + if (targetNodeId_ == localUdid) { + return ExecuteRemoteCommand(ptrCommand, false); + } + + // otherwise a remote device + CreateChannelIfNeeded(); + if (ptrChannel_ == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "targetNodeId %{public}s, channel is null.", targetNodeId_.c_str()); + return Constant::FAILURE; + } + if (ptrChannel_->BuildConnection() != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "targetNodeId %{public}s, channel is not ready.", targetNodeId_.c_str()); + return Constant::FAILURE; + } + + return ExecuteRemoteCommand(ptrCommand, true); +} + +/* + * called by RemoteCommandManager + */ +int RemoteCommandExecutor::AddCommand(const std::shared_ptr &ptrCommand) +{ + if (ptrCommand == nullptr) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "targetNodeId %{public}s, attempt to add an empty command.", + targetNodeId_.c_str()); + return Constant::INVALID_COMMAND; + } + + const std::string uniqueId = ptrCommand->remoteProtocol_.uniqueId; + ACCESSTOKEN_LOG_DEBUG( + LABEL, "targetNodeId %{public}s, add uniqueId %{public}s", targetNodeId_.c_str(), uniqueId.c_str()); + + std::unique_lock lock(mutex_); + + // make sure do not have the same command in the command buffer + for (auto bufferedCommand : commands_) { + if (bufferedCommand->remoteProtocol_.uniqueId == uniqueId) { + ACCESSTOKEN_LOG_WARN(LABEL, + "targetNodeId %{public}s, add uniqueId %{public}s, already exist in the buffer, skip", + targetNodeId_.c_str(), + uniqueId.c_str()); + return Constant::SUCCESS; + } + } + + commands_.push_back(ptrCommand); + return Constant::SUCCESS; +} + +/* + * called by RemoteCommandExecutor.ProcessCommandThread, RemoteCommandManager + */ +int RemoteCommandExecutor::ProcessBufferedCommands(bool standalone) +{ + ACCESSTOKEN_LOG_INFO( + LABEL, "begin, targetNodeId: %{public}s, standalone: %{public}d", targetNodeId_.c_str(), standalone); + + std::unique_lock lock(mutex_); + + if (commands_.empty()) { + ACCESSTOKEN_LOG_WARN(LABEL, "no command, targetNodeId %{public}s", targetNodeId_.c_str()); + running_ = false; + return Constant::SUCCESS; + } + + running_ = true; + while (true) { + // interrupt + if (!running_) { + ACCESSTOKEN_LOG_INFO( + LABEL, "end with running flag == false, targetNodeId: %{public}s", targetNodeId_.c_str()); + return Constant::FAILURE; + } + // end + if (commands_.empty()) { + running_ = false; + ACCESSTOKEN_LOG_INFO(LABEL, "end, no command left, targetNodeId: %{public}s", targetNodeId_.c_str()); + return Constant::SUCCESS; + } + + // consume queue to execute + const std::shared_ptr bufferedCommand = commands_.front(); + int status = ProcessOneCommand(bufferedCommand); + if (status == Constant::SUCCESS) { + commands_.pop_front(); + continue; + } else if (status == Constant::FAILURE_BUT_CAN_RETRY) { + ACCESSTOKEN_LOG_WARN(LABEL, + "execute failed and wait to retry, targetNodeId: %{public}s, message: %{public}s, and will retry ", + targetNodeId_.c_str(), + bufferedCommand->remoteProtocol_.message.c_str()); + + // now, the retry at once will have no effective because the network problem + // so if the before the step, one command is added, and run this function + // it should also not need to restart to process the commands buffer at once. + running_ = false; + return Constant::FAILURE; + } else { + // this command failed, move on to execute next command + commands_.pop_front(); + ACCESSTOKEN_LOG_ERROR(LABEL, + "execute failed, targetNodeId: %{public}s, commandName: %{public}s, message: %{public}s", + targetNodeId_.c_str(), + bufferedCommand->remoteProtocol_.commandName.c_str(), + bufferedCommand->remoteProtocol_.message.c_str()); + } + } +} + +/* + * called by RemoteCommandManager + */ +void RemoteCommandExecutor::ProcessBufferedCommandsWithThread() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "begin, targetNodeId: %{public}s", targetNodeId_.c_str()); + + std::unique_lock lock(mutex_); + + if (commands_.empty()) { + ACCESSTOKEN_LOG_INFO(LABEL, "No buffered commands. targetNodeId: %{public}s", targetNodeId_.c_str()); + return; + } + if (running_) { + // task is running, do not need to start one more + ACCESSTOKEN_LOG_WARN(LABEL, "task busy. targetNodeId: %{public}s", targetNodeId_.c_str()); + return; + } + + running_ = true; + const std::function runner = std::bind(&RemoteCommandExecutor::ProcessBufferedCommands, this, true); + + std::shared_ptr handler = + DelayedSingleton::GetInstance()->GetSendEventHandler(); + if (handler == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "fail to get EventHandler"); + return; + } + bool result = handler->ProxyPostTask(runner, TASK_NAME); + if (!result) { + ACCESSTOKEN_LOG_ERROR(LABEL, "post task failed, targetNodeId: %{public}s", targetNodeId_.c_str()); + } + ACCESSTOKEN_LOG_INFO(LABEL, + "post task succeed, targetNodeId: %{public}s, taskName: %{public}s", + targetNodeId_.c_str(), + TASK_NAME.c_str()); +} + +int RemoteCommandExecutor::ExecuteRemoteCommand( + const std::shared_ptr &ptrCommand, const bool isRemote) +{ + std::string uniqueId = ptrCommand->remoteProtocol_.uniqueId; + ACCESSTOKEN_LOG_INFO(LABEL, + "targetNodeId %{public}s, uniqueId %{public}s, remote %{public}d: start to execute", + targetNodeId_.c_str(), + uniqueId.c_str(), + isRemote); + + ptrCommand->remoteProtocol_.statusCode = Constant::STATUS_CODE_BEFORE_RPC; + + if (!isRemote) { + // Local device, play myself. + ptrCommand->Execute(); + int code = ClientProcessResult(ptrCommand); + ACCESSTOKEN_LOG_DEBUG(LABEL, + "command finished with status: %{public}d, message: %{public}s", + ptrCommand->remoteProtocol_.statusCode, + ptrCommand->remoteProtocol_.message.c_str()); + return code; + } + + std::string responseString = + ptrChannel_->ExecuteCommand(ptrCommand->remoteProtocol_.commandName, ptrCommand->ToJsonPayload()); + ACCESSTOKEN_LOG_INFO(LABEL, "command executed uniqueId %{public}s", uniqueId.c_str()); + if (responseString.empty()) { + ACCESSTOKEN_LOG_WARN(LABEL, + "targetNodeId %{public}s, uniqueId %{public}s, execute remote command error, response is empty.", + targetNodeId_.c_str(), + uniqueId.c_str()); + // if command send failed, also try to close session + if (commands_.empty()) { + ptrChannel_->CloseConnection(); + } + return Constant::FAILURE; + } + + std::shared_ptr ptrResponseCommand = + RemoteCommandFactory::GetInstance().NewRemoteCommandFromJson( + ptrCommand->remoteProtocol_.commandName, responseString); + if (ptrResponseCommand == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "targetNodeId %{public}s, get null response command!", targetNodeId_.c_str()); + return Constant::FAILURE; + } + int32_t result = ClientProcessResult(ptrResponseCommand); + if (commands_.empty()) { + ptrChannel_->CloseConnection(); + } + ACCESSTOKEN_LOG_DEBUG(LABEL, + "command finished with status: %{public}d, message: %{public}s", + ptrResponseCommand->remoteProtocol_.statusCode, + ptrResponseCommand->remoteProtocol_.message.c_str()); + return result; +} + +void RemoteCommandExecutor::CreateChannelIfNeeded() +{ + std::unique_lock lock(mutex_); + if (ptrChannel_ != nullptr) { + ACCESSTOKEN_LOG_INFO(LABEL, "targetNodeId %{public}s, channel is exist.", targetNodeId_.c_str()); + return; + } + + ptrChannel_ = CreateChannel(targetNodeId_); +} + +int RemoteCommandExecutor::ClientProcessResult(const std::shared_ptr &ptrCommand) +{ + std::string uniqueId = ptrCommand->remoteProtocol_.uniqueId; + if (ptrCommand->remoteProtocol_.statusCode == Constant::STATUS_CODE_BEFORE_RPC) { + ACCESSTOKEN_LOG_ERROR(LABEL, + "targetNodeId %{public}s, uniqueId %{public}s, status code after RPC is same as before, the remote side " + "may not " + "support this command", + targetNodeId_.c_str(), + uniqueId.c_str()); + return Constant::FAILURE; + } + + ptrCommand->Finish(); + int status = ptrCommand->remoteProtocol_.statusCode; + if (status != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, + "targetNodeId %{public}s, uniqueId %{public}s, execute failed, message: %{public}s", + targetNodeId_.c_str(), + uniqueId.c_str(), + ptrCommand->remoteProtocol_.message.c_str()); + } else { + ACCESSTOKEN_LOG_INFO(LABEL, + "targetNodeId %{public}s, uniqueId %{public}s, execute succeed.", + targetNodeId_.c_str(), + uniqueId.c_str()); + } + return status; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/services/tokensyncmanager/src/remote/remote_command_manager.cpp b/services/tokensyncmanager/src/remote/remote_command_manager.cpp index d9a604c455240a8fdf1a865eeb0650472b004e1b..ba05954a5bd63d9796246888a92c2cf030a0e757 100644 --- a/services/tokensyncmanager/src/remote/remote_command_manager.cpp +++ b/services/tokensyncmanager/src/remote/remote_command_manager.cpp @@ -14,14 +14,15 @@ */ #include "remote_command_manager.h" +#include #include "device_info_manager.h" #include "sync_remote_native_token_command.h" #include "remote_command_factory.h" #include "token_sync_event_handler.h" #include "token_sync_manager_service.h" #include "accesstoken_kit.h" - -#include +#include "constant_common.h" +#include "constant.h" namespace OHOS { @@ -80,11 +81,13 @@ void RemoteCommandManager::RemoveCommand(const std::string &udid) int RemoteCommandManager::ExecuteCommand(const std::string &udid, const std::shared_ptr &command) { if (udid.empty() || command == nullptr) { - ACCESSTOKEN_LOG_WARN(LABEL, "invalid udid: %{public}s, or null command", udid.c_str()); + ACCESSTOKEN_LOG_WARN(LABEL, "invalid udid: %{public}s, or null command", + ConstantCommon::EncryptDevId(udid).c_str()); return Constant::FAILURE; } std::string uniqueId = command->remoteProtocol_.uniqueId; - ACCESSTOKEN_LOG_INFO(LABEL, "start with udid: %{public}s , uniqueId: %{public}s ", udid.c_str(), uniqueId.c_str()); + ACCESSTOKEN_LOG_INFO(LABEL, "start with udid: %{public}s , uniqueId: %{public}s ", + ConstantCommon::EncryptDevId(udid).c_str(), uniqueId.c_str()); std::shared_ptr executor = GetOrCreateRemoteCommandExecutor(udid); if (executor == nullptr) { @@ -100,19 +103,20 @@ int RemoteCommandManager::ExecuteCommand(const std::string &udid, const std::sha int RemoteCommandManager::ProcessDeviceCommandImmediately(const std::string &udid) { if (udid.empty()) { - ACCESSTOKEN_LOG_WARN(LABEL, "invalid udid: %{public}s", udid.c_str()); + ACCESSTOKEN_LOG_WARN(LABEL, "invalid udid: %{public}s", ConstantCommon::EncryptDevId(udid).c_str()); return Constant::FAILURE; } - ACCESSTOKEN_LOG_INFO(LABEL, "start with udid:%{public}s ", udid.c_str()); + ACCESSTOKEN_LOG_INFO(LABEL, "start with udid:%{public}s ", ConstantCommon::EncryptDevId(udid).c_str()); auto executorIt = executors_.find(udid); if (executorIt == executors_.end()) { - ACCESSTOKEN_LOG_ERROR(LABEL, "no executor found, udid:%{public}s", udid.c_str()); + ACCESSTOKEN_LOG_ERROR(LABEL, "no executor found, udid:%{public}s", ConstantCommon::EncryptDevId(udid).c_str()); return Constant::FAILURE; } auto executor = executorIt->second; if (executor == nullptr) { - ACCESSTOKEN_LOG_INFO(LABEL, "RemoteCommandExecutor is null for udid %{public}s ", udid.c_str()); + ACCESSTOKEN_LOG_INFO(LABEL, "RemoteCommandExecutor is null for udid %{public}s ", + ConstantCommon::EncryptDevId(udid).c_str()); return Constant::FAILURE; } @@ -174,7 +178,7 @@ int RemoteCommandManager::NotifyDeviceOnline(const std::string &nodeId) std::function delayed = ([=]() { const std::shared_ptr syncRemoteNativeTokenCommand = - RemoteCommandFactory::GetInstance().NewSyncRemoteNativeTokenCommand(Constant::GetLocalDeviceId(), + RemoteCommandFactory::GetInstance().NewSyncRemoteNativeTokenCommand(ConstantCommon::GetLocalDeviceId(), nodeId); const int32_t resultCode = RemoteCommandManager::GetInstance().ExecuteCommand( diff --git a/services/tokensyncmanager/src/remote/soft_bus_device_connection_listener.cpp b/services/tokensyncmanager/src/remote/soft_bus_device_connection_listener.cpp index 5610aadcae489a51c288c6bdb95452680277233c..929740b06051324f1e2a9da9058a4e4b890fc376 100644 --- a/services/tokensyncmanager/src/remote/soft_bus_device_connection_listener.cpp +++ b/services/tokensyncmanager/src/remote/soft_bus_device_connection_listener.cpp @@ -1,120 +1,120 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "soft_bus_device_connection_listener.h" -#include "remote_command_manager.h" -#include "soft_bus_manager.h" -#include "device_info_manager.h" -#include "softbus_bus_center.h" -#include "device_manager.h" -#include "dm_device_info.h" - -namespace OHOS { -namespace Security { -namespace AccessToken { -using OHOS::DistributedHardware::DeviceStateCallback; -using OHOS::DistributedHardware::DmDeviceInfo; -using OHOS::DistributedHardware::DmInitCallback; - -namespace { -static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { - LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "SoftBusDeviceConnectionListener"}; -} - -const std::string ACCESSTOKEN_PACKAGE_NAME = "ohos.security.distributed_access_token"; - -SoftBusDeviceConnectionListener::SoftBusDeviceConnectionListener() -{ - ACCESSTOKEN_LOG_DEBUG(LABEL, "SoftBusDeviceConnectionListener()"); -} -SoftBusDeviceConnectionListener::~SoftBusDeviceConnectionListener() -{ - ACCESSTOKEN_LOG_DEBUG(LABEL, "~SoftBusDeviceConnectionListener()"); -} - -void SoftBusDeviceConnectionListener::OnDeviceOnline(const DmDeviceInfo &info) -{ - std::string networkId = info.deviceId; - std::string uuid = SoftBusManager::GetInstance().GetUniversallyUniqueIdByNodeId(networkId); - std::string udid = SoftBusManager::GetInstance().GetUniqueDeviceIdByNodeId(networkId); - - ACCESSTOKEN_LOG_INFO(LABEL, - "networkId: %{public}s, uuid: %{public}s, udid: %{public}s", - networkId.c_str(), - uuid.c_str(), - udid.c_str()); - - if (uuid != "" && udid != "") { - DeviceInfoManager::GetInstance().AddDeviceInfo( - networkId, uuid, udid, info.deviceName, std::to_string(info.deviceTypeId)); - RemoteCommandManager::GetInstance().NotifyDeviceOnline(udid); - } else { - ACCESSTOKEN_LOG_ERROR(LABEL, "uuid or udid is empty, online failed."); - } - // no need to load local permissions by now. -} - -void SoftBusDeviceConnectionListener::OnDeviceOffline(const DmDeviceInfo &info) -{ - std::string networkId = info.deviceId; - std::string uuid = DeviceInfoManager::GetInstance().ConvertToUniversallyUniqueIdOrFetch(networkId); - std::string udid = DeviceInfoManager::GetInstance().ConvertToUniqueDeviceIdOrFetch(networkId); - - ACCESSTOKEN_LOG_INFO(LABEL, - "networkId: %{public}s, uuid: %{public}s, udid: %{public}s", - networkId.c_str(), - uuid.c_str(), - udid.c_str()); - - if (uuid != "" && udid != "") { - RemoteCommandManager::GetInstance().NotifyDeviceOffline(uuid); - RemoteCommandManager::GetInstance().NotifyDeviceOffline(udid); - DeviceInfoManager::GetInstance().RemoveRemoteDeviceInfo(networkId, DeviceIdType::NETWORK_ID); - - std::string packageName = ACCESSTOKEN_PACKAGE_NAME; - std::string extra = ""; - std::vector deviceList; - - int32_t ret = DistributedHardware::DeviceManager::GetInstance().GetTrustedDeviceList(packageName, - extra, deviceList); - if (ret != Constant::SUCCESS) { - ACCESSTOKEN_LOG_ERROR(LABEL, "GetTrustedDeviceList error, result: %{public}d", ret); - return; - } - - if (deviceList.empty()) { - ACCESSTOKEN_LOG_INFO(LABEL, "there is no remote decice online, exit tokensync process"); - - exit(0); - } - } else { - ACCESSTOKEN_LOG_ERROR(LABEL, "uuid or udid is empty, offline failed."); - } -} - -void SoftBusDeviceConnectionListener::OnDeviceReady(const DmDeviceInfo &info) -{ - std::string networkId = info.deviceId; - ACCESSTOKEN_LOG_INFO(LABEL, "networkId: %{public}s", networkId.c_str()); -} - -void SoftBusDeviceConnectionListener::OnDeviceChanged(const DmDeviceInfo &info) -{ - std::string networkId = info.deviceId; - ACCESSTOKEN_LOG_INFO(LABEL, "networkId: %{public}s", networkId.c_str()); -} -} // namespace AccessToken -} // namespace Security -} // namespace OHOS +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "soft_bus_device_connection_listener.h" +#include "remote_command_manager.h" +#include "soft_bus_manager.h" +#include "device_info_manager.h" +#include "softbus_bus_center.h" +#include "device_manager.h" +#include "dm_device_info.h" +#include "constant_common.h" +namespace OHOS { +namespace Security { +namespace AccessToken { +using OHOS::DistributedHardware::DeviceStateCallback; +using OHOS::DistributedHardware::DmDeviceInfo; +using OHOS::DistributedHardware::DmInitCallback; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "SoftBusDeviceConnectionListener"}; +} + +const std::string ACCESSTOKEN_PACKAGE_NAME = "ohos.security.distributed_access_token"; + +SoftBusDeviceConnectionListener::SoftBusDeviceConnectionListener() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "SoftBusDeviceConnectionListener()"); +} +SoftBusDeviceConnectionListener::~SoftBusDeviceConnectionListener() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "~SoftBusDeviceConnectionListener()"); +} + +void SoftBusDeviceConnectionListener::OnDeviceOnline(const DmDeviceInfo &info) +{ + std::string networkId = info.deviceId; + std::string uuid = SoftBusManager::GetInstance().GetUniversallyUniqueIdByNodeId(networkId); + std::string udid = SoftBusManager::GetInstance().GetUniqueDeviceIdByNodeId(networkId); + + ACCESSTOKEN_LOG_INFO(LABEL, + "networkId: %{public}s, uuid: %{public}s, udid: %{public}s", + networkId.c_str(), + uuid.c_str(), + ConstantCommon::EncryptDevId(udid).c_str()); + + if (uuid != "" && udid != "") { + DeviceInfoManager::GetInstance().AddDeviceInfo( + networkId, uuid, udid, info.deviceName, std::to_string(info.deviceTypeId)); + RemoteCommandManager::GetInstance().NotifyDeviceOnline(udid); + } else { + ACCESSTOKEN_LOG_ERROR(LABEL, "uuid or udid is empty, online failed."); + } + // no need to load local permissions by now. +} + +void SoftBusDeviceConnectionListener::OnDeviceOffline(const DmDeviceInfo &info) +{ + std::string networkId = info.deviceId; + std::string uuid = DeviceInfoManager::GetInstance().ConvertToUniversallyUniqueIdOrFetch(networkId); + std::string udid = DeviceInfoManager::GetInstance().ConvertToUniqueDeviceIdOrFetch(networkId); + + ACCESSTOKEN_LOG_INFO(LABEL, + "networkId: %{public}s, uuid: %{public}s, udid: %{public}s", + networkId.c_str(), + uuid.c_str(), + ConstantCommon::EncryptDevId(udid).c_str()); + + if (uuid != "" && udid != "") { + RemoteCommandManager::GetInstance().NotifyDeviceOffline(uuid); + RemoteCommandManager::GetInstance().NotifyDeviceOffline(udid); + DeviceInfoManager::GetInstance().RemoveRemoteDeviceInfo(networkId, DeviceIdType::NETWORK_ID); + + std::string packageName = ACCESSTOKEN_PACKAGE_NAME; + std::string extra = ""; + std::vector deviceList; + + int32_t ret = DistributedHardware::DeviceManager::GetInstance().GetTrustedDeviceList(packageName, + extra, deviceList); + if (ret != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "GetTrustedDeviceList error, result: %{public}d", ret); + return; + } + + if (deviceList.size() == 0) { + ACCESSTOKEN_LOG_INFO(LABEL, "there is no remote decice online, exit tokensync process"); + + exit(0); + } + } else { + ACCESSTOKEN_LOG_ERROR(LABEL, "uuid or udid is empty, offline failed."); + } +} + +void SoftBusDeviceConnectionListener::OnDeviceReady(const DmDeviceInfo &info) +{ + std::string networkId = info.deviceId; + ACCESSTOKEN_LOG_INFO(LABEL, "networkId: %{public}s", networkId.c_str()); +} + +void SoftBusDeviceConnectionListener::OnDeviceChanged(const DmDeviceInfo &info) +{ + std::string networkId = info.deviceId; + ACCESSTOKEN_LOG_INFO(LABEL, "networkId: %{public}s", networkId.c_str()); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/services/tokensyncmanager/src/remote/soft_bus_manager.cpp b/services/tokensyncmanager/src/remote/soft_bus_manager.cpp index 24275c1a0f9148da4a96d0343203b63136fd4e73..1e5b49e30c081ff747574f47198579070d6131b8 100644 --- a/services/tokensyncmanager/src/remote/soft_bus_manager.cpp +++ b/services/tokensyncmanager/src/remote/soft_bus_manager.cpp @@ -1,409 +1,410 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "soft_bus_manager.h" - -#include - -#include "device_info_manager.h" -#include "parameter.h" -#include "softbus_bus_center.h" -#include "dm_device_info.h" -#include "remote_command_manager.h" - -namespace OHOS { -namespace Security { -namespace AccessToken { -namespace { -static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "SoftBusManager"}; -} -namespace { -static const std::string SESSION_GROUP_ID = "atm_dsoftbus_session_group_id"; -static const SessionAttribute SESSION_ATTR = {.dataType = TYPE_BYTES}; - -static const int REASON_EXIST = -3; -static const int OPENSESSION_RETRY_TIMES = 10 * 3; -static const int OPENSESSION_RETRY_INTERVAL_MS = 100; -static const int UDID_MAX_LENGTH = 128; // udid/uuid max length -} // namespace - -const std::string SoftBusManager::TOKEN_SYNC_PACKAGE_NAME = "ohos.security.distributed_access_token"; -const std::string SoftBusManager::SESSION_NAME = "ohos.security.atm_channel"; - -SoftBusManager::SoftBusManager() : isSoftBusServiceBindSuccess_(false), inited_(false), mutex_(), fulfillMutex_() -{ - ACCESSTOKEN_LOG_DEBUG(LABEL, "SoftBusManager()"); -} - -SoftBusManager::~SoftBusManager() -{ - ACCESSTOKEN_LOG_DEBUG(LABEL, "~SoftBusManager()"); -} - -SoftBusManager &SoftBusManager::GetInstance() -{ - static SoftBusManager instance; - return instance; -} - -int SoftBusManager::AddTrustedDeviceInfo() -{ - std::string packageName = TOKEN_SYNC_PACKAGE_NAME; - std::string extra = ""; - std::vector deviceList; - - int32_t ret = DistributedHardware::DeviceManager::GetInstance().GetTrustedDeviceList(packageName, - extra, deviceList); - if (ret != Constant::SUCCESS) { - ACCESSTOKEN_LOG_ERROR(LABEL, "AddTrustedDeviceInfo: GetTrustedDeviceList error, result: %{public}d", ret); - return Constant::FAILURE; - } - - for (const DistributedHardware::DmDeviceInfo& device : deviceList) { - std::string uuid = GetUuidByNodeId(device.networkId); - std::string udid = GetUdidByNodeId(device.networkId); - if (uuid.empty() || udid.empty()) { - ACCESSTOKEN_LOG_ERROR(LABEL, "uuid = %{public}s, udid = %{public}s, uuid or udid is empty, abort.", - uuid.c_str(), udid.c_str()); - continue; - } - - DeviceInfoManager::GetInstance().AddDeviceInfo(device.networkId, uuid, udid, device.deviceName, - std::to_string(device.deviceTypeId)); - RemoteCommandManager::GetInstance().NotifyDeviceOnline(udid); - } - - return Constant::SUCCESS; -} - -int SoftBusManager::DeviceInit() -{ - std::string packageName = TOKEN_SYNC_PACKAGE_NAME; - std::shared_ptr ptrDmInitCallback = std::make_shared(); - - int ret = DistributedHardware::DeviceManager::GetInstance().InitDeviceManager(packageName, ptrDmInitCallback); - if (ret != ERR_OK) { - ACCESSTOKEN_LOG_ERROR(LABEL, "Initialize: InitDeviceManager error, result: %{public}d", ret); - return ret; - } - - ret = AddTrustedDeviceInfo(); - if (ret != ERR_OK) { - ACCESSTOKEN_LOG_ERROR(LABEL, "Initialize: AddTrustedDeviceInfo error, result: %{public}d", ret); - return ret; - } - - std::string extra = ""; - std::shared_ptr ptrDeviceStateCallback = - std::make_shared(); - ret = DistributedHardware::DeviceManager::GetInstance().RegisterDevStateCallback(packageName, extra, - ptrDeviceStateCallback); - if (ret != ERR_OK) { - ACCESSTOKEN_LOG_ERROR(LABEL, "Initialize: RegisterDevStateCallback error, result: %{public}d", ret); - return ret; - } - - return ERR_OK; -} - -int SoftBusManager::SessionInit() -{ - // register session listener - ISessionListener sessionListener; - sessionListener.OnSessionOpened = SoftBusSessionListener::OnSessionOpened; - sessionListener.OnSessionClosed = SoftBusSessionListener::OnSessionClosed; - sessionListener.OnBytesReceived = SoftBusSessionListener::OnBytesReceived; - sessionListener.OnMessageReceived = SoftBusSessionListener::OnMessageReceived; - - int ret = ::CreateSessionServer(TOKEN_SYNC_PACKAGE_NAME.c_str(), SESSION_NAME.c_str(), &sessionListener); - ACCESSTOKEN_LOG_INFO(LABEL, "Initialize: createSessionServer, result: %{public}d", ret); - // REASON_EXIST - if ((ret != Constant::SUCCESS) && (ret != REASON_EXIST)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "Initialize: CreateSessionServer error, result: %{public}d", ret); - return ret; - } - - return ERR_OK; -} - -void SoftBusManager::Initialize() -{ - bool inited = false; - // cas failed means already inited. - if (!inited_.compare_exchange_strong(inited, true)) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "already initialized, skip"); - return; - } - - std::function runner = [&]() { - auto sleepTime = std::chrono::milliseconds(1000); - while (1) { - std::unique_lock lock(mutex_); - - int ret = DeviceInit(); - if (ret != ERR_OK) { - std::this_thread::sleep_for(sleepTime); - continue; - } - - ret = SessionInit(); - if (ret != ERR_OK) { - std::this_thread::sleep_for(sleepTime); - continue; - } - - isSoftBusServiceBindSuccess_ = true; - this->FulfillLocalDeviceInfo(); - return; - } - }; - - std::thread initThread(runner); - initThread.detach(); - ACCESSTOKEN_LOG_DEBUG(LABEL, "Initialize thread started"); -} - -void SoftBusManager::Destroy() -{ - ACCESSTOKEN_LOG_DEBUG(LABEL, "destroy, init: %{public}d, isSoftBusServiceBindSuccess: %{public}d", inited_.load(), - isSoftBusServiceBindSuccess_); - - if (!inited_.load()) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "not inited, skip"); - return; - } - - std::unique_lock lock(mutex_); - if (!inited_.load()) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "not inited, skip"); - return; - } - - if (isSoftBusServiceBindSuccess_) { - int32_t ret = ::RemoveSessionServer(TOKEN_SYNC_PACKAGE_NAME.c_str(), SESSION_NAME.c_str()); - ACCESSTOKEN_LOG_DEBUG(LABEL, "destroy, RemoveSessionServer: %{public}d", ret); - isSoftBusServiceBindSuccess_ = false; - } - - std::string packageName = TOKEN_SYNC_PACKAGE_NAME; - int ret = DistributedHardware::DeviceManager::GetInstance().UnRegisterDevStateCallback(packageName); - if (ret != ERR_OK) { - ACCESSTOKEN_LOG_ERROR(LABEL, "UnRegisterDevStateCallback failed, code: %{public}d", ret); - } - ret = DistributedHardware::DeviceManager::GetInstance().UnInitDeviceManager(packageName); - if (ret != ERR_OK) { - ACCESSTOKEN_LOG_ERROR(LABEL, "UnInitDeviceManager failed, code: %{public}d", ret); - } - - inited_.store(false); - - ACCESSTOKEN_LOG_DEBUG(LABEL, "destroy, done"); -} - -int32_t SoftBusManager::OpenSession(const std::string &deviceId) -{ -#ifdef DEBUG_API_PERFORMANCE - ACCESSTOKEN_LOG_INFO(LABEL, "api_performance:start open session"); -#endif - - DeviceInfo info; - bool result = DeviceInfoManager::GetInstance().GetDeviceInfo(deviceId, DeviceIdType::UNKNOWN, info); - if (!result) { - ACCESSTOKEN_LOG_WARN(LABEL, "device info notfound for deviceId %{private}s", deviceId.c_str()); - return Constant::FAILURE; - } - std::string networkId = info.deviceId.networkId; - ACCESSTOKEN_LOG_INFO(LABEL, "openSession, networkId: %{public}s", networkId.c_str()); - - // async open session, should waitting for OnSessionOpened event. - int sessionId = ::OpenSession(SESSION_NAME.c_str(), SESSION_NAME.c_str(), networkId.c_str(), - SESSION_GROUP_ID.c_str(), &SESSION_ATTR); - - ACCESSTOKEN_LOG_DEBUG(LABEL, "async open session"); - - // wait session opening - int retryTimes = 0; - int logSpan = 10; - auto sleepTime = std::chrono::milliseconds(OPENSESSION_RETRY_INTERVAL_MS); - while (retryTimes++ < OPENSESSION_RETRY_TIMES) { - if (SoftBusSessionListener::GetSessionState(sessionId) < 0) { - std::this_thread::sleep_for(sleepTime); - if (retryTimes % logSpan == 0) { - ACCESSTOKEN_LOG_INFO(LABEL, "openSession, waitting for: %{public}d ms", - retryTimes * OPENSESSION_RETRY_INTERVAL_MS); - } - continue; - } - break; - } -#ifdef DEBUG_API_PERFORMANCE - ACCESSTOKEN_LOG_INFO(LABEL, "api_performance:start open session success"); -#endif - int64_t state = SoftBusSessionListener::GetSessionState(sessionId); - if (state < 0) { - ACCESSTOKEN_LOG_ERROR(LABEL, "openSession, timeout, session: %{public}" PRId64, state); - return Constant::FAILURE; - } - - SoftBusSessionListener::DeleteSessionIdFromMap(sessionId); - - ACCESSTOKEN_LOG_DEBUG(LABEL, "openSession, succeed, session: %{public}" PRId64, state); - return sessionId; -} - -int SoftBusManager::CloseSession(int sessionId) -{ - if (sessionId < 0) { - ACCESSTOKEN_LOG_INFO(LABEL, "closeSession: session is invalid"); - return Constant::FAILURE; - } - - ::CloseSession(sessionId); - ACCESSTOKEN_LOG_INFO(LABEL, "closeSession "); - return Constant::SUCCESS; -} - -std::string SoftBusManager::GetUniversallyUniqueIdByNodeId(const std::string &nodeId) -{ - if (!DataValidator::IsDeviceIdValid(nodeId)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "invalid nodeId: %{public}s", nodeId.c_str()); - return ""; - } - - std::string uuid = GetUuidByNodeId(nodeId); - if (uuid.empty()) { - ACCESSTOKEN_LOG_ERROR(LABEL, "softbus return null or empty string [%{public}s]", uuid.c_str()); - return ""; - } - - DeviceInfo info; - bool result = DeviceInfoManager::GetInstance().GetDeviceInfo(uuid, DeviceIdType::UNIVERSALLY_UNIQUE_ID, info); - if (!result) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "local device info not found for uuid %{public}s", uuid.c_str()); - } else { - std::string dimUuid = info.deviceId.universallyUniqueId; - if (uuid == dimUuid) { - // refresh cache - std::function fulfillDeviceInfo = std::bind(&SoftBusManager::FulfillLocalDeviceInfo, this); - std::thread fulfill(fulfillDeviceInfo); - fulfill.detach(); - } - } - - return uuid; -} - -std::string SoftBusManager::GetUniqueDeviceIdByNodeId(const std::string &nodeId) -{ - if (!DataValidator::IsDeviceIdValid(nodeId)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "invalid nodeId: %{public}s", nodeId.c_str()); - return ""; - } - std::string udid = GetUdidByNodeId(nodeId); - if (udid.empty()) { - ACCESSTOKEN_LOG_ERROR(LABEL, "softbus return null or empty string: %{public}s", udid.c_str()); - return ""; - } - char localUdid[Constant::DEVICE_UUID_LENGTH] = {0}; - ::GetDevUdid(localUdid, Constant::DEVICE_UUID_LENGTH); - if (udid == localUdid) { - // refresh cache - std::function fulfillDeviceInfo = std::bind(&SoftBusManager::FulfillLocalDeviceInfo, this); - std::thread fulfill(fulfillDeviceInfo); - fulfill.detach(); - } - return udid; -} - -std::string SoftBusManager::GetUuidByNodeId(const std::string &nodeId) const -{ - uint8_t *info = new uint8_t[UDID_MAX_LENGTH + 1]; - if (info == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "no enough memory: %{public}d", UDID_MAX_LENGTH); - return ""; - } - (void)memset_s(info, UDID_MAX_LENGTH + 1, 0, UDID_MAX_LENGTH + 1); - int32_t ret = ::GetNodeKeyInfo(TOKEN_SYNC_PACKAGE_NAME.c_str(), nodeId.c_str(), - NodeDeviceInfoKey::NODE_KEY_UUID, info, UDID_MAX_LENGTH); - if (ret != Constant::SUCCESS) { - delete[] info; - ACCESSTOKEN_LOG_WARN(LABEL, "GetNodeKeyInfo error, return code: %{public}d", ret); - return ""; - } - std::string uuid(reinterpret_cast(info)); - delete[] info; - ACCESSTOKEN_LOG_DEBUG(LABEL, "call softbus finished. nodeId(in): %{public}s, uuid: %{public}s", nodeId.c_str(), - uuid.c_str()); - return uuid; -} - -std::string SoftBusManager::GetUdidByNodeId(const std::string &nodeId) const -{ - uint8_t *info = new uint8_t[UDID_MAX_LENGTH + 1]; - if (info == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "no enough memory: %{public}d", UDID_MAX_LENGTH); - return ""; - } - (void)memset_s(info, UDID_MAX_LENGTH + 1, 0, UDID_MAX_LENGTH + 1); - int32_t ret = ::GetNodeKeyInfo(TOKEN_SYNC_PACKAGE_NAME.c_str(), nodeId.c_str(), - NodeDeviceInfoKey::NODE_KEY_UDID, info, UDID_MAX_LENGTH); - if (ret != Constant::SUCCESS) { - delete[] info; - ACCESSTOKEN_LOG_WARN(LABEL, "GetNodeKeyInfo error, code: %{public}d", ret); - return ""; - } - std::string udid(reinterpret_cast(info)); - delete[] info; - ACCESSTOKEN_LOG_DEBUG(LABEL, "call softbus finished: nodeId(in): %{public}s", nodeId.c_str()); - return udid; -} - -int SoftBusManager::FulfillLocalDeviceInfo() -{ - // repeated task will just skip - if (!fulfillMutex_.try_lock()) { - ACCESSTOKEN_LOG_INFO(LABEL, "FulfillLocalDeviceInfo already running, skip."); - return Constant::SUCCESS; - } - - NodeBasicInfo info; - int32_t ret = ::GetLocalNodeDeviceInfo(TOKEN_SYNC_PACKAGE_NAME.c_str(), &info); - if (ret != Constant::SUCCESS) { - ACCESSTOKEN_LOG_ERROR(LABEL, "GetLocalNodeDeviceInfo error"); - fulfillMutex_.unlock(); - return Constant::FAILURE; - } - - ACCESSTOKEN_LOG_DEBUG(LABEL, "call softbus finished, networkId:%{public}s, name:%{public}s, type:%{public}d", - info.networkId, info.deviceName, info.deviceTypeId); - - std::string uuid = GetUuidByNodeId(info.networkId); - std::string udid = GetUdidByNodeId(info.networkId); - if (uuid.empty() || udid.empty()) { - ACCESSTOKEN_LOG_ERROR(LABEL, "FulfillLocalDeviceInfo: uuid or udid is empty, abort."); - fulfillMutex_.unlock(); - return Constant::FAILURE; - } - - DeviceInfoManager::GetInstance().AddDeviceInfo(info.networkId, uuid, udid, info.deviceName, - std::to_string(info.deviceTypeId)); - ACCESSTOKEN_LOG_DEBUG(LABEL, "AddDeviceInfo finished, networkId:%{public}s", - info.networkId); - - fulfillMutex_.unlock(); - return Constant::SUCCESS; -} -} // namespace AccessToken -} // namespace Security -} // namespace OHOS +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "soft_bus_manager.h" + +#include +#include "constant_common.h" +#include "device_info_manager.h" +#include "parameter.h" +#include "softbus_bus_center.h" +#include "dm_device_info.h" +#include "remote_command_manager.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "SoftBusManager"}; +} +namespace { +static const std::string SESSION_GROUP_ID = "atm_dsoftbus_session_group_id"; +static const SessionAttribute SESSION_ATTR = {.dataType = TYPE_BYTES}; + +static const int REASON_EXIST = -3; +static const int OPENSESSION_RETRY_TIMES = 10 * 3; +static const int OPENSESSION_RETRY_INTERVAL_MS = 100; +static const int UDID_MAX_LENGTH = 128; // udid/uuid max length +} // namespace + +const std::string SoftBusManager::TOKEN_SYNC_PACKAGE_NAME = "ohos.security.distributed_access_token"; +const std::string SoftBusManager::SESSION_NAME = "ohos.security.atm_channel"; + +SoftBusManager::SoftBusManager() : isSoftBusServiceBindSuccess_(false), inited_(false), mutex_(), fulfillMutex_() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "SoftBusManager()"); +} + +SoftBusManager::~SoftBusManager() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "~SoftBusManager()"); +} + +SoftBusManager &SoftBusManager::GetInstance() +{ + static SoftBusManager instance; + return instance; +} + +int SoftBusManager::AddTrustedDeviceInfo() +{ + std::string packageName = TOKEN_SYNC_PACKAGE_NAME; + std::string extra = ""; + std::vector deviceList; + + int32_t ret = DistributedHardware::DeviceManager::GetInstance().GetTrustedDeviceList(packageName, + extra, deviceList); + if (ret != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "AddTrustedDeviceInfo: GetTrustedDeviceList error, result: %{public}d", ret); + return Constant::FAILURE; + } + + for (DistributedHardware::DmDeviceInfo device : deviceList) { + std::string uuid = GetUuidByNodeId(device.networkId); + std::string udid = GetUdidByNodeId(device.networkId); + if (uuid.empty() || udid.empty()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "uuid = %{public}s, udid = %{public}s, uuid or udid is empty, abort.", + uuid.c_str(), ConstantCommon::EncryptDevId(udid).c_str()); + continue; + } + + DeviceInfoManager::GetInstance().AddDeviceInfo(device.networkId, uuid, udid, device.deviceName, + std::to_string(device.deviceTypeId)); + RemoteCommandManager::GetInstance().NotifyDeviceOnline(udid); + } + + return Constant::SUCCESS; +} + +int SoftBusManager::DeviceInit() +{ + std::string packageName = TOKEN_SYNC_PACKAGE_NAME; + std::shared_ptr ptrDmInitCallback = std::make_shared(); + + int ret = DistributedHardware::DeviceManager::GetInstance().InitDeviceManager(packageName, ptrDmInitCallback); + if (ret != ERR_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Initialize: InitDeviceManager error, result: %{public}d", ret); + return ret; + } + + ret = AddTrustedDeviceInfo(); + if (ret != ERR_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Initialize: AddTrustedDeviceInfo error, result: %{public}d", ret); + return ret; + } + + std::string extra = ""; + std::shared_ptr ptrDeviceStateCallback = + std::make_shared(); + ret = DistributedHardware::DeviceManager::GetInstance().RegisterDevStateCallback(packageName, extra, + ptrDeviceStateCallback); + if (ret != ERR_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Initialize: RegisterDevStateCallback error, result: %{public}d", ret); + return ret; + } + + return ERR_OK; +} + +int SoftBusManager::SessionInit() +{ + // register session listener + ISessionListener sessionListener; + sessionListener.OnSessionOpened = SoftBusSessionListener::OnSessionOpened; + sessionListener.OnSessionClosed = SoftBusSessionListener::OnSessionClosed; + sessionListener.OnBytesReceived = SoftBusSessionListener::OnBytesReceived; + sessionListener.OnMessageReceived = SoftBusSessionListener::OnMessageReceived; + + int ret = ::CreateSessionServer(TOKEN_SYNC_PACKAGE_NAME.c_str(), SESSION_NAME.c_str(), &sessionListener); + ACCESSTOKEN_LOG_INFO(LABEL, "Initialize: createSessionServer, result: %{public}d", ret); + // REASON_EXIST + if ((ret != Constant::SUCCESS) && (ret != REASON_EXIST)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Initialize: CreateSessionServer error, result: %{public}d", ret); + return ret; + } + + return ERR_OK; +} + +void SoftBusManager::Initialize() +{ + bool inited = false; + // cas failed means already inited. + if (!inited_.compare_exchange_strong(inited, true)) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "already initialized, skip"); + return; + } + + std::function runner = [&]() { + auto sleepTime = std::chrono::milliseconds(1000); + while (1) { + std::unique_lock lock(mutex_); + + int ret = DeviceInit(); + if (ret != ERR_OK) { + std::this_thread::sleep_for(sleepTime); + continue; + } + + ret = SessionInit(); + if (ret != ERR_OK) { + std::this_thread::sleep_for(sleepTime); + continue; + } + + isSoftBusServiceBindSuccess_ = true; + this->FulfillLocalDeviceInfo(); + return; + } + }; + + std::thread initThread(runner); + initThread.detach(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "Initialize thread started"); +} + +void SoftBusManager::Destroy() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "destroy, init: %{public}d, isSoftBusServiceBindSuccess: %{public}d", inited_.load(), + isSoftBusServiceBindSuccess_); + + if (!inited_.load()) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "not inited, skip"); + return; + } + + std::unique_lock lock(mutex_); + if (!inited_.load()) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "not inited, skip"); + return; + } + + if (isSoftBusServiceBindSuccess_) { + int32_t ret = ::RemoveSessionServer(TOKEN_SYNC_PACKAGE_NAME.c_str(), SESSION_NAME.c_str()); + ACCESSTOKEN_LOG_DEBUG(LABEL, "destroy, RemoveSessionServer: %{public}d", ret); + isSoftBusServiceBindSuccess_ = false; + } + + std::string packageName = TOKEN_SYNC_PACKAGE_NAME; + int ret = DistributedHardware::DeviceManager::GetInstance().UnRegisterDevStateCallback(packageName); + if (ret != ERR_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "UnRegisterDevStateCallback failed, code: %{public}d", ret); + } + ret = DistributedHardware::DeviceManager::GetInstance().UnInitDeviceManager(packageName); + if (ret != ERR_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "UnInitDeviceManager failed, code: %{public}d", ret); + } + + inited_.store(false); + + ACCESSTOKEN_LOG_DEBUG(LABEL, "destroy, done"); +} + +int32_t SoftBusManager::OpenSession(const std::string &deviceId) +{ +#ifdef DEBUG_API_PERFORMANCE + ACCESSTOKEN_LOG_INFO(LABEL, "api_performance:start open session"); +#endif + + DeviceInfo info; + bool result = DeviceInfoManager::GetInstance().GetDeviceInfo(deviceId, DeviceIdType::UNKNOWN, info); + if (!result) { + ACCESSTOKEN_LOG_WARN(LABEL, "device info notfound for deviceId %{public}s", + ConstantCommon::EncryptDevId(deviceId).c_str()); + return Constant::FAILURE; + } + std::string networkId = info.deviceId.networkId; + ACCESSTOKEN_LOG_INFO(LABEL, "openSession, networkId: %{public}s", networkId.c_str()); + + // async open session, should waitting for OnSessionOpened event. + int sessionId = ::OpenSession(SESSION_NAME.c_str(), SESSION_NAME.c_str(), networkId.c_str(), + SESSION_GROUP_ID.c_str(), &SESSION_ATTR); + + ACCESSTOKEN_LOG_DEBUG(LABEL, "async open session"); + + // wait session opening + int retryTimes = 0; + int logSpan = 10; + auto sleepTime = std::chrono::milliseconds(OPENSESSION_RETRY_INTERVAL_MS); + while (retryTimes++ < OPENSESSION_RETRY_TIMES) { + if (SoftBusSessionListener::GetSessionState(sessionId) < 0) { + std::this_thread::sleep_for(sleepTime); + if (retryTimes % logSpan == 0) { + ACCESSTOKEN_LOG_INFO(LABEL, "openSession, waitting for: %{public}d ms", + retryTimes * OPENSESSION_RETRY_INTERVAL_MS); + } + continue; + } + break; + } +#ifdef DEBUG_API_PERFORMANCE + ACCESSTOKEN_LOG_INFO(LABEL, "api_performance:start open session success"); +#endif + int64_t state = SoftBusSessionListener::GetSessionState(sessionId); + if (state < 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "openSession, timeout, session: %{public}" PRId64, state); + return Constant::FAILURE; + } + + SoftBusSessionListener::DeleteSessionIdFromMap(sessionId); + + ACCESSTOKEN_LOG_DEBUG(LABEL, "openSession, succeed, session: %{public}" PRId64, state); + return sessionId; +} + +int SoftBusManager::CloseSession(int sessionId) +{ + if (sessionId < 0) { + ACCESSTOKEN_LOG_INFO(LABEL, "closeSession: session is invalid"); + return Constant::FAILURE; + } + + ::CloseSession(sessionId); + ACCESSTOKEN_LOG_INFO(LABEL, "closeSession "); + return Constant::SUCCESS; +} + +std::string SoftBusManager::GetUniversallyUniqueIdByNodeId(const std::string &nodeId) +{ + if (!DataValidator::IsDeviceIdValid(nodeId)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid nodeId: %{public}s", nodeId.c_str()); + return ""; + } + + std::string uuid = GetUuidByNodeId(nodeId); + if (uuid.empty()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "softbus return null or empty string [%{public}s]", uuid.c_str()); + return ""; + } + + DeviceInfo info; + bool result = DeviceInfoManager::GetInstance().GetDeviceInfo(uuid, DeviceIdType::UNIVERSALLY_UNIQUE_ID, info); + if (!result) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "local device info not found for uuid %{public}s", uuid.c_str()); + } else { + std::string dimUuid = info.deviceId.universallyUniqueId; + if (uuid == dimUuid) { + // refresh cache + std::function fulfillDeviceInfo = std::bind(&SoftBusManager::FulfillLocalDeviceInfo, this); + std::thread fulfill(fulfillDeviceInfo); + fulfill.detach(); + } + } + + return uuid; +} + +std::string SoftBusManager::GetUniqueDeviceIdByNodeId(const std::string &nodeId) +{ + if (!DataValidator::IsDeviceIdValid(nodeId)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid nodeId: %{public}s", nodeId.c_str()); + return ""; + } + std::string udid = GetUdidByNodeId(nodeId); + if (udid.empty()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "softbus return null or empty string: %{public}s", + ConstantCommon::EncryptDevId(udid).c_str()); + return ""; + } + std::string localUdid = ConstantCommon::GetLocalDeviceId(); + if (udid == localUdid) { + // refresh cache + std::function fulfillDeviceInfo = std::bind(&SoftBusManager::FulfillLocalDeviceInfo, this); + std::thread fulfill(fulfillDeviceInfo); + fulfill.detach(); + } + return udid; +} + +std::string SoftBusManager::GetUuidByNodeId(const std::string &nodeId) const +{ + uint8_t *info = new uint8_t[UDID_MAX_LENGTH + 1]; + if (info == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "no enough memory: %{public}d", UDID_MAX_LENGTH); + return ""; + } + (void)memset_s(info, UDID_MAX_LENGTH + 1, 0, UDID_MAX_LENGTH + 1); + int32_t ret = ::GetNodeKeyInfo(TOKEN_SYNC_PACKAGE_NAME.c_str(), nodeId.c_str(), + NodeDeviceInfoKey::NODE_KEY_UUID, info, UDID_MAX_LENGTH); + if (ret != Constant::SUCCESS) { + delete[] info; + ACCESSTOKEN_LOG_WARN(LABEL, "GetNodeKeyInfo error, return code: %{public}d", ret); + return ""; + } + std::string uuid(reinterpret_cast(info)); + delete[] info; + ACCESSTOKEN_LOG_DEBUG(LABEL, "call softbus finished. nodeId(in): %{public}s, uuid: %{public}s", nodeId.c_str(), + uuid.c_str()); + return uuid; +} + +std::string SoftBusManager::GetUdidByNodeId(const std::string &nodeId) const +{ + uint8_t *info = new uint8_t[UDID_MAX_LENGTH + 1]; + if (info == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "no enough memory: %{public}d", UDID_MAX_LENGTH); + return ""; + } + (void)memset_s(info, UDID_MAX_LENGTH + 1, 0, UDID_MAX_LENGTH + 1); + int32_t ret = ::GetNodeKeyInfo(TOKEN_SYNC_PACKAGE_NAME.c_str(), nodeId.c_str(), + NodeDeviceInfoKey::NODE_KEY_UDID, info, UDID_MAX_LENGTH); + if (ret != Constant::SUCCESS) { + delete[] info; + ACCESSTOKEN_LOG_WARN(LABEL, "GetNodeKeyInfo error, code: %{public}d", ret); + return ""; + } + std::string udid(reinterpret_cast(info)); + delete[] info; + ACCESSTOKEN_LOG_DEBUG(LABEL, "call softbus finished: nodeId(in): %{public}s", nodeId.c_str()); + return udid; +} + +int SoftBusManager::FulfillLocalDeviceInfo() +{ + // repeated task will just skip + if (!fulfillMutex_.try_lock()) { + ACCESSTOKEN_LOG_INFO(LABEL, "FulfillLocalDeviceInfo already running, skip."); + return Constant::SUCCESS; + } + + NodeBasicInfo info; + int32_t ret = ::GetLocalNodeDeviceInfo(TOKEN_SYNC_PACKAGE_NAME.c_str(), &info); + if (ret != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "GetLocalNodeDeviceInfo error"); + fulfillMutex_.unlock(); + return Constant::FAILURE; + } + + ACCESSTOKEN_LOG_DEBUG(LABEL, "call softbus finished, networkId:%{public}s, name:%{public}s, type:%{public}d", + info.networkId, info.deviceName, info.deviceTypeId); + + std::string uuid = GetUuidByNodeId(info.networkId); + std::string udid = GetUdidByNodeId(info.networkId); + if (uuid.empty() || udid.empty()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "FulfillLocalDeviceInfo: uuid or udid is empty, abort."); + fulfillMutex_.unlock(); + return Constant::FAILURE; + } + + DeviceInfoManager::GetInstance().AddDeviceInfo(info.networkId, uuid, udid, info.deviceName, + std::to_string(info.deviceTypeId)); + ACCESSTOKEN_LOG_DEBUG(LABEL, "AddDeviceInfo finished, networkId:%{public}s", + info.networkId); + + fulfillMutex_.unlock(); + return Constant::SUCCESS; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/services/tokensyncmanager/src/service/token_sync_manager_service.cpp b/services/tokensyncmanager/src/service/token_sync_manager_service.cpp index 623e4fae9d03db01cf3e4f441b36656fbc6b5523..88d354599e3be574f2de9780d325d920df1c3adc 100644 --- a/services/tokensyncmanager/src/service/token_sync_manager_service.cpp +++ b/services/tokensyncmanager/src/service/token_sync_manager_service.cpp @@ -18,6 +18,7 @@ #include #include "accesstoken_log.h" +#include "constant_common.h" #include "device_info_repository.h" #include "device_info.h" #include "remote_command_manager.h" @@ -95,16 +96,16 @@ int TokenSyncManagerService::GetRemoteHapTokenInfo(const std::string& deviceID, } std::string udid = devInfo.deviceId.uniqueDeviceId; const std::shared_ptr syncRemoteHapTokenCommand = - RemoteCommandFactory::GetInstance().NewSyncRemoteHapTokenCommand(Constant::GetLocalDeviceId(), + RemoteCommandFactory::GetInstance().NewSyncRemoteHapTokenCommand(ConstantCommon::GetLocalDeviceId(), deviceID, tokenID); const int32_t resultCode = RemoteCommandManager::GetInstance().ExecuteCommand(udid, syncRemoteHapTokenCommand); if (resultCode != Constant::SUCCESS) { ACCESSTOKEN_LOG_INFO(LABEL, - "RemoteExecutorManager executeCommand SyncRemoteHapTokenCommand failed, return %d", resultCode); + "RemoteExecutorManager executeCommand SyncRemoteHapTokenCommand failed, return %{public}d", resultCode); return resultCode; } - ACCESSTOKEN_LOG_INFO(LABEL, "get resultCode: %d", resultCode); + ACCESSTOKEN_LOG_INFO(LABEL, "get resultCode: %{public}d", resultCode); return RET_SUCCESS; } @@ -116,24 +117,24 @@ int TokenSyncManagerService::DeleteRemoteHapTokenInfo(AccessTokenID tokenID) } std::vector devices = DeviceInfoRepository::GetInstance().ListDeviceInfo(); - std::string localUdid = Constant::GetLocalDeviceId(); - for (const DeviceInfo& device : devices) { + std::string localUdid = ConstantCommon::GetLocalDeviceId(); + for (DeviceInfo device : devices) { if (device.deviceId.uniqueDeviceId == localUdid) { ACCESSTOKEN_LOG_INFO(LABEL, "no need notify local device"); continue; } const std::shared_ptr deleteRemoteTokenCommand = - RemoteCommandFactory::GetInstance().NewDeleteRemoteTokenCommand(Constant::GetLocalDeviceId(), + RemoteCommandFactory::GetInstance().NewDeleteRemoteTokenCommand(ConstantCommon::GetLocalDeviceId(), device.deviceId.uniqueDeviceId, tokenID); const int32_t resultCode = RemoteCommandManager::GetInstance().ExecuteCommand( device.deviceId.uniqueDeviceId, deleteRemoteTokenCommand); if (resultCode != Constant::SUCCESS) { ACCESSTOKEN_LOG_INFO(LABEL, - "RemoteExecutorManager executeCommand DeleteRemoteTokenCommand failed, return %d", resultCode); + "RemoteExecutorManager executeCommand DeleteRemoteTokenCommand failed, return %{public}d", resultCode); continue; } - ACCESSTOKEN_LOG_INFO(LABEL, "get resultCode: %d", resultCode); + ACCESSTOKEN_LOG_INFO(LABEL, "get resultCode: %{public}d", resultCode); } return RET_SUCCESS; } @@ -141,25 +142,26 @@ int TokenSyncManagerService::DeleteRemoteHapTokenInfo(AccessTokenID tokenID) int TokenSyncManagerService::UpdateRemoteHapTokenInfo(const HapTokenInfoForSync& tokenInfo) { std::vector devices = DeviceInfoRepository::GetInstance().ListDeviceInfo(); - std::string localUdid = Constant::GetLocalDeviceId(); - for (const DeviceInfo& device : devices) { + std::string localUdid = ConstantCommon::GetLocalDeviceId(); + for (DeviceInfo device : devices) { if (device.deviceId.uniqueDeviceId == localUdid) { ACCESSTOKEN_LOG_INFO(LABEL, "no need notify local device"); continue; } const std::shared_ptr updateRemoteHapTokenCommand = - RemoteCommandFactory::GetInstance().NewUpdateRemoteHapTokenCommand(Constant::GetLocalDeviceId(), + RemoteCommandFactory::GetInstance().NewUpdateRemoteHapTokenCommand(ConstantCommon::GetLocalDeviceId(), device.deviceId.uniqueDeviceId, tokenInfo); const int32_t resultCode = RemoteCommandManager::GetInstance().ExecuteCommand( device.deviceId.uniqueDeviceId, updateRemoteHapTokenCommand); if (resultCode != Constant::SUCCESS) { ACCESSTOKEN_LOG_INFO(LABEL, - "RemoteExecutorManager executeCommand updateRemoteHapTokenCommand failed, return %d", resultCode); + "RemoteExecutorManager executeCommand updateRemoteHapTokenCommand failed, return %{public}d", + resultCode); continue; } - ACCESSTOKEN_LOG_INFO(LABEL, "get resultCode: %d", resultCode); + ACCESSTOKEN_LOG_INFO(LABEL, "get resultCode: %{public}d", resultCode); } return RET_SUCCESS; diff --git a/services/tokensyncmanager/test/mock/src/constant_mock.cpp b/services/tokensyncmanager/test/mock/src/constant_mock.cpp index 6998e7fd672ed3ac601b607dc9af79b8489860c3..fef282afcabc910127ab7f5e90765ebecd1860b9 100644 --- a/services/tokensyncmanager/test/mock/src/constant_mock.cpp +++ b/services/tokensyncmanager/test/mock/src/constant_mock.cpp @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include "constant_common.h" #include "constant.h" namespace OHOS { @@ -22,19 +23,18 @@ static const std::string REPLACE_TARGET = "****"; } // namespace const std::string Constant::COMMAND_RESULT_SUCCESS = "success"; const std::string Constant::COMMAND_RESULT_FAILED = "execute command failed"; - -std::string Constant::EncryptDevId(std::string deviceId) +std::string ConstantCommon::EncryptDevId(std::string deviceId) { std::string result = deviceId; - if (deviceId.size() >= ENCRYPTLEN) { - result.replace(ENCRYPTBEGIN, ENCRYPTEND, REPLACE_TARGET); + if (deviceId.size() > MINDEVICEIDLEN) { + result.replace(ENCRYPTBEGIN + ENCRYPTLEN, deviceId.size() - MINDEVICEIDLEN, REPLACE_TARGET); } else { - result.replace(ENCRYPTBEGIN, result.size() - 1, REPLACE_TARGET); + result.replace(ENCRYPTBEGIN, deviceId.size(), REPLACE_TARGET); } return result; } -std::string Constant::GetLocalDeviceId() +std::string ConstantCommon::GetLocalDeviceId() { return "local:udid-001"; } diff --git a/services/tokensyncmanager/test/unittest/token_sync_service/token_sync_service_test.cpp b/services/tokensyncmanager/test/unittest/token_sync_service/token_sync_service_test.cpp index 396ceaa21dd08843b0260df73cd6a259d5d8d471..722c97a0bcf2423010b9d46129775c87ff55ac42 100644 --- a/services/tokensyncmanager/test/unittest/token_sync_service/token_sync_service_test.cpp +++ b/services/tokensyncmanager/test/unittest/token_sync_service/token_sync_service_test.cpp @@ -22,10 +22,11 @@ #include #include +#include "gtest/gtest.h" #include "accesstoken_kit.h" #include "accesstoken_log.h" #include "base_remote_command.h" -#include "gtest/gtest.h" +#include "constant_common.h" #include "session.h" #include "soft_bus_device_connection_listener.h" #include "soft_bus_session_listener.h" @@ -91,7 +92,7 @@ void TokenSyncServiceTest::OnDeviceOffline(const DmDeviceInfo &info) "networkId: %{public}s, uuid: %{public}s, udid: %{public}s", networkId.c_str(), uuid.c_str(), - udid.c_str()); + ConstantCommon::EncryptDevId(udid).c_str()); if (uuid != "" && udid != "") { RemoteCommandManager::GetInstance().NotifyDeviceOffline(uuid);