blob: 7993cc02bc082819340ca1e80b974dd91716f995 [file] [log] [blame]
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "webrtc/p2p/base/port.h"
12
13#include <algorithm>
14#include <vector>
15
16#include "webrtc/p2p/base/common.h"
17#include "webrtc/p2p/base/portallocator.h"
18#include "webrtc/base/base64.h"
19#include "webrtc/base/crc32.h"
20#include "webrtc/base/helpers.h"
21#include "webrtc/base/logging.h"
22#include "webrtc/base/messagedigest.h"
23#include "webrtc/base/scoped_ptr.h"
24#include "webrtc/base/stringencode.h"
25#include "webrtc/base/stringutils.h"
26
27namespace {
28
29// Determines whether we have seen at least the given maximum number of
30// pings fail to have a response.
31inline bool TooManyFailures(
Peter Thatcher1cf6f812015-05-15 10:40:45 -070032 const std::vector<cricket::Connection::SentPing>& pings_since_last_response,
Peter Boström0c4e06b2015-10-07 12:23:21 +020033 uint32_t maximum_failures,
34 uint32_t rtt_estimate,
35 uint32_t now) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000036 // If we haven't sent that many pings, then we can't have failed that many.
37 if (pings_since_last_response.size() < maximum_failures)
38 return false;
39
40 // Check if the window in which we would expect a response to the ping has
41 // already elapsed.
Peter Boström0c4e06b2015-10-07 12:23:21 +020042 uint32_t expected_response_time =
Peter Thatcher1cf6f812015-05-15 10:40:45 -070043 pings_since_last_response[maximum_failures - 1].sent_time + rtt_estimate;
44 return now > expected_response_time;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000045}
46
47// Determines whether we have gone too long without seeing any response.
48inline bool TooLongWithoutResponse(
Peter Thatcher1cf6f812015-05-15 10:40:45 -070049 const std::vector<cricket::Connection::SentPing>& pings_since_last_response,
Peter Boström0c4e06b2015-10-07 12:23:21 +020050 uint32_t maximum_time,
51 uint32_t now) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000052 if (pings_since_last_response.size() == 0)
53 return false;
54
Peter Thatcher1cf6f812015-05-15 10:40:45 -070055 auto first = pings_since_last_response[0];
56 return now > (first.sent_time + maximum_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000057}
58
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000059// We will restrict RTT estimates (when used for determining state) to be
60// within a reasonable range.
Peter Boström0c4e06b2015-10-07 12:23:21 +020061const uint32_t MINIMUM_RTT = 100; // 0.1 seconds
62const uint32_t MAXIMUM_RTT = 3000; // 3 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000063
64// When we don't have any RTT data, we have to pick something reasonable. We
65// use a large value just in case the connection is really slow.
Peter Boström0c4e06b2015-10-07 12:23:21 +020066const uint32_t DEFAULT_RTT = MAXIMUM_RTT;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000067
68// Computes our estimate of the RTT given the current estimate.
Peter Boström0c4e06b2015-10-07 12:23:21 +020069inline uint32_t ConservativeRTTEstimate(uint32_t rtt) {
andresp@webrtc.orgff689be2015-02-12 11:54:26 +000070 return std::max(MINIMUM_RTT, std::min(MAXIMUM_RTT, 2 * rtt));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000071}
72
73// Weighting of the old rtt value to new data.
74const int RTT_RATIO = 3; // 3 : 1
75
76// The delay before we begin checking if this port is useless.
77const int kPortTimeoutDelay = 30 * 1000; // 30 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000078}
79
80namespace cricket {
81
82// TODO(ronghuawu): Use "host", "srflx", "prflx" and "relay". But this requires
83// the signaling part be updated correspondingly as well.
84const char LOCAL_PORT_TYPE[] = "local";
85const char STUN_PORT_TYPE[] = "stun";
86const char PRFLX_PORT_TYPE[] = "prflx";
87const char RELAY_PORT_TYPE[] = "relay";
88
89const char UDP_PROTOCOL_NAME[] = "udp";
90const char TCP_PROTOCOL_NAME[] = "tcp";
91const char SSLTCP_PROTOCOL_NAME[] = "ssltcp";
92
93static const char* const PROTO_NAMES[] = { UDP_PROTOCOL_NAME,
94 TCP_PROTOCOL_NAME,
95 SSLTCP_PROTOCOL_NAME };
96
97const char* ProtoToString(ProtocolType proto) {
98 return PROTO_NAMES[proto];
99}
100
101bool StringToProto(const char* value, ProtocolType* proto) {
102 for (size_t i = 0; i <= PROTO_LAST; ++i) {
103 if (_stricmp(PROTO_NAMES[i], value) == 0) {
104 *proto = static_cast<ProtocolType>(i);
105 return true;
106 }
107 }
108 return false;
109}
110
111// RFC 6544, TCP candidate encoding rules.
112const int DISCARD_PORT = 9;
113const char TCPTYPE_ACTIVE_STR[] = "active";
114const char TCPTYPE_PASSIVE_STR[] = "passive";
115const char TCPTYPE_SIMOPEN_STR[] = "so";
116
117// Foundation: An arbitrary string that is the same for two candidates
118// that have the same type, base IP address, protocol (UDP, TCP,
119// etc.), and STUN or TURN server. If any of these are different,
120// then the foundation will be different. Two candidate pairs with
121// the same foundation pairs are likely to have similar network
122// characteristics. Foundations are used in the frozen algorithm.
Honghai Zhang80f1db92016-01-27 11:54:45 -0800123static std::string ComputeFoundation(const std::string& type,
124 const std::string& protocol,
125 const std::string& relay_protocol,
126 const rtc::SocketAddress& base_address) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000127 std::ostringstream ost;
Honghai Zhang80f1db92016-01-27 11:54:45 -0800128 ost << type << base_address.ipaddr().ToString() << protocol << relay_protocol;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200129 return rtc::ToString<uint32_t>(rtc::ComputeCrc32(ost.str()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000130}
131
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000132Port::Port(rtc::Thread* thread,
133 rtc::PacketSocketFactory* factory,
134 rtc::Network* network,
135 const rtc::IPAddress& ip,
136 const std::string& username_fragment,
137 const std::string& password)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000138 : thread_(thread),
139 factory_(factory),
140 send_retransmit_count_attribute_(false),
141 network_(network),
142 ip_(ip),
143 min_port_(0),
144 max_port_(0),
145 component_(ICE_CANDIDATE_COMPONENT_DEFAULT),
146 generation_(0),
147 ice_username_fragment_(username_fragment),
148 password_(password),
149 timeout_delay_(kPortTimeoutDelay),
150 enable_port_packets_(false),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000151 ice_role_(ICEROLE_UNKNOWN),
152 tiebreaker_(0),
153 shared_socket_(true),
154 candidate_filter_(CF_ALL) {
155 Construct();
156}
157
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000158Port::Port(rtc::Thread* thread,
159 const std::string& type,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000160 rtc::PacketSocketFactory* factory,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000161 rtc::Network* network,
162 const rtc::IPAddress& ip,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200163 uint16_t min_port,
164 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000165 const std::string& username_fragment,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000166 const std::string& password)
167 : thread_(thread),
168 factory_(factory),
169 type_(type),
170 send_retransmit_count_attribute_(false),
171 network_(network),
172 ip_(ip),
173 min_port_(min_port),
174 max_port_(max_port),
175 component_(ICE_CANDIDATE_COMPONENT_DEFAULT),
176 generation_(0),
177 ice_username_fragment_(username_fragment),
178 password_(password),
179 timeout_delay_(kPortTimeoutDelay),
180 enable_port_packets_(false),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000181 ice_role_(ICEROLE_UNKNOWN),
182 tiebreaker_(0),
183 shared_socket_(false),
184 candidate_filter_(CF_ALL) {
185 ASSERT(factory_ != NULL);
186 Construct();
187}
188
189void Port::Construct() {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700190 // TODO(pthatcher): Remove this old behavior once we're sure no one
191 // relies on it. If the username_fragment and password are empty,
192 // we should just create one.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000193 if (ice_username_fragment_.empty()) {
194 ASSERT(password_.empty());
195 ice_username_fragment_ = rtc::CreateRandomString(ICE_UFRAG_LENGTH);
196 password_ = rtc::CreateRandomString(ICE_PWD_LENGTH);
197 }
198 LOG_J(LS_INFO, this) << "Port created";
199}
200
201Port::~Port() {
202 // Delete all of the remaining connections. We copy the list up front
203 // because each deletion will cause it to be modified.
204
205 std::vector<Connection*> list;
206
207 AddressMap::iterator iter = connections_.begin();
208 while (iter != connections_.end()) {
209 list.push_back(iter->second);
210 ++iter;
211 }
212
Peter Boström0c4e06b2015-10-07 12:23:21 +0200213 for (uint32_t i = 0; i < list.size(); i++)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000214 delete list[i];
215}
216
217Connection* Port::GetConnection(const rtc::SocketAddress& remote_addr) {
218 AddressMap::const_iterator iter = connections_.find(remote_addr);
219 if (iter != connections_.end())
220 return iter->second;
221 else
222 return NULL;
223}
224
225void Port::AddAddress(const rtc::SocketAddress& address,
226 const rtc::SocketAddress& base_address,
227 const rtc::SocketAddress& related_address,
228 const std::string& protocol,
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700229 const std::string& relay_protocol,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000230 const std::string& tcptype,
231 const std::string& type,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200232 uint32_t type_preference,
233 uint32_t relay_preference,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000234 bool final) {
235 if (protocol == TCP_PROTOCOL_NAME && type == LOCAL_PORT_TYPE) {
236 ASSERT(!tcptype.empty());
237 }
238
239 Candidate c;
240 c.set_id(rtc::CreateRandomString(8));
241 c.set_component(component_);
242 c.set_type(type);
243 c.set_protocol(protocol);
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700244 c.set_relay_protocol(relay_protocol);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000245 c.set_tcptype(tcptype);
246 c.set_address(address);
247 c.set_priority(c.GetPriority(type_preference, network_->preference(),
248 relay_preference));
249 c.set_username(username_fragment());
250 c.set_password(password_);
251 c.set_network_name(network_->name());
guoweis@webrtc.org950c5182014-12-16 23:01:31 +0000252 c.set_network_type(network_->type());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000253 c.set_generation(generation_);
254 c.set_related_address(related_address);
Honghai Zhang80f1db92016-01-27 11:54:45 -0800255 c.set_foundation(
256 ComputeFoundation(type, protocol, relay_protocol, base_address));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000257 candidates_.push_back(c);
258 SignalCandidateReady(this, c);
259
260 if (final) {
261 SignalPortComplete(this);
262 }
263}
264
265void Port::AddConnection(Connection* conn) {
266 connections_[conn->remote_candidate().address()] = conn;
267 conn->SignalDestroyed.connect(this, &Port::OnConnectionDestroyed);
268 SignalConnectionCreated(this, conn);
269}
270
271void Port::OnReadPacket(
272 const char* data, size_t size, const rtc::SocketAddress& addr,
273 ProtocolType proto) {
274 // If the user has enabled port packets, just hand this over.
275 if (enable_port_packets_) {
276 SignalReadPacket(this, data, size, addr);
277 return;
278 }
279
280 // If this is an authenticated STUN request, then signal unknown address and
281 // send back a proper binding response.
282 rtc::scoped_ptr<IceMessage> msg;
283 std::string remote_username;
284 if (!GetStunMessage(data, size, addr, msg.accept(), &remote_username)) {
285 LOG_J(LS_ERROR, this) << "Received non-STUN packet from unknown address ("
286 << addr.ToSensitiveString() << ")";
287 } else if (!msg) {
288 // STUN message handled already
289 } else if (msg->type() == STUN_BINDING_REQUEST) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700290 LOG(LS_INFO) << "Received STUN ping "
291 << " id=" << rtc::hex_encode(msg->transaction_id())
292 << " from unknown address " << addr.ToSensitiveString();
293
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000294 // Check for role conflicts.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700295 if (!MaybeIceRoleConflict(addr, msg.get(), remote_username)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000296 LOG(LS_INFO) << "Received conflicting role from the peer.";
297 return;
298 }
299
300 SignalUnknownAddress(this, addr, proto, msg.get(), remote_username, false);
301 } else {
302 // NOTE(tschmelcher): STUN_BINDING_RESPONSE is benign. It occurs if we
303 // pruned a connection for this port while it had STUN requests in flight,
304 // because we then get back responses for them, which this code correctly
305 // does not handle.
306 if (msg->type() != STUN_BINDING_RESPONSE) {
307 LOG_J(LS_ERROR, this) << "Received unexpected STUN message type ("
308 << msg->type() << ") from unknown address ("
309 << addr.ToSensitiveString() << ")";
310 }
311 }
312}
313
314void Port::OnReadyToSend() {
315 AddressMap::iterator iter = connections_.begin();
316 for (; iter != connections_.end(); ++iter) {
317 iter->second->OnReadyToSend();
318 }
319}
320
321size_t Port::AddPrflxCandidate(const Candidate& local) {
322 candidates_.push_back(local);
323 return (candidates_.size() - 1);
324}
325
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000326bool Port::GetStunMessage(const char* data, size_t size,
327 const rtc::SocketAddress& addr,
328 IceMessage** out_msg, std::string* out_username) {
329 // NOTE: This could clearly be optimized to avoid allocating any memory.
330 // However, at the data rates we'll be looking at on the client side,
331 // this probably isn't worth worrying about.
332 ASSERT(out_msg != NULL);
333 ASSERT(out_username != NULL);
334 *out_msg = NULL;
335 out_username->clear();
336
337 // Don't bother parsing the packet if we can tell it's not STUN.
338 // In ICE mode, all STUN packets will have a valid fingerprint.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700339 if (!StunMessage::ValidateFingerprint(data, size)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000340 return false;
341 }
342
343 // Parse the request message. If the packet is not a complete and correct
344 // STUN message, then ignore it.
345 rtc::scoped_ptr<IceMessage> stun_msg(new IceMessage());
346 rtc::ByteBuffer buf(data, size);
347 if (!stun_msg->Read(&buf) || (buf.Length() > 0)) {
348 return false;
349 }
350
351 if (stun_msg->type() == STUN_BINDING_REQUEST) {
352 // Check for the presence of USERNAME and MESSAGE-INTEGRITY (if ICE) first.
353 // If not present, fail with a 400 Bad Request.
354 if (!stun_msg->GetByteString(STUN_ATTR_USERNAME) ||
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700355 !stun_msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000356 LOG_J(LS_ERROR, this) << "Received STUN request without username/M-I "
357 << "from " << addr.ToSensitiveString();
358 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_BAD_REQUEST,
359 STUN_ERROR_REASON_BAD_REQUEST);
360 return true;
361 }
362
363 // If the username is bad or unknown, fail with a 401 Unauthorized.
364 std::string local_ufrag;
365 std::string remote_ufrag;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700366 if (!ParseStunUsername(stun_msg.get(), &local_ufrag, &remote_ufrag) ||
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000367 local_ufrag != username_fragment()) {
368 LOG_J(LS_ERROR, this) << "Received STUN request with bad local username "
369 << local_ufrag << " from "
370 << addr.ToSensitiveString();
371 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED,
372 STUN_ERROR_REASON_UNAUTHORIZED);
373 return true;
374 }
375
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000376 // If ICE, and the MESSAGE-INTEGRITY is bad, fail with a 401 Unauthorized
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700377 if (!stun_msg->ValidateMessageIntegrity(data, size, password_)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000378 LOG_J(LS_ERROR, this) << "Received STUN request with bad M-I "
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +0000379 << "from " << addr.ToSensitiveString()
380 << ", password_=" << password_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000381 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED,
382 STUN_ERROR_REASON_UNAUTHORIZED);
383 return true;
384 }
385 out_username->assign(remote_ufrag);
386 } else if ((stun_msg->type() == STUN_BINDING_RESPONSE) ||
387 (stun_msg->type() == STUN_BINDING_ERROR_RESPONSE)) {
388 if (stun_msg->type() == STUN_BINDING_ERROR_RESPONSE) {
389 if (const StunErrorCodeAttribute* error_code = stun_msg->GetErrorCode()) {
390 LOG_J(LS_ERROR, this) << "Received STUN binding error:"
391 << " class=" << error_code->eclass()
392 << " number=" << error_code->number()
393 << " reason='" << error_code->reason() << "'"
394 << " from " << addr.ToSensitiveString();
395 // Return message to allow error-specific processing
396 } else {
397 LOG_J(LS_ERROR, this) << "Received STUN binding error without a error "
398 << "code from " << addr.ToSensitiveString();
399 return true;
400 }
401 }
402 // NOTE: Username should not be used in verifying response messages.
403 out_username->clear();
404 } else if (stun_msg->type() == STUN_BINDING_INDICATION) {
405 LOG_J(LS_VERBOSE, this) << "Received STUN binding indication:"
406 << " from " << addr.ToSensitiveString();
407 out_username->clear();
408 // No stun attributes will be verified, if it's stun indication message.
409 // Returning from end of the this method.
410 } else {
411 LOG_J(LS_ERROR, this) << "Received STUN packet with invalid type ("
412 << stun_msg->type() << ") from "
413 << addr.ToSensitiveString();
414 return true;
415 }
416
417 // Return the STUN message found.
418 *out_msg = stun_msg.release();
419 return true;
420}
421
422bool Port::IsCompatibleAddress(const rtc::SocketAddress& addr) {
423 int family = ip().family();
424 // We use single-stack sockets, so families must match.
425 if (addr.family() != family) {
426 return false;
427 }
428 // Link-local IPv6 ports can only connect to other link-local IPv6 ports.
Peter Thatcherb8b01432015-07-07 16:45:53 -0700429 if (family == AF_INET6 &&
430 (IPIsLinkLocal(ip()) != IPIsLinkLocal(addr.ipaddr()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000431 return false;
432 }
433 return true;
434}
435
436bool Port::ParseStunUsername(const StunMessage* stun_msg,
437 std::string* local_ufrag,
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700438 std::string* remote_ufrag) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000439 // The packet must include a username that either begins or ends with our
440 // fragment. It should begin with our fragment if it is a request and it
441 // should end with our fragment if it is a response.
442 local_ufrag->clear();
443 remote_ufrag->clear();
444 const StunByteStringAttribute* username_attr =
445 stun_msg->GetByteString(STUN_ATTR_USERNAME);
446 if (username_attr == NULL)
447 return false;
448
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700449 // RFRAG:LFRAG
450 const std::string username = username_attr->GetString();
451 size_t colon_pos = username.find(":");
452 if (colon_pos == std::string::npos) {
453 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000454 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000455
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700456 *local_ufrag = username.substr(0, colon_pos);
457 *remote_ufrag = username.substr(colon_pos + 1, username.size());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000458 return true;
459}
460
461bool Port::MaybeIceRoleConflict(
462 const rtc::SocketAddress& addr, IceMessage* stun_msg,
463 const std::string& remote_ufrag) {
464 // Validate ICE_CONTROLLING or ICE_CONTROLLED attributes.
465 bool ret = true;
466 IceRole remote_ice_role = ICEROLE_UNKNOWN;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200467 uint64_t remote_tiebreaker = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000468 const StunUInt64Attribute* stun_attr =
469 stun_msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
470 if (stun_attr) {
471 remote_ice_role = ICEROLE_CONTROLLING;
472 remote_tiebreaker = stun_attr->value();
473 }
474
475 // If |remote_ufrag| is same as port local username fragment and
476 // tie breaker value received in the ping message matches port
477 // tiebreaker value this must be a loopback call.
478 // We will treat this as valid scenario.
479 if (remote_ice_role == ICEROLE_CONTROLLING &&
480 username_fragment() == remote_ufrag &&
481 remote_tiebreaker == IceTiebreaker()) {
482 return true;
483 }
484
485 stun_attr = stun_msg->GetUInt64(STUN_ATTR_ICE_CONTROLLED);
486 if (stun_attr) {
487 remote_ice_role = ICEROLE_CONTROLLED;
488 remote_tiebreaker = stun_attr->value();
489 }
490
491 switch (ice_role_) {
492 case ICEROLE_CONTROLLING:
493 if (ICEROLE_CONTROLLING == remote_ice_role) {
494 if (remote_tiebreaker >= tiebreaker_) {
495 SignalRoleConflict(this);
496 } else {
497 // Send Role Conflict (487) error response.
498 SendBindingErrorResponse(stun_msg, addr,
499 STUN_ERROR_ROLE_CONFLICT, STUN_ERROR_REASON_ROLE_CONFLICT);
500 ret = false;
501 }
502 }
503 break;
504 case ICEROLE_CONTROLLED:
505 if (ICEROLE_CONTROLLED == remote_ice_role) {
506 if (remote_tiebreaker < tiebreaker_) {
507 SignalRoleConflict(this);
508 } else {
509 // Send Role Conflict (487) error response.
510 SendBindingErrorResponse(stun_msg, addr,
511 STUN_ERROR_ROLE_CONFLICT, STUN_ERROR_REASON_ROLE_CONFLICT);
512 ret = false;
513 }
514 }
515 break;
516 default:
517 ASSERT(false);
518 }
519 return ret;
520}
521
522void Port::CreateStunUsername(const std::string& remote_username,
523 std::string* stun_username_attr_str) const {
524 stun_username_attr_str->clear();
525 *stun_username_attr_str = remote_username;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700526 stun_username_attr_str->append(":");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000527 stun_username_attr_str->append(username_fragment());
528}
529
530void Port::SendBindingResponse(StunMessage* request,
531 const rtc::SocketAddress& addr) {
532 ASSERT(request->type() == STUN_BINDING_REQUEST);
533
534 // Retrieve the username from the request.
535 const StunByteStringAttribute* username_attr =
536 request->GetByteString(STUN_ATTR_USERNAME);
537 ASSERT(username_attr != NULL);
538 if (username_attr == NULL) {
539 // No valid username, skip the response.
540 return;
541 }
542
543 // Fill in the response message.
544 StunMessage response;
545 response.SetType(STUN_BINDING_RESPONSE);
546 response.SetTransactionID(request->transaction_id());
547 const StunUInt32Attribute* retransmit_attr =
548 request->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
549 if (retransmit_attr) {
550 // Inherit the incoming retransmit value in the response so the other side
551 // can see our view of lost pings.
552 response.AddAttribute(new StunUInt32Attribute(
553 STUN_ATTR_RETRANSMIT_COUNT, retransmit_attr->value()));
554
555 if (retransmit_attr->value() > CONNECTION_WRITE_CONNECT_FAILURES) {
556 LOG_J(LS_INFO, this)
557 << "Received a remote ping with high retransmit count: "
558 << retransmit_attr->value();
559 }
560 }
561
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700562 response.AddAttribute(
563 new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, addr));
564 response.AddMessageIntegrity(password_);
565 response.AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000566
567 // Send the response message.
568 rtc::ByteBuffer buf;
569 response.Write(&buf);
570 rtc::PacketOptions options(DefaultDscpValue());
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700571 auto err = SendTo(buf.Data(), buf.Length(), addr, options, false);
572 if (err < 0) {
573 LOG_J(LS_ERROR, this)
574 << "Failed to send STUN ping response"
575 << ", to=" << addr.ToSensitiveString()
576 << ", err=" << err
577 << ", id=" << rtc::hex_encode(response.transaction_id());
578 } else {
579 // Log at LS_INFO if we send a stun ping response on an unwritable
580 // connection.
honghaiz9b5ee9c2015-11-11 13:19:17 -0800581 Connection* conn = GetConnection(addr);
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700582 rtc::LoggingSeverity sev = (conn && !conn->writable()) ?
583 rtc::LS_INFO : rtc::LS_VERBOSE;
584 LOG_JV(sev, this)
585 << "Sent STUN ping response"
586 << ", to=" << addr.ToSensitiveString()
587 << ", id=" << rtc::hex_encode(response.transaction_id());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000588 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000589}
590
591void Port::SendBindingErrorResponse(StunMessage* request,
592 const rtc::SocketAddress& addr,
593 int error_code, const std::string& reason) {
594 ASSERT(request->type() == STUN_BINDING_REQUEST);
595
596 // Fill in the response message.
597 StunMessage response;
598 response.SetType(STUN_BINDING_ERROR_RESPONSE);
599 response.SetTransactionID(request->transaction_id());
600
601 // When doing GICE, we need to write out the error code incorrectly to
602 // maintain backwards compatiblility.
603 StunErrorCodeAttribute* error_attr = StunAttribute::CreateErrorCode();
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700604 error_attr->SetCode(error_code);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000605 error_attr->SetReason(reason);
606 response.AddAttribute(error_attr);
607
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700608 // Per Section 10.1.2, certain error cases don't get a MESSAGE-INTEGRITY,
609 // because we don't have enough information to determine the shared secret.
610 if (error_code != STUN_ERROR_BAD_REQUEST &&
611 error_code != STUN_ERROR_UNAUTHORIZED)
612 response.AddMessageIntegrity(password_);
613 response.AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000614
615 // Send the response message.
616 rtc::ByteBuffer buf;
617 response.Write(&buf);
618 rtc::PacketOptions options(DefaultDscpValue());
619 SendTo(buf.Data(), buf.Length(), addr, options, false);
620 LOG_J(LS_INFO, this) << "Sending STUN binding error: reason=" << reason
621 << " to " << addr.ToSensitiveString();
622}
623
624void Port::OnMessage(rtc::Message *pmsg) {
honghaizd0b31432015-09-30 12:42:17 -0700625 ASSERT(pmsg->message_id == MSG_DEAD);
626 if (dead()) {
627 Destroy();
628 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000629}
630
631std::string Port::ToString() const {
632 std::stringstream ss;
633 ss << "Port[" << content_name_ << ":" << component_
634 << ":" << generation_ << ":" << type_
635 << ":" << network_->ToString() << "]";
636 return ss.str();
637}
638
639void Port::EnablePortPackets() {
640 enable_port_packets_ = true;
641}
642
643void Port::OnConnectionDestroyed(Connection* conn) {
644 AddressMap::iterator iter =
645 connections_.find(conn->remote_candidate().address());
646 ASSERT(iter != connections_.end());
647 connections_.erase(iter);
648
honghaizd0b31432015-09-30 12:42:17 -0700649 // On the controlled side, ports time out after all connections fail.
650 // Note: If a new connection is added after this message is posted, but it
651 // fails and is removed before kPortTimeoutDelay, then this message will
652 // still cause the Port to be destroyed.
653 if (dead()) {
654 thread_->PostDelayed(timeout_delay_, this, MSG_DEAD);
655 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000656}
657
658void Port::Destroy() {
659 ASSERT(connections_.empty());
660 LOG_J(LS_INFO, this) << "Port deleted";
661 SignalDestroyed(this);
662 delete this;
663}
664
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000665const std::string Port::username_fragment() const {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700666 return ice_username_fragment_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000667}
668
669// A ConnectionRequest is a simple STUN ping used to determine writability.
670class ConnectionRequest : public StunRequest {
671 public:
672 explicit ConnectionRequest(Connection* connection)
673 : StunRequest(new IceMessage()),
674 connection_(connection) {
675 }
676
677 virtual ~ConnectionRequest() {
678 }
679
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700680 void Prepare(StunMessage* request) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000681 request->SetType(STUN_BINDING_REQUEST);
682 std::string username;
683 connection_->port()->CreateStunUsername(
684 connection_->remote_candidate().username(), &username);
685 request->AddAttribute(
686 new StunByteStringAttribute(STUN_ATTR_USERNAME, username));
687
688 // connection_ already holds this ping, so subtract one from count.
689 if (connection_->port()->send_retransmit_count_attribute()) {
690 request->AddAttribute(new StunUInt32Attribute(
691 STUN_ATTR_RETRANSMIT_COUNT,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200692 static_cast<uint32_t>(connection_->pings_since_last_response_.size() -
693 1)));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000694 }
695
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700696 // Adding ICE_CONTROLLED or ICE_CONTROLLING attribute based on the role.
697 if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLING) {
698 request->AddAttribute(new StunUInt64Attribute(
699 STUN_ATTR_ICE_CONTROLLING, connection_->port()->IceTiebreaker()));
700 // Since we are trying aggressive nomination, sending USE-CANDIDATE
701 // attribute in every ping.
702 // If we are dealing with a ice-lite end point, nomination flag
703 // in Connection will be set to false by default. Once the connection
704 // becomes "best connection", nomination flag will be turned on.
705 if (connection_->use_candidate_attr()) {
706 request->AddAttribute(new StunByteStringAttribute(
707 STUN_ATTR_USE_CANDIDATE));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000708 }
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700709 } else if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLED) {
710 request->AddAttribute(new StunUInt64Attribute(
711 STUN_ATTR_ICE_CONTROLLED, connection_->port()->IceTiebreaker()));
712 } else {
713 ASSERT(false);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000714 }
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700715
716 // Adding PRIORITY Attribute.
717 // Changing the type preference to Peer Reflexive and local preference
718 // and component id information is unchanged from the original priority.
719 // priority = (2^24)*(type preference) +
720 // (2^8)*(local preference) +
721 // (2^0)*(256 - component ID)
Peter Boström0c4e06b2015-10-07 12:23:21 +0200722 uint32_t prflx_priority =
723 ICE_TYPE_PREFERENCE_PRFLX << 24 |
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700724 (connection_->local_candidate().priority() & 0x00FFFFFF);
725 request->AddAttribute(
726 new StunUInt32Attribute(STUN_ATTR_PRIORITY, prflx_priority));
727
728 // Adding Message Integrity attribute.
729 request->AddMessageIntegrity(connection_->remote_candidate().password());
730 // Adding Fingerprint.
731 request->AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000732 }
733
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700734 void OnResponse(StunMessage* response) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000735 connection_->OnConnectionRequestResponse(this, response);
736 }
737
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700738 void OnErrorResponse(StunMessage* response) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000739 connection_->OnConnectionRequestErrorResponse(this, response);
740 }
741
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700742 void OnTimeout() override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000743 connection_->OnConnectionRequestTimeout(this);
744 }
745
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700746 void OnSent() override {
747 connection_->OnConnectionRequestSent(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000748 // Each request is sent only once. After a single delay , the request will
749 // time out.
750 timeout_ = true;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700751 }
752
753 int resend_delay() override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000754 return CONNECTION_RESPONSE_TIMEOUT;
755 }
756
757 private:
758 Connection* connection_;
759};
760
761//
762// Connection
763//
764
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000765Connection::Connection(Port* port,
766 size_t index,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000767 const Candidate& remote_candidate)
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000768 : port_(port),
769 local_candidate_index_(index),
770 remote_candidate_(remote_candidate),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000771 write_state_(STATE_WRITE_INIT),
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700772 receiving_(false),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000773 connected_(true),
774 pruned_(false),
775 use_candidate_attr_(false),
honghaiz5a3acd82015-08-20 15:53:17 -0700776 nominated_(false),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000777 remote_ice_mode_(ICEMODE_FULL),
778 requests_(port->thread()),
779 rtt_(DEFAULT_RTT),
780 last_ping_sent_(0),
781 last_ping_received_(0),
782 last_data_received_(0),
783 last_ping_response_received_(0),
Tim Psiaki63046262015-09-14 10:38:08 -0700784 recv_rate_tracker_(100u, 10u),
785 send_rate_tracker_(100u, 10u),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000786 sent_packets_discarded_(0),
787 sent_packets_total_(0),
788 reported_(false),
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700789 state_(STATE_WAITING),
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700790 receiving_timeout_(WEAK_CONNECTION_RECEIVE_TIMEOUT),
791 time_created_ms_(rtc::Time()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000792 // All of our connections start in WAITING state.
793 // TODO(mallinath) - Start connections from STATE_FROZEN.
794 // Wire up to send stun packets
795 requests_.SignalSendPacket.connect(this, &Connection::OnSendStunPacket);
796 LOG_J(LS_INFO, this) << "Connection created";
797}
798
799Connection::~Connection() {
800}
801
802const Candidate& Connection::local_candidate() const {
803 ASSERT(local_candidate_index_ < port_->Candidates().size());
804 return port_->Candidates()[local_candidate_index_];
805}
806
Peter Boström0c4e06b2015-10-07 12:23:21 +0200807uint64_t Connection::priority() const {
808 uint64_t priority = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000809 // RFC 5245 - 5.7.2. Computing Pair Priority and Ordering Pairs
810 // Let G be the priority for the candidate provided by the controlling
811 // agent. Let D be the priority for the candidate provided by the
812 // controlled agent.
813 // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)
814 IceRole role = port_->GetIceRole();
815 if (role != ICEROLE_UNKNOWN) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200816 uint32_t g = 0;
817 uint32_t d = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000818 if (role == ICEROLE_CONTROLLING) {
819 g = local_candidate().priority();
820 d = remote_candidate_.priority();
821 } else {
822 g = remote_candidate_.priority();
823 d = local_candidate().priority();
824 }
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000825 priority = std::min(g, d);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000826 priority = priority << 32;
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000827 priority += 2 * std::max(g, d) + (g > d ? 1 : 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000828 }
829 return priority;
830}
831
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000832void Connection::set_write_state(WriteState value) {
833 WriteState old_value = write_state_;
834 write_state_ = value;
835 if (value != old_value) {
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +0000836 LOG_J(LS_VERBOSE, this) << "set_write_state from: " << old_value << " to "
837 << value;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000838 SignalStateChange(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000839 }
840}
841
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700842void Connection::set_receiving(bool value) {
843 if (value != receiving_) {
844 LOG_J(LS_VERBOSE, this) << "set_receiving to " << value;
845 receiving_ = value;
846 SignalStateChange(this);
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700847 }
848}
849
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000850void Connection::set_state(State state) {
851 State old_state = state_;
852 state_ = state;
853 if (state != old_state) {
854 LOG_J(LS_VERBOSE, this) << "set_state";
855 }
856}
857
858void Connection::set_connected(bool value) {
859 bool old_value = connected_;
860 connected_ = value;
861 if (value != old_value) {
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700862 LOG_J(LS_VERBOSE, this) << "set_connected from: " << old_value << " to "
863 << value;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000864 }
865}
866
867void Connection::set_use_candidate_attr(bool enable) {
868 use_candidate_attr_ = enable;
869}
870
871void Connection::OnSendStunPacket(const void* data, size_t size,
872 StunRequest* req) {
873 rtc::PacketOptions options(port_->DefaultDscpValue());
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700874 auto err = port_->SendTo(
875 data, size, remote_candidate_.address(), options, false);
876 if (err < 0) {
877 LOG_J(LS_WARNING, this) << "Failed to send STUN ping "
878 << " err=" << err
879 << " id=" << rtc::hex_encode(req->id());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000880 }
881}
882
883void Connection::OnReadPacket(
884 const char* data, size_t size, const rtc::PacketTime& packet_time) {
885 rtc::scoped_ptr<IceMessage> msg;
886 std::string remote_ufrag;
887 const rtc::SocketAddress& addr(remote_candidate_.address());
888 if (!port_->GetStunMessage(data, size, addr, msg.accept(), &remote_ufrag)) {
889 // The packet did not parse as a valid STUN message
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700890 // This is a data packet, pass it along.
891 set_receiving(true);
892 last_data_received_ = rtc::Time();
893 recv_rate_tracker_.AddSamples(size);
894 SignalReadPacket(this, data, size, packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000895
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700896 // If timed out sending writability checks, start up again
897 if (!pruned_ && (write_state_ == STATE_WRITE_TIMEOUT)) {
898 LOG(LS_WARNING) << "Received a data packet on a timed-out Connection. "
899 << "Resetting state to STATE_WRITE_INIT.";
900 set_write_state(STATE_WRITE_INIT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000901 }
902 } else if (!msg) {
903 // The packet was STUN, but failed a check and was handled internally.
904 } else {
905 // The packet is STUN and passed the Port checks.
906 // Perform our own checks to ensure this packet is valid.
honghaizd0b31432015-09-30 12:42:17 -0700907 // If this is a STUN request, then update the receiving bit and respond.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000908 // If this is a STUN response, then update the writable bit.
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700909 // Log at LS_INFO if we receive a ping on an unwritable connection.
910 rtc::LoggingSeverity sev = (!writable() ? rtc::LS_INFO : rtc::LS_VERBOSE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000911 switch (msg->type()) {
912 case STUN_BINDING_REQUEST:
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700913 LOG_JV(sev, this) << "Received STUN ping"
914 << ", id=" << rtc::hex_encode(msg->transaction_id());
915
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000916 if (remote_ufrag == remote_candidate_.username()) {
honghaiz9b5ee9c2015-11-11 13:19:17 -0800917 HandleBindingRequest(msg.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000918 } else {
919 // The packet had the right local username, but the remote username
920 // was not the right one for the remote address.
921 LOG_J(LS_ERROR, this)
922 << "Received STUN request with bad remote username "
923 << remote_ufrag;
924 port_->SendBindingErrorResponse(msg.get(), addr,
925 STUN_ERROR_UNAUTHORIZED,
926 STUN_ERROR_REASON_UNAUTHORIZED);
927
928 }
929 break;
930
931 // Response from remote peer. Does it match request sent?
932 // This doesn't just check, it makes callbacks if transaction
933 // id's match.
934 case STUN_BINDING_RESPONSE:
935 case STUN_BINDING_ERROR_RESPONSE:
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700936 if (msg->ValidateMessageIntegrity(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000937 data, size, remote_candidate().password())) {
938 requests_.CheckResponse(msg.get());
939 }
940 // Otherwise silently discard the response message.
941 break;
942
honghaizd0b31432015-09-30 12:42:17 -0700943 // Remote end point sent an STUN indication instead of regular binding
944 // request. In this case |last_ping_received_| will be updated but no
945 // response will be sent.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000946 case STUN_BINDING_INDICATION:
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700947 ReceivedPing();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000948 break;
949
950 default:
951 ASSERT(false);
952 break;
953 }
954 }
955}
956
honghaiz9b5ee9c2015-11-11 13:19:17 -0800957void Connection::HandleBindingRequest(IceMessage* msg) {
958 // This connection should now be receiving.
959 ReceivedPing();
960
961 const rtc::SocketAddress& remote_addr = remote_candidate_.address();
962 const std::string& remote_ufrag = remote_candidate_.username();
963 // Check for role conflicts.
964 if (!port_->MaybeIceRoleConflict(remote_addr, msg, remote_ufrag)) {
965 // Received conflicting role from the peer.
966 LOG(LS_INFO) << "Received conflicting role from the peer.";
967 return;
968 }
969
970 // This is a validated stun request from remote peer.
971 port_->SendBindingResponse(msg, remote_addr);
972
973 // If it timed out on writing check, start up again
974 if (!pruned_ && write_state_ == STATE_WRITE_TIMEOUT) {
975 set_write_state(STATE_WRITE_INIT);
976 }
977
978 if (port_->GetIceRole() == ICEROLE_CONTROLLED) {
979 const StunByteStringAttribute* use_candidate_attr =
980 msg->GetByteString(STUN_ATTR_USE_CANDIDATE);
981 if (use_candidate_attr) {
982 set_nominated(true);
983 SignalNominated(this);
984 }
985 }
986}
987
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000988void Connection::OnReadyToSend() {
989 if (write_state_ == STATE_WRITABLE) {
990 SignalReadyToSend(this);
991 }
992}
993
994void Connection::Prune() {
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700995 if (!pruned_ || active()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000996 LOG_J(LS_VERBOSE, this) << "Connection pruned";
997 pruned_ = true;
998 requests_.Clear();
999 set_write_state(STATE_WRITE_TIMEOUT);
1000 }
1001}
1002
1003void Connection::Destroy() {
1004 LOG_J(LS_VERBOSE, this) << "Connection destroyed";
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001005 port_->thread()->Post(this, MSG_DELETE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001006}
1007
deadbeef376e1232015-11-25 09:00:08 -08001008void Connection::FailAndDestroy() {
1009 set_state(Connection::STATE_FAILED);
1010 Destroy();
1011}
1012
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001013void Connection::PrintPingsSinceLastResponse(std::string* s, size_t max) {
1014 std::ostringstream oss;
1015 oss << std::boolalpha;
1016 if (pings_since_last_response_.size() > max) {
1017 for (size_t i = 0; i < max; i++) {
1018 const SentPing& ping = pings_since_last_response_[i];
1019 oss << rtc::hex_encode(ping.id) << " ";
1020 }
1021 oss << "... " << (pings_since_last_response_.size() - max) << " more";
1022 } else {
1023 for (const SentPing& ping : pings_since_last_response_) {
1024 oss << rtc::hex_encode(ping.id) << " ";
1025 }
1026 }
1027 *s = oss.str();
1028}
1029
Peter Boström0c4e06b2015-10-07 12:23:21 +02001030void Connection::UpdateState(uint32_t now) {
1031 uint32_t rtt = ConservativeRTTEstimate(rtt_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001032
Peter Thatcherb2d26232015-05-15 11:25:14 -07001033 if (LOG_CHECK_LEVEL(LS_VERBOSE)) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001034 std::string pings;
1035 PrintPingsSinceLastResponse(&pings, 5);
1036 LOG_J(LS_VERBOSE, this) << "UpdateState()"
1037 << ", ms since last received response="
1038 << now - last_ping_response_received_
1039 << ", ms since last received data="
1040 << now - last_data_received_
1041 << ", rtt=" << rtt
1042 << ", pings_since_last_response=" << pings;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001043 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001044
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001045 // Check the writable state. (The order of these checks is important.)
1046 //
1047 // Before becoming unwritable, we allow for a fixed number of pings to fail
1048 // (i.e., receive no response). We also have to give the response time to
1049 // get back, so we include a conservative estimate of this.
1050 //
1051 // Before timing out writability, we give a fixed amount of time. This is to
1052 // allow for changes in network conditions.
1053
1054 if ((write_state_ == STATE_WRITABLE) &&
1055 TooManyFailures(pings_since_last_response_,
1056 CONNECTION_WRITE_CONNECT_FAILURES,
1057 rtt,
1058 now) &&
1059 TooLongWithoutResponse(pings_since_last_response_,
1060 CONNECTION_WRITE_CONNECT_TIMEOUT,
1061 now)) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001062 uint32_t max_pings = CONNECTION_WRITE_CONNECT_FAILURES;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001063 LOG_J(LS_INFO, this) << "Unwritable after " << max_pings
1064 << " ping failures and "
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001065 << now - pings_since_last_response_[0].sent_time
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001066 << " ms without a response,"
1067 << " ms since last received ping="
1068 << now - last_ping_received_
1069 << " ms since last received data="
1070 << now - last_data_received_
1071 << " rtt=" << rtt;
1072 set_write_state(STATE_WRITE_UNRELIABLE);
1073 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001074 if ((write_state_ == STATE_WRITE_UNRELIABLE ||
1075 write_state_ == STATE_WRITE_INIT) &&
1076 TooLongWithoutResponse(pings_since_last_response_,
1077 CONNECTION_WRITE_TIMEOUT,
1078 now)) {
1079 LOG_J(LS_INFO, this) << "Timed out after "
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001080 << now - pings_since_last_response_[0].sent_time
1081 << " ms without a response"
1082 << ", rtt=" << rtt;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001083 set_write_state(STATE_WRITE_TIMEOUT);
1084 }
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001085
1086 // Check the receiving state.
Peter Boström0c4e06b2015-10-07 12:23:21 +02001087 uint32_t last_recv_time = last_received();
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001088 bool receiving = now <= last_recv_time + receiving_timeout_;
1089 set_receiving(receiving);
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001090 if (dead(now)) {
1091 Destroy();
1092 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001093}
1094
Peter Boström0c4e06b2015-10-07 12:23:21 +02001095void Connection::Ping(uint32_t now) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001096 last_ping_sent_ = now;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001097 ConnectionRequest *req = new ConnectionRequest(this);
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001098 pings_since_last_response_.push_back(SentPing(req->id(), now));
1099 LOG_J(LS_VERBOSE, this) << "Sending STUN ping "
1100 << ", id=" << rtc::hex_encode(req->id());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001101 requests_.Send(req);
1102 state_ = STATE_INPROGRESS;
1103}
1104
1105void Connection::ReceivedPing() {
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001106 set_receiving(true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001107 last_ping_received_ = rtc::Time();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001108}
1109
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001110void Connection::ReceivedPingResponse() {
1111 // We've already validated that this is a STUN binding response with
1112 // the correct local and remote username for this connection.
1113 // So if we're not already, become writable. We may be bringing a pruned
1114 // connection back to life, but if we don't really want it, we can always
1115 // prune it again.
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001116 set_receiving(true);
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001117 set_write_state(STATE_WRITABLE);
1118 set_state(STATE_SUCCEEDED);
1119 pings_since_last_response_.clear();
1120 last_ping_response_received_ = rtc::Time();
1121}
1122
Peter Boström0c4e06b2015-10-07 12:23:21 +02001123bool Connection::dead(uint32_t now) const {
honghaiz37389b42016-01-04 21:57:33 -08001124 if (last_received() > 0) {
1125 // If it has ever received anything, we keep it alive until it hasn't
1126 // received anything for DEAD_CONNECTION_RECEIVE_TIMEOUT. This covers the
1127 // normal case of a successfully used connection that stops working. This
1128 // also allows a remote peer to continue pinging over a locally inactive
1129 // (pruned) connection.
1130 return (now > (last_received() + DEAD_CONNECTION_RECEIVE_TIMEOUT));
1131 }
1132
1133 if (active()) {
1134 // If it has never received anything, keep it alive as long as it is
1135 // actively pinging and not pruned. Otherwise, the connection might be
1136 // deleted before it has a chance to ping. This is the normal case for a
1137 // new connection that is pinging but hasn't received anything yet.
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001138 return false;
1139 }
1140
honghaiz37389b42016-01-04 21:57:33 -08001141 // If it has never received anything and is not actively pinging (pruned), we
1142 // keep it around for at least MIN_CONNECTION_LIFETIME to prevent connections
1143 // from being pruned too quickly during a network change event when two
1144 // networks would be up simultaneously but only for a brief period.
1145 return now > (time_created_ms_ + MIN_CONNECTION_LIFETIME);
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001146}
1147
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +00001148std::string Connection::ToDebugId() const {
1149 std::stringstream ss;
1150 ss << std::hex << this;
1151 return ss.str();
1152}
1153
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001154std::string Connection::ToString() const {
1155 const char CONNECT_STATE_ABBREV[2] = {
1156 '-', // not connected (false)
1157 'C', // connected (true)
1158 };
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001159 const char RECEIVE_STATE_ABBREV[2] = {
1160 '-', // not receiving (false)
1161 'R', // receiving (true)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001162 };
1163 const char WRITE_STATE_ABBREV[4] = {
1164 'W', // STATE_WRITABLE
1165 'w', // STATE_WRITE_UNRELIABLE
1166 '-', // STATE_WRITE_INIT
1167 'x', // STATE_WRITE_TIMEOUT
1168 };
1169 const std::string ICESTATE[4] = {
1170 "W", // STATE_WAITING
1171 "I", // STATE_INPROGRESS
1172 "S", // STATE_SUCCEEDED
1173 "F" // STATE_FAILED
1174 };
1175 const Candidate& local = local_candidate();
1176 const Candidate& remote = remote_candidate();
1177 std::stringstream ss;
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +00001178 ss << "Conn[" << ToDebugId()
1179 << ":" << port_->content_name()
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001180 << ":" << local.id() << ":" << local.component()
1181 << ":" << local.generation()
1182 << ":" << local.type() << ":" << local.protocol()
1183 << ":" << local.address().ToSensitiveString()
1184 << "->" << remote.id() << ":" << remote.component()
1185 << ":" << remote.priority()
1186 << ":" << remote.type() << ":"
1187 << remote.protocol() << ":" << remote.address().ToSensitiveString() << "|"
1188 << CONNECT_STATE_ABBREV[connected()]
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001189 << RECEIVE_STATE_ABBREV[receiving()]
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001190 << WRITE_STATE_ABBREV[write_state()]
1191 << ICESTATE[state()] << "|"
1192 << priority() << "|";
1193 if (rtt_ < DEFAULT_RTT) {
1194 ss << rtt_ << "]";
1195 } else {
1196 ss << "-]";
1197 }
1198 return ss.str();
1199}
1200
1201std::string Connection::ToSensitiveString() const {
1202 return ToString();
1203}
1204
1205void Connection::OnConnectionRequestResponse(ConnectionRequest* request,
1206 StunMessage* response) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001207 // Log at LS_INFO if we receive a ping response on an unwritable
1208 // connection.
1209 rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1210
Peter Boström0c4e06b2015-10-07 12:23:21 +02001211 uint32_t rtt = request->Elapsed();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001212
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001213 ReceivedPingResponse();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001214
Peter Thatcherb2d26232015-05-15 11:25:14 -07001215 if (LOG_CHECK_LEVEL_V(sev)) {
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001216 bool use_candidate = (
1217 response->GetByteString(STUN_ATTR_USE_CANDIDATE) != nullptr);
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001218 std::string pings;
1219 PrintPingsSinceLastResponse(&pings, 5);
1220 LOG_JV(sev, this) << "Received STUN ping response"
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001221 << ", id=" << rtc::hex_encode(request->id())
1222 << ", code=0" // Makes logging easier to parse.
1223 << ", rtt=" << rtt
1224 << ", use_candidate=" << use_candidate
1225 << ", pings_since_last_response=" << pings;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001226 }
1227
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001228 rtt_ = (RTT_RATIO * rtt_ + rtt) / (RTT_RATIO + 1);
1229
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001230 MaybeAddPrflxCandidate(request, response);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001231}
1232
1233void Connection::OnConnectionRequestErrorResponse(ConnectionRequest* request,
1234 StunMessage* response) {
1235 const StunErrorCodeAttribute* error_attr = response->GetErrorCode();
1236 int error_code = STUN_ERROR_GLOBAL_FAILURE;
1237 if (error_attr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001238 error_code = error_attr->code();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001239 }
1240
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001241 LOG_J(LS_INFO, this) << "Received STUN error response"
1242 << " id=" << rtc::hex_encode(request->id())
1243 << " code=" << error_code
1244 << " rtt=" << request->Elapsed();
1245
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001246 if (error_code == STUN_ERROR_UNKNOWN_ATTRIBUTE ||
1247 error_code == STUN_ERROR_SERVER_ERROR ||
1248 error_code == STUN_ERROR_UNAUTHORIZED) {
1249 // Recoverable error, retry
1250 } else if (error_code == STUN_ERROR_STALE_CREDENTIALS) {
1251 // Race failure, retry
1252 } else if (error_code == STUN_ERROR_ROLE_CONFLICT) {
1253 HandleRoleConflictFromPeer();
1254 } else {
1255 // This is not a valid connection.
1256 LOG_J(LS_ERROR, this) << "Received STUN error response, code="
1257 << error_code << "; killing connection";
deadbeef376e1232015-11-25 09:00:08 -08001258 FailAndDestroy();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001259 }
1260}
1261
1262void Connection::OnConnectionRequestTimeout(ConnectionRequest* request) {
1263 // Log at LS_INFO if we miss a ping on a writable connection.
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001264 rtc::LoggingSeverity sev = writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1265 LOG_JV(sev, this) << "Timing-out STUN ping "
1266 << rtc::hex_encode(request->id())
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001267 << " after " << request->Elapsed() << " ms";
1268}
1269
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001270void Connection::OnConnectionRequestSent(ConnectionRequest* request) {
1271 // Log at LS_INFO if we send a ping on an unwritable connection.
1272 rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001273 bool use_candidate = use_candidate_attr();
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001274 LOG_JV(sev, this) << "Sent STUN ping"
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001275 << ", id=" << rtc::hex_encode(request->id())
1276 << ", use_candidate=" << use_candidate;
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001277}
1278
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001279void Connection::HandleRoleConflictFromPeer() {
1280 port_->SignalRoleConflict(port_);
1281}
1282
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +00001283void Connection::MaybeSetRemoteIceCredentials(const std::string& ice_ufrag,
1284 const std::string& ice_pwd) {
1285 if (remote_candidate_.username() == ice_ufrag &&
1286 remote_candidate_.password().empty()) {
1287 remote_candidate_.set_password(ice_pwd);
1288 }
1289}
1290
1291void Connection::MaybeUpdatePeerReflexiveCandidate(
1292 const Candidate& new_candidate) {
1293 if (remote_candidate_.type() == PRFLX_PORT_TYPE &&
1294 new_candidate.type() != PRFLX_PORT_TYPE &&
1295 remote_candidate_.protocol() == new_candidate.protocol() &&
1296 remote_candidate_.address() == new_candidate.address() &&
1297 remote_candidate_.username() == new_candidate.username() &&
1298 remote_candidate_.password() == new_candidate.password() &&
1299 remote_candidate_.generation() == new_candidate.generation()) {
1300 remote_candidate_ = new_candidate;
1301 }
1302}
1303
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001304void Connection::OnMessage(rtc::Message *pmsg) {
1305 ASSERT(pmsg->message_id == MSG_DELETE);
honghaizd0b31432015-09-30 12:42:17 -07001306 LOG_J(LS_INFO, this) << "Connection deleted";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001307 SignalDestroyed(this);
1308 delete this;
1309}
1310
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001311uint32_t Connection::last_received() const {
Peter Thatcher54360512015-07-08 11:08:35 -07001312 return std::max(last_data_received_,
1313 std::max(last_ping_received_, last_ping_response_received_));
1314}
1315
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001316size_t Connection::recv_bytes_second() {
Tim Psiakiad13d2f2015-11-10 16:34:50 -08001317 return round(recv_rate_tracker_.ComputeRate());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001318}
1319
1320size_t Connection::recv_total_bytes() {
Tim Psiaki63046262015-09-14 10:38:08 -07001321 return recv_rate_tracker_.TotalSampleCount();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001322}
1323
1324size_t Connection::sent_bytes_second() {
Tim Psiakiad13d2f2015-11-10 16:34:50 -08001325 return round(send_rate_tracker_.ComputeRate());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001326}
1327
1328size_t Connection::sent_total_bytes() {
Tim Psiaki63046262015-09-14 10:38:08 -07001329 return send_rate_tracker_.TotalSampleCount();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001330}
1331
guoweis@webrtc.org930e0042014-11-17 19:42:14 +00001332size_t Connection::sent_discarded_packets() {
1333 return sent_packets_discarded_;
1334}
1335
1336size_t Connection::sent_total_packets() {
1337 return sent_packets_total_;
1338}
1339
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001340void Connection::MaybeAddPrflxCandidate(ConnectionRequest* request,
1341 StunMessage* response) {
1342 // RFC 5245
1343 // The agent checks the mapped address from the STUN response. If the
1344 // transport address does not match any of the local candidates that the
1345 // agent knows about, the mapped address represents a new candidate -- a
1346 // peer reflexive candidate.
1347 const StunAddressAttribute* addr =
1348 response->GetAddress(STUN_ATTR_XOR_MAPPED_ADDRESS);
1349 if (!addr) {
1350 LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - "
1351 << "No MAPPED-ADDRESS or XOR-MAPPED-ADDRESS found in the "
1352 << "stun response message";
1353 return;
1354 }
1355
1356 bool known_addr = false;
1357 for (size_t i = 0; i < port_->Candidates().size(); ++i) {
1358 if (port_->Candidates()[i].address() == addr->GetAddress()) {
1359 known_addr = true;
1360 break;
1361 }
1362 }
1363 if (known_addr) {
1364 return;
1365 }
1366
1367 // RFC 5245
1368 // Its priority is set equal to the value of the PRIORITY attribute
1369 // in the Binding request.
1370 const StunUInt32Attribute* priority_attr =
1371 request->msg()->GetUInt32(STUN_ATTR_PRIORITY);
1372 if (!priority_attr) {
1373 LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - "
1374 << "No STUN_ATTR_PRIORITY found in the "
1375 << "stun response message";
1376 return;
1377 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02001378 const uint32_t priority = priority_attr->value();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001379 std::string id = rtc::CreateRandomString(8);
1380
1381 Candidate new_local_candidate;
1382 new_local_candidate.set_id(id);
1383 new_local_candidate.set_component(local_candidate().component());
1384 new_local_candidate.set_type(PRFLX_PORT_TYPE);
1385 new_local_candidate.set_protocol(local_candidate().protocol());
1386 new_local_candidate.set_address(addr->GetAddress());
1387 new_local_candidate.set_priority(priority);
1388 new_local_candidate.set_username(local_candidate().username());
1389 new_local_candidate.set_password(local_candidate().password());
1390 new_local_candidate.set_network_name(local_candidate().network_name());
guoweis@webrtc.org950c5182014-12-16 23:01:31 +00001391 new_local_candidate.set_network_type(local_candidate().network_type());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001392 new_local_candidate.set_related_address(local_candidate().address());
Honghai Zhang80f1db92016-01-27 11:54:45 -08001393 new_local_candidate.set_foundation(ComputeFoundation(
1394 PRFLX_PORT_TYPE, local_candidate().protocol(),
1395 local_candidate().relay_protocol(), local_candidate().address()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001396
1397 // Change the local candidate of this Connection to the new prflx candidate.
1398 local_candidate_index_ = port_->AddPrflxCandidate(new_local_candidate);
1399
1400 // SignalStateChange to force a re-sort in P2PTransportChannel as this
1401 // Connection's local candidate has changed.
1402 SignalStateChange(this);
1403}
1404
deadbeef376e1232015-11-25 09:00:08 -08001405ProxyConnection::ProxyConnection(Port* port,
1406 size_t index,
1407 const Candidate& remote_candidate)
1408 : Connection(port, index, remote_candidate) {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001409
1410int ProxyConnection::Send(const void* data, size_t size,
1411 const rtc::PacketOptions& options) {
1412 if (write_state_ == STATE_WRITE_INIT || write_state_ == STATE_WRITE_TIMEOUT) {
1413 error_ = EWOULDBLOCK;
1414 return SOCKET_ERROR;
1415 }
guoweis@webrtc.org930e0042014-11-17 19:42:14 +00001416 sent_packets_total_++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001417 int sent = port_->SendTo(data, size, remote_candidate_.address(),
1418 options, true);
1419 if (sent <= 0) {
1420 ASSERT(sent < 0);
1421 error_ = port_->GetError();
guoweis@webrtc.org930e0042014-11-17 19:42:14 +00001422 sent_packets_discarded_++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001423 } else {
Tim Psiaki63046262015-09-14 10:38:08 -07001424 send_rate_tracker_.AddSamples(sent);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001425 }
1426 return sent;
1427}
1428
1429} // namespace cricket