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