20#include <miniupnpc/miniupnpc.h>
21#include <miniupnpc/upnpcommands.h>
36using namespace std::literals;
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) {
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) {
81 igds.emplace_back(std::move(igd));
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) {
99 static std::string_view status_string(
igd_status_e status) {
104 return "No IGD device found"sv;
106 return "Valid IGD device found"sv;
107#if (MINIUPNPC_API_VERSION >= 18)
109 return "Valid IGD device found, but it has a private IP address"sv;
112 return "Valid IGD device found, but it isn't connected"sv;
114 return "A UPnP device has been found, but it wasn't recognized as an IGD"sv;
117 return "Unknown status"sv;
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);
128 auto status = UPNP_GetValidIGD(device.get(), &urls->el, data, lan_addr.data(), (
int) lan_addr.size());
138#if (MINIUPNPC_API_VERSION >= 18)
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);
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);
170 return std::countl_zero(addr_a.to_uint() ^ addr_b.to_uint());
174 if (
const auto scheme = url.find(
"://"sv); scheme != std::string_view::npos) {
175 url.remove_prefix(scheme + 3);
178 if (url.starts_with(
'[')) {
179 return std::string {url.substr(1, url.find(
']') - 1)};
182 return std::string {url.substr(0, url.find_first_of(
":/"sv))};
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;
188 for (std::size_t i = 0; i < igd_hosts.size(); ++i) {
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) {
200 if (!is_private_ipv4(inner_external_addr)) {
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) {
215 if (bits > best_bits) {
219 }
else if (best.has_value() && bits == best_bits) {
226 return ambiguous ? std::nullopt : best;
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));
241 auto wm_http = std::to_string(
net::map_port(confighttp::PORT_HTTPS));
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},
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});
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;
283 std::array<char, INET6_ADDRESS_STRLEN> lan_addr;
286 BOOST_LOG(debug) <<
"No valid IPv6 IGD: "sv << status_string(status);
290 if (data.IPv6FC.controlurl[0] != 0) {
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)
300 << (pinholeAllowed ?
"allowed"sv :
"disallowed"sv);
302 if (pinholeAllowed) {
305 auto shutdown_event =
mail::man->event<
bool>(mail::shutdown);
307 for (
auto it = std::begin(
mappings); it != std::end(
mappings) && !shutdown_event->peek(); ++it) {
309 std::array<char, 8> uniqueId;
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;
316 BOOST_LOG(debug) <<
"Failed to create pinhole for "sv << mapping.port.proto <<
' ' << mapping.port.lan <<
": "sv << err;
322 BOOST_LOG(debug) <<
"IPv6 pinholes are not allowed by the IGD"sv;
326 BOOST_LOG(debug) <<
"Failed to get IPv6 firewall status: "sv << err;
330 BOOST_LOG(debug) <<
"IPv6 Firewall Control is not supported by the IGD"sv;
344 BOOST_LOG(warning) <<
"Invalid UPnP recovery identity; refusing an unrecorded permanent mapping"sv;
348 std::ofstream out {path, std::ios::app};
353 BOOST_LOG(warning) <<
"Could not update UPnP recovery journal; refusing an unrecorded permanent mapping"sv;
359 const int fd = ::open(path.c_str(), O_RDONLY);
361 BOOST_LOG(warning) <<
"Could not reopen UPnP recovery journal for syncing"sv;
364 const bool durable = ::fsync(fd) == 0;
367 BOOST_LOG(warning) <<
"Could not sync UPnP recovery journal; refusing an unrecorded permanent mapping"sv;
387 found->permanent = found->permanent || mapping.
permanent;
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()};
402 auto deadline = std::chrono::steady_clock::time_point {};
403 const auto generic = [&](std::size_t index) {
405 deadline = std::chrono::steady_clock::now() + 5s;
406 }
else if (std::chrono::steady_clock::now() >= deadline) {
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()};
436 if (previously_owned) {
441 switch (lookup.state) {
443 BOOST_LOG(warning) <<
"UPnP port "sv << mapping.
port.wan <<
" already forwards elsewhere; leaving it unchanged"sv;
447 return lookup.enabled ==
"1"sv;
453 BOOST_LOG(debug) <<
"UPnP mapping resembles Hermes but has no ownership record; preserving it"sv;
454 return lookup.enabled ==
"1"sv;
456 wanted.
permanent = lookup.lease ==
"0"sv;
461 return lookup.enabled ==
"1"sv;
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) {
474 auto shutdown_event =
mail::man->event<
bool>(mail::shutdown);
475 if (shutdown_event->peek()) {
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()) {
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");
495 BOOST_LOG(warning) <<
"Could not retire unused UPnP recovery intent"sv;
508 if (err != UPNPCOMMAND_SUCCESS) {
511 BOOST_LOG(warning) <<
"Failed to map "sv << mapping.
port.proto <<
' ' << mapping.
port.wan <<
": "sv << err;
528 BOOST_LOG(warning) <<
"Could not check UPnP rule for cleanup: "sv << owned.
control_url <<
' ' << owned.
external_port;
536 BOOST_LOG(warning) <<
"UPnP permanent rule no longer matches its recovery record: "
544 if (removed != UPNPCOMMAND_SUCCESS && removed != 714) {
545 BOOST_LOG(warning) <<
"Failed to remove UPnP rule: "sv << removed;
553 return mapping.permanent;
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()) {
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);
597 BOOST_LOG(debug) <<
"Using the IGD on this host's network instead: "sv << igds[inner].urls->rootdescURL;
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]);
615 if (!outer.has_value()) {
618 if (external_addr.empty() || (is_private_ipv4(external_addr) && owned.target == external_addr)) {
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;
630 auto &outer_igd = igds[*outer];
633 BOOST_LOG(info) <<
"Completed UPnP port mappings to "sv << external_addr <<
" via "sv << outer_igd.urls->rootdescURL;
646 auto shutdown_event =
mail::man->event<
bool>(mail::shutdown);
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;
654 const std::string contents {(std::istreambuf_iterator<char>(journal)), std::istreambuf_iterator<char>()};
656 BOOST_LOG(error) <<
"Could not finish reading UPnP recovery journal; leaving it intact"sv;
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;
679 for (
auto dev = device.get(); dev !=
nullptr; dev = dev->pNext) {
680 BOOST_LOG(debug) <<
"Found device: "sv << dev->descURL;
683 std::array<char, INET6_ADDRESS_STRLEN> lan_addr;
685 std::vector<igd_t> igds(1);
688 BOOST_LOG(error) << status_string(status);
693 std::string lan_addr_str {lan_addr.data()};
695 BOOST_LOG(debug) <<
"Found valid IGD device: "sv << igds.front().urls->rootdescURL;
697 std::vector<std::string> igd_hosts;
698 const auto inner =
find_gateway(device, igds, igd_hosts, lan_addr_str);
702 if (!mapped && complete) {
703 BOOST_LOG(info) <<
"Completed UPnP port mappings to "sv << lan_addr_str <<
" via "sv << igds[inner].urls->rootdescURL;
713 BOOST_LOG(info) <<
"Successfully opened IPv6 pinholes on the IGD"sv;
743 std::unique_ptr<platf::deinit_t>
start() {
749 return std::make_unique<deinit_t>();
std::vector< mapping_t > mappings
Ports requested by Hermes.
void upnp_thread_proc()
Maintains UPnP port forwarding rules.
void unmap_owned_ports(bool stale_only=false)
Remove only recorded rules whose current destination, port and description still match.
std::size_t generation
Current successful discovery pass.
static std::filesystem::path journal_path()
Locate the append-only recovery journal used even when UPnP is disabled at the next start.
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.
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.
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.
std::string mapped_outer_host
Last outer gateway logged as mapped.
std::vector< owned_mapping_t > owned_mappings
Rules retained independently of discovery results.
bool map_all_upnp_ports(const igd_t &igd, const std::string &addr)
Maps every port on an IGD, stopping early on shutdown.
bool journal_mapping(const owned_mapping_t &mapping, bool added)
Append recovery intent before creating a permanent rule, or completion after removing it.
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.
bool create_ipv6_pinholes()
Opens pinholes for IPv6 traffic if the IGD is capable.
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.
~deinit_t()
Destroy the UPnP deinitializer.
std::jthread upnp_thread
Worker thread that refreshes mappings until shutdown.
bool warned_no_outer_igd
Whether the missing outer IGD has already been reported.
Owning wrapper for MiniUPnPc URLs.
std::filesystem::path appdata()
Performs migration if necessary, then returns the appdata directory.
Declarations for the configuration of Sunshine.
@ UPNP
Try Universal Plug 'n Play.
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.
constexpr auto PORT_HTTPS
The HTTPS port, as a difference from the config port.
constexpr auto PORT_HTTP
The HTTP port, as a difference from the config port.
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).
igd_status_e
Result codes returned by the installed MiniUPnPc library.
@ connected
A connected IGD was found.
@ disconnected
A disconnected IGD was found.
@ unknown_device
The device was not recognized as an IGD.
constexpr auto REFRESH_INTERVAL
Interval between mapping refresh passes.
std::string url_host(std::string_view url)
Extract the host from a URL such as http://192.168.1.1:1900/rootDesc.xml.
bool is_valid_igd(igd_status_e status)
Check whether a UPNP_GetValidIGD() status code identifies a usable IGD.
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.
constexpr auto PORT_MAPPING_LIFETIME
Requested finite mapping lifetime.
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.
util::safe_ptr< UPNPDev, freeUPNPDevlist > device_t
Owning pointer to miniupnpc device discovery results.
int shared_prefix_length(std::string_view a, std::string_view b)
Count the leading bits two IPv4 addresses have in common.
@ 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.
constexpr auto IPv6
IPv6 discovery.
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.
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.
af_e af_from_enum_string(const std::string_view &view)
Get the address family enum value from a string.
net_e from_address_ranges(const std::string_view &view)
Classify an address by the fixed ranges alone.
Declarations for networking related functions.
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.
urls_t urls
Control URLs of the IGD.
IGDdatas data
Service data of the IGD.
std::string host
Address of the IGD, taken from its description URL.
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.
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.
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.