-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpeer_selection.cpp
More file actions
205 lines (188 loc) · 8.52 KB
/
Copy pathpeer_selection.cpp
File metadata and controls
205 lines (188 loc) · 8.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
#include "peer_selection.h"
#include <chrono>
#include <vector>
#include "log.h"
#include "rendezvous_client.h"
namespace {
constexpr auto kTunIpReportInterval = std::chrono::seconds(5);
UdpEndpoint FromSockaddr(const sockaddr_storage& address, socket_len_t len) {
UdpEndpoint endpoint{};
endpoint.addr = address;
endpoint.addr_len = len;
endpoint.family = address.ss_family;
return endpoint;
}
const char* RendezvousEventName(RendezvousEventType type) {
switch (type) {
case RendezvousEventType::None: return "None";
case RendezvousEventType::Registered: return "Registered";
case RendezvousEventType::PeerUnavailable: return "PeerUnavailable";
case RendezvousEventType::Peer: return "Peer";
case RendezvousEventType::NatWait: return "NatWait";
case RendezvousEventType::NatPeerInfo: return "NatPeerInfo";
case RendezvousEventType::NatArmedAck: return "NatArmedAck";
case RendezvousEventType::NatStart: return "NatStart";
case RendezvousEventType::NatRetryWait: return "NatRetryWait";
case RendezvousEventType::NatAttempt: return "NatAttempt";
case RendezvousEventType::Error: return "Error";
default: return "Unknown";
}
}
std::string LocalSocketEndpoint(socket_t sock) {
sockaddr_storage address{};
socket_len_t len = static_cast<socket_len_t>(sizeof(address));
if (getsockname(sock, reinterpret_cast<sockaddr*>(&address), &len) != 0) {
return "unknown (getsockname err=" + std::to_string(GetSocketError()) + ")";
}
return FormatUdpEndpoint(FromSockaddr(address, len));
}
long long MillisecondsRemaining(
std::chrono::steady_clock::time_point deadline) {
const auto remaining = std::chrono::duration_cast<std::chrono::milliseconds>(
deadline - std::chrono::steady_clock::now()).count();
return remaining > 0 ? static_cast<long long>(remaining) : 0LL;
}
} // namespace
bool SelectPeer(socket_t sock, const Config& config,
const UdpEndpoint& server,
const std::atomic<bool>& running,
UdpEndpoint* peer, std::string* matchedPeerId,
std::vector<TraversalMode>* traversalModes,
NatPunchSession* natPunchSession,
std::string* error) {
if (!ValidateRendezvousSession(config, error)) return false;
traversalModes->clear();
*natPunchSession = {};
RendezvousClient rendezvous(config, server);
const auto selectionDeadline = std::chrono::steady_clock::now()
+ (config.target_peer_id.empty()
? std::chrono::hours(24 * 365)
: std::chrono::seconds(config.punch_timeout));
auto nextProbe = std::chrono::steady_clock::time_point{};
auto nextTunIpReport = std::chrono::steady_clock::time_point{};
bool registered = false;
bool tunIpReported = config.local_tun_ipv4.empty();
std::vector<uint8_t> buffer(2048);
const auto reportTunIp = [&](std::chrono::steady_clock::time_point now) {
if (config.local_tun_ipv4.empty()) return;
if (!ReportRendezvousTunIp(sock, config, server)) {
Log(LogLevel::Warn,
"Failed to report configured TUN IP during peer selection. err="
+ std::to_string(GetSocketError()));
} else if (!tunIpReported) {
Log(LogLevel::Info,
"Reported configured TUN IP during rendezvous registration: "
+ config.local_tun_ipv4);
tunIpReported = true;
}
nextTunIpReport = now + kTunIpReportInterval;
};
Log(LogLevel::Debug, "Peer selection started: mode="
+ std::string(config.target_peer_id.empty() ? "wait" : "connect")
+ ", peer_id=" + config.peer_id
+ (config.target_peer_id.empty()
? "" : ", target_peer_id=" + config.target_peer_id)
+ ", selection_timeout_ms="
+ std::to_string(
static_cast<unsigned long long>(config.punch_timeout) * 1000ULL));
while (running.load()) {
const auto now = std::chrono::steady_clock::now();
if (rendezvous.ResponseTimedOut(now, error)) {
Log(LogLevel::Error, "Peer selection aborted: " + *error);
return false;
}
if (rendezvous.HasResponded() && now >= selectionDeadline) break;
if (now >= nextProbe) {
if (!rendezvous.SendProbe(sock)) {
Log(LogLevel::Warn, "Failed to send rendezvous probe to "
+ FormatUdpEndpoint(server) + ". err="
+ std::to_string(GetSocketError()));
} else {
Log(LogLevel::Debug, "Sent rendezvous probe; local="
+ LocalSocketEndpoint(sock) + ", server="
+ FormatUdpEndpoint(server));
}
nextProbe = now + std::chrono::milliseconds(500);
}
if (registered && now >= nextTunIpReport) {
reportTunIp(now);
}
sockaddr_storage sourceAddress{};
socket_len_t sourceLen =
static_cast<socket_len_t>(sizeof(sourceAddress));
const int received = recvfrom(
sock, reinterpret_cast<char*>(buffer.data()),
static_cast<int>(buffer.size()), 0,
reinterpret_cast<sockaddr*>(&sourceAddress), &sourceLen);
if (received < 0) {
const int socketError = GetSocketError();
if (IsRecvTimeout(socketError)) continue;
if (rendezvous.HandleUnreachableError(socketError, error)) {
Log(LogLevel::Error,
"Peer selection failed before rendezvous response: "
+ *error + ". err=" + std::to_string(socketError));
return false;
}
if (IsUdpDestinationUnreachable(socketError)) {
Log(LogLevel::Debug,
"Transient UDP unreachable during peer selection; "
"continuing. err=" + std::to_string(socketError)
+ ", deadline_ms="
+ std::to_string(
MillisecondsRemaining(selectionDeadline)));
continue;
}
*error = "UDP receive failed during peer selection. err="
+ std::to_string(socketError);
Log(LogLevel::Error, *error);
return false;
}
const UdpEndpoint source = FromSockaddr(sourceAddress, sourceLen);
const RendezvousEvent event = rendezvous.HandlePacket(
source, buffer.data(), static_cast<size_t>(received));
Log(LogLevel::Debug, "Peer selection RX: source="
+ FormatUdpEndpoint(source)
+ ", bytes=" + std::to_string(received)
+ ", rendezvous_event=" + RendezvousEventName(event.type));
if (event.type == RendezvousEventType::Error) {
*error = event.error;
Log(LogLevel::Error, "Rendezvous packet rejected: " + *error);
return false;
}
if (event.type == RendezvousEventType::Registered) {
registered = true;
const auto registeredAt = std::chrono::steady_clock::now();
if (registeredAt >= nextTunIpReport) {
reportTunIp(registeredAt);
}
continue;
}
if (event.type == RendezvousEventType::Peer
&& (config.target_peer_id.empty()
|| event.peerId == config.target_peer_id)) {
if (!tunIpReported) {
reportTunIp(std::chrono::steady_clock::now());
}
*peer = event.peer;
*matchedPeerId = event.peerId;
*traversalModes = event.traversalModes;
natPunchSession->sessionId = event.sessionId;
natPunchSession->attemptId = event.attemptId;
natPunchSession->role = event.natPunchRole;
natPunchSession->protocolVersion = event.natPunchVersion;
natPunchSession->punchToken = event.natPunchToken;
Log(LogLevel::Info, "Rendezvous selected peer id="
+ *matchedPeerId + ", endpoint=" + FormatUdpEndpoint(*peer)
+ ", peer_capabilities="
+ SerializeTraversalModeSequence(event.peerCapabilities)
+ ", traversal_modes="
+ SerializeTraversalModeSequence(*traversalModes));
return true;
}
}
*error = running.load() ? "Timed out waiting for selected peer"
: "Peer selection stopped by request";
Log(running.load() ? LogLevel::Error : LogLevel::Debug,
"Peer selection finished without a peer: " + *error);
return false;
}