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