1 /*
2 * Copyright (C) 2021 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 #include <cstdlib>
16 #include <sys/mount.h>
17 #include <sys/wait.h>
18
19 #include "daemon_unity.h"
20
21 namespace Hdc {
HdcDaemonUnity(HTaskInfo hTaskInfo)22 HdcDaemonUnity::HdcDaemonUnity(HTaskInfo hTaskInfo)
23 : HdcTaskBase(hTaskInfo)
24 {
25 currentDataCommand = CMD_KERNEL_ECHO_RAW; // Default output to shelldata
26 }
27
~HdcDaemonUnity()28 HdcDaemonUnity::~HdcDaemonUnity()
29 {
30 WRITE_LOG(LOG_DEBUG, "~HdcDaemonUnity channelId:%u", taskInfo->channelId);
31 }
32
StopTask()33 void HdcDaemonUnity::StopTask()
34 {
35 // Remove jpid tracker when stopping task
36 RemoveJdwpTracker();
37 asyncCommand.DoRelease();
38 }
39
ReadyForRelease()40 bool HdcDaemonUnity::ReadyForRelease()
41 {
42 if (!HdcTaskBase::ReadyForRelease() || !asyncCommand.ReadyForRelease()) {
43 WRITE_LOG(LOG_DEBUG, "not ready for release channelId:%u", taskInfo->channelId);
44 return false;
45 }
46 return true;
47 }
48
AsyncCmdOut(bool finish,int64_t exitStatus,const string result)49 bool HdcDaemonUnity::AsyncCmdOut(bool finish, int64_t exitStatus, const string result)
50 {
51 #ifdef UNIT_TEST
52 Base::WriteBinFile((UT_TMP_PATH + "/execute.result").c_str(), (uint8_t *)result.c_str(), result.size(),
53 countUt++ == 0);
54 #endif
55 bool ret = false;
56 bool wantFinish = false;
57 do {
58 if (finish) {
59 wantFinish = true;
60 ret = true;
61 --refCount;
62 break;
63 }
64 if (!SendToAnother(currentDataCommand, reinterpret_cast<uint8_t *>(const_cast<char *>(result.c_str())),
65 result.size())) {
66 break;
67 }
68 ret = true;
69 } while (false);
70 if (wantFinish) {
71 TaskFinish();
72 }
73 return ret;
74 }
75
CheckbundlePath(const string & bundleName,string & mountPath)76 bool HdcDaemonUnity::CheckbundlePath(const string &bundleName, string &mountPath)
77 {
78 if (access(DEBUG_BUNDLE_PATH.c_str(), F_OK) != 0 || !Base::CheckBundleName(bundleName)) {
79 WRITE_LOG(LOG_FATAL, "debug path %s not found", DEBUG_BUNDLE_PATH.c_str());
80 LogMsg(MSG_FAIL, "[E003001] Invalid bundle name: %s", bundleName.c_str());
81 return false;
82 }
83 string targetPath = "";
84 targetPath += DEBUG_BUNDLE_PATH;
85 targetPath += bundleName;
86 if ((access(targetPath.c_str(), F_OK) != 0)) {
87 WRITE_LOG(LOG_FATAL, "bundle mount path %s not found", targetPath.c_str());
88 LogMsg(MSG_FAIL, "[E003001] Invalid bundle name: %s", bundleName.c_str());
89 return false;
90 }
91 mountPath = targetPath;
92 return true;
93 }
94
ExecuteOptionShell(const string & shellCommand,const string & bundleName)95 int HdcDaemonUnity::ExecuteOptionShell(const string &shellCommand, const string &bundleName)
96 {
97 string mountPath = "";
98 if (!CheckbundlePath(bundleName, mountPath)) {
99 return -1;
100 }
101 return ExecuteShell(shellCommand, mountPath);
102 }
103
ExecuteShell(const string & shellCommand,string optionPath)104 int HdcDaemonUnity::ExecuteShell(const string &shellCommand, string optionPath)
105 {
106 do {
107 AsyncCmd::CmdResultCallback funcResultOutput;
108 funcResultOutput = [this](bool finish, int64_t exitStatus, const string result) -> bool {
109 return this->AsyncCmdOut(finish, exitStatus, result);
110 };
111 if (!asyncCommand.Initial(loopTask, funcResultOutput)) {
112 break;
113 }
114 asyncCommand.ExecuteCommand(shellCommand, optionPath);
115 ++refCount;
116 return RET_SUCCESS;
117 } while (false);
118
119 TaskFinish();
120 WRITE_LOG(LOG_DEBUG, "Shell failed finish");
121 return -1;
122 }
123
ExecuteShellExtend(const uint8_t * payload,const int payloadSize)124 int HdcDaemonUnity::ExecuteShellExtend(const uint8_t *payload, const int payloadSize)
125 {
126 string bundleName = "";
127 string command = "";
128 string errMsg = "";
129 TlvBuf tlvbuf(const_cast<uint8_t *>(payload), payloadSize, Base::REGISTERD_TAG_SET);
130 tlvbuf.Display();
131 if (tlvbuf.ContainInvalidTag()) {
132 LogMsg(MSG_FAIL, "[E003004] Device does not support this shell option");
133 return -1;
134 } else {
135 if (!tlvbuf.FindTlv(TAG_SHELL_BUNDLE, bundleName)) {
136 WRITE_LOG(LOG_FATAL, "ExecuteShellExtend bundleName is empty");
137 }
138 if (!tlvbuf.FindTlv(TAG_SHELL_CMD, command)) {
139 WRITE_LOG(LOG_FATAL, "ExecuteShellExtend command is empty");
140 }
141 }
142 WRITE_LOG(LOG_DEBUG, "ExecuteShellExtend command: %s, bundleName: %s", command.c_str(), bundleName.c_str());
143 return ExecuteOptionShell(command, bundleName);
144 }
145
FindMountDeviceByPath(const char * toQuery,char * dev)146 bool HdcDaemonUnity::FindMountDeviceByPath(const char *toQuery, char *dev)
147 {
148 int ret = false;
149 int len = BUF_SIZE_DEFAULT2;
150 char buf[BUF_SIZE_DEFAULT2];
151
152 FILE *fp = fopen("/proc/mounts", "r");
153 if (fp == nullptr) {
154 WRITE_LOG(LOG_FATAL, "fopen /proc/mounts error:%d", errno);
155 return false;
156 }
157
158 while (fgets(buf, len, fp) != nullptr) {
159 char dir[BUF_SIZE_SMALL] = "";
160 int freq;
161 int passnno;
162 int res = 0;
163 // clang-format off
164 res = sscanf_s(buf, "%255s %255s %*s %*s %d %d\n", dev, BUF_SIZE_SMALL - 1,
165 dir, BUF_SIZE_SMALL - 1, &freq, &passnno);
166 // clang-format on
167 dev[BUF_SIZE_SMALL - 1] = '\0';
168 dir[BUF_SIZE_SMALL - 1] = '\0';
169 if (res == 4 && (strcmp(toQuery, dir) == 0)) { // 4 : The correct number of parameters
170 WRITE_LOG(LOG_DEBUG, "FindMountDeviceByPath dev:%s dir:%s", dev, dir);
171 ret = true;
172 break;
173 }
174 }
175 int rc = fclose(fp);
176 if (rc != 0) {
177 WRITE_LOG(LOG_WARN, "fclose rc:%d error:%d", rc, errno);
178 }
179 if (!ret) {
180 WRITE_LOG(LOG_FATAL, "FindMountDeviceByPath not found %s", toQuery);
181 }
182 return ret;
183 }
184
RemountPartition(const char * dir)185 bool HdcDaemonUnity::RemountPartition(const char *dir)
186 {
187 int fd;
188 int off = 0;
189 char dev[BUF_SIZE_SMALL] = "";
190
191 if (!FindMountDeviceByPath(dir, dev) || strlen(dev) < 4) { // 4 : file count
192 WRITE_LOG(LOG_FATAL, "FindMountDeviceByPath failed %s", dir);
193 return false;
194 }
195
196 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
197 WRITE_LOG(LOG_FATAL, "Open device:%s failed,error:%d", dev, errno);
198 return false;
199 }
200 ioctl(fd, BLKROSET, &off);
201 Base::CloseFd(fd);
202
203 if (mount(dev, dir, "none", MS_REMOUNT, nullptr) < 0) {
204 WRITE_LOG(LOG_FATAL, "Mount device failed dev:%s dir:%s error:%d", dev, dir, errno);
205 return false;
206 }
207 return true;
208 }
209
CallRemount()210 bool HdcDaemonUnity::CallRemount()
211 {
212 int pipefd[2];
213 pid_t pid;
214 int exitStatus;
215
216 if (pipe(pipefd) == -1) {
217 WRITE_LOG(LOG_FATAL, "Failed to create pipe: %s", strerror(errno));
218 return false;
219 }
220 pid = fork();
221 if (pid < 0) {
222 WRITE_LOG(LOG_FATAL, "Failed to fork: %s", strerror(errno));
223 return false;
224 }
225 if (pid == 0) {
226 close(pipefd[0]);
227 signal(SIGCHLD, SIG_DFL);
228 exitStatus = system("remount");
229 write(pipefd[1], &exitStatus, sizeof(int));
230 close(pipefd[1]);
231 _exit(0);
232 } else {
233 close(pipefd[1]);
234 read(pipefd[0], &exitStatus, sizeof(int));
235 close(pipefd[0]);
236 waitpid(pid, nullptr, 0);
237 if (exitStatus == -1) {
238 WRITE_LOG(LOG_FATAL, "Failed to execute /bin/remount: %s", strerror(errno));
239 return false;
240 } else if (WIFEXITED(exitStatus) && WEXITSTATUS(exitStatus) != 0) {
241 WRITE_LOG(LOG_FATAL, "Remount failed with exit code: %d", WEXITSTATUS(exitStatus));
242 return false;
243 }
244 }
245
246 return true;
247 }
248
RemountDevice()249 bool HdcDaemonUnity::RemountDevice()
250 {
251 if (getuid() != 0) {
252 LogMsg(MSG_FAIL, "Operate need running as root");
253 return false;
254 }
255 struct stat info;
256 if (!lstat("/vendor", &info) && (info.st_mode & S_IFMT) == S_IFDIR) {
257 if (!RemountPartition("/vendor")) {
258 WRITE_LOG(LOG_FATAL, "Mount failed /vendor (via mount)");
259 }
260 }
261 if (!lstat("/system", &info) && (info.st_mode & S_IFMT) == S_IFDIR) {
262 if (!RemountPartition("/")) {
263 WRITE_LOG(LOG_FATAL, "Mount failed /system (via mount)");
264 }
265 }
266
267 if (CallRemount()) {
268 LogMsg(MSG_OK, "Mount finish");
269 return true;
270 } else {
271 LogMsg(MSG_FAIL, "Mount failed");
272 return false;
273 }
274 }
275
RebootDevice(const string & cmd)276 bool HdcDaemonUnity::RebootDevice(const string &cmd)
277 {
278 sync();
279 return SystemDepend::RebootDevice(cmd);
280 }
281
SetDeviceRunMode(const char * cmd)282 bool HdcDaemonUnity::SetDeviceRunMode(const char *cmd)
283 {
284 WRITE_LOG(LOG_INFO, "Set run mode:%s", cmd);
285 string tmp(cmd);
286 char *ptr = tmp.data();
287 char *token = nullptr;
288
289 #ifdef HDC_EMULATOR
290 LogMsg(MSG_FAIL, "[E001300]Not support tmode for Emulator");
291 return true;
292 #endif
293
294 // hdc tmode usb, do nothing
295 if (strcmp(CMDSTR_TMODE_USB.c_str(), cmd) == 0) {
296 LogMsg(MSG_FAIL, "[E001000]For USB debugging, please set it on the device's Settings UI");
297 return true;
298 }
299 // not usb and not tcp
300 if (strncmp("port", cmd, strlen("port")) != 0) {
301 LogMsg(MSG_FAIL, "[E001001]Unknown command");
302 return false;
303 }
304
305 // bypass port
306 token = strtok_r(ptr, " ", &ptr);
307 // get next token
308 token = strtok_r(ptr, " ", &ptr);
309 // hdc tmode port
310 if (token == nullptr) {
311 LogMsg(MSG_OK, "Set device run mode successful.");
312 SystemDepend::SetDevItem("persist.hdc.mode", "tcp");
313 SystemDepend::SetDevItem("persist.hdc.mode.tcp", "enable");
314 } else {
315 /*
316 * hdc tmode port xxxxxx
317 * hdc tmode port close
318 */
319 if (strcmp(token, "close") == 0) {
320 SystemDepend::SetDevItem("persist.hdc.port", "0");
321 SystemDepend::SetDevItem("persist.hdc.mode.tcp", "disable");
322 } else {
323 string tmp(token);
324 if (tmp.find_first_not_of("0123456789") != string::npos) {
325 LogMsg(MSG_FAIL, "[E001100]Invalid port");
326 return false;
327 }
328 LogMsg(MSG_OK, "Set device run mode successful.");
329 SystemDepend::SetDevItem("persist.hdc.mode", "tcp");
330 SystemDepend::SetDevItem("persist.hdc.port", token);
331 SystemDepend::SetDevItem("persist.hdc.mode.tcp", "enable");
332 }
333 }
334 return true;
335 }
336
GetHiLog(const char * cmd)337 inline bool HdcDaemonUnity::GetHiLog(const char *cmd)
338 {
339 string cmdDo = "hilog";
340 if (cmd && !strcmp(const_cast<char *>(cmd), "h")) {
341 cmdDo += " -h";
342 }
343 ExecuteShell(cmdDo.c_str());
344 return true;
345 }
346
ListJdwpProcess(void * daemonIn)347 inline bool HdcDaemonUnity::ListJdwpProcess(void *daemonIn)
348 {
349 HdcDaemon *daemon = (HdcDaemon *)daemonIn;
350 string result = ((HdcJdwp *)daemon->clsJdwp)->GetProcessList();
351 if (!result.size()) {
352 result = EMPTY_ECHO;
353 } else {
354 result.erase(result.end() - 1); // remove tail \n
355 }
356 LogMsg(MSG_OK, result.c_str());
357 return true;
358 }
359
TrackJdwpProcess(void * daemonIn,const string & param)360 inline bool HdcDaemonUnity::TrackJdwpProcess(void *daemonIn, const string& param)
361 {
362 HdcDaemon *daemon = static_cast<HdcDaemon *>(daemonIn);
363 taskInfo->debugRelease = 1;
364 if (param == "p") {
365 taskInfo->debugRelease = 0;
366 } else if (param == "a") {
367 // allApp with display debug or release
368 constexpr uint8_t allAppWithDr = 3;
369 taskInfo->debugRelease = allAppWithDr;
370 }
371 if (!((static_cast<HdcJdwp *>(daemon->clsJdwp))->CreateJdwpTracker(taskInfo))) {
372 string result = MESSAGE_FAIL;
373 LogMsg(MSG_OK, result.c_str());
374 return false;
375 }
376 return true;
377 }
378
RemoveJdwpTracker()379 inline void HdcDaemonUnity::RemoveJdwpTracker()
380 {
381 HdcDaemon *daemon = static_cast<HdcDaemon *>(taskInfo->ownerSessionClass);
382 (static_cast<HdcJdwp *>(daemon->clsJdwp))->RemoveJdwpTracker(taskInfo);
383 }
384
CommandDispatch(const uint16_t command,uint8_t * payload,const int payloadSize)385 bool HdcDaemonUnity::CommandDispatch(const uint16_t command, uint8_t *payload, const int payloadSize)
386 {
387 bool ret = true;
388 HdcDaemon *daemon = (HdcDaemon *)taskInfo->ownerSessionClass;
389 // Both are not executed, do not need to be detected 'childReady'
390 string strPayload = string(reinterpret_cast<char *>(payload), payloadSize);
391 #ifdef HDC_DEBUG
392 WRITE_LOG(LOG_DEBUG, "CommandDispatch command:%d", command);
393 #endif // HDC_DEBUG
394 switch (command) {
395 case CMD_UNITY_EXECUTE: {
396 ExecuteShell(const_cast<char *>(strPayload.c_str()));
397 break;
398 }
399 case CMD_UNITY_EXECUTE_EX: {
400 if (ExecuteShellExtend(payload, payloadSize) != 0) {
401 ret = false;
402 }
403 break;
404 }
405 case CMD_UNITY_REMOUNT: {
406 ret = false;
407 RemountDevice();
408 break;
409 }
410 case CMD_UNITY_REBOOT: {
411 ret = false;
412 RebootDevice(strPayload);
413 break;
414 }
415 case CMD_UNITY_RUNMODE: {
416 ret = false;
417 SetDeviceRunMode(strPayload.c_str());
418 break;
419 }
420 case CMD_UNITY_HILOG: {
421 GetHiLog(strPayload.c_str());
422 break;
423 }
424 case CMD_UNITY_ROOTRUN: {
425 ret = false;
426 string debugMode;
427 // hdcd restart in old pid
428 bool restart = true;
429 SystemDepend::GetDevItem("const.debuggable", debugMode);
430 if (debugMode == "1") {
431 if (payloadSize != 0 && !strcmp(strPayload.c_str(), "r")) {
432 SystemDepend::SetDevItem("persist.hdc.root", "0");
433 } else {
434 // hdcd restart in new pid
435 restart = false;
436 SystemDepend::SetDevItem("persist.hdc.root", "1");
437 }
438 } else {
439 LogMsg(MSG_FAIL, "Cannot set root run mode in undebuggable version.");
440 return false;
441 }
442 daemon->PostStopInstanceMessage(restart);
443 break;
444 }
445 case CMD_UNITY_BUGREPORT_INIT: {
446 currentDataCommand = CMD_UNITY_BUGREPORT_DATA;
447 ExecuteShell("hidumper");
448 break;
449 }
450 case CMD_JDWP_LIST: {
451 ret = false;
452 ListJdwpProcess(daemon);
453 break;
454 }
455 case CMD_JDWP_TRACK: {
456 if (!TrackJdwpProcess(daemon, strPayload)) {
457 ret = false;
458 }
459 break;
460 }
461 default:
462 break;
463 }
464 #ifdef HDC_DEBUG
465 WRITE_LOG(LOG_DEBUG, "CommandDispatch command:%d finish.", command);
466 #endif // HDC_LOCAL_DEBUG
467 return ret;
468 };
469 } // namespace Hdc
470