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 "server.h"
18 #include "server_for_client.h"
19
20 #ifndef HARMONY_PROJECT
21 #include "../test/ut_command.h"
22 using namespace HdcTest;
23 #endif
24
25 #include "server.h"
26 #include "server_for_client.h"
27 #include "ext_client.h"
28 using namespace Hdc;
29
30 namespace {
31 bool g_isServerMode = false;
32 bool g_isPullServer = true;
33 bool g_isPcDebugRun = false;
34 bool g_isTCPorUSB = false;
35 bool g_isCustomLoglevel = false;
36 bool g_externalCmd = 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%interfacename: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:Sd:t:l:")) != -1) {
295 switch (ch) {
296 case 'h': {
297 string usage = Hdc::TranslateCommand::Usage();
298 if (optind < optArgc && optind >= 0 && string(optArgv[optind]) == "verbose") {
299 usage = Hdc::TranslateCommand::Verbose();
300 }
301 fprintf(stderr, "%s", usage.c_str());
302 needExit = true;
303 return needExit;
304 }
305 case 'v': {
306 string ver = Base::GetVersion();
307 fprintf(stdout, "%s\n", ver.c_str());
308 needExit = true;
309 return needExit;
310 }
311 case 'f': { // [not-publish]
312 break;
313 }
314 case 'l': {
315 int logLevel = atoi(optarg);
316 if (logLevel < 0 || logLevel > LOG_LAST) {
317 Base::PrintMessage("Loglevel error!");
318 needExit = true;
319 return needExit;
320 }
321 g_isCustomLoglevel = true;
322 Base::SetLogLevel(logLevel);
323 break;
324 }
325 case 'm': { // [not-publish] is server mode,or client mode
326 g_isServerMode = true;
327 break;
328 }
329 case 'n': {
330 g_containerInOut = "-n";
331 break;
332 }
333 case 'c': {
334 g_containerInOut = "-c";
335 break;
336 }
337 case 'p': { // [not-publish] not pullup server
338 g_isPullServer = false;
339 break;
340 }
341 case 't': { // key
342 if (strlen(optarg) > MAX_CONNECTKEY_SIZE) {
343 Base::PrintMessage("Sizeo of of parament '-t' %d is too long", strlen(optarg));
344 needExit = true;
345 return needExit;
346 }
347 g_connectKey = optarg;
348 break;
349 }
350 case 's': {
351 if (!Hdc::ParseServerListenString(g_serverListenString, optarg)) {
352 needExit = true;
353 return needExit;
354 }
355 break;
356 }
357 case 'S': {
358 g_externalCmd = true;
359 break;
360 }
361 case 'd': // [Undisclosed parameters] debug mode
362 g_isPcDebugRun = true;
363 if (optarg[0] == 't') {
364 g_isTCPorUSB = true;
365 } else if (optarg[0] == 'u') {
366 g_isTCPorUSB = false;
367 } else {
368 Base::PrintMessage("Unknown debug parameters");
369 needExit = true;
370 return needExit;
371 }
372 g_isTestMethod = atoi(optarg + 1);
373 break;
374 case '?':
375 break;
376 default: {
377 Base::PrintMessage("Unknown parameters");
378 needExit = true;
379 return needExit;
380 }
381 }
382 }
383 return needExit;
384 }
385
InitServerAddr(void)386 void InitServerAddr(void)
387 {
388 int port;
389 do {
390 char *env = getenv(ENV_SERVER_PORT.c_str());
391 if (!env) {
392 port = DEFAULT_PORT;
393 break;
394 }
395
396 size_t len = strlen(env);
397 size_t maxLen = 5;
398 if (len > maxLen) {
399 fprintf(stderr, "OHOS_HDC_SERVER_PORT %s is not in (0, 65535] range\n", env);
400 return;
401 }
402
403 for (size_t i = 0; i < len; i++) {
404 if (isdigit(env[i]) == 0) {
405 fprintf(stderr, "OHOS_HDC_SERVER_PORT %s is not digit\n", env);
406 return;
407 }
408 }
409
410 port = atoi(env);
411 if (port > MAX_IP_PORT || port <= 0) {
412 fprintf(stderr, "OHOS_HDC_SERVER_PORT %s is not in (0, 65535] range\n", env);
413 return;
414 }
415 } while (0);
416 g_serverListenString = DEFAULT_SERVER_ADDR_IP;
417 g_serverListenString += ":";
418 g_serverListenString += std::to_string(port);
419 }
420
RunExternalClient(string & str,string & connectKey,string & containerInOut)421 void RunExternalClient(string &str, string &connectKey, string &containerInOut)
422 {
423 ExtClient extClient;
424 extClient.connectKey = connectKey;
425 extClient.containerInOut = containerInOut;
426 extClient.Init();
427 extClient.ExecuteCommand(str);
428 }
429 }
430
431 #ifndef UNIT_TEST
432 // hdc -l4 -m -s ip:port|hdc -l4 -m
433 // hdc -l4 - s ip:port list targets
main(int argc,const char * argv[])434 int main(int argc, const char *argv[])
435 {
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 if (g_isServerMode) {
451 // -m server.Run alone in the background, no -s will be listen loopback address
452 Hdc::RunServerMode(g_serverListenString);
453 } else if (g_isPcDebugRun) {
454 Hdc::RunPcDebugMode(g_isPullServer, g_isTCPorUSB, g_isTestMethod);
455 } else {
456 if (!g_isCustomLoglevel) {
457 Base::SetLogLevel(LOG_INFO);
458 }
459
460 if (!ExtClient::SharedLibraryExist()) {
461 Hdc::RunClientMode(commands, g_serverListenString, g_connectKey, g_isPullServer);
462 Hdc::Base::RemoveLogCache();
463 return 0;
464 }
465 string str = "list targets";
466 if (!strncmp(commands.c_str(), CMDSTR_LIST_TARGETS.c_str(), CMDSTR_LIST_TARGETS.size())) {
467 string lista = "list targets -a";
468 if (!strncmp(commands.c_str(), lista.c_str(), lista.size())) {
469 str = "list targets -v";
470 } else {
471 str = commands;
472 }
473 Hdc::RunExternalClient(str, g_connectKey, g_containerInOut);
474 Hdc::RunClientMode(str, g_serverListenString, g_connectKey, g_isPullServer);
475 } else if (!strncmp(commands.c_str(), CMDSTR_SOFTWARE_VERSION.c_str(), CMDSTR_SOFTWARE_VERSION.size()) ||
476 !strncmp(commands.c_str(), CMDSTR_SOFTWARE_HELP.c_str(), CMDSTR_SOFTWARE_HELP.size()) ||
477 !strncmp(commands.c_str(), CMDSTR_TARGET_DISCOVER.c_str(), CMDSTR_TARGET_DISCOVER.size()) ||
478 !strncmp(commands.c_str(), CMDSTR_SERVICE_START.c_str(), CMDSTR_SERVICE_START.size()) ||
479 !strncmp(commands.c_str(), CMDSTR_SERVICE_KILL.c_str(), CMDSTR_SERVICE_KILL.size()) ||
480 !strncmp(commands.c_str(), CMDSTR_WAIT_FOR.c_str(), CMDSTR_WAIT_FOR.size())) {
481 Hdc::RunExternalClient(commands, g_connectKey, g_containerInOut);
482 Hdc::RunClientMode(commands, g_serverListenString, g_connectKey, g_isPullServer);
483 } else if (!strncmp(commands.c_str(), CMDSTR_CONNECT_TARGET.c_str(), CMDSTR_CONNECT_TARGET.size()) ||
484 !strncmp(commands.c_str(), CMDSTR_TARGET_MODE.c_str(), CMDSTR_TARGET_MODE.size()) || g_externalCmd) {
485 Hdc::RunExternalClient(commands, g_connectKey, g_containerInOut);
486 } else {
487 g_show = false;
488 Hdc::RunExternalClient(str, g_connectKey, g_containerInOut);
489 Hdc::RunClientMode(str, g_serverListenString, g_connectKey, g_isPullServer);
490 g_show = true;
491 if (g_connectKey.empty()) {
492 if (g_lists.size() == 0) {
493 Base::PrintMessage("No any target");
494 } else if (g_lists.size() == 1) {
495 auto iter = g_lists.begin();
496 g_connectKey = iter->first;
497 } else {
498 Base::PrintMessage("Specify one target");
499 }
500 }
501 if (g_lists[g_connectKey] == "external") {
502 Hdc::RunExternalClient(commands, g_connectKey, g_containerInOut);
503 } else if (g_lists[g_connectKey] == "hdc") {
504 Hdc::RunClientMode(commands, g_serverListenString, g_connectKey, g_isPullServer);
505 }
506 }
507 }
508 WRITE_LOG(LOG_DEBUG, "!!!!!!!!!Main finish main");
509 Hdc::Base::RemoveLogCache();
510 return 0;
511 }
512 #endif // no UNIT_TEST
513