1 // Copyright 2021 Google LLC
2 //
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 #include "net_config.h"
16 
17 #include <linux/if.h>
18 #include <net/if_arp.h>
19 #include <sys/ioctl.h>
20 #include <sys/types.h>
21 #include <sys/wait.h>
22 #include <unistd.h>
23 
24 #include <sdbusplus/bus.hpp>
25 #include <stdplus/fd/create.hpp>
26 #include <stdplus/fd/ops.hpp>
27 #include <stdplus/print.hpp>
28 #include <stdplus/util/string.hpp>
29 
30 #include <cstdio>
31 #include <cstring>
32 #include <filesystem>
33 #include <format>
34 #include <thread>
35 #include <utility>
36 #include <variant>
37 
38 /* Most of the code for interacting with DBus is from
39  * phosphor-host-ipmid/utils.cpp
40  */
41 
42 namespace net
43 {
44 
45 namespace
46 {
47 
48 constexpr auto IFACE_ROOT = "/xyz/openbmc_project/network/";
49 constexpr auto MAC_FORMAT = "%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx";
50 // 2 chars for every byte + 5 colons + Null byte
51 constexpr auto MAC_FORMAT_LENGTH = 6 * 2 + 5 + 1;
52 constexpr auto MAC_INTERFACE = "xyz.openbmc_project.Network.MACAddress";
53 constexpr auto NETWORK_SERVICE = "xyz.openbmc_project.Network";
54 constexpr auto PROP_INTERFACE = "org.freedesktop.DBus.Properties";
55 
format_mac(const mac_addr_t & mac)56 std::string format_mac(const mac_addr_t& mac)
57 {
58     // 2 chars for every byte + 5 colons + Null byte
59     char mac_str[MAC_FORMAT_LENGTH];
60     snprintf(mac_str, sizeof(mac_str), MAC_FORMAT, mac.octet[0], mac.octet[1],
61              mac.octet[2], mac.octet[3], mac.octet[4], mac.octet[5]);
62 
63     return std::string{mac_str};
64 }
65 
66 } // namespace
67 
PhosphorConfig(const std::string & iface_name)68 PhosphorConfig::PhosphorConfig(const std::string& iface_name) :
69     iface_name_{iface_name}, iface_path_{std::string(IFACE_ROOT) + iface_name},
70     shared_host_mac_(std::experimental::nullopt),
71     bus(sdbusplus::bus::new_default())
72 {}
73 
get_mac_addr(mac_addr_t * mac)74 int PhosphorConfig::get_mac_addr(mac_addr_t* mac)
75 {
76     if (mac == nullptr)
77     {
78         stdplus::println(stderr, "mac is nullptr");
79         return -1;
80     }
81 
82     // Cache hit: we have stored host MAC.
83     if (shared_host_mac_)
84     {
85         *mac = shared_host_mac_.value();
86     }
87     else // Cache miss: read from interface, cache it for future requests.
88     {
89         struct ifreq ifr = {};
90         try
91         {
92             auto fd = stdplus::fd::socket(stdplus::fd::SocketDomain::INet6,
93                                           stdplus::fd::SocketType::Datagram,
94                                           stdplus::fd::SocketProto::IP);
95             call_nic(fd, ifr, SIOCGIFHWADDR);
96         }
97         catch (const std::exception& ex)
98         {
99             stdplus::println(
100                 stderr,
101                 "Failed to get MAC Addr for Interface {} writing file: {}",
102                 iface_name_, ex.what());
103             return -1;
104         }
105         std::copy_n(ifr.ifr_addr.sa_data, sizeof(*mac), mac->octet);
106         shared_host_mac_ = *mac;
107     }
108     return 0;
109 }
110 
call_nic(auto fd,struct ifreq & ifr,int op)111 void PhosphorConfig::call_nic(auto fd, struct ifreq& ifr, int op)
112 {
113     std::copy_n(iface_name_.c_str(), iface_name_.size() + 1, ifr.ifr_name);
114     fd.ioctl(op, &ifr);
115 }
116 
set_mac_addr(const mac_addr_t & mac)117 int PhosphorConfig::set_mac_addr(const mac_addr_t& mac)
118 {
119     std::variant<std::string> mac_value(format_mac(mac));
120     struct ifreq ifr = {};
121     short flags_copy;
122 
123     try
124     {
125         auto netdir = std::format("/run/systemd/network/00-bmc-{}.network.d",
126                                   iface_name_);
127         std::filesystem::create_directories(netdir);
128         auto netfile = std::format("{}/60-ncsi-mac.conf", netdir);
129         auto fd = stdplus::fd::open(
130             netfile,
131             stdplus::fd::OpenFlags(stdplus::fd::OpenAccess::WriteOnly)
132                 .set(stdplus::fd::OpenFlag::Create),
133             0644);
134         auto contents = std::format("[Link]\nMACAddress={}\n",
135                                     std::get<std::string>(mac_value));
136         stdplus::fd::writeExact(fd, contents);
137     }
138     catch (const std::exception& ex)
139     {
140         stdplus::println(stderr, "Failed to set MAC Addr `{}` writing file: {}",
141                          std::get<std::string>(mac_value), ex.what());
142         return -1;
143     }
144     try
145     {
146         auto fd = stdplus::fd::socket(stdplus::fd::SocketDomain::INet6,
147                                       stdplus::fd::SocketType::Datagram,
148                                       stdplus::fd::SocketProto::IP);
149         // Try setting MAC Address directly without bringing interface down
150         try
151         {
152             std::copy_n(mac.octet, 6, ifr.ifr_hwaddr.sa_data);
153             call_nic(fd, ifr, SIOCSIFHWADDR);
154         }
155         catch (const std::exception& e)
156         {
157             // Regardless of error attempt to set MAC Address again after
158             // bringing interface down
159             stdplus::println(
160                 stderr,
161                 "Could not set MAC Address directly, retrying after bringing interface down, error = {}",
162                 e.what());
163             try
164             {
165                 // Read interface flags configuration and store (once interface
166                 // is brought down, existing state is lost)
167                 call_nic(fd, ifr, SIOCGIFFLAGS);
168                 flags_copy = ifr.ifr_flags;
169                 // set interface down
170                 ifr.ifr_flags &= ~IFF_UP;
171                 call_nic(fd, ifr, SIOCSIFFLAGS);
172                 // Wait for 1 milliseconds - sometimes interface is still
173                 // going down
174                 std::this_thread::sleep_for(std::chrono::milliseconds(1));
175                 // set MAC Address
176                 ifr.ifr_hwaddr.sa_family = ARPHRD_ETHER;
177                 std::copy_n(mac.octet, 6, ifr.ifr_hwaddr.sa_data);
178                 call_nic(fd, ifr, SIOCSIFHWADDR);
179                 // set interface up with the flags state prior to bringing
180                 // it down
181                 ifr.ifr_flags = flags_copy | IFF_UP;
182                 call_nic(fd, ifr, SIOCSIFFLAGS);
183             }
184             catch (const std::exception& e)
185             {
186                 stdplus::println(
187                     stderr, "Failed to set MAC Address {} writing file: {}",
188                     std::get<std::string>(mac_value), e.what());
189                 return -1;
190             }
191         }
192     }
193     catch (const std::exception& e)
194     {
195         stdplus::println(stderr, "Error creating socket: {}", e.what());
196         return -1;
197     }
198     stdplus::println(stderr, "Success setting Mac address for {}: {}",
199                      iface_name_, std::get<std::string>(mac_value));
200     shared_host_mac_ = std::experimental::nullopt;
201     return 0;
202 }
203 
set_nic_hostless(bool is_nic_hostless)204 int PhosphorConfig::set_nic_hostless(bool is_nic_hostless)
205 {
206     // Ensure that we don't trigger the target multiple times. This is
207     // undesirable because it will cause any inactive services to re-trigger
208     // every time we run this code. Since the loop calling this executes this
209     // code every 1s, we don't want to keep re-executing services. A fresh
210     // start of the daemon will always trigger the service to ensure system
211     // consistency.
212     if (was_nic_hostless_ && is_nic_hostless == *was_nic_hostless_)
213     {
214         return 0;
215     }
216 
217     static constexpr auto systemdService = "org.freedesktop.systemd1";
218     static constexpr auto systemdRoot = "/org/freedesktop/systemd1";
219     static constexpr auto systemdInterface = "org.freedesktop.systemd1.Manager";
220 
221     auto method = bus.new_method_call(systemdService, systemdRoot,
222                                       systemdInterface, "StartUnit");
223     if (is_nic_hostless)
224     {
225         method.append(
226             stdplus::util::strCat("nic-hostless@", iface_name_, ".target"));
227     }
228     else
229     {
230         method.append(
231             stdplus::util::strCat("nic-hostful@", iface_name_, ".target"));
232     }
233 
234     // Specify --job-mode (see systemctl(1) for detail).
235     method.append("replace");
236 
237     try
238     {
239         bus.call_noreply(method);
240         was_nic_hostless_ = is_nic_hostless;
241         return 0;
242     }
243     catch (const sdbusplus::exception::SdBusError& ex)
244     {
245         stdplus::println(stderr, "Failed to set systemd nic status: {}",
246                          ex.what());
247         return 1;
248     }
249 }
250 
251 } // namespace net
252