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