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
16 #include <iostream>
17 #include "ext_client.h"
18 #include "server.h"
19 #include "server_for_client.h"
20
21 #ifdef _WIN32
22 #include <windows.h>
23 #endif
24
25 #ifndef HARMONY_PROJECT
26 #include "ut_command.h"
27 using namespace HdcTest;
28 #endif
29
30 using namespace Hdc;
31
32 namespace {
33 bool g_isServerMode = false;
34 bool g_isPullServer = true;
35 bool g_isPcDebugRun = false;
36 bool g_isTCPorUSB = false;
37 bool g_isCustomLoglevel = false;
38 bool g_externalCmd = false;
39 int g_isTestMethod = 0;
40 string g_connectKey = "";
41 string g_serverListenString = "";
42 string g_containerInOut = "";
43 }
44
45 namespace Hdc {
46 // return value: 0 == not command, 1 == one command, 2 == double command
IsRegisterCommand(string & outCommand,const char * cmd,const char * cmdnext)47 int IsRegisterCommand(string &outCommand, const char *cmd, const char *cmdnext)
48 {
49 string sCmdNext = cmdnext == nullptr ? string("") : string(cmdnext);
50 string doubleCommand = cmd + string(" ") + sCmdNext;
51 vector<string> registerCommand;
52 registerCommand.push_back(CMDSTR_SOFTWARE_VERSION);
53 registerCommand.push_back(CMDSTR_SOFTWARE_HELP);
54 registerCommand.push_back(CMDSTR_TARGET_DISCOVER);
55 registerCommand.push_back(CMDSTR_LIST_TARGETS);
56 registerCommand.push_back(CMDSTR_CHECK_SERVER);
57 registerCommand.push_back(CMDSTR_CHECK_DEVICE);
58 registerCommand.push_back(CMDSTR_WAIT_FOR);
59 registerCommand.push_back(CMDSTR_CONNECT_ANY);
60 registerCommand.push_back(CMDSTR_CONNECT_TARGET);
61 registerCommand.push_back(CMDSTR_SHELL);
62 registerCommand.push_back(CMDSTR_SHELL_EX);
63 registerCommand.push_back(CMDSTR_FILE_SEND);
64 registerCommand.push_back(CMDSTR_FILE_RECV);
65 registerCommand.push_back(CMDSTR_FORWARD_FPORT);
66 registerCommand.push_back(CMDSTR_FORWARD_RPORT);
67 registerCommand.push_back(CMDSTR_SERVICE_KILL);
68 registerCommand.push_back(CMDSTR_SERVICE_START);
69 registerCommand.push_back(CMDSTR_GENERATE_KEY);
70 registerCommand.push_back(CMDSTR_APP_INSTALL);
71 registerCommand.push_back(CMDSTR_APP_UNINSTALL);
72 registerCommand.push_back(CMDSTR_TARGET_MOUNT);
73 registerCommand.push_back(CMDSTR_HILOG);
74 registerCommand.push_back(CMDSTR_STARTUP_MODE);
75 registerCommand.push_back(CMDSTR_BUGREPORT);
76 registerCommand.push_back(CMDSTR_TARGET_MODE);
77 registerCommand.push_back(CMDSTR_APP_SIDELOAD);
78 registerCommand.push_back(CMDSTR_TARGET_REBOOT);
79 registerCommand.push_back(CMDSTR_LIST_JDWP);
80 registerCommand.push_back(CMDSTR_TRACK_JDWP);
81 registerCommand.push_back(CMDSTR_FLASHD_UPDATE);
82 registerCommand.push_back(CMDSTR_FLASHD_FLASH);
83 registerCommand.push_back(CMDSTR_FLASHD_ERASE);
84 registerCommand.push_back(CMDSTR_FLASHD_FORMAT);
85
86 for (string v : registerCommand) {
87 if (doubleCommand == v) {
88 outCommand = doubleCommand;
89 return CMD_ARG1_COUNT;
90 }
91 if (cmd == v || !strncmp(cmd, CMDSTR_WAIT_FOR.c_str(), CMDSTR_WAIT_FOR.size())) {
92 outCommand = cmd;
93 return 1;
94 }
95 }
96 return 0;
97 }
98
AppendCwdWhenTransfer(string & outCommand)99 void AppendCwdWhenTransfer(string &outCommand)
100 {
101 if (outCommand != CMDSTR_FILE_SEND && outCommand != CMDSTR_FILE_RECV && outCommand != CMDSTR_APP_INSTALL &&
102 outCommand != CMDSTR_APP_SIDELOAD) {
103 return;
104 }
105 int value = -1;
106 char path[PATH_MAX] = "";
107 size_t size = sizeof(path);
108 value = uv_cwd(path, &size);
109 if (value < 0) {
110 constexpr int bufSize = 1024;
111 char buf[bufSize] = { 0 };
112 uv_strerror_r(value, buf, bufSize);
113 WRITE_LOG(LOG_FATAL, "append cwd path failed: %s", buf);
114 return;
115 }
116 if (strlen(path) >= PATH_MAX - 1) {
117 WRITE_LOG(LOG_FATAL, "append cwd path failed: buffer space max");
118 return;
119 }
120 if (path[strlen(path) - 1] != Base::GetPathSep()) {
121 path[strlen(path)] = Base::GetPathSep();
122 }
123 outCommand += outCommand.size() ? " " : "";
124 outCommand += CMDSTR_REMOTE_PARAMETER;
125 outCommand += outCommand.size() ? " -cwd " : "-cwd ";
126 outCommand += Base::StringFormat("\"%s\"", path);
127 }
128
SplitOptionAndCommand(int argc,const char ** argv,string & outOption,string & outCommand)129 int SplitOptionAndCommand(int argc, const char **argv, string &outOption, string &outCommand)
130 {
131 bool foundCommand = false;
132 int resultChild = 0;
133 // we want to start from 1, ignore argv[0], but it has issue
134 for (int i = 0; i < argc; ++i) {
135 if (!foundCommand) {
136 resultChild = IsRegisterCommand(outCommand, argv[i], (i == argc - 1) ? nullptr : argv[i + 1]);
137 if (resultChild > 0) {
138 foundCommand = true;
139 if (resultChild == 2) {
140 ++i;
141 }
142 AppendCwdWhenTransfer(outCommand);
143 continue;
144 }
145 }
146 if (foundCommand) {
147 outCommand += outCommand.size() ? " " : "";
148 string rawCmd = Base::UnicodeToUtf8(argv[i]);
149 outCommand += rawCmd.find(" ") == string::npos ? rawCmd : Base::StringFormat("\"%s\"", rawCmd.c_str());
150 } else {
151 outOption += outOption.size() ? " " : "";
152 string rawOption = Base::UnicodeToUtf8(argv[i]);
153 outOption += (i == 0) ? Base::StringFormat("\"%s\"", rawOption.c_str()) : rawOption;
154 }
155 }
156 return 0;
157 }
158
RunServerMode(string & serverListenString)159 int RunServerMode(string &serverListenString)
160 {
161 if (serverListenString.empty()) {
162 return -1;
163 }
164 /*
165 * Notice !!!!!!
166 * For hdc server, all setenv must befor Base::RemoveLogFile()
167 * RemoveLogFile will create thread to run ThreadCompressLog and RemoveOlderLogFiles which will
168 * call uv_os_tmpdir and libuv inner wiil call getenv
169 * setenv and getenv concurrent calling wiil cause crash
170 * NOW, for hdc server setenv are SetLibusbLogLevelEnv and HdcServer construct
171 */
172 HdcHostUSB::SetLibusbLogLevelEnv(HdcHostUSB::GetLibusbLogLevel());
173 HdcServer server(true);
174 if (!server.Initial(serverListenString.c_str())) {
175 Base::PrintMessage("Initial failed");
176 return -1;
177 }
178 server.WorkerPendding();
179 return 0;
180 }
181
RunPcDebugMode(bool isPullServer,bool isTCPorUSB,int isTestMethod)182 int RunPcDebugMode(bool isPullServer, bool isTCPorUSB, int isTestMethod)
183 {
184 #ifdef HARMONY_PROJECT
185 Base::PrintMessage("Not support command...");
186 #else
187 pthread_t pt;
188 if (isPullServer) {
189 pthread_create(&pt, nullptr, TestBackgroundServerForClient, nullptr);
190 uv_sleep(200); // give time to start serverForClient,at least 200ms
191 }
192 TestRuntimeCommandSimple(isTCPorUSB, isTestMethod, true);
193 if (isPullServer) {
194 pthread_join(pt, nullptr);
195 WRITE_LOG(LOG_DEBUG, "!!!!!!!!!Server finish");
196 }
197 #endif
198 return 0;
199 }
200
RunClientMode(string & commands,string & serverListenString,string & connectKey,bool isPullServer)201 int RunClientMode(string &commands, string &serverListenString, string &connectKey, bool isPullServer)
202 {
203 if (serverListenString.empty()) {
204 return -1;
205 }
206 uv_loop_t loopMain;
207 uv_loop_init(&loopMain);
208 HdcClient client(false, serverListenString, &loopMain, commands == CMDSTR_CHECK_SERVER);
209 if (!commands.size()) {
210 Base::PrintMessage("Unknown operation command...");
211 std::cerr << TranslateCommand::Usage();
212 return 0;
213 }
214 if (!strncmp(commands.c_str(), CMDSTR_GENERATE_KEY.c_str(), CMDSTR_GENERATE_KEY.size()) ||
215 !strncmp(commands.c_str(), CMDSTR_SERVICE_KILL.c_str(), CMDSTR_SERVICE_KILL.size())) {
216 client.CtrlServiceWork(commands.c_str());
217 return 0;
218 }
219 if (!strncmp(commands.c_str(), CMDSTR_SERVICE_START.c_str(), CMDSTR_SERVICE_START.size())) {
220 client.ChannelCtrlServer(commands, connectKey);
221 return 0;
222 }
223 if (isPullServer && Base::ProgramMutex(SERVER_NAME.c_str(), true) == 0) {
224 // default pullup, just default listenstr.If want to customer listen-string, please use 'hdc -m -s lanip:port'
225 HdcServer::PullupServer(serverListenString.c_str());
226 uv_sleep(START_SERVER_FOR_CLIENT_TIME); // give time to start serverForClient,at least 200ms
227 }
228 client.Initial(connectKey);
229 client.ExecuteCommand(commands.c_str());
230 return 0;
231 }
232
ParseServerListenString(string & serverListenString,char * optarg)233 bool ParseServerListenString(string &serverListenString, char *optarg)
234 {
235 if (strlen(optarg) > strlen("0000::0000:0000:0000:0000%interfacename:65535")) {
236 Base::PrintMessage("Unknown content of parament '-s'");
237 return false;
238 }
239 char buf[BUF_SIZE_TINY] = "";
240 if (strcpy_s(buf, sizeof(buf), optarg) != 0) {
241 Base::PrintMessage("strcpy_s error %d", errno);
242 return false;
243 }
244 char *p = strrchr(buf, ':');
245 if (!p) { // Only port
246 if (strlen(buf) > PORT_MAX_LEN) {
247 Base::PrintMessage("The port-string's length must < 5");
248 return false;
249 }
250 size_t len = strlen(buf);
251 for (size_t i = 0; i < len; i++) {
252 if (isdigit(buf[i]) == 0) {
253 Base::PrintMessage("The port must be digit buf:%s", buf);
254 return false;
255 }
256 }
257 int port = atoi(buf);
258 if (port <= 0 || port > MAX_IP_PORT) {
259 Base::PrintMessage("Port range incorrect");
260 return false;
261 }
262 (void)snprintf_s(buf, sizeof(buf), sizeof(buf) - 1, "::ffff:127.0.0.1:%d", port);
263 serverListenString = buf;
264 } else {
265 *p = '\0';
266 char *str = p + 1;
267 size_t len = strlen(str);
268 for (size_t i = 0; i < len; i++) {
269 if (isdigit(str[i]) == 0) {
270 Base::PrintMessage("The port must be digit str:%s", str);
271 return false;
272 }
273 }
274 int port = atoi(p + 1);
275 sockaddr_in addrv4;
276 sockaddr_in6 addrv6;
277
278 if ((port <= 0 || port > MAX_IP_PORT)) {
279 Base::PrintMessage("-s content port incorrect.");
280 return false;
281 }
282
283 if (uv_ip4_addr(buf, port, &addrv4) == 0) {
284 serverListenString = IPV4_MAPPING_PREFIX;
285 serverListenString += optarg;
286 } else if (uv_ip6_addr(buf, port, &addrv6) == 0) {
287 serverListenString = optarg;
288 } else {
289 Base::PrintMessage("-s content IP incorrect.");
290 return false;
291 }
292 }
293 return true;
294 }
295
GetCommandlineOptions(int optArgc,const char * optArgv[])296 bool GetCommandlineOptions(int optArgc, const char *optArgv[])
297 {
298 int ch = 0;
299 bool needExit = false;
300 opterr = 0;
301 // get option parameters first
302 while ((ch = getopt(optArgc, const_cast<char *const*>(optArgv), "hvpfmncs:Sd:t:l:")) != -1) {
303 switch (ch) {
304 case 'h': {
305 string usage = Hdc::TranslateCommand::Usage();
306 if (optind < optArgc && optind >= 0 && string(optArgv[optind]) == "verbose") {
307 usage = Hdc::TranslateCommand::Verbose();
308 }
309 fprintf(stderr, "%s", usage.c_str());
310 needExit = true;
311 return needExit;
312 }
313 case 'v': {
314 string ver = Base::GetVersion();
315 fprintf(stdout, "%s\n", ver.c_str());
316 needExit = true;
317 return needExit;
318 }
319 case 'f': { // [not-publish]
320 break;
321 }
322 case 'l': {
323 int logLevel = atoi(optarg);
324 if (logLevel < 0 || logLevel > LOG_LAST) {
325 Base::PrintMessage("Loglevel error!");
326 needExit = true;
327 return needExit;
328 }
329 g_isCustomLoglevel = true;
330 Base::SetLogLevel(logLevel);
331 break;
332 }
333 case 'm': { // [not-publish] is server mode,or client mode
334 g_isServerMode = true;
335 break;
336 }
337 case 'n': {
338 g_containerInOut = "-n";
339 break;
340 }
341 case 'c': {
342 g_containerInOut = "-c";
343 break;
344 }
345 case 'p': { // [not-publish] not pullup server
346 g_isPullServer = false;
347 break;
348 }
349 case 't': { // key
350 if (strlen(optarg) > MAX_CONNECTKEY_SIZE) {
351 Base::PrintMessage("Sizeo of of parament '-t' %d is too long", strlen(optarg));
352 needExit = true;
353 return needExit;
354 }
355 g_connectKey = optarg;
356 break;
357 }
358 case 's': {
359 if (!Hdc::ParseServerListenString(g_serverListenString, optarg)) {
360 needExit = true;
361 return needExit;
362 }
363 break;
364 }
365 case 'S': {
366 g_externalCmd = true;
367 break;
368 }
369 case 'd': // [Undisclosed parameters] debug mode
370 g_isPcDebugRun = true;
371 if (optarg[0] == 't') {
372 g_isTCPorUSB = true;
373 } else if (optarg[0] == 'u') {
374 g_isTCPorUSB = false;
375 } else {
376 Base::PrintMessage("Unknown debug parameters");
377 needExit = true;
378 return needExit;
379 }
380 g_isTestMethod = atoi(optarg + 1);
381 break;
382 case '?':
383 break;
384 default: {
385 Base::PrintMessage("Unknown parameters");
386 needExit = true;
387 return needExit;
388 }
389 }
390 }
391 return needExit;
392 }
393
InitServerAddr(void)394 void InitServerAddr(void)
395 {
396 int port;
397 do {
398 char *env = getenv(ENV_SERVER_PORT.c_str());
399 if (!env) {
400 port = DEFAULT_PORT;
401 break;
402 }
403
404 size_t len = strlen(env);
405 size_t maxLen = 5;
406 if (len > maxLen) {
407 fprintf(stderr, "OHOS_HDC_SERVER_PORT %s is not in (0, 65535] range\n", env);
408 return;
409 }
410
411 for (size_t i = 0; i < len; i++) {
412 if (isdigit(env[i]) == 0) {
413 fprintf(stderr, "OHOS_HDC_SERVER_PORT %s is not digit\n", env);
414 return;
415 }
416 }
417
418 port = atoi(env);
419 if (port > MAX_IP_PORT || port <= 0) {
420 fprintf(stderr, "OHOS_HDC_SERVER_PORT %s is not in (0, 65535] range\n", env);
421 return;
422 }
423 } while (0);
424 g_serverListenString = DEFAULT_SERVER_ADDR_IP;
425 g_serverListenString += ":";
426 g_serverListenString += std::to_string(port);
427 }
428
RunExternalClient(string & str,string & connectKey,string & containerInOut)429 void RunExternalClient(string &str, string &connectKey, string &containerInOut)
430 {
431 ExtClient extClient;
432 extClient.connectKey = connectKey;
433 extClient.containerInOut = containerInOut;
434 extClient.Init();
435 extClient.ExecuteCommand(str);
436 }
437 }
438
439 #ifndef UNIT_TEST
440
441 // hdc -l4 -m -s ip:port|hdc -l4 -m
442 // hdc -l4 - s ip:port list targets
main(int argc,const char * argv[])443 int main(int argc, const char *argv[])
444 {
445 Base::UpdateEnvCache();
446 #ifdef _WIN32
447 SetConsoleOutputCP(CP_UTF8);
448 #endif
449 string options;
450 string commands;
451 Hdc::SplitOptionAndCommand(argc, argv, options, commands);
452 uv_setup_args(argc, const_cast<char **>(argv));
453 int optArgc = 0;
454 char **optArgv = Base::SplitCommandToArgs(options.c_str(), &optArgc);
455 bool cmdOptionResult;
456
457 InitServerAddr();
458 cmdOptionResult = GetCommandlineOptions(optArgc, const_cast<const char **>(optArgv));
459 delete[](reinterpret_cast<char*>(optArgv));
460 if (cmdOptionResult) {
461 return 0;
462 }
463 Base::InitProcess();
464 if (g_isServerMode) {
465 #ifdef FEATURE_HOST_LOG_COMPRESS
466 Base::CreateLogDir();
467 #endif
468 // -m server.Run alone in the background, no -s will be listen loopback address
469 Hdc::RunServerMode(g_serverListenString);
470 } else if (g_isPcDebugRun) {
471 Hdc::RunPcDebugMode(g_isPullServer, g_isTCPorUSB, g_isTestMethod);
472 } else {
473 if (!g_isCustomLoglevel) {
474 Base::SetLogLevel(LOG_INFO);
475 }
476
477 if (!ExtClient::SharedLibraryExist()) {
478 Hdc::RunClientMode(commands, g_serverListenString, g_connectKey, g_isPullServer);
479 Hdc::Base::RemoveLogCache();
480 _exit(0);
481 }
482 string str = "list targets";
483 if (!strncmp(commands.c_str(), CMDSTR_LIST_TARGETS.c_str(), CMDSTR_LIST_TARGETS.size())) {
484 string lista = "list targets -a";
485 if (!strncmp(commands.c_str(), lista.c_str(), lista.size())) {
486 str = "list targets -v";
487 } else {
488 str = commands;
489 }
490 Hdc::RunExternalClient(str, g_connectKey, g_containerInOut);
491 Hdc::RunClientMode(str, g_serverListenString, g_connectKey, g_isPullServer);
492 } else if (!strncmp(commands.c_str(), CMDSTR_SOFTWARE_VERSION.c_str(), CMDSTR_SOFTWARE_VERSION.size()) ||
493 !strncmp(commands.c_str(), CMDSTR_SOFTWARE_HELP.c_str(), CMDSTR_SOFTWARE_HELP.size()) ||
494 !strncmp(commands.c_str(), CMDSTR_TARGET_DISCOVER.c_str(), CMDSTR_TARGET_DISCOVER.size()) ||
495 !strncmp(commands.c_str(), CMDSTR_SERVICE_START.c_str(), CMDSTR_SERVICE_START.size()) ||
496 !strncmp(commands.c_str(), CMDSTR_SERVICE_KILL.c_str(), CMDSTR_SERVICE_KILL.size()) ||
497 !strncmp(commands.c_str(), CMDSTR_WAIT_FOR.c_str(), CMDSTR_WAIT_FOR.size())) {
498 Hdc::RunExternalClient(commands, g_connectKey, g_containerInOut);
499 Hdc::RunClientMode(commands, g_serverListenString, g_connectKey, g_isPullServer);
500 } else if (!strncmp(commands.c_str(), CMDSTR_CONNECT_TARGET.c_str(), CMDSTR_CONNECT_TARGET.size()) ||
501 !strncmp(commands.c_str(), CMDSTR_TARGET_MODE.c_str(), CMDSTR_TARGET_MODE.size()) || g_externalCmd) {
502 Hdc::RunExternalClient(commands, g_connectKey, g_containerInOut);
503 } else {
504 g_show = false;
505 Hdc::RunExternalClient(str, g_connectKey, g_containerInOut);
506 Hdc::RunClientMode(str, g_serverListenString, g_connectKey, g_isPullServer);
507 g_show = true;
508 if (g_connectKey.empty()) {
509 if (g_lists.size() == 0) {
510 Base::PrintMessage("No any target");
511 } else if (g_lists.size() == 1) {
512 auto iter = g_lists.begin();
513 g_connectKey = iter->first;
514 } else {
515 Base::PrintMessage("Specify one target");
516 }
517 }
518 if (g_lists[g_connectKey] == "external") {
519 Hdc::RunExternalClient(commands, g_connectKey, g_containerInOut);
520 } else if (g_lists[g_connectKey] == "hdc") {
521 Hdc::RunClientMode(commands, g_serverListenString, g_connectKey, g_isPullServer);
522 }
523 }
524 }
525 WRITE_LOG(LOG_DEBUG, "!!!!!!!!!Main finish main");
526 Hdc::Base::RemoveLogCache();
527 return 0;
528 }
529 #endif // no UNIT_TEST
530