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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "remoting/protocol/ice_transport_channel.h"
#include <algorithm>
#include "base/callback.h"
#include "base/callback_helpers.h"
#include "base/single_thread_task_runner.h"
#include "base/thread_task_runner_handle.h"
#include "jingle/glue/utils.h"
#include "net/base/net_errors.h"
#include "remoting/protocol/channel_socket_adapter.h"
#include "third_party/webrtc/base/network.h"
#include "third_party/webrtc/p2p/base/constants.h"
#include "third_party/webrtc/p2p/base/p2ptransportchannel.h"
#include "third_party/webrtc/p2p/base/port.h"
#include "third_party/webrtc/p2p/client/httpportallocator.h"
namespace remoting {
namespace protocol {
namespace {
// Try connecting ICE twice with timeout of 15 seconds for each attempt.
const int kMaxReconnectAttempts = 2;
const int kReconnectDelaySeconds = 15;
// Utility function to map a cricket::Candidate string type to a
// TransportRoute::RouteType enum value.
TransportRoute::RouteType CandidateTypeToTransportRouteType(
const std::string& candidate_type) {
if (candidate_type == "local") {
return TransportRoute::DIRECT;
} else if (candidate_type == "stun" || candidate_type == "prflx") {
return TransportRoute::STUN;
} else if (candidate_type == "relay") {
return TransportRoute::RELAY;
} else {
LOG(FATAL) << "Unknown candidate type: " << candidate_type;
return TransportRoute::DIRECT;
}
}
} // namespace
IceTransportChannel::IceTransportChannel(cricket::PortAllocator* port_allocator,
const NetworkSettings& network_settings,
TransportRole role)
: port_allocator_(port_allocator),
network_settings_(network_settings),
role_(role),
delegate_(nullptr),
ice_username_fragment_(
rtc::CreateRandomString(cricket::ICE_UFRAG_LENGTH)),
can_start_(false),
connect_attempts_left_(kMaxReconnectAttempts),
weak_factory_(this) {
DCHECK(!ice_username_fragment_.empty());
}
IceTransportChannel::~IceTransportChannel() {
DCHECK(delegate_);
delegate_->OnTransportDeleted(this);
if (channel_.get()) {
base::ThreadTaskRunnerHandle::Get()->DeleteSoon(
FROM_HERE, channel_.release());
}
}
void IceTransportChannel::OnCanStart() {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(!can_start_);
can_start_ = true;
// If Connect() has been called then start connection.
if (!callback_.is_null())
DoStart();
// Pass pending ICE credentials and candidates to the channel.
if (!remote_ice_username_fragment_.empty()) {
channel_->SetRemoteIceCredentials(remote_ice_username_fragment_,
remote_ice_password_);
}
while (!pending_candidates_.empty()) {
channel_->AddRemoteCandidate(pending_candidates_.front());
pending_candidates_.pop_front();
}
}
void IceTransportChannel::Connect(const std::string& name,
Delegate* delegate,
const ConnectedCallback& callback) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(!name.empty());
DCHECK(delegate);
DCHECK(!callback.is_null());
DCHECK(name_.empty());
name_ = name;
delegate_ = delegate;
callback_ = callback;
if (can_start_)
DoStart();
}
void IceTransportChannel::DoStart() {
DCHECK(!channel_.get());
// Create P2PTransportChannel, attach signal handlers and connect it.
// TODO(sergeyu): Specify correct component ID for the channel.
channel_.reset(new cricket::P2PTransportChannel(
std::string(), 0, nullptr, port_allocator_));
std::string ice_password = rtc::CreateRandomString(cricket::ICE_PWD_LENGTH);
channel_->SetIceProtocolType(cricket::ICEPROTO_RFC5245);
channel_->SetIceRole((role_ == TransportRole::CLIENT)
? cricket::ICEROLE_CONTROLLING
: cricket::ICEROLE_CONTROLLED);
delegate_->OnTransportIceCredentials(this, ice_username_fragment_,
ice_password);
channel_->SetIceCredentials(ice_username_fragment_, ice_password);
channel_->SignalCandidateGathered.connect(
this, &IceTransportChannel::OnCandidateGathered);
channel_->SignalRouteChange.connect(
this, &IceTransportChannel::OnRouteChange);
channel_->SignalReceivingState.connect(
this, &IceTransportChannel::OnReceivingState);
channel_->SignalWritableState.connect(
this, &IceTransportChannel::OnWritableState);
channel_->set_incoming_only(
!(network_settings_.flags & NetworkSettings::NAT_TRAVERSAL_OUTGOING));
channel_->Connect();
channel_->MaybeStartGathering();
--connect_attempts_left_;
// Start reconnection timer.
reconnect_timer_.Start(
FROM_HERE, base::TimeDelta::FromSeconds(kReconnectDelaySeconds),
this, &IceTransportChannel::TryReconnect);
}
void IceTransportChannel::NotifyConnected() {
// Create P2PDatagramSocket adapter for the P2PTransportChannel.
scoped_ptr<TransportChannelSocketAdapter> socket(
new TransportChannelSocketAdapter(channel_.get()));
socket->SetOnDestroyedCallback(base::Bind(
&IceTransportChannel::OnChannelDestroyed, base::Unretained(this)));
base::ResetAndReturn(&callback_).Run(socket.Pass());
}
void IceTransportChannel::SetRemoteCredentials(const std::string& ufrag,
const std::string& password) {
DCHECK(thread_checker_.CalledOnValidThread());
remote_ice_username_fragment_ = ufrag;
remote_ice_password_ = password;
if (channel_)
channel_->SetRemoteIceCredentials(ufrag, password);
}
void IceTransportChannel::AddRemoteCandidate(
const cricket::Candidate& candidate) {
DCHECK(thread_checker_.CalledOnValidThread());
// To enforce the no-relay setting, it's not enough to not produce relay
// candidates. It's also necessary to discard remote relay candidates.
bool relay_allowed = (network_settings_.flags &
NetworkSettings::NAT_TRAVERSAL_RELAY) != 0;
if (!relay_allowed && candidate.type() == cricket::RELAY_PORT_TYPE)
return;
if (channel_) {
channel_->AddRemoteCandidate(candidate);
} else {
pending_candidates_.push_back(candidate);
}
}
const std::string& IceTransportChannel::name() const {
DCHECK(thread_checker_.CalledOnValidThread());
return name_;
}
bool IceTransportChannel::is_connected() const {
DCHECK(thread_checker_.CalledOnValidThread());
return callback_.is_null();
}
void IceTransportChannel::OnCandidateGathered(
cricket::TransportChannelImpl* channel,
const cricket::Candidate& candidate) {
DCHECK(thread_checker_.CalledOnValidThread());
delegate_->OnTransportCandidate(this, candidate);
}
void IceTransportChannel::OnRouteChange(
cricket::TransportChannel* channel,
const cricket::Candidate& candidate) {
// Ignore notifications if the channel is not writable.
if (channel_->writable())
NotifyRouteChanged();
}
void IceTransportChannel::OnReceivingState(cricket::TransportChannel* channel) {
DCHECK_EQ(channel, static_cast<cricket::TransportChannel*>(channel_.get()));
if (channel->receiving() && !callback_.is_null())
NotifyConnected();
}
void IceTransportChannel::OnWritableState(cricket::TransportChannel* channel) {
DCHECK_EQ(channel, static_cast<cricket::TransportChannel*>(channel_.get()));
if (channel->writable()) {
connect_attempts_left_ = kMaxReconnectAttempts;
reconnect_timer_.Stop();
// Route change notifications are ignored when the |channel_| is not
// writable. Notify the event handler about the current route once the
// channel is writable.
NotifyRouteChanged();
} else {
reconnect_timer_.Reset();
TryReconnect();
}
}
void IceTransportChannel::OnChannelDestroyed() {
// The connection socket is being deleted, so delete the transport too.
delete this;
}
void IceTransportChannel::NotifyRouteChanged() {
TransportRoute route;
DCHECK(channel_->best_connection());
const cricket::Connection* connection = channel_->best_connection();
// A connection has both a local and a remote candidate. For our purposes, the
// route type is determined by the most indirect candidate type. For example:
// it's possible for the local candidate be a "relay" type, while the remote
// candidate is "local". In this case, we still want to report a RELAY route
// type.
static_assert(TransportRoute::DIRECT < TransportRoute::STUN &&
TransportRoute::STUN < TransportRoute::RELAY,
"Route type enum values are ordered by 'indirectness'");
route.type = std::max(
CandidateTypeToTransportRouteType(connection->local_candidate().type()),
CandidateTypeToTransportRouteType(connection->remote_candidate().type()));
if (!jingle_glue::SocketAddressToIPEndPoint(
connection->remote_candidate().address(), &route.remote_address)) {
LOG(FATAL) << "Failed to convert peer IP address.";
}
const cricket::Candidate& local_candidate =
channel_->best_connection()->local_candidate();
if (!jingle_glue::SocketAddressToIPEndPoint(
local_candidate.address(), &route.local_address)) {
LOG(FATAL) << "Failed to convert local IP address.";
}
delegate_->OnTransportRouteChange(this, route);
}
void IceTransportChannel::TryReconnect() {
DCHECK(!channel_->writable());
if (connect_attempts_left_ <= 0) {
reconnect_timer_.Stop();
// Notify the caller that ICE connection has failed - normally that will
// terminate Jingle connection (i.e. the transport will be destroyed).
delegate_->OnTransportFailed(this);
return;
}
--connect_attempts_left_;
// Restart ICE by resetting ICE password.
std::string ice_password = rtc::CreateRandomString(cricket::ICE_PWD_LENGTH);
delegate_->OnTransportIceCredentials(this, ice_username_fragment_,
ice_password);
channel_->SetIceCredentials(ice_username_fragment_, ice_password);
}
} // namespace protocol
} // namespace remoting
|