1 /*
2 * Copyright (C) 2023 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 "tdd_util.h"
17
18 #include <csignal>
19 #include <cstdint>
20 #include <sstream>
21 #include <string>
22 #include <unistd.h>
23 #include <vector>
24
25 #include "accesstoken_kit.h"
26 #include "global.h"
27 #include "if_system_ability_manager.h"
28 #include "iservice_registry.h"
29 #include "nativetoken_kit.h"
30 #include "os_account_manager.h"
31 #include "system_ability.h"
32 #include "system_ability_definition.h"
33 #include "token_setproc.h"
34
35 namespace OHOS {
36 namespace MiscServices {
37 using namespace OHOS::Security::AccessToken;
38 using namespace OHOS::AccountSA;
39 using namespace Rosen;
40 constexpr int32_t INVALID_USER_ID = -1;
41 constexpr int32_t MAIN_USER_ID = 100;
42 constexpr const uint16_t EACH_LINE_LENGTH = 500;
43 constexpr int32_t BUFF_LENGTH = 10;
44 constexpr const char *CMD_PIDOF_IMS = "pidof inputmethod_ser";
45 static constexpr int32_t MAX_TIMEOUT_WAIT_FOCUS = 2000;
46 uint64_t TddUtil::selfTokenID_ = 0;
47 int32_t TddUtil::userID_ = INVALID_USER_ID;
48 sptr<Window> TddUtil::WindowManager::window_ = nullptr;
49 int32_t TddUtil::WindowManager::currentWindowId_ = 0;
50 std::shared_ptr<BlockData<bool>> FocusChangedListenerTestImpl::isFocused_ =
51 std::make_shared<BlockData<bool>>(MAX_TIMEOUT_WAIT_FOCUS, false);
52 std::shared_ptr<BlockData<bool>> FocusChangedListenerTestImpl::unFocused_ =
53 std::make_shared<BlockData<bool>>(MAX_TIMEOUT_WAIT_FOCUS, false);
OnFocused(const sptr<Rosen::FocusChangeInfo> & focusChangeInfo)54 void FocusChangedListenerTestImpl::OnFocused(const sptr<Rosen::FocusChangeInfo> &focusChangeInfo)
55 {
56 IMSA_HILOGI("get onFocus information from window manager.");
57 if (focusChangeInfo->windowId_ == TddUtil::WindowManager::currentWindowId_) {
58 getFocus_ = true;
59 isFocused_->SetValue(getFocus_);
60 unFocused_->Clear(false);
61 }
62 }
63
OnUnfocused(const sptr<Rosen::FocusChangeInfo> & focusChangeInfo)64 void FocusChangedListenerTestImpl::OnUnfocused(const sptr<Rosen::FocusChangeInfo> &focusChangeInfo)
65 {
66 IMSA_HILOGI("get unfocus information from window manager.");
67 if (focusChangeInfo->windowId_ == TddUtil::WindowManager::currentWindowId_) {
68 getFocus_ = false;
69 isFocused_->Clear(false);
70 bool unFocus = !getFocus_;
71 unFocused_->SetValue(unFocus);
72 }
73 }
74
GetCurrentUserId()75 int32_t TddUtil::GetCurrentUserId()
76 {
77 if (userID_ != INVALID_USER_ID) {
78 return userID_;
79 }
80 std::vector<int32_t> userIds;
81 auto ret = OsAccountManager::QueryActiveOsAccountIds(userIds);
82 if (ret != ErrorCode::NO_ERROR || userIds.empty()) {
83 IMSA_HILOGE("query active os account id failed");
84 return MAIN_USER_ID;
85 }
86 return userIds[0];
87 }
StorageSelfTokenID()88 void TddUtil::StorageSelfTokenID()
89 {
90 selfTokenID_ = GetSelfTokenID();
91 }
92
AllocTestTokenID(bool isSystemApp,bool needPermission,const std::string & bundleName)93 uint64_t TddUtil::AllocTestTokenID(bool isSystemApp, bool needPermission, const std::string &bundleName)
94 {
95 IMSA_HILOGI("bundleName: %{public}s", bundleName.c_str());
96 HapInfoParams infoParams = { .userID = GetCurrentUserId(),
97 .bundleName = bundleName,
98 .instIndex = 0,
99 .appIDDesc = bundleName,
100 .isSystemApp = isSystemApp };
101 PermissionStateFull permissionState = { .permissionName = "ohos.permission.CONNECT_IME_ABILITY",
102 .isGeneral = true,
103 .resDeviceID = { "local" },
104 .grantStatus = { PermissionState::PERMISSION_GRANTED },
105 .grantFlags = { 1 } };
106 HapPolicyParams policyParams = { .apl = APL_NORMAL,
107 .domain = bundleName,
108 .permList = {},
109 .permStateList = { permissionState } };
110 if (!needPermission) {
111 policyParams = { .apl = APL_NORMAL, .domain = bundleName, .permList = {}, .permStateList = {} };
112 }
113 auto tokenInfo = AccessTokenKit::AllocHapToken(infoParams, policyParams);
114 return tokenInfo.tokenIDEx;
115 }
116
GetTestTokenID(const std::string & bundleName)117 uint64_t TddUtil::GetTestTokenID(const std::string &bundleName)
118 {
119 HapInfoParams infoParams = { .userID = GetUserIdByBundleName(bundleName, GetCurrentUserId()),
120 .bundleName = bundleName,
121 .instIndex = 0,
122 .appIDDesc = "ohos.inputmethod_test.demo" };
123 return AccessTokenKit::GetHapTokenID(infoParams.userID, infoParams.bundleName, infoParams.instIndex);
124 }
125
DeleteTestTokenID(uint64_t tokenId)126 void TddUtil::DeleteTestTokenID(uint64_t tokenId)
127 {
128 AccessTokenKit::DeleteToken(tokenId);
129 }
130
SetTestTokenID(uint64_t tokenId)131 void TddUtil::SetTestTokenID(uint64_t tokenId)
132 {
133 auto ret = SetSelfTokenID(tokenId);
134 IMSA_HILOGI("SetSelfTokenID ret: %{public}d", ret);
135 }
136
RestoreSelfTokenID()137 void TddUtil::RestoreSelfTokenID()
138 {
139 auto ret = SetSelfTokenID(selfTokenID_);
140 IMSA_HILOGI("SetSelfTokenID ret = %{public}d", ret);
141 }
142
ExecuteCmd(const std::string & cmd,std::string & result)143 bool TddUtil::ExecuteCmd(const std::string &cmd, std::string &result)
144 {
145 char buff[EACH_LINE_LENGTH] = { 0x00 };
146 std::stringstream output;
147 FILE *ptr = popen(cmd.c_str(), "r");
148 if (ptr != nullptr) {
149 while (fgets(buff, sizeof(buff), ptr) != nullptr) {
150 output << buff;
151 }
152 pclose(ptr);
153 ptr = nullptr;
154 } else {
155 return false;
156 }
157 result = output.str();
158 return true;
159 }
160
GetImsaPid()161 pid_t TddUtil::GetImsaPid()
162 {
163 char buff[BUFF_LENGTH] = { 0 };
164 FILE *fp = popen(CMD_PIDOF_IMS, "r");
165 if (fp == nullptr) {
166 IMSA_HILOGI("get pid failed.");
167 return -1;
168 }
169 fgets(buff, sizeof(buff), fp);
170 pid_t pid = atoi(buff);
171 pclose(fp);
172 fp = nullptr;
173 return pid;
174 }
175
KillImsaProcess()176 void TddUtil::KillImsaProcess()
177 {
178 pid_t pid = GetImsaPid();
179 if (pid == -1) {
180 IMSA_HILOGE("Pid of Imsa is not exist.");
181 return;
182 }
183 auto ret = kill(pid, SIGTERM);
184 if (ret != 0) {
185 IMSA_HILOGE("Kill failed, ret: %{public}d", ret);
186 return;
187 }
188 IMSA_HILOGI("Kill success.");
189 }
190
GetBundleMgr()191 sptr<OHOS::AppExecFwk::IBundleMgr> TddUtil::GetBundleMgr()
192 {
193 sptr<ISystemAbilityManager> systemAbilityManager =
194 SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
195 if (systemAbilityManager == nullptr) {
196 IMSA_HILOGE("systemAbilityManager is nullptr");
197 return nullptr;
198 }
199 sptr<IRemoteObject> remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
200 if (remoteObject == nullptr) {
201 IMSA_HILOGE("remoteObject is nullptr");
202 return nullptr;
203 }
204 return iface_cast<AppExecFwk::IBundleMgr>(remoteObject);
205 }
206
GetUserIdByBundleName(const std::string & bundleName,const int currentUserId)207 int TddUtil::GetUserIdByBundleName(const std::string &bundleName, const int currentUserId)
208 {
209 auto bundleMgr = TddUtil::GetBundleMgr();
210 if (bundleMgr == nullptr) {
211 IMSA_HILOGE("Get bundleMgr failed.");
212 return -1;
213 }
214 auto uid = bundleMgr->GetUidByBundleName(bundleName, currentUserId);
215 if (uid == -1) {
216 IMSA_HILOGE("failed to get information and the parameters may be wrong.");
217 return -1;
218 }
219 // 200000 means userId = uid / 200000.
220 return uid/200000;
221 }
222
CreateWindow()223 void TddUtil::WindowManager::CreateWindow()
224 {
225 std::string windowName = "inputmethod_test_window";
226 sptr<WindowOption> winOption = new OHOS::Rosen::WindowOption();
227 winOption->SetWindowType(WindowType::WINDOW_TYPE_FLOAT);
228 winOption->SetFocusable(true);
229 std::shared_ptr<AbilityRuntime::Context> context = nullptr;
230 WMError wmError = WMError::WM_OK;
231 window_ = Window::Create(windowName, winOption, context, wmError);
232 IMSA_HILOGI("Create window ret:%{public}d", wmError);
233 currentWindowId_ = window_->GetWindowId();
234 }
235
ShowWindow()236 void TddUtil::WindowManager::ShowWindow()
237 {
238 if (window_ == nullptr) {
239 IMSA_HILOGE("window is not exist.");
240 return;
241 }
242 auto ret = window_->Show();
243 IMSA_HILOGI("Show window end, ret = %{public}d", ret);
244 }
245
HideWindow()246 void TddUtil::WindowManager::HideWindow()
247 {
248 if (window_ == nullptr) {
249 IMSA_HILOGE("window is not exist.");
250 return;
251 }
252 auto ret = window_->Hide();
253 IMSA_HILOGI("Hide window end, ret = %{public}d", ret);
254 }
255
DestroyWindow()256 void TddUtil::WindowManager::DestroyWindow()
257 {
258 if (window_ != nullptr) {
259 window_->Destroy();
260 }
261 }
262
RegisterFocusChangeListener()263 void TddUtil::WindowManager::RegisterFocusChangeListener()
264 {
265 auto listener = new (std::nothrow) FocusChangedListenerTestImpl();
266 WMError ret = Rosen::WindowManager::GetInstance().RegisterFocusChangedListener(listener);
267 IMSA_HILOGI("register focus changed listener ret: %{public}d", ret);
268 }
269 } // namespace MiscServices
270 } // namespace OHOS
271