1 /*
2 * Copyright (C) 2022-2024 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 "netmanager_base_common_utils.h"
17
18 #include <algorithm>
19 #include <arpa/inet.h>
20 #include <cstddef>
21 #include <cstdlib>
22 #include <netinet/in.h>
23 #include <regex>
24 #include <sstream>
25 #include <set>
26 #include <string>
27 #include <sys/socket.h>
28 #include <sys/wait.h>
29 #include <thread>
30 #include <type_traits>
31 #include <unistd.h>
32 #include <vector>
33 #include <numeric>
34 #include <fstream>
35
36 #include "net_manager_constants.h"
37 #include "net_mgr_log_wrapper.h"
38 #include "securec.h"
39
40 namespace OHOS::NetManagerStandard::CommonUtils {
41 constexpr int32_t INET_OPTION_SUC = 1;
42 constexpr int32_t DECIMAL_SYSTEM = 10;
43 constexpr uint32_t CONST_MASK = 0x80000000;
44 constexpr size_t MAX_DISPLAY_NUM = 2;
45 constexpr uint32_t IPV4_DOT_NUM = 3;
46 constexpr int32_t MIN_BYTE = 0;
47 constexpr int32_t MAX_BYTE = 255;
48 constexpr int32_t BYTE_16 = 16;
49 constexpr uint32_t BIT_NUM_BYTE = 8;
50 constexpr int32_t BITS_32 = 32;
51 constexpr int32_t BITS_24 = 24;
52 constexpr int32_t BITS_16 = 16;
53 constexpr int32_t BITS_8 = 8;
54 constexpr uint32_t INTERFACE_NAME_MAX_SIZE = 16;
55 constexpr int32_t CHAR_ARRAY_SIZE_MAX = 1024;
56 constexpr int32_t PIPE_FD_NUM = 2;
57 constexpr int32_t PIPE_OUT = 0;
58 constexpr int32_t PIPE_IN = 1;
59 constexpr int32_t DOMAIN_VALID_MIN_PART_SIZE = 2;
60 constexpr int32_t DOMAIN_VALID_MAX_PART_SIZE = 5;
61 constexpr int32_t NET_MASK_MAX_LENGTH = 32;
62 constexpr int32_t NET_MASK_GROUP_COUNT = 4;
63 constexpr int32_t MAX_IPV6_PREFIX_LENGTH = 128;
64 const std::string IPADDR_DELIMITER = ".";
65 constexpr const char *CMD_SEP = " ";
66 constexpr const char *DOMAIN_DELIMITER = ".";
67 constexpr const char *TLDS_SPLIT_SYMBOL = "|";
68 constexpr const char *HOST_DOMAIN_PATTERN_HEADER = "^(https?://)?[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.(";
69 constexpr const char *HOST_DOMAIN_PATTERN_TAIL = ")$";
70 constexpr const char *DEFAULT_IPV6_ANY_INIT_ADDR = "::";
71 const std::regex IP_PATTERN{
72 "((2([0-4]\\d|5[0-5])|1\\d\\d|[1-9]\\d|\\d)\\.){3}(2([0-4]\\d|5[0-5])|1\\d\\d|[1-9]\\d|\\d)"};
73
74 const std::regex IP_MASK_PATTERN{
75 "((2([0-4]\\d|5[0-5])|1\\d\\d|[1-9]\\d|\\d)\\.){3}(2([0-4]\\d|5[0-5])|1\\d\\d|[1-9]\\d|\\d)/"
76 "(3[0-2]|[1-2]\\d|\\d)"};
77
78 const std::regex IPV6_PATTERN{"([\\da-fA-F]{0,4}:){2,7}([\\da-fA-F]{0,4})"};
79
80 const std::regex IPV6_MASK_PATTERN{"([\\da-fA-F]{0,4}:){2,7}([\\da-fA-F]{0,4})/(1[0-2][0-8]|[1-9]\\d|[1-9])"};
81
82 std::vector<std::string> HOST_DOMAIN_TLDS{"com", "net", "org", "edu", "gov", "mil", "cn", "hk", "tw",
83 "jp", "de", "uk", "fr", "au", "ca", "br", "ru", "it",
84 "es", "in", "online", "shop", "vip", "club", "xyz", "top", "icu",
85 "work", "website", "tech", "asia", "xin", "co", "mobi", "info"};
86 std::mutex g_commonUtilsMutex;
87 std::mutex g_forkExecMutex;
88
Strip(const std::string & str,char ch)89 std::string Strip(const std::string &str, char ch)
90 {
91 auto size = static_cast<int64_t>(str.size());
92 int64_t i = 0;
93 while (i < size && str[i] == ch) {
94 ++i;
95 }
96 int64_t j = size - 1;
97 while (j > 0 && str[j] == ch) {
98 --j;
99 }
100 if (i >= 0 && i < size && j >= 0 && j < size && j - i + 1 > 0) {
101 return str.substr(i, j - i + 1);
102 }
103 return "";
104 }
105
ToLower(const std::string & s)106 std::string ToLower(const std::string &s)
107 {
108 std::string res = s;
109 std::transform(res.begin(), res.end(), res.begin(), tolower);
110 return res;
111 }
112
IsValidIPV4(const std::string & ip)113 bool IsValidIPV4(const std::string &ip)
114 {
115 if (ip.empty()) {
116 return false;
117 }
118 struct in_addr s;
119 return inet_pton(AF_INET, ip.c_str(), reinterpret_cast<void *>(&s)) == INET_OPTION_SUC;
120 }
121
IsValidIPV6(const std::string & ip)122 bool IsValidIPV6(const std::string &ip)
123 {
124 if (ip.empty()) {
125 return false;
126 }
127 struct in6_addr s;
128 return inet_pton(AF_INET6, ip.c_str(), reinterpret_cast<void *>(&s)) == INET_OPTION_SUC;
129 }
130
GetAddrFamily(const std::string & ip)131 int8_t GetAddrFamily(const std::string &ip)
132 {
133 if (IsValidIPV4(ip)) {
134 return AF_INET;
135 }
136 if (IsValidIPV6(ip)) {
137 return AF_INET6;
138 }
139 return 0;
140 }
141
GetMaskLength(const std::string & mask)142 int GetMaskLength(const std::string &mask)
143 {
144 int netMask = 0;
145 unsigned int maskTmp = ntohl(static_cast<int>(inet_addr(mask.c_str())));
146 while (maskTmp & CONST_MASK) {
147 ++netMask;
148 maskTmp = (maskTmp << 1);
149 }
150 return netMask;
151 }
152
GetMaskByLength(uint32_t length)153 std::string GetMaskByLength(uint32_t length)
154 {
155 const uint32_t mask = length == 0 ? 0 : 0xFFFFFFFF << (NET_MASK_MAX_LENGTH - length);
156 auto maskGroup = new int[NET_MASK_GROUP_COUNT];
157 for (int i = 0; i < NET_MASK_GROUP_COUNT; i++) {
158 int pos = NET_MASK_GROUP_COUNT - 1 - i;
159 maskGroup[pos] = (static_cast<uint32_t>(mask) >> (i * BIT_NUM_BYTE)) & 0x000000ff;
160 }
161 std::string sMask = "" + std::to_string(maskGroup[0]);
162 for (int i = 1; i < NET_MASK_GROUP_COUNT; i++) {
163 sMask = sMask + "." + std::to_string(maskGroup[i]);
164 }
165 delete[] maskGroup;
166 return sMask;
167 }
168
GetIpv6Prefix(const std::string & ipv6Addr,uint8_t prefixLen)169 std::string GetIpv6Prefix(const std::string &ipv6Addr, uint8_t prefixLen)
170 {
171 if (prefixLen >= MAX_IPV6_PREFIX_LENGTH) {
172 return ipv6Addr;
173 }
174
175 in6_addr ipv6AddrBuf = IN6ADDR_ANY_INIT;
176 inet_pton(AF_INET6, ipv6Addr.c_str(), &ipv6AddrBuf);
177
178 char buf[INET6_ADDRSTRLEN] = {0};
179 if (inet_ntop(AF_INET6, &ipv6AddrBuf, buf, INET6_ADDRSTRLEN) == nullptr) {
180 return ipv6Addr;
181 }
182
183 in6_addr ipv6Prefix = IN6ADDR_ANY_INIT;
184 uint32_t byteIndex = prefixLen / BIT_NUM_BYTE;
185 if (memset_s(ipv6Prefix.s6_addr, sizeof(ipv6Prefix.s6_addr), 0, sizeof(ipv6Prefix.s6_addr)) != EOK ||
186 memcpy_s(ipv6Prefix.s6_addr, sizeof(ipv6Prefix.s6_addr), &ipv6AddrBuf, byteIndex) != EOK) {
187 return DEFAULT_IPV6_ANY_INIT_ADDR;
188 }
189 uint32_t bitOffset = prefixLen & 0x7;
190 if ((bitOffset != 0) && (byteIndex < INET_ADDRSTRLEN)) {
191 ipv6Prefix.s6_addr[byteIndex] = ipv6AddrBuf.s6_addr[byteIndex] & (0xff00 >> bitOffset);
192 }
193 char ipv6PrefixBuf[INET6_ADDRSTRLEN] = {0};
194 inet_ntop(AF_INET6, &ipv6Prefix, ipv6PrefixBuf, INET6_ADDRSTRLEN);
195 return ipv6PrefixBuf;
196 }
197
ConvertIpv4Address(uint32_t addressIpv4)198 std::string ConvertIpv4Address(uint32_t addressIpv4)
199 {
200 if (addressIpv4 == 0) {
201 return "";
202 }
203
204 std::ostringstream stream;
205 stream << ((addressIpv4 >> BITS_24) & 0xFF) << IPADDR_DELIMITER << ((addressIpv4 >> BITS_16) & 0xFF)
206 << IPADDR_DELIMITER << ((addressIpv4 >> BITS_8) & 0xFF) << IPADDR_DELIMITER << (addressIpv4 & 0xFF);
207 return stream.str();
208 }
209
ConvertIpv4Address(const std::string & address)210 uint32_t ConvertIpv4Address(const std::string &address)
211 {
212 std::string tmpAddress = address;
213 uint32_t addrInt = 0;
214 uint32_t i = 0;
215 for (i = 0; i < IPV4_DOT_NUM; i++) {
216 std::string::size_type npos = tmpAddress.find(IPADDR_DELIMITER);
217 if (npos == std::string::npos) {
218 break;
219 }
220 const auto &value = tmpAddress.substr(0, npos);
221 int32_t itmp = std::atoi(value.c_str());
222 if ((itmp < MIN_BYTE) || (itmp > MAX_BYTE)) {
223 break;
224 }
225 uint32_t utmp = static_cast<uint32_t>(itmp);
226 addrInt += utmp << ((IPV4_DOT_NUM - i) * BIT_NUM_BYTE);
227 tmpAddress = tmpAddress.substr(npos + 1);
228 }
229
230 if (i != IPV4_DOT_NUM) {
231 return 0;
232 }
233 int32_t itmp = std::atoi(tmpAddress.c_str());
234 if ((itmp < MIN_BYTE) || (itmp > MAX_BYTE)) {
235 return 0;
236 }
237 uint32_t utmp = static_cast<uint32_t>(itmp);
238 addrInt += utmp;
239
240 return addrInt;
241 }
242
Ipv4PrefixLen(const std::string & ip)243 int32_t Ipv4PrefixLen(const std::string &ip)
244 {
245 if (ip.empty()) {
246 return 0;
247 }
248 int32_t ret = 0;
249 uint32_t ipNum = 0;
250 uint8_t c1 = 0;
251 uint8_t c2 = 0;
252 uint8_t c3 = 0;
253 uint8_t c4 = 0;
254 int32_t cnt = 0;
255 ret = sscanf_s(ip.c_str(), "%hhu.%hhu.%hhu.%hhu", &c1, &c2, &c3, &c4);
256 if (ret != sizeof(int32_t)) {
257 return 0;
258 }
259 ipNum = (c1 << static_cast<uint32_t>(BITS_24)) | (c2 << static_cast<uint32_t>(BITS_16)) |
260 (c3 << static_cast<uint32_t>(BITS_8)) | c4;
261 if (ipNum == 0xFFFFFFFF) {
262 return BITS_32;
263 }
264 if (ipNum == 0xFFFFFF00) {
265 return BITS_24;
266 }
267 if (ipNum == 0xFFFF0000) {
268 return BITS_16;
269 }
270 if (ipNum == 0xFF000000) {
271 return BITS_8;
272 }
273 for (int32_t i = 0; i < BITS_32; i++) {
274 if ((ipNum << i) & 0x80000000) {
275 cnt++;
276 } else {
277 break;
278 }
279 }
280 return cnt;
281 }
282
Ipv6PrefixLen(const std::string & ip)283 int32_t Ipv6PrefixLen(const std::string &ip)
284 {
285 constexpr int32_t LENGTH_8 = 8;
286 constexpr int32_t LENGTH_7 = 7;
287 constexpr int32_t LENGTH_6 = 6;
288 constexpr int32_t LENGTH_5 = 5;
289 constexpr int32_t LENGTH_4 = 4;
290 constexpr int32_t LENGTH_3 = 3;
291 constexpr int32_t LENGTH_2 = 2;
292 constexpr int32_t LENGTH_1 = 1;
293 if (ip.empty()) {
294 return 0;
295 }
296 in6_addr addr{};
297 inet_pton(AF_INET6, ip.c_str(), &addr);
298 int32_t prefixLen = 0;
299 for (int32_t i = 0; i < BYTE_16; ++i) {
300 if (addr.s6_addr[i] == 0xFF) {
301 prefixLen += LENGTH_8;
302 } else if (addr.s6_addr[i] == 0xFE) {
303 prefixLen += LENGTH_7;
304 break;
305 } else if (addr.s6_addr[i] == 0xFC) {
306 prefixLen += LENGTH_6;
307 break;
308 } else if (addr.s6_addr[i] == 0xF8) {
309 prefixLen += LENGTH_5;
310 break;
311 } else if (addr.s6_addr[i] == 0xF0) {
312 prefixLen += LENGTH_4;
313 break;
314 } else if (addr.s6_addr[i] == 0xE0) {
315 prefixLen += LENGTH_3;
316 break;
317 } else if (addr.s6_addr[i] == 0xC0) {
318 prefixLen += LENGTH_2;
319 break;
320 } else if (addr.s6_addr[i] == 0x80) {
321 prefixLen += LENGTH_1;
322 break;
323 } else {
324 break;
325 }
326 }
327 return prefixLen;
328 }
329
ParseInt(const std::string & str,int32_t * value)330 bool ParseInt(const std::string &str, int32_t *value)
331 {
332 char *end;
333 long long v = strtoll(str.c_str(), &end, 10);
334 if (std::string(end) == str || *end != '\0' || v < INT_MIN || v > INT_MAX) {
335 return false;
336 }
337 *value = v;
338 return true;
339 }
340
ConvertToInt64(const std::string & str)341 int64_t ConvertToInt64(const std::string &str)
342 {
343 return strtoll(str.c_str(), nullptr, DECIMAL_SYSTEM);
344 }
345
MaskIpv4(std::string & maskedResult)346 std::string MaskIpv4(std::string &maskedResult)
347 {
348 int maxDisplayNum = MAX_DISPLAY_NUM;
349 for (char &i : maskedResult) {
350 if (i == '/') {
351 break;
352 }
353 if (maxDisplayNum > 0) {
354 if (i == '.') {
355 maxDisplayNum--;
356 }
357 } else {
358 if (i != '.') {
359 i = '*';
360 }
361 }
362 }
363 return maskedResult;
364 }
365
MaskIpv6(std::string & maskedResult)366 std::string MaskIpv6(std::string &maskedResult)
367 {
368 size_t colonCount = 0;
369 for (char &i : maskedResult) {
370 if (i == '/') {
371 break;
372 }
373 if (i == ':') {
374 colonCount++;
375 }
376
377 if (colonCount >= MAX_DISPLAY_NUM) { // An legal ipv6 address has at least 2 ':'.
378 if (i != ':' && i != '/') {
379 i = '*';
380 }
381 }
382 }
383 return maskedResult;
384 }
385
ToAnonymousIp(const std::string & input)386 std::string ToAnonymousIp(const std::string &input)
387 {
388 std::lock_guard<std::mutex> lock(g_commonUtilsMutex);
389 std::string maskedResult{input};
390 // Mask ipv4 address.
391 if (std::regex_match(maskedResult, IP_PATTERN) || std::regex_match(maskedResult, IP_MASK_PATTERN)) {
392 return MaskIpv4(maskedResult);
393 }
394 // Mask ipv6 address.
395 if (std::regex_match(maskedResult, IPV6_PATTERN) || std::regex_match(maskedResult, IPV6_MASK_PATTERN)) {
396 return MaskIpv6(maskedResult);
397 }
398 return input;
399 }
400
StrToInt(const std::string & value,int32_t defaultErr)401 int32_t StrToInt(const std::string &value, int32_t defaultErr)
402 {
403 errno = 0;
404 char *pEnd = nullptr;
405 int64_t result = std::strtol(value.c_str(), &pEnd, 0);
406 if (pEnd == value.c_str() || (result < INT_MIN || result > LONG_MAX) || errno == ERANGE) {
407 return defaultErr;
408 }
409 return result;
410 }
411
StrToUint(const std::string & value,uint32_t defaultErr)412 uint32_t StrToUint(const std::string &value, uint32_t defaultErr)
413 {
414 errno = 0;
415 char *pEnd = nullptr;
416 uint64_t result = std::strtoul(value.c_str(), &pEnd, 0);
417 if (pEnd == value.c_str() || result > UINT32_MAX || errno == ERANGE) {
418 return defaultErr;
419 }
420 return result;
421 }
422
StrToBool(const std::string & value,bool defaultErr)423 bool StrToBool(const std::string &value, bool defaultErr)
424 {
425 errno = 0;
426 char *pEnd = nullptr;
427 uint64_t result = std::strtoul(value.c_str(), &pEnd, 0);
428 if (pEnd == value.c_str() || result > UINT32_MAX || errno == ERANGE) {
429 return defaultErr;
430 }
431 return static_cast<bool>(result);
432 }
433
StrToLong(const std::string & value,int64_t defaultErr)434 int64_t StrToLong(const std::string &value, int64_t defaultErr)
435 {
436 errno = 0;
437 char *pEnd = nullptr;
438 int64_t result = std::strtoll(value.c_str(), &pEnd, 0);
439 if (pEnd == value.c_str() || errno == ERANGE) {
440 return defaultErr;
441 }
442 return result;
443 }
444
StrToUint64(const std::string & value,uint64_t defaultErr)445 uint64_t StrToUint64(const std::string &value, uint64_t defaultErr)
446 {
447 errno = 0;
448 char *pEnd = nullptr;
449 uint64_t result = std::strtoull(value.c_str(), &pEnd, 0);
450 if (pEnd == value.c_str() || errno == ERANGE) {
451 return defaultErr;
452 }
453 return result;
454 }
455
CheckIfaceName(const std::string & name)456 bool CheckIfaceName(const std::string &name)
457 {
458 uint32_t index = 0;
459 if (name.empty()) {
460 return false;
461 }
462 size_t len = name.size();
463 if (len > INTERFACE_NAME_MAX_SIZE) {
464 return false;
465 }
466 while (index < len) {
467 if ((index == 0) && !isalnum(name[index])) {
468 return false;
469 }
470 if (!isalnum(name[index]) && (name[index] != '-') && (name[index] != '_') && (name[index] != '.') &&
471 (name[index] != ':')) {
472 return false;
473 }
474 index++;
475 }
476 return true;
477 }
478
FormatCmd(const std::vector<std::string> & cmd)479 std::vector<const char *> FormatCmd(const std::vector<std::string> &cmd)
480 {
481 std::vector<const char *> res;
482 res.reserve(cmd.size() + 1);
483
484 // string is converted to char * and the result is saved in res
485 std::transform(cmd.begin(), cmd.end(), std::back_inserter(res), [](const std::string &str) { return str.c_str(); });
486 res.emplace_back(nullptr);
487 return res;
488 }
489
ForkExecChildProcess(const int32_t * pipeFd,int32_t count,const std::vector<const char * > & args)490 int32_t ForkExecChildProcess(const int32_t *pipeFd, int32_t count, const std::vector<const char *> &args)
491 {
492 if (count != PIPE_FD_NUM) {
493 NETMGR_LOG_E("fork exec parent process failed");
494 _exit(-1);
495 }
496 if (close(pipeFd[PIPE_OUT]) != 0) {
497 NETMGR_LOG_E("close failed, errorno:%{public}d, errormsg:%{public}s", errno, strerror(errno));
498 _exit(-1);
499 }
500 if (dup2(pipeFd[PIPE_IN], STDOUT_FILENO) == -1) {
501 NETMGR_LOG_E("dup2 failed, errorno:%{public}d, errormsg:%{public}s", errno, strerror(errno));
502 _exit(-1);
503 }
504 if (execv(args[0], const_cast<char *const *>(&args[0])) == -1) {
505 NETMGR_LOG_E("execv command failed, errorno:%{public}d, errormsg:%{public}s", errno, strerror(errno));
506 }
507 if (close(pipeFd[PIPE_IN]) != 0) {
508 NETMGR_LOG_E("close failed, errorno:%{public}d, errormsg:%{public}s", errno, strerror(errno));
509 _exit(-1);
510 }
511 _exit(-1);
512 }
513
514 struct ParentProcessHelper {
515 std::atomic_bool waitDoneFlag = false;
516 pid_t ret = 0;
517 std::mutex parentMutex;
518 std::condition_variable parentCv;
519 };
520
ForkExecParentProcess(const int32_t * pipeFd,int32_t count,pid_t childPid,std::string * out)521 int32_t ForkExecParentProcess(const int32_t *pipeFd, int32_t count, pid_t childPid, std::string *out)
522 {
523 if (count != PIPE_FD_NUM) {
524 NETMGR_LOG_E("fork exec parent process failed");
525 return NETMANAGER_ERROR;
526 }
527 if (close(pipeFd[PIPE_IN]) != 0) {
528 NETMGR_LOG_E("close failed, errorno:%{public}d, errormsg:%{public}s", errno, strerror(errno));
529 }
530 if (out != nullptr) {
531 char buf[CHAR_ARRAY_SIZE_MAX] = {0};
532 out->clear();
533 while (read(pipeFd[PIPE_OUT], buf, CHAR_ARRAY_SIZE_MAX - 1) > 0) {
534 out->append(buf);
535 if (memset_s(buf, sizeof(buf), 0, sizeof(buf)) != 0) {
536 NETMGR_LOG_E("memset is false");
537 }
538 }
539 }
540
541 if (close(pipeFd[PIPE_OUT]) != 0) {
542 NETMGR_LOG_E("close failed, errorno:%{public}d, errormsg:%{public}s", errno, strerror(errno));
543 }
544 auto helper = std::make_shared<ParentProcessHelper>();
545 auto parentThread = std::thread([helper, childPid]() {
546 helper->ret = waitpid(childPid, nullptr, 0);
547 helper->waitDoneFlag = true;
548 helper->parentCv.notify_all();
549 NETMGR_LOG_I("waitpid %{public}d done", childPid);
550 });
551 #ifndef CROSS_PLATFORM
552 pthread_setname_np(parentThread.native_handle(), "ExecParentThread");
553 #endif
554 parentThread.detach();
555 const int32_t waitTime = 10;
556 std::unique_lock uLock(helper->parentMutex);
557 auto waitRet = helper->parentCv.wait_for(uLock, std::chrono::seconds(waitTime),
558 [&helper] { return helper->waitDoneFlag.load(); });
559 if (!waitRet) {
560 NETMGR_LOG_E("waitpid[%{public}d] timeout", childPid);
561 return NETMANAGER_ERROR;
562 }
563 pid_t pidRet = helper->ret;
564 if (pidRet != childPid) {
565 NETMGR_LOG_E("waitpid[%{public}d] failed, pidRet:%{public}d", childPid, pidRet);
566 return NETMANAGER_ERROR;
567 }
568 return NETMANAGER_SUCCESS;
569 }
570
ForkExec(const std::string & command,std::string * out)571 int32_t ForkExec(const std::string &command, std::string *out)
572 {
573 std::unique_lock<std::mutex> lock(g_forkExecMutex);
574 const std::vector<std::string> cmd = Split(command, CMD_SEP);
575 std::vector<const char *> args = FormatCmd(cmd);
576 int32_t pipeFd[PIPE_FD_NUM] = {0};
577 if (pipe(pipeFd) < 0) {
578 NETMGR_LOG_E("creat pipe failed, errorno:%{public}d, errormsg:%{public}s", errno, strerror(errno));
579 return NETMANAGER_ERROR;
580 }
581 pid_t pid = fork();
582 if (pid < 0) {
583 NETMGR_LOG_E("fork failed, errorno:%{public}d, errormsg:%{public}s", errno, strerror(errno));
584 return NETMANAGER_ERROR;
585 }
586 if (pid == 0) {
587 ForkExecChildProcess(pipeFd, PIPE_FD_NUM, args);
588 return NETMANAGER_SUCCESS;
589 } else {
590 return ForkExecParentProcess(pipeFd, PIPE_FD_NUM, pid, out);
591 }
592 }
593
IsValidDomain(const std::string & domain)594 bool IsValidDomain(const std::string &domain)
595 {
596 if (domain.empty()) {
597 return false;
598 }
599
600 std::string pattern = HOST_DOMAIN_PATTERN_HEADER;
601 pattern = std::accumulate(HOST_DOMAIN_TLDS.begin(), HOST_DOMAIN_TLDS.end(), pattern,
602 [](const std::string &pattern, const std::string &tlds) { return pattern + tlds + TLDS_SPLIT_SYMBOL; });
603 pattern = pattern.replace(pattern.size() - 1, 1, "") + HOST_DOMAIN_PATTERN_TAIL;
604 std::regex reg(pattern);
605 if (!std::regex_match(domain, reg)) {
606 NETMGR_LOG_E("Domain regex match failed.");
607 return false;
608 }
609
610 std::vector<std::string> parts = Split(domain, DOMAIN_DELIMITER);
611 if (parts.size() < DOMAIN_VALID_MIN_PART_SIZE || parts.size() > DOMAIN_VALID_MAX_PART_SIZE) {
612 NETMGR_LOG_E("The domain parts size:[%{public}d] is invalid", static_cast<int>(parts.size()));
613 return false;
614 }
615
616 std::set<std::string> tldsList;
617 for (const auto &item : parts) {
618 if (std::find(HOST_DOMAIN_TLDS.begin(), HOST_DOMAIN_TLDS.end(), item) == HOST_DOMAIN_TLDS.end()) {
619 continue;
620 }
621 if (tldsList.find(item) != tldsList.end()) {
622 NETMGR_LOG_E("Domain has duplicate tlds:%{public}s", item.c_str());
623 return false;
624 }
625 tldsList.insert(item);
626 }
627 return true;
628 }
629
WriteFile(const std::string & filePath,const std::string & fileContent)630 bool WriteFile(const std::string &filePath, const std::string &fileContent)
631 {
632 std::ofstream file(filePath, std::ios::out | std::ios::trunc);
633 if (!file.is_open()) {
634 NETMGR_LOG_E("write file=%{public}s fstream failed. err %{public}d %{public}s",
635 filePath.c_str(), errno, strerror(errno));
636 return false;
637 }
638 file << fileContent;
639 file.close();
640 return true;
641 }
642
HasInternetPermission()643 bool HasInternetPermission()
644 {
645 int testSock = socket(AF_INET, SOCK_STREAM, 0);
646 if (testSock < 0 && errno == EPERM) {
647 NETMGR_LOG_E("make tcp testSock failed errno is %{public}d %{public}s", errno, strerror(errno));
648 return false;
649 }
650 if (testSock > 0) {
651 close(testSock);
652 }
653 return true;
654 }
655
Trim(const std::string & str)656 std::string Trim(const std::string &str)
657 {
658 size_t start = str.find_first_not_of(" \t\n\r");
659 size_t end = str.find_last_not_of(" \t\n\r");
660 if (start == std::string::npos || end == std::string::npos) {
661 return "";
662 }
663 return str.substr(start, end - start + 1);
664 }
665
IsUrlRegexValid(const std::string & regex)666 bool IsUrlRegexValid(const std::string ®ex)
667 {
668 if (Trim(regex).empty()) {
669 return false;
670 }
671 return regex_match(regex, std::regex("^[a-zA-Z0-9\\-_\\.*]+$"));
672 }
673
InsertCharBefore(const std::string & input,const char from,const char preChar,const char nextChar)674 std::string InsertCharBefore(const std::string &input, const char from, const char preChar, const char nextChar)
675 {
676 std::ostringstream output;
677 for (size_t i = 0; i < input.size(); ++i) {
678 if (input[i] == from && (i == input.size() - 1 || input[i + 1] != nextChar)) {
679 output << preChar;
680 }
681 output << input[i];
682 }
683 return output.str();
684 }
685
ReplaceCharacters(const std::string & input)686 std::string ReplaceCharacters(const std::string &input)
687 {
688 std::string output = InsertCharBefore(input, '*', '.', '\0');
689 output = InsertCharBefore(output, '.', '\\', '*');
690 return output;
691 }
692
UrlRegexParse(const std::string & str,const std::string & patternStr)693 bool UrlRegexParse(const std::string &str, const std::string &patternStr)
694 {
695 if (patternStr.empty()) {
696 return false;
697 }
698 if (patternStr == "*") {
699 return true;
700 }
701 if (!IsUrlRegexValid(patternStr)) {
702 return patternStr == str;
703 }
704 std::regex pattern(ReplaceCharacters(patternStr));
705 return !patternStr.empty() && std::regex_match(str, pattern);
706 }
707 } // namespace OHOS::NetManagerStandard::CommonUtils
708