1/*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16#include "sys_cap_util.h"
17#include "string_util.h"
18#include "window_manager_hilog.h"
19
20#include <accesstoken_kit.h>
21#include <bundle_mgr_interface.h>
22#include <ipc_skeleton.h>
23#include <iservice_registry.h>
24#include <system_ability_definition.h>
25
26namespace OHOS {
27namespace Rosen {
28namespace {
29constexpr HiviewDFX::HiLogLabel LABEL = {LOG_CORE, HILOG_DOMAIN_WINDOW, "SysCapUtil"};
30}
31
32std::string SysCapUtil::GetClientName()
33{
34    std::string bn = GetBundleName();
35    if (!bn.empty()) {
36        WLOGFD("bundle name [%{public}s]", bn.c_str());
37        return bn;
38    }
39
40    std::string pn = GetProcessName();
41    if (!pn.empty()) {
42        WLOGFD("process name [%{public}s]", pn.c_str());
43        return pn;
44    }
45
46    WLOGFD("unknown name");
47    return "unknown";
48}
49
50std::string SysCapUtil::GetBundleName()
51{
52    OHOS::sptr<OHOS::ISystemAbilityManager> systemAbilityManager =
53        OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
54    OHOS::sptr<OHOS::IRemoteObject> remoteObject =
55        systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
56    sptr<AppExecFwk::IBundleMgr> iBundleMgr = OHOS::iface_cast<AppExecFwk::IBundleMgr>(remoteObject);
57    if (iBundleMgr == nullptr) {
58        WLOGFW("IBundleMgr is null");
59        return "";
60    }
61
62    std::string bundleName = "";
63    AppExecFwk::BundleInfo bundleInfo;
64    if (iBundleMgr->GetBundleInfoForSelf(0, bundleInfo) == ERR_OK) {
65        bundleName = bundleInfo.name;
66    } else {
67        WLOGFW("Call for GetBundleInfoForSelf failed");
68    }
69    return StringUtil::Trim(bundleName);
70}
71
72std::string SysCapUtil::GetProcessName()
73{
74    OHOS::Security::AccessToken::NativeTokenInfo info;
75    if (Security::AccessToken::AccessTokenKit::GetNativeTokenInfo(IPCSkeleton::GetCallingTokenID(), info) != 0) {
76        WLOGFW("get token info failed");
77        return "";
78    }
79    return StringUtil::Trim(info.processName);
80}
81} // namespace Rosen
82} // namespace OHOS