shortcuts: fix dimension rounding issues and standardise names/types
[chromium-blink-merge.git] / remoting / protocol / libjingle_transport_factory.cc
blob83c59804b7ea0716a14af5d2f6c4438dcd782fb3
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "remoting/protocol/libjingle_transport_factory.h"
7 #include <algorithm>
9 #include "base/callback.h"
10 #include "base/callback_helpers.h"
11 #include "base/single_thread_task_runner.h"
12 #include "base/thread_task_runner_handle.h"
13 #include "base/timer/timer.h"
14 #include "jingle/glue/utils.h"
15 #include "net/base/net_errors.h"
16 #include "remoting/protocol/channel_socket_adapter.h"
17 #include "remoting/protocol/network_settings.h"
18 #include "remoting/signaling/jingle_info_request.h"
19 #include "third_party/webrtc/base/network.h"
20 #include "third_party/webrtc/p2p/base/constants.h"
21 #include "third_party/webrtc/p2p/base/p2ptransportchannel.h"
22 #include "third_party/webrtc/p2p/base/port.h"
23 #include "third_party/webrtc/p2p/client/basicportallocator.h"
24 #include "third_party/webrtc/p2p/client/httpportallocator.h"
26 namespace remoting {
27 namespace protocol {
29 namespace {
31 // Try connecting ICE twice with timeout of 15 seconds for each attempt.
32 const int kMaxReconnectAttempts = 2;
33 const int kReconnectDelaySeconds = 15;
35 // Get fresh STUN/Relay configuration every hour.
36 const int kJingleInfoUpdatePeriodSeconds = 3600;
38 // Utility function to map a cricket::Candidate string type to a
39 // TransportRoute::RouteType enum value.
40 TransportRoute::RouteType CandidateTypeToTransportRouteType(
41 const std::string& candidate_type) {
42 if (candidate_type == "local") {
43 return TransportRoute::DIRECT;
44 } else if (candidate_type == "stun" || candidate_type == "prflx") {
45 return TransportRoute::STUN;
46 } else if (candidate_type == "relay") {
47 return TransportRoute::RELAY;
48 } else {
49 LOG(FATAL) << "Unknown candidate type: " << candidate_type;
50 return TransportRoute::DIRECT;
54 class LibjingleTransport
55 : public Transport,
56 public base::SupportsWeakPtr<LibjingleTransport>,
57 public sigslot::has_slots<> {
58 public:
59 LibjingleTransport(cricket::PortAllocator* port_allocator,
60 const NetworkSettings& network_settings,
61 TransportRole role);
62 ~LibjingleTransport() override;
64 // Called by JingleTransportFactory when it has fresh Jingle info.
65 void OnCanStart();
67 // Transport interface.
68 void Connect(const std::string& name,
69 Transport::EventHandler* event_handler,
70 const Transport::ConnectedCallback& callback) override;
71 void SetRemoteCredentials(const std::string& ufrag,
72 const std::string& password) override;
73 void AddRemoteCandidate(const cricket::Candidate& candidate) override;
74 const std::string& name() const override;
75 bool is_connected() const override;
77 private:
78 void DoStart();
79 void NotifyConnected();
81 // Signal handlers for cricket::TransportChannel.
82 void OnRequestSignaling(cricket::TransportChannelImpl* channel);
83 void OnCandidateReady(cricket::TransportChannelImpl* channel,
84 const cricket::Candidate& candidate);
85 void OnRouteChange(cricket::TransportChannel* channel,
86 const cricket::Candidate& candidate);
87 void OnWritableState(cricket::TransportChannel* channel);
89 // Callback for TransportChannelSocketAdapter to notify when the socket is
90 // destroyed.
91 void OnChannelDestroyed();
93 void NotifyRouteChanged();
95 // Tries to connect by restarting ICE. Called by |reconnect_timer_|.
96 void TryReconnect();
98 cricket::PortAllocator* port_allocator_;
99 NetworkSettings network_settings_;
100 TransportRole role_;
102 std::string name_;
103 EventHandler* event_handler_;
104 Transport::ConnectedCallback callback_;
105 std::string ice_username_fragment_;
107 bool can_start_;
109 std::string remote_ice_username_fragment_;
110 std::string remote_ice_password_;
111 std::list<cricket::Candidate> pending_candidates_;
112 scoped_ptr<cricket::P2PTransportChannel> channel_;
113 int connect_attempts_left_;
114 base::RepeatingTimer<LibjingleTransport> reconnect_timer_;
116 base::WeakPtrFactory<LibjingleTransport> weak_factory_;
118 DISALLOW_COPY_AND_ASSIGN(LibjingleTransport);
121 LibjingleTransport::LibjingleTransport(cricket::PortAllocator* port_allocator,
122 const NetworkSettings& network_settings,
123 TransportRole role)
124 : port_allocator_(port_allocator),
125 network_settings_(network_settings),
126 role_(role),
127 event_handler_(nullptr),
128 ice_username_fragment_(
129 rtc::CreateRandomString(cricket::ICE_UFRAG_LENGTH)),
130 can_start_(false),
131 connect_attempts_left_(kMaxReconnectAttempts),
132 weak_factory_(this) {
133 DCHECK(!ice_username_fragment_.empty());
136 LibjingleTransport::~LibjingleTransport() {
137 DCHECK(event_handler_);
139 event_handler_->OnTransportDeleted(this);
141 if (channel_.get()) {
142 base::ThreadTaskRunnerHandle::Get()->DeleteSoon(
143 FROM_HERE, channel_.release());
147 void LibjingleTransport::OnCanStart() {
148 DCHECK(CalledOnValidThread());
150 DCHECK(!can_start_);
151 can_start_ = true;
153 // If Connect() has been called then start connection.
154 if (!callback_.is_null())
155 DoStart();
157 // Pass pending ICE credentials and candidates to the channel.
158 if (!remote_ice_username_fragment_.empty()) {
159 channel_->SetRemoteIceCredentials(remote_ice_username_fragment_,
160 remote_ice_password_);
163 while (!pending_candidates_.empty()) {
164 channel_->OnCandidate(pending_candidates_.front());
165 pending_candidates_.pop_front();
169 void LibjingleTransport::Connect(
170 const std::string& name,
171 Transport::EventHandler* event_handler,
172 const Transport::ConnectedCallback& callback) {
173 DCHECK(CalledOnValidThread());
174 DCHECK(!name.empty());
175 DCHECK(event_handler);
176 DCHECK(!callback.is_null());
178 DCHECK(name_.empty());
179 name_ = name;
180 event_handler_ = event_handler;
181 callback_ = callback;
183 if (can_start_)
184 DoStart();
187 void LibjingleTransport::DoStart() {
188 DCHECK(!channel_.get());
190 // Create P2PTransportChannel, attach signal handlers and connect it.
191 // TODO(sergeyu): Specify correct component ID for the channel.
192 channel_.reset(new cricket::P2PTransportChannel(
193 std::string(), 0, nullptr, port_allocator_));
194 std::string ice_password = rtc::CreateRandomString(cricket::ICE_PWD_LENGTH);
195 channel_->SetIceRole((role_ == TransportRole::CLIENT)
196 ? cricket::ICEROLE_CONTROLLING
197 : cricket::ICEROLE_CONTROLLED);
198 event_handler_->OnTransportIceCredentials(this, ice_username_fragment_,
199 ice_password);
200 channel_->SetIceCredentials(ice_username_fragment_, ice_password);
201 channel_->SignalRequestSignaling.connect(
202 this, &LibjingleTransport::OnRequestSignaling);
203 channel_->SignalCandidateReady.connect(
204 this, &LibjingleTransport::OnCandidateReady);
205 channel_->SignalRouteChange.connect(
206 this, &LibjingleTransport::OnRouteChange);
207 channel_->SignalWritableState.connect(
208 this, &LibjingleTransport::OnWritableState);
209 channel_->set_incoming_only(
210 !(network_settings_.flags & NetworkSettings::NAT_TRAVERSAL_OUTGOING));
212 channel_->Connect();
214 --connect_attempts_left_;
216 // Start reconnection timer.
217 reconnect_timer_.Start(
218 FROM_HERE, base::TimeDelta::FromSeconds(kReconnectDelaySeconds),
219 this, &LibjingleTransport::TryReconnect);
221 base::ThreadTaskRunnerHandle::Get()->PostTask(
222 FROM_HERE, base::Bind(&LibjingleTransport::NotifyConnected,
223 weak_factory_.GetWeakPtr()));
226 void LibjingleTransport::NotifyConnected() {
227 // Create P2PDatagramSocket adapter for the P2PTransportChannel.
228 scoped_ptr<TransportChannelSocketAdapter> socket(
229 new TransportChannelSocketAdapter(channel_.get()));
230 socket->SetOnDestroyedCallback(base::Bind(
231 &LibjingleTransport::OnChannelDestroyed, base::Unretained(this)));
232 base::ResetAndReturn(&callback_).Run(socket.Pass());
235 void LibjingleTransport::SetRemoteCredentials(const std::string& ufrag,
236 const std::string& password) {
237 DCHECK(CalledOnValidThread());
239 remote_ice_username_fragment_ = ufrag;
240 remote_ice_password_ = password;
242 if (channel_)
243 channel_->SetRemoteIceCredentials(ufrag, password);
246 void LibjingleTransport::AddRemoteCandidate(
247 const cricket::Candidate& candidate) {
248 DCHECK(CalledOnValidThread());
250 // To enforce the no-relay setting, it's not enough to not produce relay
251 // candidates. It's also necessary to discard remote relay candidates.
252 bool relay_allowed = (network_settings_.flags &
253 NetworkSettings::NAT_TRAVERSAL_RELAY) != 0;
254 if (!relay_allowed && candidate.type() == cricket::RELAY_PORT_TYPE)
255 return;
257 if (channel_) {
258 channel_->OnCandidate(candidate);
259 } else {
260 pending_candidates_.push_back(candidate);
264 const std::string& LibjingleTransport::name() const {
265 DCHECK(CalledOnValidThread());
266 return name_;
269 bool LibjingleTransport::is_connected() const {
270 DCHECK(CalledOnValidThread());
271 return callback_.is_null();
274 void LibjingleTransport::OnRequestSignaling(
275 cricket::TransportChannelImpl* channel) {
276 DCHECK(CalledOnValidThread());
277 channel_->OnSignalingReady();
280 void LibjingleTransport::OnCandidateReady(
281 cricket::TransportChannelImpl* channel,
282 const cricket::Candidate& candidate) {
283 DCHECK(CalledOnValidThread());
284 event_handler_->OnTransportCandidate(this, candidate);
287 void LibjingleTransport::OnRouteChange(
288 cricket::TransportChannel* channel,
289 const cricket::Candidate& candidate) {
290 // Ignore notifications if the channel is not writable.
291 if (channel_->writable())
292 NotifyRouteChanged();
295 void LibjingleTransport::OnWritableState(
296 cricket::TransportChannel* channel) {
297 DCHECK_EQ(channel, channel_.get());
299 if (channel->writable()) {
300 connect_attempts_left_ = kMaxReconnectAttempts;
301 reconnect_timer_.Stop();
303 // Route change notifications are ignored when the |channel_| is not
304 // writable. Notify the event handler about the current route once the
305 // channel is writable.
306 NotifyRouteChanged();
307 } else {
308 reconnect_timer_.Reset();
309 TryReconnect();
313 void LibjingleTransport::OnChannelDestroyed() {
314 // The connection socket is being deleted, so delete the transport too.
315 delete this;
318 void LibjingleTransport::NotifyRouteChanged() {
319 TransportRoute route;
321 DCHECK(channel_->best_connection());
322 const cricket::Connection* connection = channel_->best_connection();
324 // A connection has both a local and a remote candidate. For our purposes, the
325 // route type is determined by the most indirect candidate type. For example:
326 // it's possible for the local candidate be a "relay" type, while the remote
327 // candidate is "local". In this case, we still want to report a RELAY route
328 // type.
329 static_assert(TransportRoute::DIRECT < TransportRoute::STUN &&
330 TransportRoute::STUN < TransportRoute::RELAY,
331 "Route type enum values are ordered by 'indirectness'");
332 route.type = std::max(
333 CandidateTypeToTransportRouteType(connection->local_candidate().type()),
334 CandidateTypeToTransportRouteType(connection->remote_candidate().type()));
336 if (!jingle_glue::SocketAddressToIPEndPoint(
337 connection->remote_candidate().address(), &route.remote_address)) {
338 LOG(FATAL) << "Failed to convert peer IP address.";
341 const cricket::Candidate& local_candidate =
342 channel_->best_connection()->local_candidate();
343 if (!jingle_glue::SocketAddressToIPEndPoint(
344 local_candidate.address(), &route.local_address)) {
345 LOG(FATAL) << "Failed to convert local IP address.";
348 event_handler_->OnTransportRouteChange(this, route);
351 void LibjingleTransport::TryReconnect() {
352 DCHECK(!channel_->writable());
354 if (connect_attempts_left_ <= 0) {
355 reconnect_timer_.Stop();
357 // Notify the caller that ICE connection has failed - normally that will
358 // terminate Jingle connection (i.e. the transport will be destroyed).
359 event_handler_->OnTransportFailed(this);
360 return;
362 --connect_attempts_left_;
364 // Restart ICE by resetting ICE password.
365 std::string ice_password = rtc::CreateRandomString(cricket::ICE_PWD_LENGTH);
366 event_handler_->OnTransportIceCredentials(this, ice_username_fragment_,
367 ice_password);
368 channel_->SetIceCredentials(ice_username_fragment_, ice_password);
371 } // namespace
373 LibjingleTransportFactory::LibjingleTransportFactory(
374 SignalStrategy* signal_strategy,
375 scoped_ptr<cricket::HttpPortAllocatorBase> port_allocator,
376 const NetworkSettings& network_settings,
377 TransportRole role)
378 : signal_strategy_(signal_strategy),
379 port_allocator_(port_allocator.Pass()),
380 network_settings_(network_settings),
381 role_(role) {
384 LibjingleTransportFactory::~LibjingleTransportFactory() {
385 // This method may be called in response to a libjingle signal, so
386 // libjingle objects must be deleted asynchronously.
387 scoped_refptr<base::SingleThreadTaskRunner> task_runner =
388 base::ThreadTaskRunnerHandle::Get();
389 task_runner->DeleteSoon(FROM_HERE, port_allocator_.release());
392 void LibjingleTransportFactory::PrepareTokens() {
393 EnsureFreshJingleInfo();
396 scoped_ptr<Transport> LibjingleTransportFactory::CreateTransport() {
397 scoped_ptr<LibjingleTransport> result(
398 new LibjingleTransport(port_allocator_.get(), network_settings_, role_));
400 EnsureFreshJingleInfo();
402 // If there is a pending |jingle_info_request_| delay starting the new
403 // transport until the request is finished.
404 if (jingle_info_request_) {
405 on_jingle_info_callbacks_.push_back(
406 base::Bind(&LibjingleTransport::OnCanStart,
407 result->AsWeakPtr()));
408 } else {
409 result->OnCanStart();
412 return result.Pass();
415 void LibjingleTransportFactory::EnsureFreshJingleInfo() {
416 uint32 stun_or_relay_flags = NetworkSettings::NAT_TRAVERSAL_STUN |
417 NetworkSettings::NAT_TRAVERSAL_RELAY;
418 if (!(network_settings_.flags & stun_or_relay_flags) ||
419 jingle_info_request_) {
420 return;
423 if (base::TimeTicks::Now() - last_jingle_info_update_time_ >
424 base::TimeDelta::FromSeconds(kJingleInfoUpdatePeriodSeconds)) {
425 jingle_info_request_.reset(new JingleInfoRequest(signal_strategy_));
426 jingle_info_request_->Send(base::Bind(
427 &LibjingleTransportFactory::OnJingleInfo, base::Unretained(this)));
431 void LibjingleTransportFactory::OnJingleInfo(
432 const std::string& relay_token,
433 const std::vector<std::string>& relay_hosts,
434 const std::vector<rtc::SocketAddress>& stun_hosts) {
435 if (!relay_token.empty() && !relay_hosts.empty()) {
436 port_allocator_->SetRelayHosts(relay_hosts);
437 port_allocator_->SetRelayToken(relay_token);
439 if (!stun_hosts.empty()) {
440 port_allocator_->SetStunHosts(stun_hosts);
443 jingle_info_request_.reset();
444 if ((!relay_token.empty() && !relay_hosts.empty()) || !stun_hosts.empty())
445 last_jingle_info_update_time_ = base::TimeTicks::Now();
447 while (!on_jingle_info_callbacks_.empty()) {
448 on_jingle_info_callbacks_.begin()->Run();
449 on_jingle_info_callbacks_.pop_front();
453 } // namespace protocol
454 } // namespace remoting