• 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 #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     HdcServer server(true);
165     if (!server.Initial(serverListenString.c_str())) {
166         Base::PrintMessage("Initial failed");
167         return -1;
168     }
169     server.WorkerPendding();
170     return 0;
171 }
172 
RunPcDebugMode(bool isPullServer,bool isTCPorUSB,int isTestMethod)173 int RunPcDebugMode(bool isPullServer, bool isTCPorUSB, int isTestMethod)
174 {
175 #ifdef HARMONY_PROJECT
176     Base::PrintMessage("Not support command...");
177 #else
178     pthread_t pt;
179     if (isPullServer) {
180         pthread_create(&pt, nullptr, TestBackgroundServerForClient, nullptr);
181         uv_sleep(200);  // give time to start serverForClient,at least 200ms
182     }
183     TestRuntimeCommandSimple(isTCPorUSB, isTestMethod, true);
184     if (isPullServer) {
185         pthread_join(pt, nullptr);
186         WRITE_LOG(LOG_DEBUG, "!!!!!!!!!Server finish");
187     }
188 #endif
189     return 0;
190 }
191 
RunClientMode(string & commands,string & serverListenString,string & connectKey,bool isPullServer)192 int RunClientMode(string &commands, string &serverListenString, string &connectKey, bool isPullServer)
193 {
194     if (serverListenString.empty()) {
195         return -1;
196     }
197     uv_loop_t loopMain;
198     uv_loop_init(&loopMain);
199     HdcClient client(false, serverListenString, &loopMain, commands == CMDSTR_CHECK_SERVER);
200     if (!commands.size()) {
201         Base::PrintMessage("Unknown operation command...");
202         std::cerr << TranslateCommand::Usage();
203         return 0;
204     }
205     if (!strncmp(commands.c_str(), CMDSTR_SERVICE_START.c_str(), CMDSTR_SERVICE_START.size()) ||
206         !strncmp(commands.c_str(), CMDSTR_SERVICE_KILL.c_str(), CMDSTR_SERVICE_KILL.size()) ||
207         !strncmp(commands.c_str(), CMDSTR_GENERATE_KEY.c_str(), CMDSTR_GENERATE_KEY.size())) {
208         client.CtrlServiceWork(commands.c_str());
209         return 0;
210     }
211     if (isPullServer && Base::ProgramMutex(SERVER_NAME.c_str(), true) == 0) {
212         // default pullup, just default listenstr.If want to customer listen-string, please use 'hdc -m -s lanip:port'
213         HdcServer::PullupServer(serverListenString.c_str());
214         uv_sleep(START_SERVER_FOR_CLIENT_TIME);  // give time to start serverForClient,at least 200ms
215     }
216     client.Initial(connectKey);
217     client.ExecuteCommand(commands.c_str());
218     return 0;
219 }
220 
ParseServerListenString(string & serverListenString,char * optarg)221 bool ParseServerListenString(string &serverListenString, char *optarg)
222 {
223     if (strlen(optarg) > strlen("0000::0000:0000:0000:0000%interfacename:65535")) {
224         Base::PrintMessage("Unknown content of parament '-s'");
225         return false;
226     }
227     char buf[BUF_SIZE_TINY] = "";
228     if (strcpy_s(buf, sizeof(buf), optarg) != 0) {
229         Base::PrintMessage("strcpy_s error %d", errno);
230         return false;
231     }
232     char *p = strrchr(buf, ':');
233     if (!p) {  // Only port
234         if (strlen(buf) > PORT_MAX_LEN) {
235             Base::PrintMessage("The port-string's length must < 5");
236             return false;
237         }
238         size_t len = strlen(buf);
239         for (size_t i = 0; i < len; i++) {
240             if (isdigit(buf[i]) == 0) {
241                 Base::PrintMessage("The port must be digit buf:%s", buf);
242                 return false;
243             }
244         }
245         int port = atoi(buf);
246         if (port <= 0 || port > MAX_IP_PORT) {
247             Base::PrintMessage("Port range incorrect");
248             return false;
249         }
250         (void)snprintf_s(buf, sizeof(buf), sizeof(buf) - 1, "::ffff:127.0.0.1:%d", port);
251         serverListenString = buf;
252     } else {
253         *p = '\0';
254         char *str = p + 1;
255         size_t len = strlen(str);
256         for (size_t i = 0; i < len; i++) {
257             if (isdigit(str[i]) == 0) {
258                 Base::PrintMessage("The port must be digit str:%s", str);
259                 return false;
260             }
261         }
262         int port = atoi(p + 1);
263         sockaddr_in addrv4;
264         sockaddr_in6 addrv6;
265 
266         if ((port <= 0 || port > MAX_IP_PORT)) {
267             Base::PrintMessage("-s content port incorrect.");
268             return false;
269         }
270 
271         if (uv_ip4_addr(buf, port, &addrv4) == 0) {
272             serverListenString = IPV4_MAPPING_PREFIX;
273             serverListenString += optarg;
274         } else if (uv_ip6_addr(buf, port, &addrv6) == 0) {
275             serverListenString = optarg;
276         } else {
277             Base::PrintMessage("-s content IP incorrect.");
278             return false;
279         }
280     }
281     return true;
282 }
283 
GetCommandlineOptions(int optArgc,const char * optArgv[])284 bool GetCommandlineOptions(int optArgc, const char *optArgv[])
285 {
286     int ch = 0;
287     bool needExit = false;
288     opterr = 0;
289     // get option parameters first
290     while ((ch = getopt(optArgc, const_cast<char *const*>(optArgv), "hvpfmncs:Sd:t:l:")) != -1) {
291         switch (ch) {
292             case 'h': {
293                 string usage = Hdc::TranslateCommand::Usage();
294                 if (optind < optArgc && optind >= 0 && string(optArgv[optind]) == "verbose") {
295                     usage = Hdc::TranslateCommand::Verbose();
296                 }
297                 fprintf(stderr, "%s", usage.c_str());
298                 needExit = true;
299                 return needExit;
300             }
301             case 'v': {
302                 string ver = Base::GetVersion();
303                 fprintf(stdout, "%s\n", ver.c_str());
304                 needExit = true;
305                 return needExit;
306             }
307             case 'f': {  // [not-publish]
308                 break;
309             }
310             case 'l': {
311                 int logLevel = atoi(optarg);
312                 if (logLevel < 0 || logLevel > LOG_LAST) {
313                     Base::PrintMessage("Loglevel error!");
314                     needExit = true;
315                     return needExit;
316                 }
317                 g_isCustomLoglevel = true;
318                 Base::SetLogLevel(logLevel);
319                 break;
320             }
321             case 'm': {  // [not-publish] is server mode,or client mode
322                 g_isServerMode = true;
323                 break;
324             }
325             case 'n': {
326                 g_containerInOut = "-n";
327                 break;
328             }
329             case 'c': {
330                 g_containerInOut = "-c";
331                 break;
332             }
333             case 'p': {  // [not-publish]  not pullup server
334                 g_isPullServer = false;
335                 break;
336             }
337             case 't': {  // key
338                 if (strlen(optarg) > MAX_CONNECTKEY_SIZE) {
339                     Base::PrintMessage("Sizeo of of parament '-t' %d is too long", strlen(optarg));
340                     needExit = true;
341                     return needExit;
342                 }
343                 g_connectKey = optarg;
344                 break;
345             }
346             case 's': {
347                 if (!Hdc::ParseServerListenString(g_serverListenString, optarg)) {
348                     needExit = true;
349                     return needExit;
350                 }
351                 break;
352             }
353             case 'S': {
354                 g_externalCmd = true;
355                 break;
356             }
357             case 'd':  // [Undisclosed parameters] debug mode
358                 g_isPcDebugRun = true;
359                 if (optarg[0] == 't') {
360                     g_isTCPorUSB = true;
361                 } else if (optarg[0] == 'u') {
362                     g_isTCPorUSB = false;
363                 } else {
364                     Base::PrintMessage("Unknown debug parameters");
365                     needExit = true;
366                     return needExit;
367                 }
368                 g_isTestMethod = atoi(optarg + 1);
369                 break;
370             case '?':
371                 break;
372             default: {
373                 Base::PrintMessage("Unknown parameters");
374                 needExit = true;
375                 return needExit;
376             }
377         }
378     }
379     return needExit;
380 }
381 
InitServerAddr(void)382 void InitServerAddr(void)
383 {
384     int port;
385     do {
386         char *env = getenv(ENV_SERVER_PORT.c_str());
387         if (!env) {
388             port = DEFAULT_PORT;
389             break;
390         }
391 
392         size_t len = strlen(env);
393         size_t maxLen = 5;
394         if (len > maxLen) {
395             fprintf(stderr, "OHOS_HDC_SERVER_PORT %s is not in (0, 65535] range\n", env);
396             return;
397         }
398 
399         for (size_t i = 0; i < len; i++) {
400             if (isdigit(env[i]) == 0) {
401                 fprintf(stderr, "OHOS_HDC_SERVER_PORT %s is not digit\n", env);
402                 return;
403             }
404         }
405 
406         port = atoi(env);
407         if (port > MAX_IP_PORT || port <= 0) {
408             fprintf(stderr, "OHOS_HDC_SERVER_PORT %s is not in (0, 65535] range\n", env);
409             return;
410         }
411     } while (0);
412     g_serverListenString = DEFAULT_SERVER_ADDR_IP;
413     g_serverListenString += ":";
414     g_serverListenString += std::to_string(port);
415 }
416 
RunExternalClient(string & str,string & connectKey,string & containerInOut)417 void RunExternalClient(string &str, string &connectKey, string &containerInOut)
418 {
419     ExtClient extClient;
420     extClient.connectKey = connectKey;
421     extClient.containerInOut = containerInOut;
422     extClient.Init();
423     extClient.ExecuteCommand(str);
424 }
425 }
426 
427 #ifndef UNIT_TEST
428 
429 // hdc -l4 -m -s ip:port|hdc -l4 -m
430 // hdc -l4 - s ip:port list targets
main(int argc,const char * argv[])431 int main(int argc, const char *argv[])
432 {
433 #ifdef _WIN32
434     SetConsoleOutputCP(CP_UTF8);
435 #endif
436     string options;
437     string commands;
438     Hdc::SplitOptionAndCommand(argc, argv, options, commands);
439     uv_setup_args(argc, const_cast<char **>(argv));
440     int optArgc = 0;
441     char **optArgv = Base::SplitCommandToArgs(options.c_str(), &optArgc);
442     bool cmdOptionResult;
443 
444     InitServerAddr();
445     cmdOptionResult = GetCommandlineOptions(optArgc, const_cast<const char **>(optArgv));
446     delete[](reinterpret_cast<char*>(optArgv));
447     if (cmdOptionResult) {
448         return 0;
449     }
450     Base::InitProcess();
451     if (g_isServerMode) {
452         // -m server.Run alone in the background, no -s will be listen loopback address
453         Hdc::RunServerMode(g_serverListenString);
454     } else if (g_isPcDebugRun) {
455         Hdc::RunPcDebugMode(g_isPullServer, g_isTCPorUSB, g_isTestMethod);
456     } else {
457         if (!g_isCustomLoglevel) {
458             Base::SetLogLevel(LOG_INFO);
459         }
460 
461         if (!ExtClient::SharedLibraryExist()) {
462             Hdc::RunClientMode(commands, g_serverListenString, g_connectKey, g_isPullServer);
463             Hdc::Base::RemoveLogCache();
464             _exit(0);
465         }
466         string str = "list targets";
467         if (!strncmp(commands.c_str(), CMDSTR_LIST_TARGETS.c_str(), CMDSTR_LIST_TARGETS.size())) {
468             string lista = "list targets -a";
469             if (!strncmp(commands.c_str(), lista.c_str(), lista.size())) {
470                 str = "list targets -v";
471             } else {
472                 str = commands;
473             }
474             Hdc::RunExternalClient(str, g_connectKey, g_containerInOut);
475             Hdc::RunClientMode(str, g_serverListenString, g_connectKey, g_isPullServer);
476         } else if (!strncmp(commands.c_str(), CMDSTR_SOFTWARE_VERSION.c_str(), CMDSTR_SOFTWARE_VERSION.size()) ||
477                    !strncmp(commands.c_str(), CMDSTR_SOFTWARE_HELP.c_str(), CMDSTR_SOFTWARE_HELP.size()) ||
478                    !strncmp(commands.c_str(), CMDSTR_TARGET_DISCOVER.c_str(), CMDSTR_TARGET_DISCOVER.size()) ||
479                    !strncmp(commands.c_str(), CMDSTR_SERVICE_START.c_str(), CMDSTR_SERVICE_START.size()) ||
480                    !strncmp(commands.c_str(), CMDSTR_SERVICE_KILL.c_str(), CMDSTR_SERVICE_KILL.size()) ||
481                    !strncmp(commands.c_str(), CMDSTR_WAIT_FOR.c_str(), CMDSTR_WAIT_FOR.size())) {
482             Hdc::RunExternalClient(commands, g_connectKey, g_containerInOut);
483             Hdc::RunClientMode(commands, g_serverListenString, g_connectKey, g_isPullServer);
484         } else if (!strncmp(commands.c_str(), CMDSTR_CONNECT_TARGET.c_str(), CMDSTR_CONNECT_TARGET.size()) ||
485                    !strncmp(commands.c_str(), CMDSTR_TARGET_MODE.c_str(), CMDSTR_TARGET_MODE.size()) || g_externalCmd) {
486             Hdc::RunExternalClient(commands, g_connectKey, g_containerInOut);
487         } else {
488             g_show = false;
489             Hdc::RunExternalClient(str, g_connectKey, g_containerInOut);
490             Hdc::RunClientMode(str, g_serverListenString, g_connectKey, g_isPullServer);
491             g_show = true;
492             if (g_connectKey.empty()) {
493                 if (g_lists.size() == 0) {
494                     Base::PrintMessage("No any target");
495                 } else if (g_lists.size() == 1) {
496                     auto iter = g_lists.begin();
497                     g_connectKey = iter->first;
498                 } else {
499                     Base::PrintMessage("Specify one target");
500                 }
501             }
502             if (g_lists[g_connectKey] == "external") {
503                 Hdc::RunExternalClient(commands, g_connectKey, g_containerInOut);
504             } else if (g_lists[g_connectKey] == "hdc") {
505                 Hdc::RunClientMode(commands, g_serverListenString, g_connectKey, g_isPullServer);
506             }
507         }
508     }
509     WRITE_LOG(LOG_DEBUG, "!!!!!!!!!Main finish main");
510     Hdc::Base::RemoveLogCache();
511     return 0;
512 }
513 #endif  // no UNIT_TEST
514