Hermes 0.7.0
Linux game streaming host
Loading...
Searching...
No Matches
upnp_mapping.h
Go to the documentation of this file.
1
5#pragma once
6
7// standard includes
8#include <algorithm>
9#include <charconv>
10#include <cstddef>
11#include <cstdint>
12#include <iomanip>
13#include <optional>
14#include <sstream>
15#include <string>
16#include <string_view>
17#include <tuple>
18#include <utility>
19#include <vector>
20
21namespace upnp {
27 inline bool lease_needs_refresh(std::string_view lease) {
28 unsigned long seconds = 0;
29 const auto result = std::from_chars(lease.data(), lease.data() + lease.size(), seconds);
30 return result.ec == std::errc {} && result.ptr == lease.data() + lease.size() && seconds > 0 && seconds <= 600;
31 }
32
37 std::string control_url;
38 std::string service;
39 std::string target;
40 std::string external_port;
41 std::string internal_port;
42 std::string protocol;
43 std::string description;
44 bool permanent = false;
45 std::size_t generation = 0;
46
52 bool operator==(const owned_mapping_t &other) const {
54 std::tie(other.control_url, other.service, other.target, other.external_port, other.internal_port, other.protocol, other.description);
55 }
56 };
57
61 enum class mapping_state_e {
62 missing,
66 unknown,
67 };
68
78 inline mapping_state_e classify_mapping(int result, std::string_view client, std::string_view port, std::string_view description, const owned_mapping_t &wanted) {
79 if (result == 714) {
81 }
82 if (result != 0) {
84 }
85 if (client != wanted.target || port != wanted.internal_port) {
87 }
88 return description == wanted.description ? mapping_state_e::ours : mapping_state_e::existing;
89 }
90
95 inline bool may_manage_mapping(mapping_state_e state, bool recorded) {
96 return recorded && state == mapping_state_e::ours;
97 }
98
101 int result = -1;
102 std::string client {};
103 std::string internal_port {};
104 std::string description {};
105 std::string enabled {};
106 std::string lease {};
107 std::string external_port {};
108 std::string protocol {};
109 std::string remote_host {};
110 };
111
118
130 template<class Specific, class Generic>
131 mapping_lookup_t verify_mapping_lookup(const owned_mapping_t &wanted, bool recorded, Specific specific, Generic generic) {
132 const auto first = specific();
133 const auto state = classify_mapping(first.result, first.client, first.internal_port, first.description, wanted);
134 if (!recorded || first.result != 0 || first.internal_port != "0" || first.client != wanted.target || first.description != wanted.description) {
135 return {state, first.enabled, first.lease};
136 }
137 if (first.enabled != "0" && first.enabled != "1") {
138 return {};
139 }
140 const auto parse_number = [](const std::string &text) -> std::optional<std::uint32_t> {
141 std::uint32_t number = 0;
142 const auto parsed = std::from_chars(text.data(), text.data() + text.size(), number);
143 if (parsed.ec != std::errc {} || parsed.ptr != text.data() + text.size()) {
144 return std::nullopt;
145 }
146 return number;
147 };
148
149 std::optional<mapping_reply_t> match;
150 std::size_t match_index = 0;
151 bool complete = false;
152 // A broken IGD must not make renewal or shutdown enumerate indefinitely.
153 for (std::size_t index = 0; index < 256; ++index) {
154 auto entry = generic(index);
155 if (entry.result == 713) {
156 complete = true;
157 break;
158 }
159 if (entry.result != 0) {
160 return {};
161 }
162 const auto external_port = parse_number(entry.external_port);
163 const auto internal_port = parse_number(entry.internal_port);
164 if (!external_port || *external_port == 0 || *external_port > 65535 || !internal_port || *internal_port == 0 || *internal_port > 65535 || entry.client.empty() || (entry.protocol != "TCP" && entry.protocol != "UDP") || (entry.enabled != "0" && entry.enabled != "1")) {
165 return {};
166 }
167 if (entry.external_port != wanted.external_port || entry.protocol != wanted.protocol || (!entry.remote_host.empty() && entry.remote_host != "0.0.0.0")) {
168 continue;
169 }
170 if (match || entry.client != wanted.target || entry.internal_port != wanted.internal_port || entry.enabled != first.enabled) {
171 return {};
172 }
173 match = std::move(entry);
174 match_index = index;
175 }
176 if (!complete || !match) {
177 return {};
178 }
179
180 // Enumeration is not atomic. Recheck the precise key and ownership marker;
181 // an error, disappearance or replacement is uncertainty, never permission to add.
182 const auto last = specific();
183 if (last.result != 0 || last.client != first.client || last.internal_port != first.internal_port || last.description != first.description || last.enabled != first.enabled) {
184 return {};
185 }
186 // Port zero in the specific recheck cannot reveal a changed internal port.
187 // Re-read the selected table row as well; a shifted index or replacement fails closed.
188 const auto current = generic(match_index);
189 if (current.result != 0 || current.external_port != wanted.external_port || current.protocol != wanted.protocol || (!current.remote_host.empty() && current.remote_host != "0.0.0.0") || current.client != wanted.target || current.internal_port != wanted.internal_port || current.enabled != first.enabled) {
190 return {};
191 }
192 auto duration = parse_number(first.lease);
193 if (!duration) {
194 return {};
195 }
196 for (const auto *reply : {&std::as_const(*match), &last, &current}) {
197 const auto seconds = parse_number(reply->lease);
198 if (!seconds || ((*duration == 0) != (*seconds == 0))) {
199 return {};
200 }
201 duration = std::min(*duration, *seconds);
202 }
203 // Prefer the smaller remaining lifetime; some IGDs report the original lease
204 // through one query. A permanent lease requires agreement from both queries.
205 return {mapping_state_e::ours, last.enabled, std::to_string(*duration)};
206 }
207
212 inline bool should_retain_recovery_record(mapping_state_e state, bool permanent) {
213 return permanent && (state == mapping_state_e::existing || state == mapping_state_e::conflict || state == mapping_state_e::unknown);
214 }
215
222 inline std::string mapping_journal_event(const owned_mapping_t &mapping, bool added) {
223 for (const auto *field : {&mapping.control_url, &mapping.service, &mapping.target, &mapping.external_port, &mapping.internal_port, &mapping.protocol, &mapping.description}) {
224 if (field->empty() || field->find_first_of("\r\n") != std::string::npos) {
225 return {};
226 }
227 }
228 std::ostringstream out;
229 out << '\n'
230 << (added ? '+' : '-') << ' ' << std::quoted(mapping.control_url) << ' ' << std::quoted(mapping.service) << ' '
231 << std::quoted(mapping.target) << ' ' << std::quoted(mapping.external_port) << ' ' << std::quoted(mapping.internal_port)
232 << ' ' << std::quoted(mapping.protocol) << ' ' << std::quoted(mapping.description) << '\n';
233 return out.str();
234 }
235
241 inline std::vector<owned_mapping_t> read_mapping_journal(const std::string &text) {
242 std::vector<owned_mapping_t> mappings;
243 std::istringstream input {text};
244 std::string line;
245 while (std::getline(input, line)) {
246 std::istringstream entry {line};
247 char event = 0;
248 owned_mapping_t mapping;
249 if (!(entry >> event >> std::quoted(mapping.control_url) >> std::quoted(mapping.service) >> std::quoted(mapping.target) >> std::quoted(mapping.external_port) >> std::quoted(mapping.internal_port) >> std::quoted(mapping.protocol) >> std::quoted(mapping.description)) || (event != '+' && event != '-') || mapping.control_url.empty() || mapping.service.empty() || mapping.target.empty() || mapping.external_port.empty() || mapping.internal_port.empty() || (mapping.protocol != "TCP" && mapping.protocol != "UDP") || mapping.description.empty()) {
250 continue;
251 }
252 mapping.permanent = true;
253 const auto found = std::find(mappings.begin(), mappings.end(), mapping);
254 if (event == '+' && found == mappings.end()) {
255 mappings.push_back(std::move(mapping));
256 } else if (event == '-' && found != mappings.end()) {
257 mappings.erase(found);
258 }
259 }
260 return mappings;
261 }
262} // namespace upnp
UPnP port mapping.
Definition upnp.cpp:38
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.
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.
mapping_state_e
Relationship between a gateway's existing mapping and the requested rule.
@ 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.
std::vector< owned_mapping_t > read_mapping_journal(const std::string &text)
Recover outstanding permanent rules, ignoring incomplete or invalid journal lines.
mapping_state_e classify_mapping(int result, std::string_view client, std::string_view port, std::string_view description, const owned_mapping_t &wanted)
Classify a lookup without treating a destination alone as proof of ownership.
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.
Verified ownership and lease information for one mapping.
mapping_state_e state
Defaults to preserving the router rule and ownership record.
std::string enabled
Verified enabled flag.
std::string lease
Verified remaining lifetime.
Fields returned by a specific or generic mapping query.
std::string external_port
Generic entry's external port.
std::string enabled
Router's enabled flag.
std::string description
Specific query's ownership marker; generic descriptions are unreliable.
std::string remote_host
Generic entry's remote restriction; empty or 0.0.0.0 means wildcard.
std::string lease
Remaining lifetime in seconds, or zero for permanent rules.
std::string internal_port
Internal destination port, possibly the defective zero.
std::string protocol
Generic entry's transport protocol.
std::string client
Internal destination address.
int result
MiniUPnPc result; a default reply cannot authorize a mutation.
A forwarding rule Hermes owns, including its gateway and destination.
std::string target
Host or inner router receiving the forwarded traffic.
bool operator==(const owned_mapping_t &other) const
Compare persistent rule identities, excluding refresh bookkeeping.
std::string description
Description used when Hermes created the rule.
std::string internal_port
Destination port.
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.