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