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 "base/callback.h"
8 #include "base/single_thread_task_runner.h"
9 #include "base/thread_task_runner_handle.h"
10 #include "base/timer/timer.h"
11 #include "jingle/glue/channel_socket_adapter.h"
12 #include "jingle/glue/pseudotcp_adapter.h"
13 #include "jingle/glue/utils.h"
14 #include "net/base/net_errors.h"
15 #include "remoting/base/constants.h"
16 #include "remoting/protocol/channel_authenticator.h"
17 #include "remoting/protocol/network_settings.h"
18 #include "remoting/signaling/jingle_info_request.h"
19 #include "third_party/libjingle/source/talk/p2p/base/constants.h"
20 #include "third_party/libjingle/source/talk/p2p/base/p2ptransportchannel.h"
21 #include "third_party/libjingle/source/talk/p2p/base/port.h"
22 #include "third_party/libjingle/source/talk/p2p/client/basicportallocator.h"
23 #include "third_party/libjingle/source/talk/p2p/client/httpportallocator.h"
24 #include "third_party/webrtc/base/network.h"
31 // Value is chosen to balance the extra latency against the reduced
32 // load due to ACK traffic.
33 const int kTcpAckDelayMilliseconds
= 10;
35 // Values for the TCP send and receive buffer size. This should be tuned to
36 // accommodate high latency network but not backlog the decoding pipeline.
37 const int kTcpReceiveBufferSize
= 256 * 1024;
38 const int kTcpSendBufferSize
= kTcpReceiveBufferSize
+ 30 * 1024;
40 // Try connecting ICE twice with timeout of 15 seconds for each attempt.
41 const int kMaxReconnectAttempts
= 2;
42 const int kReconnectDelaySeconds
= 15;
44 // Get fresh STUN/Relay configuration every hour.
45 const int kJingleInfoUpdatePeriodSeconds
= 3600;
47 class LibjingleStreamTransport
48 : public StreamTransport
,
49 public base::SupportsWeakPtr
<LibjingleStreamTransport
>,
50 public sigslot::has_slots
<> {
52 LibjingleStreamTransport(cricket::PortAllocator
* port_allocator
,
53 const NetworkSettings
& network_settings
);
54 virtual ~LibjingleStreamTransport();
56 // Called by JingleTransportFactory when it has fresh Jingle info.
59 // StreamTransport interface.
60 virtual void Initialize(
61 const std::string
& name
,
62 Transport::EventHandler
* event_handler
,
63 scoped_ptr
<ChannelAuthenticator
> authenticator
) OVERRIDE
;
65 const StreamTransport::ConnectedCallback
& callback
) OVERRIDE
;
66 virtual void AddRemoteCandidate(const cricket::Candidate
& candidate
) OVERRIDE
;
67 virtual const std::string
& name() const OVERRIDE
;
68 virtual bool is_connected() const OVERRIDE
;
73 // Signal handlers for cricket::TransportChannel.
74 void OnRequestSignaling(cricket::TransportChannelImpl
* channel
);
75 void OnCandidateReady(cricket::TransportChannelImpl
* channel
,
76 const cricket::Candidate
& candidate
);
77 void OnRouteChange(cricket::TransportChannel
* channel
,
78 const cricket::Candidate
& candidate
);
79 void OnWritableState(cricket::TransportChannel
* channel
);
81 // Callback for PseudoTcpAdapter::Connect().
82 void OnTcpConnected(int result
);
84 // Callback for Authenticator::SecureAndAuthenticate();
85 void OnAuthenticationDone(net::Error error
,
86 scoped_ptr
<net::StreamSocket
> socket
);
88 // Callback for jingle_glue::TransportChannelSocketAdapter to notify when the
89 // socket is destroyed.
90 void OnChannelDestroyed();
92 // Tries to connect by restarting ICE. Called by |reconnect_timer_|.
95 // Helper methods to call |callback_|.
96 void NotifyConnected(scoped_ptr
<net::StreamSocket
> socket
);
97 void NotifyConnectFailed();
99 cricket::PortAllocator
* port_allocator_
;
100 NetworkSettings network_settings_
;
103 EventHandler
* event_handler_
;
104 StreamTransport::ConnectedCallback callback_
;
105 scoped_ptr
<ChannelAuthenticator
> authenticator_
;
106 std::string ice_username_fragment_
;
107 std::string ice_password_
;
111 std::list
<cricket::Candidate
> pending_candidates_
;
112 scoped_ptr
<cricket::P2PTransportChannel
> channel_
;
113 bool channel_was_writable_
;
114 int connect_attempts_left_
;
115 base::RepeatingTimer
<LibjingleStreamTransport
> reconnect_timer_
;
117 // We own |socket_| until it is connected.
118 scoped_ptr
<jingle_glue::PseudoTcpAdapter
> socket_
;
120 DISALLOW_COPY_AND_ASSIGN(LibjingleStreamTransport
);
123 LibjingleStreamTransport::LibjingleStreamTransport(
124 cricket::PortAllocator
* port_allocator
,
125 const NetworkSettings
& network_settings
)
126 : port_allocator_(port_allocator
),
127 network_settings_(network_settings
),
128 event_handler_(NULL
),
129 ice_username_fragment_(
130 rtc::CreateRandomString(cricket::ICE_UFRAG_LENGTH
)),
131 ice_password_(rtc::CreateRandomString(cricket::ICE_PWD_LENGTH
)),
133 channel_was_writable_(false),
134 connect_attempts_left_(kMaxReconnectAttempts
) {
135 DCHECK(!ice_username_fragment_
.empty());
136 DCHECK(!ice_password_
.empty());
139 LibjingleStreamTransport::~LibjingleStreamTransport() {
140 DCHECK(event_handler_
);
141 event_handler_
->OnTransportDeleted(this);
142 // Channel should be already destroyed if we were connected.
143 DCHECK(!is_connected() || socket_
.get() == NULL
);
145 if (channel_
.get()) {
146 base::ThreadTaskRunnerHandle::Get()->DeleteSoon(
147 FROM_HERE
, channel_
.release());
151 void LibjingleStreamTransport::OnCanStart() {
152 DCHECK(CalledOnValidThread());
157 // If Connect() has been called then start connection.
158 if (!callback_
.is_null())
161 while (!pending_candidates_
.empty()) {
162 channel_
->OnCandidate(pending_candidates_
.front());
163 pending_candidates_
.pop_front();
167 void LibjingleStreamTransport::Initialize(
168 const std::string
& name
,
169 Transport::EventHandler
* event_handler
,
170 scoped_ptr
<ChannelAuthenticator
> authenticator
) {
171 DCHECK(CalledOnValidThread());
173 DCHECK(!name
.empty());
174 DCHECK(event_handler
);
176 // Can be initialized only once.
177 DCHECK(name_
.empty());
180 event_handler_
= event_handler
;
181 authenticator_
= authenticator
.Pass();
184 void LibjingleStreamTransport::Connect(
185 const StreamTransport::ConnectedCallback
& callback
) {
186 DCHECK(CalledOnValidThread());
187 callback_
= callback
;
193 void LibjingleStreamTransport::DoStart() {
194 DCHECK(!channel_
.get());
196 // Create P2PTransportChannel, attach signal handlers and connect it.
197 // TODO(sergeyu): Specify correct component ID for the channel.
198 channel_
.reset(new cricket::P2PTransportChannel(
199 std::string(), 0, NULL
, port_allocator_
));
200 channel_
->SetIceProtocolType(cricket::ICEPROTO_GOOGLE
);
201 channel_
->SetIceCredentials(ice_username_fragment_
, ice_password_
);
202 channel_
->SignalRequestSignaling
.connect(
203 this, &LibjingleStreamTransport::OnRequestSignaling
);
204 channel_
->SignalCandidateReady
.connect(
205 this, &LibjingleStreamTransport::OnCandidateReady
);
206 channel_
->SignalRouteChange
.connect(
207 this, &LibjingleStreamTransport::OnRouteChange
);
208 channel_
->SignalWritableState
.connect(
209 this, &LibjingleStreamTransport::OnWritableState
);
210 channel_
->set_incoming_only(
211 !(network_settings_
.flags
& NetworkSettings::NAT_TRAVERSAL_OUTGOING
));
215 --connect_attempts_left_
;
217 // Start reconnection timer.
218 reconnect_timer_
.Start(
219 FROM_HERE
, base::TimeDelta::FromSeconds(kReconnectDelaySeconds
),
220 this, &LibjingleStreamTransport::TryReconnect
);
222 // Create net::Socket adapter for the P2PTransportChannel.
223 scoped_ptr
<jingle_glue::TransportChannelSocketAdapter
> channel_adapter(
224 new jingle_glue::TransportChannelSocketAdapter(channel_
.get()));
226 channel_adapter
->SetOnDestroyedCallback(base::Bind(
227 &LibjingleStreamTransport::OnChannelDestroyed
, base::Unretained(this)));
229 // Configure and connect PseudoTCP adapter.
231 new jingle_glue::PseudoTcpAdapter(channel_adapter
.release()));
232 socket_
->SetSendBufferSize(kTcpSendBufferSize
);
233 socket_
->SetReceiveBufferSize(kTcpReceiveBufferSize
);
234 socket_
->SetNoDelay(true);
235 socket_
->SetAckDelay(kTcpAckDelayMilliseconds
);
237 // TODO(sergeyu): This is a hack to improve latency of the video
238 // channel. Consider removing it once we have better flow control
240 if (name_
== kVideoChannelName
)
241 socket_
->SetWriteWaitsForSend(true);
243 int result
= socket_
->Connect(
244 base::Bind(&LibjingleStreamTransport::OnTcpConnected
,
245 base::Unretained(this)));
246 if (result
!= net::ERR_IO_PENDING
)
247 OnTcpConnected(result
);
250 void LibjingleStreamTransport::AddRemoteCandidate(
251 const cricket::Candidate
& candidate
) {
252 DCHECK(CalledOnValidThread());
254 // To enforce the no-relay setting, it's not enough to not produce relay
255 // candidates. It's also necessary to discard remote relay candidates.
256 bool relay_allowed
= (network_settings_
.flags
&
257 NetworkSettings::NAT_TRAVERSAL_RELAY
) != 0;
258 if (!relay_allowed
&& candidate
.type() == cricket::RELAY_PORT_TYPE
)
262 channel_
->OnCandidate(candidate
);
264 pending_candidates_
.push_back(candidate
);
268 const std::string
& LibjingleStreamTransport::name() const {
269 DCHECK(CalledOnValidThread());
273 bool LibjingleStreamTransport::is_connected() const {
274 DCHECK(CalledOnValidThread());
275 return callback_
.is_null();
278 void LibjingleStreamTransport::OnRequestSignaling(
279 cricket::TransportChannelImpl
* channel
) {
280 DCHECK(CalledOnValidThread());
281 channel_
->OnSignalingReady();
284 void LibjingleStreamTransport::OnCandidateReady(
285 cricket::TransportChannelImpl
* channel
,
286 const cricket::Candidate
& candidate
) {
287 DCHECK(CalledOnValidThread());
288 event_handler_
->OnTransportCandidate(this, candidate
);
291 void LibjingleStreamTransport::OnRouteChange(
292 cricket::TransportChannel
* channel
,
293 const cricket::Candidate
& candidate
) {
294 TransportRoute route
;
296 if (candidate
.type() == "local") {
297 route
.type
= TransportRoute::DIRECT
;
298 } else if (candidate
.type() == "stun") {
299 route
.type
= TransportRoute::STUN
;
300 } else if (candidate
.type() == "relay") {
301 route
.type
= TransportRoute::RELAY
;
303 LOG(FATAL
) << "Unknown candidate type: " << candidate
.type();
306 if (!jingle_glue::SocketAddressToIPEndPoint(
307 candidate
.address(), &route
.remote_address
)) {
308 LOG(FATAL
) << "Failed to convert peer IP address.";
311 DCHECK(channel_
->best_connection());
312 const cricket::Candidate
& local_candidate
=
313 channel_
->best_connection()->local_candidate();
314 if (!jingle_glue::SocketAddressToIPEndPoint(
315 local_candidate
.address(), &route
.local_address
)) {
316 LOG(FATAL
) << "Failed to convert local IP address.";
319 event_handler_
->OnTransportRouteChange(this, route
);
322 void LibjingleStreamTransport::OnWritableState(
323 cricket::TransportChannel
* channel
) {
324 DCHECK_EQ(channel
, channel_
.get());
326 if (channel
->writable()) {
327 channel_was_writable_
= true;
328 connect_attempts_left_
= kMaxReconnectAttempts
;
329 reconnect_timer_
.Stop();
330 } else if (!channel
->writable() && channel_was_writable_
) {
331 reconnect_timer_
.Reset();
336 void LibjingleStreamTransport::OnTcpConnected(int result
) {
337 DCHECK(CalledOnValidThread());
339 if (result
!= net::OK
) {
340 NotifyConnectFailed();
344 authenticator_
->SecureAndAuthenticate(
345 socket_
.PassAs
<net::StreamSocket
>(),
346 base::Bind(&LibjingleStreamTransport::OnAuthenticationDone
,
347 base::Unretained(this)));
350 void LibjingleStreamTransport::OnAuthenticationDone(
352 scoped_ptr
<net::StreamSocket
> socket
) {
353 if (error
!= net::OK
) {
354 NotifyConnectFailed();
358 NotifyConnected(socket
.Pass());
361 void LibjingleStreamTransport::OnChannelDestroyed() {
362 if (is_connected()) {
363 // The connection socket is being deleted, so delete the transport too.
368 void LibjingleStreamTransport::TryReconnect() {
369 DCHECK(!channel_
->writable());
371 if (connect_attempts_left_
<= 0) {
372 reconnect_timer_
.Stop();
374 // Notify the caller that ICE connection has failed - normally that will
375 // terminate Jingle connection (i.e. the transport will be destroyed).
376 event_handler_
->OnTransportFailed(this);
379 --connect_attempts_left_
;
381 // Restart ICE by resetting ICE password.
382 ice_password_
= rtc::CreateRandomString(cricket::ICE_PWD_LENGTH
);
383 channel_
->SetIceCredentials(ice_username_fragment_
, ice_password_
);
386 void LibjingleStreamTransport::NotifyConnected(
387 scoped_ptr
<net::StreamSocket
> socket
) {
388 DCHECK(!is_connected());
389 StreamTransport::ConnectedCallback callback
= callback_
;
391 callback
.Run(socket
.Pass());
394 void LibjingleStreamTransport::NotifyConnectFailed() {
395 DCHECK(!is_connected());
399 // This method may be called in response to a libjingle signal, so
400 // libjingle objects must be deleted asynchronously.
401 if (channel_
.get()) {
402 base::ThreadTaskRunnerHandle::Get()->DeleteSoon(
403 FROM_HERE
, channel_
.release());
406 authenticator_
.reset();
408 NotifyConnected(scoped_ptr
<net::StreamSocket
>());
413 LibjingleTransportFactory::LibjingleTransportFactory(
414 SignalStrategy
* signal_strategy
,
415 scoped_ptr
<cricket::HttpPortAllocatorBase
> port_allocator
,
416 const NetworkSettings
& network_settings
)
417 : signal_strategy_(signal_strategy
),
418 port_allocator_(port_allocator
.Pass()),
419 network_settings_(network_settings
) {
422 LibjingleTransportFactory::~LibjingleTransportFactory() {
423 // This method may be called in response to a libjingle signal, so
424 // libjingle objects must be deleted asynchronously.
425 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner
=
426 base::ThreadTaskRunnerHandle::Get();
427 task_runner
->DeleteSoon(FROM_HERE
, port_allocator_
.release());
430 void LibjingleTransportFactory::PrepareTokens() {
431 EnsureFreshJingleInfo();
434 scoped_ptr
<StreamTransport
> LibjingleTransportFactory::CreateStreamTransport() {
435 scoped_ptr
<LibjingleStreamTransport
> result(
436 new LibjingleStreamTransport(port_allocator_
.get(), network_settings_
));
438 EnsureFreshJingleInfo();
440 // If there is a pending |jingle_info_request_| delay starting the new
441 // transport until the request is finished.
442 if (jingle_info_request_
) {
443 on_jingle_info_callbacks_
.push_back(
444 base::Bind(&LibjingleStreamTransport::OnCanStart
,
445 result
->AsWeakPtr()));
447 result
->OnCanStart();
450 return result
.PassAs
<StreamTransport
>();
453 scoped_ptr
<DatagramTransport
>
454 LibjingleTransportFactory::CreateDatagramTransport() {
456 return scoped_ptr
<DatagramTransport
>();
459 void LibjingleTransportFactory::EnsureFreshJingleInfo() {
460 uint32 stun_or_relay_flags
= NetworkSettings::NAT_TRAVERSAL_STUN
|
461 NetworkSettings::NAT_TRAVERSAL_RELAY
;
462 if (!(network_settings_
.flags
& stun_or_relay_flags
) ||
463 jingle_info_request_
) {
467 if (base::TimeTicks::Now() - last_jingle_info_update_time_
>
468 base::TimeDelta::FromSeconds(kJingleInfoUpdatePeriodSeconds
)) {
469 jingle_info_request_
.reset(new JingleInfoRequest(signal_strategy_
));
470 jingle_info_request_
->Send(base::Bind(
471 &LibjingleTransportFactory::OnJingleInfo
, base::Unretained(this)));
475 void LibjingleTransportFactory::OnJingleInfo(
476 const std::string
& relay_token
,
477 const std::vector
<std::string
>& relay_hosts
,
478 const std::vector
<rtc::SocketAddress
>& stun_hosts
) {
479 if (!relay_token
.empty() && !relay_hosts
.empty()) {
480 port_allocator_
->SetRelayHosts(relay_hosts
);
481 port_allocator_
->SetRelayToken(relay_token
);
483 if (!stun_hosts
.empty()) {
484 port_allocator_
->SetStunHosts(stun_hosts
);
487 jingle_info_request_
.reset();
488 if ((!relay_token
.empty() && !relay_hosts
.empty()) || !stun_hosts
.empty())
489 last_jingle_info_update_time_
= base::TimeTicks::Now();
491 while (!on_jingle_info_callbacks_
.empty()) {
492 on_jingle_info_callbacks_
.begin()->Run();
493 on_jingle_info_callbacks_
.pop_front();
497 } // namespace protocol
498 } // namespace remoting