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