Hermes 0.7.0
Linux game streaming host
Loading...
Searching...
No Matches
network.cpp
Go to the documentation of this file.
1
5// standard includes
6#include <algorithm>
7#include <boost/asio.hpp>
8#include <cerrno>
9#include <cstring>
10#include <sstream>
11
12 #include <fcntl.h>
13 #include <ifaddrs.h>
14 #include <net/if.h>
15
16// local includes
17#include "config.h"
18#include "logging.h"
19#include "network.h"
20#include "utility.h"
21
22using namespace std::literals;
23
24namespace ip = boost::asio::ip;
25
26namespace net {
27 std::vector<ip::network_v4> pc_ips_v4 {
28 ip::make_network_v4("127.0.0.0/8"sv),
29 };
30 std::vector<ip::network_v4> lan_ips_v4 {
31 ip::make_network_v4("192.168.0.0/16"sv),
32 ip::make_network_v4("172.16.0.0/12"sv),
33 ip::make_network_v4("10.0.0.0/8"sv),
34 ip::make_network_v4("100.64.0.0/10"sv),
35 ip::make_network_v4("169.254.0.0/16"sv),
36 };
37
38 std::vector<ip::network_v6> pc_ips_v6 {
39 ip::make_network_v6("::1/128"sv),
40 };
41 std::vector<ip::network_v6> lan_ips_v6 {
42 ip::make_network_v6("fc00::/7"sv),
43 ip::make_network_v6("fe80::/64"sv),
44 };
45
46 net_e from_enum_string(const std::string_view &view) {
47 if (view == "wan") {
48 return WAN;
49 }
50 if (view == "lan") {
51 return LAN;
52 }
53
54 return PC;
55 }
56
57 namespace {
61 net_e from_ranges(const ip::address &addr) {
62 if (addr.is_v6()) {
63 for (auto &range : pc_ips_v6) {
64 if (range.hosts().find(addr.to_v6()) != range.hosts().end()) {
65 return PC;
66 }
67 }
68
69 for (auto &range : lan_ips_v6) {
70 if (range.hosts().find(addr.to_v6()) != range.hosts().end()) {
71 return LAN;
72 }
73 }
74 } else {
75 for (auto &range : pc_ips_v4) {
76 if (range.hosts().find(addr.to_v4()) != range.hosts().end()) {
77 return PC;
78 }
79 }
80
81 for (auto &range : lan_ips_v4) {
82 if (range.hosts().find(addr.to_v4()) != range.hosts().end()) {
83 return LAN;
84 }
85 }
86 }
87
88 return WAN;
89 }
90 } // namespace
91
92 raw_address_t to_raw_address(const boost::asio::ip::address &address) {
93 raw_address_t raw;
94 const auto normalized = normalize_address(address);
95 if (normalized.is_v4()) {
96 const auto bytes = normalized.to_v4().to_bytes();
97 std::copy(bytes.begin(), bytes.end(), raw.bytes.begin());
98 return raw;
99 }
100 const auto v6 = normalized.to_v6();
101 const auto bytes = v6.to_bytes();
102 std::copy(bytes.begin(), bytes.end(), raw.bytes.begin());
103 raw.v6 = true;
104 raw.scope = static_cast<std::uint32_t>(v6.scope_id());
105 return raw;
106 }
107
108 net_e from_address_ranges(const std::string_view &view) {
109 return from_ranges(normalize_address(ip::make_address(view)));
110 }
111
112 net_e from_address(const std::string_view &view, std::span<const interface_address_t> links) {
113 const auto addr = normalize_address(ip::make_address(view));
114 if (const auto kind = from_ranges(addr); kind != WAN) {
115 return kind;
116 }
117 return on_link(to_raw_address(addr), links) ? LAN : WAN;
118 }
119
120 net_e from_address(const std::string_view &view) {
121 const auto addr = normalize_address(ip::make_address(view));
122 if (const auto kind = from_ranges(addr); kind != WAN) {
123 return kind;
124 }
125 // Only an address outside the fixed ranges pays for listing the interfaces.
126 // A client on the home network over an IPv6 global address is local: Hestia
127 // RS streams to it as LAN, and so should the host.
128 const auto links = interface_addresses();
129 return on_link(to_raw_address(addr), links) ? LAN : WAN;
130 }
131
132 std::vector<interface_address_t> interface_addresses() {
133 std::vector<interface_address_t> result;
134 ifaddrs *list = nullptr;
135 if (getifaddrs(&list) != 0) {
136 return result;
137 }
138 for (auto *entry = list; entry != nullptr; entry = entry->ifa_next) {
139 if ((entry->ifa_flags & IFF_UP) == 0 || (entry->ifa_flags & IFF_LOOPBACK) != 0) {
140 continue;
141 }
142 const auto address = raw_from_sockaddr(entry->ifa_addr);
143 if (!address) {
144 continue;
145 }
146 result.push_back({*address, prefix_from_netmask(entry->ifa_netmask, entry->ifa_addr->sa_family == AF_INET6)});
147 }
148 freeifaddrs(list);
149 return result;
150 }
151
152 std::string_view to_enum_string(net_e net) {
153 switch (net) {
154 case PC:
155 return "pc"sv;
156 case LAN:
157 return "lan"sv;
158 case WAN:
159 return "wan"sv;
160 }
161
162 // avoid warning
163 return "wan"sv;
164 }
165
166 af_e af_from_enum_string(const std::string_view &view) {
167 if (view == "ipv4") {
168 return IPV4;
169 }
170 if (view == "both") {
171 return BOTH;
172 }
173
174 // avoid warning
175 return BOTH;
176 }
177
178 std::string_view af_to_any_address_string(af_e af) {
179 switch (af) {
180 case IPV4:
181 return "0.0.0.0"sv;
182 case BOTH:
183 return "::"sv;
184 }
185
186 // avoid warning
187 return "::"sv;
188 }
189
190 boost::asio::ip::address normalize_address(boost::asio::ip::address address) {
191 // Convert IPv6-mapped IPv4 addresses into regular IPv4 addresses
192 if (address.is_v6()) {
193 auto v6 = address.to_v6();
194 if (v6.is_v4_mapped()) {
195 return boost::asio::ip::make_address_v4(boost::asio::ip::v4_mapped, v6);
196 }
197 }
198
199 return address;
200 }
201
202 std::string addr_to_normalized_string(boost::asio::ip::address address) {
203 return normalize_address(address).to_string();
204 }
205
206 std::string addr_to_url_escaped_string(boost::asio::ip::address address) {
207 address = normalize_address(address);
208 if (address.is_v6()) {
209 std::stringstream ss;
210 ss << '[' << address.to_string() << ']';
211 return ss.str();
212 } else {
213 return address.to_string();
214 }
215 }
216
217 int encryption_mode_for_address(boost::asio::ip::address address) {
218 auto nettype = net::from_address(address.to_string());
219 if (nettype == net::net_e::PC || nettype == net::net_e::LAN) {
220 return config::stream.lan_encryption_mode;
221 } else {
222 return config::stream.wan_encryption_mode;
223 }
224 }
225
226 host_t host_create(af_e af, ENetAddress &addr, std::uint16_t port, boost::system::error_code *error_out) {
227 if (error_out) {
228 error_out->clear();
229 }
230 auto fail = [&](boost::system::error_code ec) {
231 if (error_out) {
232 *error_out = ec;
233 }
234 BOOST_LOG(error) << "Couldn't initialize ENet control host on ["sv
235 << net::af_to_any_address_string(af) << ':' << port << "]: "
236 << ec.message() << " (" << ec.category().name() << ':' << ec.value() << ')';
237 };
238 static std::once_flag enet_init_flag;
239 static int enet_init_result;
240 std::call_once(enet_init_flag, []() {
241 enet_init_result = enet_initialize();
242 });
243 if (enet_init_result != 0) {
244 fail(boost::system::errc::make_error_code(boost::system::errc::io_error));
245 return host_t {};
246 }
247
248 // Build the wildcard address instead of resolving it. enet resolves names
249 // through getaddrinfo with AI_ADDRCONFIG, which refuses to return "::" on a
250 // host whose only IPv6 address is on loopback - the loopback does not count
251 // as a configured address for that flag. enet then reports the failure
252 // through a return value nobody reads, leaving the address zeroed, and the
253 // bind goes out with a length of zero and fails with EINVAL. The result was
254 // a host that could never stream while the wildcard bind it actually needed
255 // would have worked perfectly.
256 //
257 // The wildcard is not a name and has nothing to resolve, so build it.
258 std::memset(&addr, 0, sizeof(addr));
259 if (af == IPV4) {
260 auto *sin = reinterpret_cast<sockaddr_in *>(&addr.address);
261 sin->sin_family = AF_INET;
262 sin->sin_addr.s_addr = htonl(INADDR_ANY);
263 sin->sin_port = htons(port);
264 addr.addressLength = sizeof(sockaddr_in);
265 } else {
266 auto *sin6 = reinterpret_cast<sockaddr_in6 *>(&addr.address);
267 sin6->sin6_family = AF_INET6;
268 sin6->sin6_addr = in6addr_any;
269 sin6->sin6_port = htons(port);
270 addr.addressLength = sizeof(sockaddr_in6);
271 }
272
273 // Maximum of 128 clients, which should be enough for anyone
274 errno = 0;
275 auto host = host_t {enet_host_create(af == IPV4 ? AF_INET : AF_INET6, &addr, 128, 0, 0, 0)};
276 if (!host) {
277 // Snapshot before logging can change the OS error. ENet can also fail
278 // allocating memory, so a null host alone does not prove EADDRINUSE.
279 const int allocation_error = errno;
280 const int socket_error = allocation_error;
281 if (socket_error) {
282 fail({socket_error, boost::system::system_category()});
283 } else if (allocation_error) {
284 fail({allocation_error, boost::system::generic_category()});
285 } else {
286 fail(boost::system::errc::make_error_code(boost::system::errc::io_error));
287 }
288 return host;
289 }
290
291 // The bundled ENet creates sockets without close-on-exec. A helper
292 // launched during streaming must not keep our control port alive after
293 // the last session releases its ENet host.
294 boost::system::error_code ec;
295 if (!prevent_socket_inheritance(host->socket, ec)) {
296 fail(ec);
297 return host_t {};
298 }
299
300 // Enable opportunistic QoS tagging (automatically disables if the network appears to drop tagged packets)
301 enet_socket_set_option(host->socket, ENET_SOCKOPT_QOS, 1);
302
303 return host;
304 }
305
306 bool prevent_socket_inheritance(boost::asio::ip::udp::socket::native_handle_type socket, boost::system::error_code &error) {
307 error.clear();
308 const int flags = fcntl(socket, F_GETFD);
309 if (flags == -1 || fcntl(socket, F_SETFD, flags | FD_CLOEXEC) == -1) {
310 error = {errno, boost::system::system_category()};
311 return false;
312 }
313 return true;
314 }
315
316 bool udp_port_available(af_e af, std::uint16_t port) {
317 boost::asio::io_context io_context;
318 boost::system::error_code ec;
319
320 const auto protocol = af == IPV4 ? boost::asio::ip::udp::v4() : boost::asio::ip::udp::v6();
321 boost::asio::ip::udp::socket probe {io_context};
322 probe.open(protocol, ec);
323 if (ec) {
324 // The family itself is unavailable, which is a different problem from a
325 // taken port and not one this answer should claim.
326 return true;
327 }
328
329 const auto any = af == IPV4 ?
330 boost::asio::ip::udp::endpoint {boost::asio::ip::udp::v4(), port} :
331 boost::asio::ip::udp::endpoint {boost::asio::ip::udp::v6(), port};
332 probe.bind(any, ec);
333 const bool available = !ec;
334 probe.close(ec);
335 return available;
336 }
337
338 void free_host(ENetHost *host) {
339 std::for_each(host->peers, host->peers + host->peerCount, [](ENetPeer &peer_ref) {
340 ENetPeer *peer = &peer_ref;
341
342 if (peer) {
343 enet_peer_disconnect_now(peer, 0);
344 }
345 });
346
347 enet_host_destroy(host);
348 }
349
350 std::uint16_t map_port(int port) {
351 // calculate the port from the config port
352 auto mapped_port = (std::uint16_t) ((int) config::sunshine.port + port);
353
354 // Ensure port is in the range of 1024-65535
355 if (mapped_port < 1024 || mapped_port > 65535) {
356 BOOST_LOG(warning) << "Port out of range: "sv << mapped_port;
357 }
358
359 return mapped_port;
360 }
361
367 std::string mdns_instance_name(const std::string_view &hostname) {
368 // Start with the unmodified hostname
369 std::string instancename {hostname.data(), hostname.size()};
370
371 // Truncate to 63 characters per RFC 6763 section 7.2.
372 if (instancename.size() > 63) {
373 instancename.resize(63);
374 }
375
376 for (auto i = 0; i < instancename.size(); i++) {
377 // Replace any spaces with dashes
378 if (instancename[i] == ' ') {
379 instancename[i] = '-';
380 } else if (!std::isalnum(instancename[i]) && instancename[i] != '-') {
381 // Stop at the first invalid character
382 instancename.resize(i);
383 break;
384 }
385 }
386
387 return !instancename.empty() ? instancename : "Hermes";
388 }
389} // namespace net
Declarations for the configuration of Sunshine.
Declarations for logging related functions.
raw_address_t to_raw_address(const boost::asio::ip::address &address)
The raw bytes of an address, IPv4-mapped IPv6 as IPv4, the IPv6 scope kept.
Definition network.cpp:92
std::uint16_t map_port(int port)
Map a specified port based on the base port.
Definition network.cpp:350
std::string addr_to_url_escaped_string(boost::asio::ip::address address)
Get the given address in a normalized form for the host portion of a URL.
Definition network.cpp:206
bool udp_port_available(af_e af, std::uint16_t port)
Whether a UDP port can still be bound on this host.
Definition network.cpp:316
net_e from_address(const std::string_view &view, std::span< const interface_address_t > links)
Classify an address against the given interface subnets.
Definition network.cpp:112
std::string_view af_to_any_address_string(af_e af)
Get the wildcard binding address for a given address family.
Definition network.cpp:178
std::string addr_to_normalized_string(boost::asio::ip::address address)
Get the given address in normalized string form.
Definition network.cpp:202
std::vector< interface_address_t > interface_addresses()
The addresses of every interface that is up, loopback aside, with their prefix lengths.
Definition network.cpp:132
std::string mdns_instance_name(const std::string_view &hostname)
Returns a string for use as the instance name for mDNS.
Definition network.cpp:367
boost::asio::ip::address normalize_address(boost::asio::ip::address address)
Convert an address to a normalized form.
Definition network.cpp:190
af_e af_from_enum_string(const std::string_view &view)
Get the address family enum value from a string.
Definition network.cpp:166
int encryption_mode_for_address(boost::asio::ip::address address)
Get the encryption mode for the given remote endpoint address.
Definition network.cpp:217
net_e from_address_ranges(const std::string_view &view)
Classify an address by the fixed ranges alone.
Definition network.cpp:108
Declarations for networking related functions.
af_e
Definition network.h:45
@ IPV4
IPv4 only.
Definition network.h:46
@ BOTH
IPv4 and IPv6.
Definition network.h:47
net_e
Definition network.h:39
@ PC
PC.
Definition network.h:40
@ WAN
WAN.
Definition network.h:42
@ LAN
LAN.
Definition network.h:41
An IP address as the bytes the network carries it in.
bool v6
IPv6 when set, IPv4 otherwise.
std::uint32_t scope
IPv6 scope (interface index), 0 when it has none.
std::array< std::uint8_t, 16 > bytes
Network byte order; IPv4 uses the first four.
Declarations for utility functions.