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