MXL : Media eXchange Layer
MXL
Loading...
Searching...
No Matches
FabricAddress.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 Contributors to the Media eXchange Layer project.
2//
3// SPDX-License-Identifier: Apache-2.0
4
5#include "FabricAddress.hpp"
6#include <cstdint>
7#include <cstdlib>
8#include <cstring>
9#include <algorithm>
10#include <optional>
11#include <stdexcept>
12#include <string>
13#include <variant>
14#include <sys/socket.h>
15#include <arpa/inet.h>
16#include <fmt/format.h>
17#include <Format.hpp>
19#include "Exception.hpp"
20#include "VariantUtils.hpp"
21
23{
24 namespace
25 {
26 [[nodiscard]]
27 FabricAddress::Native parseInternetAddress(std::string const& ipString, std::uint16_t port = 0)
28 {
29 if (std::ranges::find(ipString, ':') != ipString.end())
30 {
31 auto addr = ::in6_addr{};
32 if (!::inet_pton(AF_INET6, ipString.c_str(), &addr))
33 {
34 throw Exception::invalidArgument("invalid node address");
35 }
37 ::sockaddr_in6{.sin6_family = AF_INET6, .sin6_port = port, .sin6_flowinfo = 0, .sin6_addr = addr, .sin6_scope_id = 0}
38 };
39 }
40 else
41 {
42 auto addr = ::in_addr{};
43 if (!::inet_pton(AF_INET, ipString.c_str(), &addr))
44 {
45 throw Exception::invalidArgument("invalid node address");
46 }
48 ::sockaddr_in{.sin_family = AF_INET, .sin_port = port, .sin_addr = addr, .sin_zero = {}}
49 };
50 }
51 }
52
54 [[nodiscard]]
55 std::optional<std::string> ipToString(int family, void const* addr)
56 {
57 char str[INET6_ADDRSTRLEN] = {};
58 if (!::inet_ntop(family, addr, str, sizeof(str)))
59 {
60 return std::nullopt;
61 }
62 return std::string{str};
63 }
64
66 [[nodiscard]]
67 std::optional<std::string> toString(::sockaddr_in const& sin)
68 {
69 auto const ip = ipToString(sin.sin_family, &sin.sin_addr);
70 if (!ip)
71 {
72 return std::nullopt;
73 }
74 return fmt::format("fi_sockaddr_in://{}:{}", *ip, ntohs(sin.sin_port));
75 }
76
78 [[nodiscard]]
79 std::optional<std::string> toString(::sockaddr_in6 const& sin6)
80 {
81 auto const ip = ipToString(sin6.sin6_family, &sin6.sin6_addr);
82 if (!ip)
83 {
84 return std::nullopt;
85 }
86 return fmt::format("fi_sockaddr_in6://[{}]:{}", *ip, ntohs(sin6.sin6_port));
87 }
88
90 [[nodiscard]]
91 std::optional<std::string> toString(OfiSockaddrIb const& sib)
92 {
93 auto const gid = ipToString(AF_INET6, sib.sib_addr);
94 if (!gid)
95 {
96 return std::nullopt;
97 }
98 return fmt::format("fi_sockaddr_ib://[{}]:0x{:x}:0x{:x}:0x{:x}",
99 *gid, // GID
100 ntohs(sib.sib_pkey), // P_Key
101 static_cast<std::uint16_t>((be64toh(sib.sib_sid) >> 16) & 0xfff), // port space
102 static_cast<std::uint8_t>(be64toh(sib.sib_scope_id) & 0xff)); // Scope ID
103 }
104
106 [[nodiscard]]
107 std::optional<std::string> toString(EfaAddress const& efa)
108 {
109 auto const gid = ipToString(AF_INET6, efa.gid);
110 if (!gid)
111 {
112 return std::nullopt;
113 }
114 return fmt::format("fi_addr_efa://[{}]:{}:{}", *gid, efa.qpn, efa.qkey);
115 }
116
118 [[nodiscard]]
119 std::optional<std::string> toString(std::string const& str)
120 {
121 return str;
122 }
123
125 [[nodiscard]]
126 std::optional<std::string> hostString(::sockaddr_in const& sin)
127 {
128 return ipToString(sin.sin_family, &sin.sin_addr);
129 }
130
131 [[nodiscard]]
132 std::optional<std::string> hostString(::sockaddr_in6 const& sin6)
133 {
134 return ipToString(sin6.sin6_family, &sin6.sin6_addr);
135 }
136
137 [[nodiscard]]
138 std::optional<std::string> hostString(OfiSockaddrIb const& sib)
139 {
140 return ipToString(AF_INET6, sib.sib_addr);
141 }
142
143 [[nodiscard]]
144 std::optional<std::string> hostString(EfaAddress const& efa)
145 {
146 return ipToString(AF_INET6, efa.gid);
147 }
148
149 [[nodiscard]]
150 std::optional<std::string> hostString(std::string const& str)
151 {
152 return str.substr(0, str.find(':'));
153 }
154
155 [[nodiscard]]
156 std::optional<std::string> serviceString(::sockaddr_in const& sin)
157 {
158 return sin.sin_port == 0 ? std::nullopt : std::make_optional(std::to_string(sin.sin_port));
159 }
160
161 [[nodiscard]]
162 std::optional<std::string> serviceString(::sockaddr_in6 const& sin)
163 {
164 return sin.sin6_port == 0 ? std::nullopt : std::make_optional(std::to_string(sin.sin6_port));
165 }
166
167 [[nodiscard]]
168 std::optional<std::string> serviceString(OfiSockaddrIb)
169 {
170 return std::nullopt;
171 }
172
173 [[nodiscard]]
174 std::optional<std::string> serviceString(EfaAddress)
175 {
176 return std::nullopt;
177 }
178
179 [[nodiscard]]
180 std::optional<std::string> serviceString(std::string const& addr)
181 {
182 auto const pos = addr.find(':');
183 if (pos == std::string::npos)
184 {
185 return std::nullopt;
186 }
187 return addr.substr(pos + 1);
188 }
189 }
190
191 FabricAddressFormat convertAddressFormat(std::uint32_t fiAddrFormat)
192 {
193 // clang-format off
194 constexpr static auto const valid = std::array<FabricAddressFormat, 8>{
203 // clang-format on
204
205 auto val = static_cast<FabricAddressFormat>(fiAddrFormat);
206 if (std::ranges::find(valid, val) == valid.end())
207 {
209 }
210
211 return val;
212 }
213
215 {
216 auto val = convertAddressFormat(fiAddrFormat);
218 {
219 throw Exception::invalidArgument("Invalid or unsupported address format value: {}", fiToString(&fiAddrFormat, FI_TYPE_ADDR_FORMAT));
220 }
221
222 return val;
223 }
224
226 : _native{std::monostate{}}
227 {}
228
232
234 {
235 return decode(mustConvertAddressFormat(info->addr_format), info->src_addr, info->src_addrlen);
236 }
237
239 {
240 return decode(mustConvertAddressFormat(info->addr_format), info->dest_addr, info->dest_addrlen);
241 }
242
243 FabricAddress FabricAddress::decode(FabricAddressFormat format, void const* addr, std::size_t len)
244 {
245 // Mirror ofi_straddr: nothing to decode without an address.
246 if (!addr)
247 {
248 return FabricAddress{};
249 }
250
251 auto const sockAddrFamily = [&]
252 {
253 return static_cast<::sockaddr const*>(addr)->sa_family;
254 };
255
256 switch (format)
257 {
259 // Dispatch on the embedded address family (IPv4, IPv6 or IB).
260 switch (sockAddrFamily())
261 {
262 case AF_INET: return decode(FabricAddressFormat::SockaddrIn, addr, len);
263 case AF_INET6: return decode(FabricAddressFormat::SockaddrIn6, addr, len);
264 case AF_IB: return decode(FabricAddressFormat::SockaddrIb, addr, len);
265 default: return FabricAddress{};
266 }
268 // Like FI_SOCKADDR, but IB is not a valid family here.
269 switch (sockAddrFamily())
270 {
271 case AF_INET: return decode(FabricAddressFormat::SockaddrIn, addr, len);
272 case AF_INET6: return decode(FabricAddressFormat::SockaddrIn6, addr, len);
273 default: return FabricAddress{};
274 }
276 {
277 if (len < sizeof(::sockaddr_in))
278 {
279 return FabricAddress{};
280 }
281 auto sin = ::sockaddr_in{};
282 std::memcpy(&sin, addr, sizeof(sin));
283 return FabricAddress{sin};
284 }
286 {
287 if (len < sizeof(::sockaddr_in6))
288 {
289 return FabricAddress{};
290 }
291 auto sin6 = ::sockaddr_in6{};
292 std::memcpy(&sin6, addr, sizeof(sin6));
293 return FabricAddress{sin6};
294 }
296 {
297 if (len < sizeof(OfiSockaddrIb))
298 {
299 return FabricAddress{};
300 }
301 auto sib = OfiSockaddrIb{};
302 std::memcpy(&sib, addr, sizeof(sib));
303 return FabricAddress{sib};
304 }
306 {
307 // 16-byte IPv6 GID, 16-bit QPN at offset 16, 32-bit QKey at offset 20.
308 constexpr auto efaAddrLen = std::size_t{24};
309 if (len < efaAddrLen)
310 {
311 return FabricAddress{};
312 }
313 auto const* bytes = static_cast<std::uint8_t const*>(addr);
314 auto efa = EfaAddress{};
315 std::memcpy(efa.gid, bytes, sizeof(efa.gid));
316 std::memcpy(&efa.qpn, bytes + 16, sizeof(efa.qpn));
317 std::memcpy(&efa.qkey, bytes + 20, sizeof(efa.qkey));
318 return FabricAddress{efa};
319 }
320 case FabricAddressFormat::String: return FabricAddress{std::string{static_cast<char const*>(addr)}};
321 default: return FabricAddress{};
322 }
323 }
324
325 std::string FabricAddress::toString() const
326 {
327 return std::visit(
328 [](auto const& value) -> std::string
329 {
330 using T = std::decay_t<decltype(value)>;
331 if constexpr (std::is_same_v<T, std::monostate>)
332 {
333 return "";
334 }
335 else
336 {
337 return ofi::toString(value).value_or("");
338 }
339 },
340 _native);
341 }
342
343 std::optional<std::string> FabricAddress::node() const
344 {
345 return std::visit(
346 [](auto const& value) -> std::optional<std::string>
347 {
348 using T = std::decay_t<decltype(value)>;
349 if constexpr (std::is_same_v<T, std::monostate>)
350 {
351 return std::nullopt;
352 }
353 else
354 {
355 return ofi::hostString(value);
356 }
357 },
358 _native);
359 }
360
361 std::optional<std::string> FabricAddress::service() const
362 {
363 return std::visit(
364 [](auto const& value) -> std::optional<std::string>
365 {
366 using T = std::decay_t<decltype(value)>;
367 if constexpr (std::is_same_v<T, std::monostate>)
368 {
369 return std::nullopt;
370 }
371 else
372 {
373 return ofi::serviceString(value);
374 }
375 },
376 _native);
377 }
378
380 {
381 return std::visit(
383 [](std::monostate const&) { return FabricAddressFormat::Unspec; },
384 [](::sockaddr_in const&) { return FabricAddressFormat::SockaddrIn; },
385 [](::sockaddr_in6 const&) { return FabricAddressFormat::SockaddrIn6; },
386 [](OfiSockaddrIb const&) { return FabricAddressFormat::SockaddrIb; },
387 [](EfaAddress const&) { return FabricAddressFormat::Efa; },
388 [](std::string const&) { return FabricAddressFormat::String; },
389 },
390 _native);
391 }
392
393 FabricAddress FabricAddress::parse(Provider provider, std::optional<std::string> node, std::optional<std::string> service)
394 {
395 if (!node)
396 {
397 if (service)
398 {
399 throw Exception::invalidArgument("node address is required when service address is specified");
400 }
401
402 return FabricAddress{};
403 }
404
405 switch (provider)
406 {
407 // SHM provider always expected FI_ADDR_STR
408 case Provider::SHM:
409 {
410 if (service && !service->empty())
411 {
412 return FabricAddress{*node + ":" + *service};
413 }
414 else
415 {
416 return FabricAddress{*node};
417 }
418 };
419 // For TCP and Verbs we only support FI_SOCKADDR_IN and FI_SOCKADDR_IN6
420 case Provider::TCP: [[fallthrough]];
421 case Provider::VERBS:
422 {
423 if (service && !service->empty())
424 {
425 auto port = std::uint16_t{0};
426 try
427 {
428 port = stringToInteger<std::uint16_t>(*service, "service");
429 }
430 catch (std::invalid_argument const& e)
431 {
432 throw Exception::invalidArgument("{}", e.what());
433 }
434 return FabricAddress{parseInternetAddress(*node, port)};
435 }
436 return FabricAddress{parseInternetAddress(*node)};
437 }
438 // EFA only supports FI_ADDR_EFA
439 case Provider::EFA:
440 {
441 auto parsed = parseInternetAddress(*node);
442 auto sin6 = std::get_if<::sockaddr_in6>(&parsed);
443 if (!sin6)
444 {
445 throw Exception::invalidArgument("invalid address format for EFA provider");
446 }
447
448 auto addr = EfaAddress{.gid = {}, .qpn = 0, .qkey = 0};
449 std::memcpy(addr.gid, &sin6->sin6_addr, sizeof(addr.gid));
450 return FabricAddress{addr};
451 }
452 default: throw Exception::invalidState("must specify provider");
453 }
454 }
455}
static Exception invalidArgument(fmt::format_string< T... > fmt, T &&... args)
Make an MXL_ERR_INVALID_ARG exception.
Definition Exception.hpp:43
static Exception invalidState(fmt::format_string< T... > fmt, T &&... args)
Make an MXL_ERR_INVALID_STATE exception.
Definition Exception.hpp:59
static FabricAddress parse(Provider provider, std::optional< std::string > node, std::optional< std::string > service)
Parse a node/service pair into a typed address for the given provider.
Native const & native() const noexcept
Access the underlying variant.
std::optional< std::string > node() const
Return the host portion of the address as a string.
FabricAddressFormat addressFormat() const noexcept
Return the libfabric address format constant (FI_SOCKADDR_IN, etc.).
static FabricAddress fromSource(FabricInfoView info) noexcept
Build a FabricAddress from the source address of info.
static FabricAddress decode(FabricAddressFormat addrFormat, void const *addr, std::size_t len)
Decode a raw libfabric address buffer of the given addr_format.
static FabricAddress fromDestination(FabricInfoView info) noexcept
Build a FabricAddress from the destination address of info.
std::optional< std::string > service() const
Return the service/port portion of the address as a string.
std::string toString() const
Format the address exactly as libfabric's internal ofi_straddr.
std::variant< std::monostate, ::sockaddr_in, ::sockaddr_in6, OfiSockaddrIb, EfaAddress, std::string > Native
Non-owning view of a FabricInfo. Returned when iterating over a FabricInfoList.
FabricAddressFormat convertAddressFormat(std::uint32_t fiAddrFormat)
Convert from libfabric address format value to FabricAddressFormat.
std::string fiToString(void *any, ::fi_type type)
Definition Format.cpp:45
Provider
Internal representation of supported libfabric providers.
Definition Provider.hpp:17
FabricAddressFormat mustConvertAddressFormat(std::uint32_t fiAddrFormat)
Convert from libfabric address format value to FabricAddressFormat Never returns FabricAddressFormat:...
T stringToInteger(std::string_view text, std::string_view name)
Decoded representation of an FI_ADDR_EFA address.
Local declaration of libfabric's internal struct ofi_sockaddr_ib.