Hermes 0.7.0
Linux game streaming host
Loading...
Searching...
No Matches
upnp.cpp
Go to the documentation of this file.
1
5// standard includes
6#include <array>
7#include <bit>
8#include <chrono>
9#include <filesystem>
10#include <fstream>
11#include <set>
12#include <sstream>
13
14// Synchronize the recovery journal before installing permanent router rules.
15#include <fcntl.h>
16 #include <unistd.h>
17#include <stddef.h> // workaround for type_t error in miniupnpc 2.3.3, see https://github.com/miniupnp/miniupnp/commit/e263ab6f56c382e10fed31347ec68095d691a0e8
18
19// lib includes
20#include <miniupnpc/miniupnpc.h>
21#include <miniupnpc/upnpcommands.h>
22
23// local includes
24#include "config.h"
25#include "confighttp.h"
26#include "globals.h"
27#include "logging.h"
28#include "network.h"
29#include "nvhttp.h"
30#include "rtsp.h"
31#include "stream.h"
32#include "upnp.h"
33#include "upnp_mapping.h"
34#include "utility.h"
35
36using namespace std::literals;
37
38namespace upnp {
39
43 struct mapping_t {
44 struct {
45 std::string wan;
46 std::string lan;
47 std::string proto;
48 } port;
49
50 std::string description;
51 };
52
56 struct igd_t {
57 std::string host;
59 IGDdatas data {};
60 };
61
67 static void add_other_igds(const device_t &device, std::vector<igd_t> &igds) {
68 std::set<std::string, std::less<>> seen {igds.front().urls->rootdescURL};
69 for (auto dev = device.get(); dev != nullptr; dev = dev->pNext) {
70 if (!seen.emplace(dev->descURL).second) {
71 continue;
72 }
73
74 igd_t igd;
75 std::array<char, INET6_ADDRESS_STRLEN> lan_addr {};
76 if (UPNP_GetIGDFromUrl(dev->descURL, &igd.urls.el, &igd.data, lan_addr.data(), (int) lan_addr.size()) != 1 || igd.urls->controlURL == nullptr || igd.urls->controlURL[0] == 0 || igd.data.first.servicetype[0] == 0) {
77 continue;
78 }
79
80 igd.host = url_host(dev->descURL);
81 igds.emplace_back(std::move(igd));
82 }
83 }
84
90 static std::string external_address(const igd_t &igd) {
91 std::array<char, INET6_ADDRESS_STRLEN> addr {};
92 if (UPNP_GetExternalIPAddress(igd.urls->controlURL, igd.data.first.servicetype, addr.data()) != UPNPCOMMAND_SUCCESS) {
93 return {};
94 }
95
96 return addr.data();
97 }
98
99 static std::string_view status_string(igd_status_e status) {
100 using enum igd_status_e;
101
102 switch (status) {
103 case none:
104 return "No IGD device found"sv;
105 case connected:
106 return "Valid IGD device found"sv;
107#if (MINIUPNPC_API_VERSION >= 18)
108 case private_ip:
109 return "Valid IGD device found, but it has a private IP address"sv;
110#endif
111 case disconnected:
112 return "Valid IGD device found, but it isn't connected"sv;
113 case unknown_device:
114 return "A UPnP device has been found, but it wasn't recognized as an IGD"sv;
115 }
116
117 return "Unknown status"sv;
118 }
119
124 igd_status_e UPNP_GetValidIGDStatus(device_t &device, urls_t *urls, IGDdatas *data, std::array<char, INET6_ADDRESS_STRLEN> &lan_addr) {
125#if (MINIUPNPC_API_VERSION >= 18)
126 auto status = UPNP_GetValidIGD(device.get(), &urls->el, data, lan_addr.data(), (int) lan_addr.size(), nullptr, 0);
127#else
128 auto status = UPNP_GetValidIGD(device.get(), &urls->el, data, lan_addr.data(), (int) lan_addr.size());
129#endif
130 return static_cast<igd_status_e>(status);
131 }
132
134 using enum igd_status_e;
135
136 switch (status) {
137 case connected:
138#if (MINIUPNPC_API_VERSION >= 18)
139 case private_ip:
140#endif
141 case disconnected:
142 return true;
143 default:
144 return false;
145 }
146 }
147
153 static bool is_private_ipv4(std::string_view address) {
154 boost::system::error_code ec;
155 const auto addr = boost::asio::ip::make_address_v4(std::string {address}, ec);
156 // The fixed ranges only: whether this host shares a subnet with the address
157 // says nothing about whether the address itself is private.
158 return !ec && net::from_address_ranges(addr.to_string()) == net::LAN;
159 }
160
161 int shared_prefix_length(std::string_view a, std::string_view b) {
162 boost::system::error_code ec_a;
163 boost::system::error_code ec_b;
164 const auto addr_a = boost::asio::ip::make_address_v4(std::string {a}, ec_a);
165 const auto addr_b = boost::asio::ip::make_address_v4(std::string {b}, ec_b);
166 if (ec_a || ec_b) {
167 return -1;
168 }
169
170 return std::countl_zero(addr_a.to_uint() ^ addr_b.to_uint());
171 }
172
173 std::string url_host(std::string_view url) {
174 if (const auto scheme = url.find("://"sv); scheme != std::string_view::npos) {
175 url.remove_prefix(scheme + 3);
176 }
177
178 if (url.starts_with('[')) {
179 return std::string {url.substr(1, url.find(']') - 1)};
180 }
181
182 return std::string {url.substr(0, url.find_first_of(":/"sv))};
183 }
184
185 std::size_t select_inner_igd(const std::vector<std::string> &igd_hosts, std::string_view lan_addr) {
186 std::size_t best = 0;
187 int best_bits = -1;
188 for (std::size_t i = 0; i < igd_hosts.size(); ++i) {
189 if (const auto bits = shared_prefix_length(igd_hosts[i], lan_addr); bits > best_bits) {
190 best = i;
191 best_bits = bits;
192 }
193 }
194
195 return best;
196 }
197
198 std::optional<std::size_t> select_outer_igd(const std::vector<std::string> &igd_hosts, std::size_t inner, std::string_view inner_external_addr) {
199 // A public external address means the inner gateway is the edge router: there is nothing in front of it to map.
200 if (!is_private_ipv4(inner_external_addr)) {
201 return std::nullopt;
202 }
203
204 // The outer router sits in the same network as the inner gateway's external address.
205 constexpr int min_shared_bits = 16;
206 std::optional<std::size_t> best;
207 int best_bits = min_shared_bits - 1;
208 bool ambiguous = false;
209 for (std::size_t i = 0; i < igd_hosts.size(); ++i) {
210 if (i == inner) {
211 continue;
212 }
213
214 const auto bits = shared_prefix_length(igd_hosts[i], inner_external_addr);
215 if (bits > best_bits) {
216 best = i;
217 best_bits = bits;
218 ambiguous = false;
219 } else if (best.has_value() && bits == best_bits) {
220 // Two equally plausible gateways: never forward public traffic to an
221 // arbitrary device when the IPv4-prefix heuristic cannot distinguish them.
222 ambiguous = true;
223 }
224 }
225
226 return ambiguous ? std::nullopt : best;
227 }
228
232 class deinit_t: public platf::deinit_t {
233 public:
234 deinit_t() {
235 auto rtsp = std::to_string(net::map_port(rtsp_stream::RTSP_SETUP_PORT));
236 auto video = std::to_string(net::map_port(stream::VIDEO_STREAM_PORT));
237 auto audio = std::to_string(net::map_port(stream::AUDIO_STREAM_PORT));
238 auto control = std::to_string(net::map_port(stream::CONTROL_PORT));
239 auto gs_http = std::to_string(net::map_port(nvhttp::PORT_HTTP));
240 auto gs_https = std::to_string(net::map_port(nvhttp::PORT_HTTPS));
241 auto wm_http = std::to_string(net::map_port(confighttp::PORT_HTTPS));
242
243 mappings.assign({
244 {{rtsp, rtsp, "TCP"s}, "Hermes - RTSP"s},
245 {{video, video, "UDP"s}, "Hermes - Video"s},
246 {{audio, audio, "UDP"s}, "Hermes - Audio"s},
247 {{control, control, "UDP"s}, "Hermes - Control"s},
248 {{gs_http, gs_http, "TCP"s}, "Hermes - Client HTTP"s},
249 {{gs_https, gs_https, "TCP"s}, "Hermes - Client HTTPS"s},
250 });
251
252 // Only map port for the Web Manager if it is configured to accept connection from WAN
253 if (net::from_enum_string(config::nvhttp.origin_web_ui_allowed) > net::LAN) {
254 mappings.emplace_back(mapping_t {{wm_http, wm_http, "TCP"s}, "Hermes - Web UI"s});
255 }
256
257 // Start the mapping thread
258 upnp_thread = std::jthread {&deinit_t::upnp_thread_proc, this};
259 }
260
265 upnp_thread.join();
266 }
267
274 int err;
275 device_t device {upnpDiscover(2000, nullptr, nullptr, 0, IPv6, 2, &err)};
276 if (!device || err) {
277 BOOST_LOG(debug) << "Couldn't discover any IPv6 UPNP devices"sv;
278 return false;
279 }
280
281 IGDdatas data;
282 urls_t urls;
283 std::array<char, INET6_ADDRESS_STRLEN> lan_addr;
284 auto status = upnp::UPNP_GetValidIGDStatus(device, &urls, &data, lan_addr);
285 if (!is_valid_igd(status)) {
286 BOOST_LOG(debug) << "No valid IPv6 IGD: "sv << status_string(status);
287 return false;
288 }
289
290 if (data.IPv6FC.controlurl[0] != 0) {
291 int firewallEnabled;
292 int pinholeAllowed;
293
294 // Check if this firewall supports IPv6 pinholes
295 err = UPNP_GetFirewallStatus(urls->controlURL_6FC, data.IPv6FC.servicetype, &firewallEnabled, &pinholeAllowed);
296 if (err == UPNPCOMMAND_SUCCESS) {
297 BOOST_LOG(debug) << "UPnP IPv6 firewall control available. Firewall is "sv
298 << (firewallEnabled ? "enabled"sv : "disabled"sv)
299 << ", pinhole is "sv
300 << (pinholeAllowed ? "allowed"sv : "disallowed"sv);
301
302 if (pinholeAllowed) {
303 // Create pinholes for each port
304 auto mapping_period = std::to_string(PORT_MAPPING_LIFETIME.count());
305 auto shutdown_event = mail::man->event<bool>(mail::shutdown);
306
307 for (auto it = std::begin(mappings); it != std::end(mappings) && !shutdown_event->peek(); ++it) {
308 auto mapping = *it;
309 std::array<char, 8> uniqueId;
310
311 // Open a pinhole for the LAN port, since there will be no WAN->LAN port mapping on IPv6
312 err = UPNP_AddPinhole(urls->controlURL_6FC, data.IPv6FC.servicetype, "", "0", lan_addr.data(), mapping.port.lan.c_str(), mapping.port.proto.c_str(), mapping_period.c_str(), uniqueId.data());
313 if (err == UPNPCOMMAND_SUCCESS) {
314 BOOST_LOG(debug) << "Successfully created pinhole for "sv << mapping.port.proto << ' ' << mapping.port.lan;
315 } else {
316 BOOST_LOG(debug) << "Failed to create pinhole for "sv << mapping.port.proto << ' ' << mapping.port.lan << ": "sv << err;
317 }
318 }
319
320 return err == 0;
321 } else {
322 BOOST_LOG(debug) << "IPv6 pinholes are not allowed by the IGD"sv;
323 return false;
324 }
325 } else {
326 BOOST_LOG(debug) << "Failed to get IPv6 firewall status: "sv << err;
327 return false;
328 }
329 } else {
330 BOOST_LOG(debug) << "IPv6 Firewall Control is not supported by the IGD"sv;
331 return false;
332 }
333 }
334
341 bool journal_mapping(const owned_mapping_t &mapping, bool added) {
342 const auto event = mapping_journal_event(mapping, added);
343 if (event.empty()) {
344 BOOST_LOG(warning) << "Invalid UPnP recovery identity; refusing an unrecorded permanent mapping"sv;
345 return false;
346 }
347 const auto path = journal_path();
348 std::ofstream out {path, std::ios::app};
349 out << event;
350 out.flush();
351 out.close();
352 if (!out) {
353 BOOST_LOG(warning) << "Could not update UPnP recovery journal; refusing an unrecorded permanent mapping"sv;
354 return false;
355 }
356
357 // Closing an ofstream does not promise that the record survives a power failure.
358 // Flush file contents to stable storage before asking the router for a permanent lease.
359 const int fd = ::open(path.c_str(), O_RDONLY);
360 if (fd < 0) {
361 BOOST_LOG(warning) << "Could not reopen UPnP recovery journal for syncing"sv;
362 return false;
363 }
364 const bool durable = ::fsync(fd) == 0;
365 ::close(fd);
366 if (!durable) {
367 BOOST_LOG(warning) << "Could not sync UPnP recovery journal; refusing an unrecorded permanent mapping"sv;
368 return false;
369 }
370 return true;
371 }
372
378 bool remember_mapping(owned_mapping_t mapping, bool recovery_intent_already_written = false) {
379 auto found = std::find(owned_mappings.begin(), owned_mappings.end(), mapping);
380 if (mapping.permanent && !recovery_intent_already_written && (found == owned_mappings.end() || !found->permanent) && !journal_mapping(mapping, true)) {
381 return false;
382 }
383 if (found == owned_mappings.end()) {
384 owned_mappings.push_back(std::move(mapping));
385 } else {
386 found->generation = generation;
387 found->permanent = found->permanent || mapping.permanent;
388 }
389 return true;
390 }
391
393 static mapping_lookup_t lookup_mapping(const owned_mapping_t &wanted, bool recorded) {
394 const auto specific = [&]() {
395 std::array<char, 16> client {}, lease {};
396 std::array<char, 6> port {};
397 std::array<char, 80> description {};
398 std::array<char, 4> enabled {};
399 const auto result = UPNP_GetSpecificPortMappingEntry(wanted.control_url.c_str(), wanted.service.c_str(), wanted.external_port.c_str(), wanted.protocol.c_str(), nullptr, client.data(), port.data(), description.data(), enabled.data(), lease.data());
400 return mapping_reply_t {result, client.data(), port.data(), description.data(), enabled.data(), lease.data()};
401 };
402 auto deadline = std::chrono::steady_clock::time_point {};
403 const auto generic = [&](std::size_t index) {
404 if (index == 0) {
405 deadline = std::chrono::steady_clock::now() + 5s;
406 } else if (std::chrono::steady_clock::now() >= deadline) {
407 return mapping_reply_t {};
408 }
409 std::array<char, 16> client {}, lease {};
410 std::array<char, 6> port {}, external_port {};
411 std::array<char, 80> description {};
412 std::array<char, 4> enabled {}, protocol {};
413 std::array<char, 64> remote_host {};
414 const auto number = std::to_string(index);
415 const auto result = UPNP_GetGenericPortMappingEntry(wanted.control_url.c_str(), wanted.service.c_str(), number.c_str(), external_port.data(), client.data(), port.data(), protocol.data(), description.data(), enabled.data(), remote_host.data(), lease.data());
416 return mapping_reply_t {result, client.data(), port.data(), description.data(), enabled.data(), lease.data(), external_port.data(), protocol.data(), remote_host.data()};
417 };
418 return verify_mapping_lookup(wanted, recorded, specific, generic);
419 }
420
429 bool map_upnp_port(const IGDdatas &data, const urls_t &urls, const std::string &lan_addr, const mapping_t &mapping) {
430 owned_mapping_t wanted {urls->controlURL, data.first.servicetype, lan_addr, mapping.port.wan, mapping.port.lan, mapping.port.proto, mapping.description, false, generation};
431 // A matching description alone is not proof that Hermes created the rule.
432 // Only mappings already recorded by this process (or recovered from its journal)
433 // are eligible for renewal and deletion.
434 auto recorded = std::find(owned_mappings.begin(), owned_mappings.end(), wanted);
435 const bool previously_owned = recorded != owned_mappings.end();
436 if (previously_owned) {
437 // A failed refresh must not forget a rule that was successfully added earlier.
438 recorded->generation = generation;
439 }
440 const auto lookup = lookup_mapping(wanted, previously_owned);
441 switch (lookup.state) {
443 BOOST_LOG(warning) << "UPnP port "sv << mapping.port.wan << " already forwards elsewhere; leaving it unchanged"sv;
444 return false;
446 // A manual rule already does what we need. Never renew or remove it.
447 return lookup.enabled == "1"sv;
449 BOOST_LOG(warning) << "UPnP mapping ownership could not be verified for "sv << wanted.control_url << ' ' << wanted.protocol << ' ' << wanted.external_port;
450 return false;
452 if (!may_manage_mapping(mapping_state_e::ours, previously_owned)) {
453 BOOST_LOG(debug) << "UPnP mapping resembles Hermes but has no ownership record; preserving it"sv;
454 return lookup.enabled == "1"sv;
455 }
456 wanted.permanent = lookup.lease == "0"sv;
457 if (!remember_mapping(wanted)) {
458 return false;
459 }
460 if (wanted.permanent) {
461 return lookup.enabled == "1"sv;
462 }
463 // Some IGDs accept repeated adds without resetting the lease. Only replace our own expiring rule.
464 if (lease_needs_refresh(lookup.lease)) {
465 const auto removed = UPNP_DeletePortMapping(urls->controlURL, data.first.servicetype, mapping.port.wan.c_str(), mapping.port.proto.c_str(), nullptr);
466 if (removed != UPNPCOMMAND_SUCCESS && removed != 714) {
467 return false;
468 }
469 }
470 break;
472 break;
473 }
474 auto shutdown_event = mail::man->event<bool>(mail::shutdown);
475 if (shutdown_event->peek()) {
476 return false;
477 }
478 const auto period = std::to_string(PORT_MAPPING_LIFETIME.count());
479 auto err = UPNP_AddPortMapping(urls->controlURL, data.first.servicetype, mapping.port.wan.c_str(), mapping.port.lan.c_str(), lan_addr.c_str(), mapping.description.c_str(), mapping.port.proto.c_str(), nullptr, period.c_str());
480 bool permanent_intent_written = false;
481 if (err == 725 && !shutdown_event->peek()) { // OnlyPermanentLeasesSupported
482 wanted.permanent = true;
483 // Write and sync recovery intent BEFORE the permanent AddPortMapping.
484 // Do not claim ownership in memory until the router actually accepts the rule.
485 if (!journal_mapping(wanted, true)) {
486 return false;
487 }
488 permanent_intent_written = true;
489 err = UPNP_AddPortMapping(urls->controlURL, data.first.servicetype, mapping.port.wan.c_str(), mapping.port.lan.c_str(), lan_addr.c_str(), mapping.description.c_str(), mapping.port.proto.c_str(), nullptr, "0");
490 }
491 if (err == 718) {
492 // A conflict is not evidence that the new rule was installed. Clear any
493 // provisional intent rather than adopting a pre-existing manual rule.
494 if (permanent_intent_written && !journal_mapping(wanted, false)) {
495 BOOST_LOG(warning) << "Could not retire unused UPnP recovery intent"sv;
496 }
497 const auto conflict = lookup_mapping(wanted, previously_owned);
498 if (conflict.enabled == "1"sv) {
499 if (conflict.state == mapping_state_e::existing || (conflict.state == mapping_state_e::ours && !previously_owned)) {
500 return true; // The destination is usable, but that mapping is not ours to manage.
501 }
502 if (may_manage_mapping(conflict.state, previously_owned)) {
503 wanted.permanent = conflict.lease == "0"sv;
504 return remember_mapping(std::move(wanted));
505 }
506 }
507 }
508 if (err != UPNPCOMMAND_SUCCESS) {
509 // If the response was lost, the permanent mapping might exist despite
510 // the reported error. Keep the on-disk intent for crash recovery.
511 BOOST_LOG(warning) << "Failed to map "sv << mapping.port.proto << ' ' << mapping.port.wan << ": "sv << err;
512 return false;
513 }
514 return remember_mapping(std::move(wanted), permanent_intent_written);
515 }
516
521 void unmap_owned_ports(bool stale_only = false) {
522 std::erase_if(owned_mappings, [this, stale_only](const owned_mapping_t &owned) {
523 if (stale_only && owned.generation == generation) {
524 return false;
525 }
526 const auto state = lookup_mapping(owned, true).state;
527 if (state == mapping_state_e::unknown) {
528 BOOST_LOG(warning) << "Could not check UPnP rule for cleanup: "sv << owned.control_url << ' ' << owned.external_port;
529 return false;
530 }
531 if (state == mapping_state_e::existing || state == mapping_state_e::conflict) {
532 // Another rule now occupies this port. Do not delete it. If our old
533 // rule was permanent, keep the recovery record for later inspection
534 // instead of silently declaring the potentially exposed port cleaned.
535 if (should_retain_recovery_record(state, owned.permanent)) {
536 BOOST_LOG(warning) << "UPnP permanent rule no longer matches its recovery record: "
537 << owned.control_url << ' ' << owned.external_port << "; retaining journal entry"sv;
538 return false;
539 }
540 return true;
541 }
542 if (state == mapping_state_e::ours) {
543 const auto removed = UPNP_DeletePortMapping(owned.control_url.c_str(), owned.service.c_str(), owned.external_port.c_str(), owned.protocol.c_str(), nullptr);
544 if (removed != UPNPCOMMAND_SUCCESS && removed != 714) {
545 BOOST_LOG(warning) << "Failed to remove UPnP rule: "sv << removed;
546 return false;
547 }
548 }
549 // Missing or successfully removed rules can be forgotten.
550 return !owned.permanent || journal_mapping(owned, false);
551 });
552 if (std::none_of(owned_mappings.begin(), owned_mappings.end(), [](const auto &mapping) {
553 return mapping.permanent;
554 })) {
555 std::error_code ec;
556 std::filesystem::remove(journal_path(), ec);
557 }
558 }
559
566 bool map_all_upnp_ports(const igd_t &igd, const std::string &addr) {
567 auto shutdown_event = mail::man->event<bool>(mail::shutdown);
568 bool complete = true;
569 for (const auto &mapping : mappings) {
570 if (shutdown_event->peek()) {
571 return false;
572 }
573 complete = map_upnp_port(igd.data, igd.urls, addr, mapping) && complete;
574 }
575 return complete;
576 }
577
588 static std::size_t find_gateway(const device_t &device, std::vector<igd_t> &igds, std::vector<std::string> &igd_hosts, const std::string &lan_addr) {
589 igds.front().host = url_host(igds.front().urls->rootdescURL);
590 add_other_igds(device, igds);
591 for (const auto &igd : igds) {
592 igd_hosts.push_back(igd.host);
593 }
594
595 const auto inner = select_inner_igd(igd_hosts, lan_addr);
596 if (inner != 0) {
597 BOOST_LOG(debug) << "Using the IGD on this host's network instead: "sv << igds[inner].urls->rootdescURL;
598 }
599
600 return inner;
601 }
602
612 void map_outer_upnp_ports(std::vector<igd_t> &igds, const std::vector<std::string> &igd_hosts, std::size_t inner, bool first_pass) {
613 const auto external_addr = external_address(igds[inner]);
614 const auto outer = select_outer_igd(igd_hosts, inner, external_addr);
615 if (!outer.has_value()) {
616 // A missing reply is not proof that a working outer mapping is obsolete.
617 for (auto &owned : owned_mappings) {
618 if (external_addr.empty() || (is_private_ipv4(external_addr) && owned.target == external_addr)) {
619 owned.generation = generation;
620 }
621 }
622 if (is_private_ipv4(external_addr) && !warned_no_outer_igd) {
623 BOOST_LOG(warning) << "The IGD's external address "sv << external_addr
624 << " is private and no UPnP IGD answered in front of it: ports must be forwarded on the outer router"sv;
625 warned_no_outer_igd = true;
626 }
627 return;
628 }
629
630 auto &outer_igd = igds[*outer];
631 const bool complete = map_all_upnp_ports(outer_igd, external_addr);
632 if (complete && (first_pass || mapped_outer_host != outer_igd.host)) {
633 BOOST_LOG(info) << "Completed UPnP port mappings to "sv << external_addr << " via "sv << outer_igd.urls->rootdescURL;
634 }
635
636 if (complete) {
637 mapped_outer_host = outer_igd.host;
638 }
639 warned_no_outer_igd = false;
640 }
641
646 auto shutdown_event = mail::man->event<bool>(mail::shutdown);
647 std::ifstream journal {journal_path()};
648 std::error_code journal_error;
649 const bool journal_exists = std::filesystem::exists(journal_path(), journal_error);
650 if (journal_error || (journal_exists && !journal.is_open())) {
651 BOOST_LOG(error) << "Could not read UPnP recovery journal; leaving it intact and skipping new mappings"sv;
652 return;
653 }
654 const std::string contents {(std::istreambuf_iterator<char>(journal)), std::istreambuf_iterator<char>()};
655 if (journal.bad()) {
656 BOOST_LOG(error) << "Could not finish reading UPnP recovery journal; leaving it intact"sv;
657 return;
658 }
659 journal.close();
662 if (!config::sunshine.flags[config::flag::UPNP]) {
663 return;
664 }
665 bool mapped = false;
666 auto address_family = net::af_from_enum_string(config::sunshine.address_family);
667
668 // Refresh UPnP rules every few minutes. They can be lost if the router reboots,
669 // WAN IP address changes, or various other conditions.
670 do {
671 int err = 0;
672 device_t device {upnpDiscover(2000, nullptr, nullptr, 0, IPv4, 2, &err)};
673 if (!device || err) {
674 BOOST_LOG(warning) << "Couldn't discover any IPv4 UPNP devices"sv;
675 mapped = false;
676 continue;
677 }
678
679 for (auto dev = device.get(); dev != nullptr; dev = dev->pNext) {
680 BOOST_LOG(debug) << "Found device: "sv << dev->descURL;
681 }
682
683 std::array<char, INET6_ADDRESS_STRLEN> lan_addr;
684
685 std::vector<igd_t> igds(1);
686 auto status = upnp::UPNP_GetValidIGDStatus(device, &igds.front().urls, &igds.front().data, lan_addr);
687 if (!is_valid_igd(status)) {
688 BOOST_LOG(error) << status_string(status);
689 mapped = false;
690 continue;
691 }
692
693 std::string lan_addr_str {lan_addr.data()};
694
695 BOOST_LOG(debug) << "Found valid IGD device: "sv << igds.front().urls->rootdescURL;
696
697 std::vector<std::string> igd_hosts;
698 const auto inner = find_gateway(device, igds, igd_hosts, lan_addr_str);
699 ++generation;
700 const bool complete = map_all_upnp_ports(igds[inner], lan_addr_str);
701
702 if (!mapped && complete) {
703 BOOST_LOG(info) << "Completed UPnP port mappings to "sv << lan_addr_str << " via "sv << igds[inner].urls->rootdescURL;
704 }
705
706 map_outer_upnp_ports(igds, igd_hosts, inner, !mapped);
707 unmap_owned_ports(true);
708
709 // If we are listening on IPv6 and the IGD has an IPv6 firewall enabled, try to create IPv6 firewall pinholes
710 if (address_family == net::af_e::BOTH) {
711 if (create_ipv6_pinholes() && !mapped) {
712 // Only log the first time through
713 BOOST_LOG(info) << "Successfully opened IPv6 pinholes on the IGD"sv;
714 }
715 }
716
717 mapped = complete;
718 } while (!shutdown_event->view(REFRESH_INTERVAL));
719
720 // Discovery failures and gateway changes never discard ownership records.
722 }
723
728 static std::filesystem::path journal_path() {
729 return platf::appdata() / "upnp_mappings.journal";
730 }
731
732 std::vector<mapping_t> mappings;
733 std::vector<owned_mapping_t> owned_mappings;
734 std::string mapped_outer_host;
735 std::size_t generation = 0;
736 bool warned_no_outer_igd = false;
737 std::jthread upnp_thread;
738 };
739
743 std::unique_ptr<platf::deinit_t> start() {
744 std::error_code ec;
745 if (!config::sunshine.flags[config::flag::UPNP] && !std::filesystem::exists(platf::appdata() / "upnp_mappings.journal", ec)) {
746 return nullptr;
747 }
748
749 return std::make_unique<deinit_t>();
750 }
751} // namespace upnp
std::vector< mapping_t > mappings
Ports requested by Hermes.
Definition upnp.cpp:732
void upnp_thread_proc()
Maintains UPnP port forwarding rules.
Definition upnp.cpp:645
void unmap_owned_ports(bool stale_only=false)
Remove only recorded rules whose current destination, port and description still match.
Definition upnp.cpp:521
std::size_t generation
Current successful discovery pass.
Definition upnp.cpp:735
static std::filesystem::path journal_path()
Locate the append-only recovery journal used even when UPnP is disabled at the next start.
Definition upnp.cpp:728
bool map_upnp_port(const IGDdatas &data, const urls_t &urls, const std::string &lan_addr, const mapping_t &mapping)
Maps one port without deleting or adopting a rule belonging to another application.
Definition upnp.cpp:429
static mapping_lookup_t lookup_mapping(const owned_mapping_t &wanted, bool recorded)
Query one rule, corroborating a broken zero-port response only for recorded mappings.
Definition upnp.cpp:393
void map_outer_upnp_ports(std::vector< igd_t > &igds, const std::vector< std::string > &igd_hosts, std::size_t inner, bool first_pass)
Behind double NAT, map the ports on the IGD in front of the gateway.
Definition upnp.cpp:612
std::string mapped_outer_host
Last outer gateway logged as mapped.
Definition upnp.cpp:734
std::vector< owned_mapping_t > owned_mappings
Rules retained independently of discovery results.
Definition upnp.cpp:733
bool map_all_upnp_ports(const igd_t &igd, const std::string &addr)
Maps every port on an IGD, stopping early on shutdown.
Definition upnp.cpp:566
bool journal_mapping(const owned_mapping_t &mapping, bool added)
Append recovery intent before creating a permanent rule, or completion after removing it.
Definition upnp.cpp:341
bool remember_mapping(owned_mapping_t mapping, bool recovery_intent_already_written=false)
Remember a rule independently of discovery and persist permanent-rule intent before adding it.
Definition upnp.cpp:378
bool create_ipv6_pinholes()
Opens pinholes for IPv6 traffic if the IGD is capable.
Definition upnp.cpp:273
static std::size_t find_gateway(const device_t &device, std::vector< igd_t > &igds, std::vector< std::string > &igd_hosts, const std::string &lan_addr)
Find the IGD of the network this host is attached to.
Definition upnp.cpp:588
~deinit_t()
Destroy the UPnP deinitializer.
Definition upnp.cpp:264
std::jthread upnp_thread
Worker thread that refreshes mappings until shutdown.
Definition upnp.cpp:737
bool warned_no_outer_igd
Whether the missing outer IGD has already been reported.
Definition upnp.cpp:736
Owning wrapper for MiniUPnPc URLs.
Definition upnp.h:37
std::filesystem::path appdata()
Performs migration if necessary, then returns the appdata directory.
Definition misc.cpp:301
Declarations for the configuration of Sunshine.
@ UPNP
Try Universal Plug 'n Play.
Definition config.h:211
Declarations for the Web UI Config HTTP server.
Declarations for globally accessible variables and functions.
Declarations for logging related functions.
safe::mail_t man
A process-wide communication mechanism.
Definition globals.cpp:8
constexpr auto PORT_HTTPS
The HTTPS port, as a difference from the config port.
Definition nvhttp.h:54
constexpr auto PORT_HTTP
The HTTP port, as a difference from the config port.
Definition nvhttp.h:49
UPnP port mapping.
Definition upnp.cpp:38
std::optional< std::size_t > select_outer_igd(const std::vector< std::string > &igd_hosts, std::size_t inner, std::string_view inner_external_addr)
Select the IGD in front of the inner gateway when Hermes is behind two routers (double NAT).
Definition upnp.cpp:198
igd_status_e
Result codes returned by the installed MiniUPnPc library.
Definition upnp.h:46
@ connected
A connected IGD was found.
Definition upnp.h:48
@ none
No IGD was found.
Definition upnp.h:47
@ disconnected
A disconnected IGD was found.
Definition upnp.h:52
@ unknown_device
The device was not recognized as an IGD.
Definition upnp.h:53
constexpr auto REFRESH_INTERVAL
Interval between mapping refresh passes.
Definition upnp.h:28
std::string url_host(std::string_view url)
Extract the host from a URL such as http://192.168.1.1:1900/rootDesc.xml.
Definition upnp.cpp:173
bool is_valid_igd(igd_status_e status)
Check whether a UPNP_GetValidIGD() status code identifies a usable IGD.
Definition upnp.cpp:133
bool may_manage_mapping(mapping_state_e state, bool recorded)
Require a local ownership record as well as a matching router response.
bool should_retain_recovery_record(mapping_state_e state, bool permanent)
Keep permanent recovery records when router ownership is ambiguous.
std::size_t select_inner_igd(const std::vector< std::string > &igd_hosts, std::string_view lan_addr)
Select the IGD of the network Hermes is attached to.
Definition upnp.cpp:185
constexpr auto PORT_MAPPING_LIFETIME
Requested finite mapping lifetime.
Definition upnp.h:27
bool lease_needs_refresh(std::string_view lease)
Detect an owned finite lease that needs replacement on routers that do not renew repeated adds.
mapping_lookup_t verify_mapping_lookup(const owned_mapping_t &wanted, bool recorded, Specific specific, Generic generic)
Verify an owned rule even when GetSpecificPortMappingEntry reports port zero.
std::unique_ptr< platf::deinit_t > start()
Start UPnP port mapping and return its shutdown guard.
Definition upnp.cpp:743
util::safe_ptr< UPNPDev, freeUPNPDevlist > device_t
Owning pointer to miniupnpc device discovery results.
Definition upnp.h:33
int shared_prefix_length(std::string_view a, std::string_view b)
Count the leading bits two IPv4 addresses have in common.
Definition upnp.cpp:161
@ conflict
Rule forwards elsewhere and must be left untouched.
@ ours
Destination, port and description match Hermes's record.
@ unknown
Lookup failed; ownership cannot be established.
@ missing
Gateway explicitly reports no such mapping.
@ existing
Someone else's rule already forwards to the requested destination.
constexpr auto IPv4
IPv4 discovery.
Definition upnp.h:25
constexpr auto IPv6
IPv6 discovery.
Definition upnp.h:26
std::vector< owned_mapping_t > read_mapping_journal(const std::string &text)
Recover outstanding permanent rules, ignoring incomplete or invalid journal lines.
igd_status_e UPNP_GetValidIGDStatus(device_t &device, urls_t *urls, IGDdatas *data, std::array< char, INET6_ADDRESS_STRLEN > &lan_addr)
Get the valid IGD status.
Definition upnp.cpp:124
std::string mapping_journal_event(const owned_mapping_t &mapping, bool added)
Encode one append-only recovery event before adding or after removing a permanent rule.
std::uint16_t map_port(int port)
Map a specified port based on the base port.
Definition network.cpp:350
af_e af_from_enum_string(const std::string_view &view)
Get the address family enum value from a string.
Definition network.cpp:166
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.
@ BOTH
IPv4 and IPv6.
Definition network.h:47
@ LAN
LAN.
Definition network.h:41
Declarations for the nvhttp (GameStream) server.
Declarations for RTSP streaming.
Declarations for the streaming protocols.
A discovered IGD and the data needed to manage its port mappings.
Definition upnp.cpp:56
urls_t urls
Control URLs of the IGD.
Definition upnp.cpp:58
IGDdatas data
Service data of the IGD.
Definition upnp.cpp:59
std::string host
Address of the IGD, taken from its description URL.
Definition upnp.cpp:57
Verified ownership and lease information for one mapping.
mapping_state_e state
Defaults to preserving the router rule and ownership record.
Fields returned by a specific or generic mapping query.
std::string wan
External gateway port exposed by the mapping.
std::string proto
Transport protocol used by the mapping.
std::string lan
Internal Hermes port targeted by the mapping.
UPnP port mapping description and lease state.
Definition upnp.cpp:43
struct upnp::mapping_t::@075347204134365057062272364162353203257244043213 port
WAN/LAN/protocol tuple for the mapped port.
std::string description
Human-readable UPnP lease description advertised to the gateway.
Definition upnp.cpp:50
A forwarding rule Hermes owns, including its gateway and destination.
std::string external_port
Gateway port.
std::size_t generation
Last successful discovery pass that wanted this exact rule.
std::string control_url
Gateway's SOAP endpoint.
std::string protocol
TCP or UDP.
bool permanent
Rule requires recovery after an unexpected process exit.
std::string service
Gateway's WAN connection service.
Declarations for UPnP port mapping.
Ownership and recovery records for UPnP port mappings.
Declarations for utility functions.