xref: /openbmc/phosphor-networkd/src/util.cpp (revision b03a760f)
1 #include "config.h"
2 
3 #include "util.hpp"
4 
5 #include "config_parser.hpp"
6 #include "types.hpp"
7 
8 #include <fmt/compile.h>
9 #include <fmt/format.h>
10 #include <sys/wait.h>
11 
12 #include <cctype>
13 #include <phosphor-logging/elog-errors.hpp>
14 #include <phosphor-logging/log.hpp>
15 #include <string>
16 #include <string_view>
17 #include <xyz/openbmc_project/Common/error.hpp>
18 
19 namespace phosphor
20 {
21 namespace network
22 {
23 
24 using std::literals::string_view_literals::operator""sv;
25 using namespace phosphor::logging;
26 using namespace sdbusplus::xyz::openbmc_project::Common::Error;
27 
28 namespace internal
29 {
30 
31 void executeCommandinChildProcess(stdplus::const_zstring path, char** args)
32 {
33     using namespace std::string_literals;
34     pid_t pid = fork();
35 
36     if (pid == 0)
37     {
38         execv(path.c_str(), args);
39         exit(255);
40     }
41     else if (pid < 0)
42     {
43         auto error = errno;
44         log<level::ERR>("Error occurred during fork", entry("ERRNO=%d", error));
45         elog<InternalFailure>();
46     }
47     else if (pid > 0)
48     {
49         int status;
50         while (waitpid(pid, &status, 0) == -1)
51         {
52             if (errno != EINTR)
53             {
54                 status = -1;
55                 break;
56             }
57         }
58 
59         if (status < 0)
60         {
61             fmt::memory_buffer buf;
62             fmt::format_to(fmt::appender(buf), "`{}`", path);
63             for (size_t i = 0; args[i] != nullptr; ++i)
64             {
65                 fmt::format_to(fmt::appender(buf), " `{}`", args[i]);
66             }
67             buf.push_back('\0');
68             log<level::ERR>("Unable to execute the command",
69                             entry("CMD=%s", buf.data()),
70                             entry("STATUS=%d", status));
71             elog<InternalFailure>();
72         }
73     }
74 }
75 
76 /** @brief Get ignored interfaces from environment */
77 std::string_view getIgnoredInterfacesEnv()
78 {
79     auto r = std::getenv("IGNORED_INTERFACES");
80     if (r == nullptr)
81     {
82         return "";
83     }
84     return r;
85 }
86 
87 /** @brief Parse the comma separated interface names */
88 std::unordered_set<std::string_view>
89     parseInterfaces(std::string_view interfaces)
90 {
91     std::unordered_set<std::string_view> result;
92     while (true)
93     {
94         auto sep = interfaces.find(',');
95         auto interface = interfaces.substr(0, sep);
96         while (!interface.empty() && std::isspace(interface.front()))
97         {
98             interface.remove_prefix(1);
99         }
100         while (!interface.empty() && std::isspace(interface.back()))
101         {
102             interface.remove_suffix(1);
103         }
104         if (!interface.empty())
105         {
106             result.insert(interface);
107         }
108         if (sep == interfaces.npos)
109         {
110             break;
111         }
112         interfaces = interfaces.substr(sep + 1);
113     }
114     return result;
115 }
116 
117 /** @brief Get the ignored interfaces */
118 const std::unordered_set<std::string_view>& getIgnoredInterfaces()
119 {
120     static auto ignoredInterfaces = parseInterfaces(getIgnoredInterfacesEnv());
121     return ignoredInterfaces;
122 }
123 
124 } // namespace internal
125 
126 std::optional<std::string> interfaceToUbootEthAddr(std::string_view intf)
127 {
128     constexpr auto pfx = "eth"sv;
129     if (!intf.starts_with(pfx))
130     {
131         return std::nullopt;
132     }
133     intf.remove_prefix(pfx.size());
134     unsigned idx;
135     try
136     {
137         idx = DecodeInt<unsigned, 10>{}(intf);
138     }
139     catch (...)
140     {
141         return std::nullopt;
142     }
143     if (idx == 0)
144     {
145         return "ethaddr";
146     }
147     return fmt::format(FMT_COMPILE("eth{}addr"), idx);
148 }
149 
150 static std::optional<DHCPVal> systemdParseDHCP(std::string_view str)
151 {
152     if (config::icaseeq(str, "ipv4"))
153     {
154         return DHCPVal{.v4 = true, .v6 = false};
155     }
156     if (config::icaseeq(str, "ipv6"))
157     {
158         return DHCPVal{.v4 = false, .v6 = true};
159     }
160     if (auto b = config::parseBool(str); b)
161     {
162         return DHCPVal{.v4 = *b, .v6 = *b};
163     }
164     return std::nullopt;
165 }
166 
167 inline auto systemdParseLast(const config::Parser& config,
168                              std::string_view section, std::string_view key,
169                              auto&& fun)
170 {
171     if (!config.getFileExists())
172     {
173     }
174     else if (auto str = config.map.getLastValueString(section, key);
175              str == nullptr)
176     {
177         auto err = fmt::format("Unable to get the value of {}[{}] from {}",
178                                section, key, config.getFilename().native());
179         log<level::NOTICE>(err.c_str(),
180                            entry("FILE=%s", config.getFilename().c_str()));
181     }
182     else if (auto val = fun(*str); !val)
183     {
184         auto err = fmt::format("Invalid value of {}[{}] from {}: {}", section,
185                                key, config.getFilename().native(), *str);
186         log<level::NOTICE>(err.c_str(), entry("VALUE=%s", str->c_str()),
187                            entry("FILE=%s", config.getFilename().c_str()));
188     }
189     else
190     {
191         return val;
192     }
193     return decltype(fun(std::string_view{}))(std::nullopt);
194 }
195 
196 bool getIPv6AcceptRA(const config::Parser& config)
197 {
198 #ifdef ENABLE_IPV6_ACCEPT_RA
199     constexpr bool def = true;
200 #else
201     constexpr bool def = false;
202 #endif
203     return systemdParseLast(config, "Network", "IPv6AcceptRA",
204                             config::parseBool)
205         .value_or(def);
206 }
207 
208 DHCPVal getDHCPValue(const config::Parser& config)
209 {
210     return systemdParseLast(config, "Network", "DHCP", systemdParseDHCP)
211         .value_or(DHCPVal{.v4 = true, .v6 = true});
212 }
213 
214 bool getDHCPProp(const config::Parser& config, std::string_view key)
215 {
216     return systemdParseLast(config, "DHCP", key, config::parseBool)
217         .value_or(true);
218 }
219 
220 namespace mac_address
221 {
222 
223 bool isEmpty(const ether_addr& mac)
224 {
225     return mac == ether_addr{};
226 }
227 
228 bool isMulticast(const ether_addr& mac)
229 {
230     return mac.ether_addr_octet[0] & 0b1;
231 }
232 
233 bool isUnicast(const ether_addr& mac)
234 {
235     return !isEmpty(mac) && !isMulticast(mac);
236 }
237 
238 } // namespace mac_address
239 } // namespace network
240 } // namespace phosphor
241