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 "remote_command_executor.h"
17 #ifdef EVENTHANDLER_ENABLE
18 #include "access_event_handler.h"
19 #endif
20 #include "constant_common.h"
21 #include "device_info_manager.h"
22 #include "singleton.h"
23 #include "soft_bus_channel.h"
24 #include "token_sync_manager_service.h"
25
26 namespace OHOS {
27 namespace Security {
28 namespace AccessToken {
29 namespace {
30 static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "RemoteCommandExecutor"};
31 static const std::string TASK_NAME = "RemoteCommandExecutor::ProcessBufferedCommandsWithThread";
32 } // namespace
RemoteCommandExecutor(const std::string & targetNodeId)33 RemoteCommandExecutor::RemoteCommandExecutor(const std::string &targetNodeId)
34 : targetNodeId_(targetNodeId), ptrChannel_(nullptr), mutex_(), commands_(), running_(false)
35 {
36 ACCESSTOKEN_LOG_DEBUG(LABEL, "RemoteCommandExecutor()");
37 }
38
~RemoteCommandExecutor()39 RemoteCommandExecutor::~RemoteCommandExecutor()
40 {
41 ACCESSTOKEN_LOG_DEBUG(LABEL, "~RemoteCommandExecutor() begin");
42 running_ = false;
43 }
44
CreateChannel(const std::string & targetNodeId)45 const std::shared_ptr<RpcChannel> RemoteCommandExecutor::CreateChannel(const std::string &targetNodeId)
46 {
47 ACCESSTOKEN_LOG_DEBUG(LABEL, "CreateChannel: targetNodeId=%{public}s",
48 ConstantCommon::EncryptDevId(targetNodeId).c_str());
49 // only consider SoftBusChannel
50 std::shared_ptr<RpcChannel> ptrChannel = std::make_shared<SoftBusChannel>(targetNodeId);
51 return ptrChannel;
52 }
53
54 /*
55 * called by RemoteCommandExecutor, RemoteCommandManager
56 */
ProcessOneCommand(const std::shared_ptr<BaseRemoteCommand> & ptrCommand)57 int RemoteCommandExecutor::ProcessOneCommand(const std::shared_ptr<BaseRemoteCommand>& ptrCommand)
58 {
59 if (ptrCommand == nullptr) {
60 ACCESSTOKEN_LOG_WARN(LABEL, "targetNodeId %{public}s, attempt to process on null command.",
61 ConstantCommon::EncryptDevId(targetNodeId_).c_str());
62 return Constant::SUCCESS;
63 }
64 const std::string uniqueId = ptrCommand->remoteProtocol_.uniqueId;
65 ACCESSTOKEN_LOG_INFO(LABEL, "targetNodeId %{public}s, process one command start, uniqueId: %{public}s",
66 ConstantCommon::EncryptDevId(targetNodeId_).c_str(), uniqueId.c_str());
67
68 ptrCommand->Prepare();
69 int status = ptrCommand->remoteProtocol_.statusCode;
70 if (status != Constant::SUCCESS) {
71 ACCESSTOKEN_LOG_ERROR(LABEL,
72 "targetNodeId %{public}s, process one command error, uniqueId: %{public}s, message: "
73 "prepare failure code %{public}d", ConstantCommon::EncryptDevId(targetNodeId_).c_str(),
74 uniqueId.c_str(), status);
75 return status;
76 }
77
78 std::string localUdid = ConstantCommon::GetLocalDeviceId();
79 if (targetNodeId_ == localUdid) {
80 return ExecuteRemoteCommand(ptrCommand, false);
81 }
82
83 // otherwise a remote device
84 CreateChannelIfNeeded();
85 if (ptrChannel_ == nullptr) {
86 ACCESSTOKEN_LOG_ERROR(LABEL, "targetNodeId %{public}s, channel is null.",
87 ConstantCommon::EncryptDevId(targetNodeId_).c_str());
88 return Constant::FAILURE;
89 }
90 if (ptrChannel_->BuildConnection() != Constant::SUCCESS) {
91 ACCESSTOKEN_LOG_ERROR(LABEL, "targetNodeId %{public}s, channel is not ready.",
92 ConstantCommon::EncryptDevId(targetNodeId_).c_str());
93 return Constant::FAILURE;
94 }
95
96 return ExecuteRemoteCommand(ptrCommand, true);
97 }
98
99 /*
100 * called by RemoteCommandManager
101 */
AddCommand(const std::shared_ptr<BaseRemoteCommand> & ptrCommand)102 int RemoteCommandExecutor::AddCommand(const std::shared_ptr<BaseRemoteCommand>& ptrCommand)
103 {
104 if (ptrCommand == nullptr) {
105 ACCESSTOKEN_LOG_DEBUG(LABEL, "targetNodeId %{public}s, attempt to add an empty command.",
106 ConstantCommon::EncryptDevId(targetNodeId_).c_str());
107 return Constant::INVALID_COMMAND;
108 }
109
110 const std::string uniqueId = ptrCommand->remoteProtocol_.uniqueId;
111 ACCESSTOKEN_LOG_DEBUG(LABEL, "targetNodeId %{public}s, add uniqueId %{public}s",
112 ConstantCommon::EncryptDevId(targetNodeId_).c_str(), uniqueId.c_str());
113
114 std::unique_lock<std::recursive_mutex> lock(mutex_);
115
116 // make sure do not have the same command in the command buffer
117 if (std::any_of(commands_.begin(), commands_.end(),
118 [uniqueId](const auto& buffCommand) {return buffCommand->remoteProtocol_.uniqueId == uniqueId; })) {
119 ACCESSTOKEN_LOG_WARN(LABEL,
120 "targetNodeId %{public}s, add uniqueId %{public}s, already exist in the buffer, skip",
121 ConstantCommon::EncryptDevId(targetNodeId_).c_str(),
122 uniqueId.c_str());
123 return Constant::SUCCESS;
124 }
125
126 commands_.push_back(ptrCommand);
127 return Constant::SUCCESS;
128 }
129
130 /*
131 * called by RemoteCommandExecutor.ProcessCommandThread, RemoteCommandManager
132 */
ProcessBufferedCommands(bool standalone)133 int RemoteCommandExecutor::ProcessBufferedCommands(bool standalone)
134 {
135 ACCESSTOKEN_LOG_INFO(LABEL, "begin, targetNodeId: %{public}s, standalone: %{public}d",
136 ConstantCommon::EncryptDevId(targetNodeId_).c_str(), standalone);
137
138 std::unique_lock<std::recursive_mutex> lock(mutex_);
139
140 if (commands_.empty()) {
141 ACCESSTOKEN_LOG_WARN(LABEL, "no command, targetNodeId %{public}s",
142 ConstantCommon::EncryptDevId(targetNodeId_).c_str());
143 running_ = false;
144 return Constant::SUCCESS;
145 }
146
147 running_ = true;
148 while (true) {
149 // interrupt
150 if (!running_) {
151 ACCESSTOKEN_LOG_INFO(LABEL, "end with running flag == false, targetNodeId: %{public}s",
152 ConstantCommon::EncryptDevId(targetNodeId_).c_str());
153 return Constant::FAILURE;
154 }
155 // end
156 if (commands_.empty()) {
157 running_ = false;
158 ACCESSTOKEN_LOG_INFO(LABEL, "end, no command left, targetNodeId: %{public}s",
159 ConstantCommon::EncryptDevId(targetNodeId_).c_str());
160 return Constant::SUCCESS;
161 }
162
163 // consume queue to execute
164 const std::shared_ptr<BaseRemoteCommand> bufferedCommand = commands_.front();
165 int status = ProcessOneCommand(bufferedCommand);
166 if (status == Constant::SUCCESS) {
167 commands_.pop_front();
168 continue;
169 } else if (status == Constant::FAILURE_BUT_CAN_RETRY) {
170 ACCESSTOKEN_LOG_WARN(LABEL,
171 "execute failed and wait to retry, targetNodeId: %{public}s, message: %{public}s, and will retry ",
172 ConstantCommon::EncryptDevId(targetNodeId_).c_str(),
173 bufferedCommand->remoteProtocol_.message.c_str());
174
175 // now, the retry at once will have no effective because the network problem
176 // so if the before the step, one command is added, and run this function
177 // it should also not need to restart to process the commands buffer at once.
178 running_ = false;
179 return Constant::FAILURE;
180 } else {
181 // this command failed, move on to execute next command
182 commands_.pop_front();
183 ACCESSTOKEN_LOG_ERROR(LABEL,
184 "execute failed, targetNodeId: %{public}s, commandName: %{public}s, message: %{public}s",
185 ConstantCommon::EncryptDevId(targetNodeId_).c_str(),
186 bufferedCommand->remoteProtocol_.commandName.c_str(),
187 bufferedCommand->remoteProtocol_.message.c_str());
188 }
189 }
190 }
191
192 /*
193 * called by RemoteCommandManager
194 */
ProcessBufferedCommandsWithThread()195 void RemoteCommandExecutor::ProcessBufferedCommandsWithThread()
196 {
197 ACCESSTOKEN_LOG_INFO(LABEL, "begin, targetNodeId: %{public}s", ConstantCommon::EncryptDevId(targetNodeId_).c_str());
198
199 std::unique_lock<std::recursive_mutex> lock(mutex_);
200
201 if (commands_.empty()) {
202 ACCESSTOKEN_LOG_INFO(LABEL, "No buffered commands. targetNodeId: %{public}s",
203 ConstantCommon::EncryptDevId(targetNodeId_).c_str());
204 return;
205 }
206 if (running_) {
207 // task is running, do not need to start one more
208 ACCESSTOKEN_LOG_WARN(LABEL, "task busy. targetNodeId: %{public}s",
209 ConstantCommon::EncryptDevId(targetNodeId_).c_str());
210 return;
211 }
212
213 running_ = true;
214 const std::function<void()> runner = std::bind(&RemoteCommandExecutor::ProcessBufferedCommands, this, true);
215
216 #ifdef EVENTHANDLER_ENABLE
217 std::shared_ptr<AccessEventHandler> handler =
218 DelayedSingleton<TokenSyncManagerService>::GetInstance()->GetSendEventHandler();
219 if (handler == nullptr) {
220 ACCESSTOKEN_LOG_ERROR(LABEL, "fail to get EventHandler");
221 return;
222 }
223 bool result = handler->ProxyPostTask(runner, TASK_NAME);
224 if (!result) {
225 ACCESSTOKEN_LOG_ERROR(LABEL, "post task failed, targetNodeId: %{public}s",
226 ConstantCommon::EncryptDevId(targetNodeId_).c_str());
227 }
228 #endif
229 ACCESSTOKEN_LOG_INFO(LABEL,
230 "post task succeed, targetNodeId: %{public}s, taskName: %{public}s",
231 ConstantCommon::EncryptDevId(targetNodeId_).c_str(),
232 TASK_NAME.c_str());
233 }
234
ExecuteRemoteCommand(const std::shared_ptr<BaseRemoteCommand> & ptrCommand,const bool isRemote)235 int RemoteCommandExecutor::ExecuteRemoteCommand(
236 const std::shared_ptr<BaseRemoteCommand>& ptrCommand, const bool isRemote)
237 {
238 std::string uniqueId = ptrCommand->remoteProtocol_.uniqueId;
239 ACCESSTOKEN_LOG_INFO(LABEL,
240 "targetNodeId %{public}s, uniqueId %{public}s, remote %{public}d: start to execute",
241 ConstantCommon::EncryptDevId(targetNodeId_).c_str(),
242 uniqueId.c_str(),
243 isRemote);
244
245 ptrCommand->remoteProtocol_.statusCode = Constant::STATUS_CODE_BEFORE_RPC;
246
247 if (!isRemote) {
248 // Local device, play myself.
249 ptrCommand->Execute();
250 int code = ClientProcessResult(ptrCommand);
251 ACCESSTOKEN_LOG_DEBUG(LABEL,
252 "command finished with status: %{public}d, message: %{public}s",
253 ptrCommand->remoteProtocol_.statusCode,
254 ptrCommand->remoteProtocol_.message.c_str());
255 return code;
256 }
257
258 std::string responseString =
259 ptrChannel_->ExecuteCommand(ptrCommand->remoteProtocol_.commandName, ptrCommand->ToJsonPayload());
260 ACCESSTOKEN_LOG_INFO(LABEL, "command executed uniqueId %{public}s", uniqueId.c_str());
261 if (responseString.empty()) {
262 ACCESSTOKEN_LOG_WARN(LABEL,
263 "targetNodeId %{public}s, uniqueId %{public}s, execute remote command error, response is empty.",
264 ConstantCommon::EncryptDevId(targetNodeId_).c_str(),
265 uniqueId.c_str());
266 // if command send failed, also try to close session
267 if (commands_.empty()) {
268 ptrChannel_->CloseConnection();
269 }
270 return Constant::FAILURE;
271 }
272
273 std::shared_ptr<BaseRemoteCommand> ptrResponseCommand =
274 RemoteCommandFactory::GetInstance().NewRemoteCommandFromJson(
275 ptrCommand->remoteProtocol_.commandName, responseString);
276 if (ptrResponseCommand == nullptr) {
277 ACCESSTOKEN_LOG_ERROR(LABEL, "targetNodeId %{public}s, get null response command!",
278 ConstantCommon::EncryptDevId(targetNodeId_).c_str());
279 return Constant::FAILURE;
280 }
281 int32_t result = ClientProcessResult(ptrResponseCommand);
282 if (commands_.empty()) {
283 ptrChannel_->CloseConnection();
284 }
285 ACCESSTOKEN_LOG_DEBUG(LABEL,
286 "command finished with status: %{public}d, message: %{public}s",
287 ptrResponseCommand->remoteProtocol_.statusCode,
288 ptrResponseCommand->remoteProtocol_.message.c_str());
289 return result;
290 }
291
CreateChannelIfNeeded()292 void RemoteCommandExecutor::CreateChannelIfNeeded()
293 {
294 std::unique_lock<std::recursive_mutex> lock(mutex_);
295 if (ptrChannel_ != nullptr) {
296 ACCESSTOKEN_LOG_INFO(LABEL, "targetNodeId %{public}s, channel is exist.",
297 ConstantCommon::EncryptDevId(targetNodeId_).c_str());
298 return;
299 }
300
301 ptrChannel_ = CreateChannel(targetNodeId_);
302 }
303
ClientProcessResult(const std::shared_ptr<BaseRemoteCommand> & ptrCommand)304 int RemoteCommandExecutor::ClientProcessResult(const std::shared_ptr<BaseRemoteCommand>& ptrCommand)
305 {
306 std::string uniqueId = ptrCommand->remoteProtocol_.uniqueId;
307 if (ptrCommand->remoteProtocol_.statusCode == Constant::STATUS_CODE_BEFORE_RPC) {
308 ACCESSTOKEN_LOG_ERROR(LABEL,
309 "targetNodeId %{public}s, uniqueId %{public}s, status code after RPC is same as before, the remote side "
310 "may not "
311 "support this command",
312 ConstantCommon::EncryptDevId(targetNodeId_).c_str(),
313 uniqueId.c_str());
314 return Constant::FAILURE;
315 }
316
317 ptrCommand->Finish();
318 int status = ptrCommand->remoteProtocol_.statusCode;
319 if (status != Constant::SUCCESS) {
320 ACCESSTOKEN_LOG_ERROR(LABEL,
321 "targetNodeId %{public}s, uniqueId %{public}s, execute failed, message: %{public}s",
322 ConstantCommon::EncryptDevId(targetNodeId_).c_str(),
323 uniqueId.c_str(),
324 ptrCommand->remoteProtocol_.message.c_str());
325 } else {
326 ACCESSTOKEN_LOG_INFO(LABEL,
327 "targetNodeId %{public}s, uniqueId %{public}s, execute succeed.",
328 ConstantCommon::EncryptDevId(targetNodeId_).c_str(),
329 uniqueId.c_str());
330 }
331 return status;
332 }
333 } // namespace AccessToken
334 } // namespace Security
335 } // namespace OHOS
336