Fix leak when a PeerConnection offer or answer is created.
[chromium-blink-merge.git] / remoting / protocol / libjingle_transport_factory.cc
blob3b4f830fccc8857e98b5f7d91b709097b95038f7
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/base64.h"
8 #include "base/callback.h"
9 #include "base/rand_util.h"
10 #include "base/single_thread_task_runner.h"
11 #include "base/thread_task_runner_handle.h"
12 #include "base/timer/timer.h"
13 #include "jingle/glue/channel_socket_adapter.h"
14 #include "jingle/glue/pseudotcp_adapter.h"
15 #include "jingle/glue/utils.h"
16 #include "net/base/net_errors.h"
17 #include "remoting/base/constants.h"
18 #include "remoting/jingle_glue/jingle_info_request.h"
19 #include "remoting/jingle_glue/network_settings.h"
20 #include "remoting/protocol/channel_authenticator.h"
21 #include "third_party/libjingle/source/talk/base/network.h"
22 #include "third_party/libjingle/source/talk/p2p/base/constants.h"
23 #include "third_party/libjingle/source/talk/p2p/base/p2ptransportchannel.h"
24 #include "third_party/libjingle/source/talk/p2p/client/basicportallocator.h"
25 #include "third_party/libjingle/source/talk/p2p/client/httpportallocator.h"
27 namespace remoting {
28 namespace protocol {
30 namespace {
32 // Value is chosen to balance the extra latency against the reduced
33 // load due to ACK traffic.
34 const int kTcpAckDelayMilliseconds = 10;
36 // Values for the TCP send and receive buffer size. This should be tuned to
37 // accommodate high latency network but not backlog the decoding pipeline.
38 const int kTcpReceiveBufferSize = 256 * 1024;
39 const int kTcpSendBufferSize = kTcpReceiveBufferSize + 30 * 1024;
41 // Try connecting ICE twice with timeout of 15 seconds for each attempt.
42 const int kMaxReconnectAttempts = 2;
43 const int kReconnectDelaySeconds = 15;
45 // Get fresh STUN/Relay configuration every hour.
46 const int kJingleInfoUpdatePeriodSeconds = 3600;
48 // TODO(sergeyu): Remove this function and use talk_base::CreateRandomString()
49 // when it's fixed to work reliably. See crbug.com/364689 .
50 std::string CreateRandomString(int length) {
51 // Number of random bytes to generate base64 string at least |length|
52 // characters long.
53 int raw_length = (length + 1) * 3 / 4;
54 std::string base64;
55 base::Base64Encode(base::RandBytesAsString(raw_length), &base64);
56 DCHECK(static_cast<int>(base64.size()) == length ||
57 static_cast<int>(base64.size()) == length + 1);
58 base64.resize(length);
59 return base64;
62 class LibjingleStreamTransport
63 : public StreamTransport,
64 public base::SupportsWeakPtr<LibjingleStreamTransport>,
65 public sigslot::has_slots<> {
66 public:
67 LibjingleStreamTransport(cricket::PortAllocator* port_allocator,
68 const NetworkSettings& network_settings);
69 virtual ~LibjingleStreamTransport();
71 // Called by JingleTransportFactory when it has fresh Jingle info.
72 void OnCanStart();
74 // StreamTransport interface.
75 virtual void Initialize(
76 const std::string& name,
77 Transport::EventHandler* event_handler,
78 scoped_ptr<ChannelAuthenticator> authenticator) OVERRIDE;
79 virtual void Connect(
80 const StreamTransport::ConnectedCallback& callback) OVERRIDE;
81 virtual void AddRemoteCandidate(const cricket::Candidate& candidate) OVERRIDE;
82 virtual const std::string& name() const OVERRIDE;
83 virtual bool is_connected() const OVERRIDE;
85 private:
86 void DoStart();
88 // Signal handlers for cricket::TransportChannel.
89 void OnRequestSignaling(cricket::TransportChannelImpl* channel);
90 void OnCandidateReady(cricket::TransportChannelImpl* channel,
91 const cricket::Candidate& candidate);
92 void OnRouteChange(cricket::TransportChannel* channel,
93 const cricket::Candidate& candidate);
94 void OnWritableState(cricket::TransportChannel* channel);
96 // Callback for PseudoTcpAdapter::Connect().
97 void OnTcpConnected(int result);
99 // Callback for Authenticator::SecureAndAuthenticate();
100 void OnAuthenticationDone(net::Error error,
101 scoped_ptr<net::StreamSocket> socket);
103 // Callback for jingle_glue::TransportChannelSocketAdapter to notify when the
104 // socket is destroyed.
105 void OnChannelDestroyed();
107 // Tries to connect by restarting ICE. Called by |reconnect_timer_|.
108 void TryReconnect();
110 // Helper methods to call |callback_|.
111 void NotifyConnected(scoped_ptr<net::StreamSocket> socket);
112 void NotifyConnectFailed();
114 cricket::PortAllocator* port_allocator_;
115 NetworkSettings network_settings_;
117 std::string name_;
118 EventHandler* event_handler_;
119 StreamTransport::ConnectedCallback callback_;
120 scoped_ptr<ChannelAuthenticator> authenticator_;
121 std::string ice_username_fragment_;
122 std::string ice_password_;
124 bool can_start_;
126 std::list<cricket::Candidate> pending_candidates_;
127 scoped_ptr<cricket::P2PTransportChannel> channel_;
128 bool channel_was_writable_;
129 int connect_attempts_left_;
130 base::RepeatingTimer<LibjingleStreamTransport> reconnect_timer_;
132 // We own |socket_| until it is connected.
133 scoped_ptr<jingle_glue::PseudoTcpAdapter> socket_;
135 DISALLOW_COPY_AND_ASSIGN(LibjingleStreamTransport);
138 LibjingleStreamTransport::LibjingleStreamTransport(
139 cricket::PortAllocator* port_allocator,
140 const NetworkSettings& network_settings)
141 : port_allocator_(port_allocator),
142 network_settings_(network_settings),
143 event_handler_(NULL),
144 ice_username_fragment_(CreateRandomString(cricket::ICE_UFRAG_LENGTH)),
145 ice_password_(CreateRandomString(cricket::ICE_PWD_LENGTH)),
146 can_start_(false),
147 channel_was_writable_(false),
148 connect_attempts_left_(kMaxReconnectAttempts) {
149 DCHECK(!ice_username_fragment_.empty());
150 DCHECK(!ice_password_.empty());
153 LibjingleStreamTransport::~LibjingleStreamTransport() {
154 DCHECK(event_handler_);
155 event_handler_->OnTransportDeleted(this);
156 // Channel should be already destroyed if we were connected.
157 DCHECK(!is_connected() || socket_.get() == NULL);
159 if (channel_.get()) {
160 base::ThreadTaskRunnerHandle::Get()->DeleteSoon(
161 FROM_HERE, channel_.release());
165 void LibjingleStreamTransport::OnCanStart() {
166 DCHECK(CalledOnValidThread());
168 DCHECK(!can_start_);
169 can_start_ = true;
171 // If Connect() has been called then start connection.
172 if (!callback_.is_null())
173 DoStart();
175 while (!pending_candidates_.empty()) {
176 channel_->OnCandidate(pending_candidates_.front());
177 pending_candidates_.pop_front();
181 void LibjingleStreamTransport::Initialize(
182 const std::string& name,
183 Transport::EventHandler* event_handler,
184 scoped_ptr<ChannelAuthenticator> authenticator) {
185 DCHECK(CalledOnValidThread());
187 DCHECK(!name.empty());
188 DCHECK(event_handler);
190 // Can be initialized only once.
191 DCHECK(name_.empty());
193 name_ = name;
194 event_handler_ = event_handler;
195 authenticator_ = authenticator.Pass();
198 void LibjingleStreamTransport::Connect(
199 const StreamTransport::ConnectedCallback& callback) {
200 DCHECK(CalledOnValidThread());
201 callback_ = callback;
203 if (can_start_)
204 DoStart();
207 void LibjingleStreamTransport::DoStart() {
208 DCHECK(!channel_.get());
210 // Create P2PTransportChannel, attach signal handlers and connect it.
211 // TODO(sergeyu): Specify correct component ID for the channel.
212 channel_.reset(new cricket::P2PTransportChannel(
213 std::string(), 0, NULL, port_allocator_));
214 channel_->SetIceProtocolType(cricket::ICEPROTO_GOOGLE);
215 channel_->SetIceCredentials(ice_username_fragment_, ice_password_);
216 channel_->SignalRequestSignaling.connect(
217 this, &LibjingleStreamTransport::OnRequestSignaling);
218 channel_->SignalCandidateReady.connect(
219 this, &LibjingleStreamTransport::OnCandidateReady);
220 channel_->SignalRouteChange.connect(
221 this, &LibjingleStreamTransport::OnRouteChange);
222 channel_->SignalWritableState.connect(
223 this, &LibjingleStreamTransport::OnWritableState);
224 channel_->set_incoming_only(
225 !(network_settings_.flags & NetworkSettings::NAT_TRAVERSAL_OUTGOING));
227 channel_->Connect();
229 --connect_attempts_left_;
231 // Start reconnection timer.
232 reconnect_timer_.Start(
233 FROM_HERE, base::TimeDelta::FromSeconds(kReconnectDelaySeconds),
234 this, &LibjingleStreamTransport::TryReconnect);
236 // Create net::Socket adapter for the P2PTransportChannel.
237 scoped_ptr<jingle_glue::TransportChannelSocketAdapter> channel_adapter(
238 new jingle_glue::TransportChannelSocketAdapter(channel_.get()));
240 channel_adapter->SetOnDestroyedCallback(base::Bind(
241 &LibjingleStreamTransport::OnChannelDestroyed, base::Unretained(this)));
243 // Configure and connect PseudoTCP adapter.
244 socket_.reset(
245 new jingle_glue::PseudoTcpAdapter(channel_adapter.release()));
246 socket_->SetSendBufferSize(kTcpSendBufferSize);
247 socket_->SetReceiveBufferSize(kTcpReceiveBufferSize);
248 socket_->SetNoDelay(true);
249 socket_->SetAckDelay(kTcpAckDelayMilliseconds);
251 // TODO(sergeyu): This is a hack to improve latency of the video
252 // channel. Consider removing it once we have better flow control
253 // implemented.
254 if (name_ == kVideoChannelName)
255 socket_->SetWriteWaitsForSend(true);
257 int result = socket_->Connect(
258 base::Bind(&LibjingleStreamTransport::OnTcpConnected,
259 base::Unretained(this)));
260 if (result != net::ERR_IO_PENDING)
261 OnTcpConnected(result);
264 void LibjingleStreamTransport::AddRemoteCandidate(
265 const cricket::Candidate& candidate) {
266 DCHECK(CalledOnValidThread());
267 if (channel_) {
268 channel_->OnCandidate(candidate);
269 } else {
270 pending_candidates_.push_back(candidate);
274 const std::string& LibjingleStreamTransport::name() const {
275 DCHECK(CalledOnValidThread());
276 return name_;
279 bool LibjingleStreamTransport::is_connected() const {
280 DCHECK(CalledOnValidThread());
281 return callback_.is_null();
284 void LibjingleStreamTransport::OnRequestSignaling(
285 cricket::TransportChannelImpl* channel) {
286 DCHECK(CalledOnValidThread());
287 channel_->OnSignalingReady();
290 void LibjingleStreamTransport::OnCandidateReady(
291 cricket::TransportChannelImpl* channel,
292 const cricket::Candidate& candidate) {
293 DCHECK(CalledOnValidThread());
294 event_handler_->OnTransportCandidate(this, candidate);
297 void LibjingleStreamTransport::OnRouteChange(
298 cricket::TransportChannel* channel,
299 const cricket::Candidate& candidate) {
300 TransportRoute route;
302 if (candidate.type() == "local") {
303 route.type = TransportRoute::DIRECT;
304 } else if (candidate.type() == "stun") {
305 route.type = TransportRoute::STUN;
306 } else if (candidate.type() == "relay") {
307 route.type = TransportRoute::RELAY;
308 } else {
309 LOG(FATAL) << "Unknown candidate type: " << candidate.type();
312 if (!jingle_glue::SocketAddressToIPEndPoint(
313 candidate.address(), &route.remote_address)) {
314 LOG(FATAL) << "Failed to convert peer IP address.";
317 DCHECK(channel_->best_connection());
318 const cricket::Candidate& local_candidate =
319 channel_->best_connection()->local_candidate();
320 if (!jingle_glue::SocketAddressToIPEndPoint(
321 local_candidate.address(), &route.local_address)) {
322 LOG(FATAL) << "Failed to convert local IP address.";
325 event_handler_->OnTransportRouteChange(this, route);
328 void LibjingleStreamTransport::OnWritableState(
329 cricket::TransportChannel* channel) {
330 DCHECK_EQ(channel, channel_.get());
332 if (channel->writable()) {
333 channel_was_writable_ = true;
334 connect_attempts_left_ = kMaxReconnectAttempts;
335 reconnect_timer_.Stop();
336 } else if (!channel->writable() && channel_was_writable_) {
337 reconnect_timer_.Reset();
338 TryReconnect();
342 void LibjingleStreamTransport::OnTcpConnected(int result) {
343 DCHECK(CalledOnValidThread());
345 if (result != net::OK) {
346 NotifyConnectFailed();
347 return;
350 authenticator_->SecureAndAuthenticate(
351 socket_.PassAs<net::StreamSocket>(),
352 base::Bind(&LibjingleStreamTransport::OnAuthenticationDone,
353 base::Unretained(this)));
356 void LibjingleStreamTransport::OnAuthenticationDone(
357 net::Error error,
358 scoped_ptr<net::StreamSocket> socket) {
359 if (error != net::OK) {
360 NotifyConnectFailed();
361 return;
364 NotifyConnected(socket.Pass());
367 void LibjingleStreamTransport::OnChannelDestroyed() {
368 if (is_connected()) {
369 // The connection socket is being deleted, so delete the transport too.
370 delete this;
374 void LibjingleStreamTransport::TryReconnect() {
375 DCHECK(!channel_->writable());
377 if (connect_attempts_left_ <= 0) {
378 reconnect_timer_.Stop();
380 // Notify the caller that ICE connection has failed - normally that will
381 // terminate Jingle connection (i.e. the transport will be destroyed).
382 event_handler_->OnTransportFailed(this);
383 return;
385 --connect_attempts_left_;
387 // Restart ICE by resetting ICE password.
388 ice_password_ = CreateRandomString(cricket::ICE_PWD_LENGTH);
389 channel_->SetIceCredentials(ice_username_fragment_, ice_password_);
392 void LibjingleStreamTransport::NotifyConnected(
393 scoped_ptr<net::StreamSocket> socket) {
394 DCHECK(!is_connected());
395 StreamTransport::ConnectedCallback callback = callback_;
396 callback_.Reset();
397 callback.Run(socket.Pass());
400 void LibjingleStreamTransport::NotifyConnectFailed() {
401 DCHECK(!is_connected());
403 socket_.reset();
405 // This method may be called in response to a libjingle signal, so
406 // libjingle objects must be deleted asynchronously.
407 if (channel_.get()) {
408 base::ThreadTaskRunnerHandle::Get()->DeleteSoon(
409 FROM_HERE, channel_.release());
412 authenticator_.reset();
414 NotifyConnected(scoped_ptr<net::StreamSocket>());
417 } // namespace
419 LibjingleTransportFactory::LibjingleTransportFactory(
420 SignalStrategy* signal_strategy,
421 scoped_ptr<cricket::HttpPortAllocatorBase> port_allocator,
422 const NetworkSettings& network_settings)
423 : signal_strategy_(signal_strategy),
424 port_allocator_(port_allocator.Pass()),
425 network_settings_(network_settings) {
428 LibjingleTransportFactory::~LibjingleTransportFactory() {
429 // This method may be called in response to a libjingle signal, so
430 // libjingle objects must be deleted asynchronously.
431 scoped_refptr<base::SingleThreadTaskRunner> task_runner =
432 base::ThreadTaskRunnerHandle::Get();
433 task_runner->DeleteSoon(FROM_HERE, port_allocator_.release());
436 void LibjingleTransportFactory::PrepareTokens() {
437 EnsureFreshJingleInfo();
440 scoped_ptr<StreamTransport> LibjingleTransportFactory::CreateStreamTransport() {
441 scoped_ptr<LibjingleStreamTransport> result(
442 new LibjingleStreamTransport(port_allocator_.get(), network_settings_));
444 EnsureFreshJingleInfo();
446 // If there is a pending |jingle_info_request_| delay starting the new
447 // transport until the request is finished.
448 if (jingle_info_request_) {
449 on_jingle_info_callbacks_.push_back(
450 base::Bind(&LibjingleStreamTransport::OnCanStart,
451 result->AsWeakPtr()));
452 } else {
453 result->OnCanStart();
456 return result.PassAs<StreamTransport>();
459 scoped_ptr<DatagramTransport>
460 LibjingleTransportFactory::CreateDatagramTransport() {
461 NOTIMPLEMENTED();
462 return scoped_ptr<DatagramTransport>();
465 void LibjingleTransportFactory::EnsureFreshJingleInfo() {
466 uint32 stun_or_relay_flags = NetworkSettings::NAT_TRAVERSAL_STUN |
467 NetworkSettings::NAT_TRAVERSAL_RELAY;
468 if (!(network_settings_.flags & stun_or_relay_flags) ||
469 jingle_info_request_) {
470 return;
473 if (base::TimeTicks::Now() - last_jingle_info_update_time_ >
474 base::TimeDelta::FromSeconds(kJingleInfoUpdatePeriodSeconds)) {
475 jingle_info_request_.reset(new JingleInfoRequest(signal_strategy_));
476 jingle_info_request_->Send(base::Bind(
477 &LibjingleTransportFactory::OnJingleInfo, base::Unretained(this)));
481 void LibjingleTransportFactory::OnJingleInfo(
482 const std::string& relay_token,
483 const std::vector<std::string>& relay_hosts,
484 const std::vector<talk_base::SocketAddress>& stun_hosts) {
485 if (!relay_token.empty() && !relay_hosts.empty()) {
486 port_allocator_->SetRelayHosts(relay_hosts);
487 port_allocator_->SetRelayToken(relay_token);
489 if (!stun_hosts.empty()) {
490 port_allocator_->SetStunHosts(stun_hosts);
493 jingle_info_request_.reset();
494 if ((!relay_token.empty() && !relay_hosts.empty()) || !stun_hosts.empty())
495 last_jingle_info_update_time_ = base::TimeTicks::Now();
497 while (!on_jingle_info_callbacks_.empty()) {
498 on_jingle_info_callbacks_.begin()->Run();
499 on_jingle_info_callbacks_.pop_front();
503 } // namespace protocol
504 } // namespace remoting