blob: 0238aa2ba207ac7b4478f2ad40797d562c1bcea4 [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"
honghaize3c6c822016-02-17 13:00:28 -080023#include "webrtc/base/network.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000024#include "webrtc/base/scoped_ptr.h"
25#include "webrtc/base/stringencode.h"
26#include "webrtc/base/stringutils.h"
27
28namespace {
29
30// Determines whether we have seen at least the given maximum number of
31// pings fail to have a response.
32inline bool TooManyFailures(
Peter Thatcher1cf6f812015-05-15 10:40:45 -070033 const std::vector<cricket::Connection::SentPing>& pings_since_last_response,
Peter Boström0c4e06b2015-10-07 12:23:21 +020034 uint32_t maximum_failures,
honghaiz34b11eb2016-03-16 08:55:44 -070035 int rtt_estimate,
36 int64_t now) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000037 // If we haven't sent that many pings, then we can't have failed that many.
38 if (pings_since_last_response.size() < maximum_failures)
39 return false;
40
41 // Check if the window in which we would expect a response to the ping has
42 // already elapsed.
honghaiz34b11eb2016-03-16 08:55:44 -070043 int64_t expected_response_time =
Peter Thatcher1cf6f812015-05-15 10:40:45 -070044 pings_since_last_response[maximum_failures - 1].sent_time + rtt_estimate;
45 return now > expected_response_time;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000046}
47
48// Determines whether we have gone too long without seeing any response.
49inline bool TooLongWithoutResponse(
Peter Thatcher1cf6f812015-05-15 10:40:45 -070050 const std::vector<cricket::Connection::SentPing>& pings_since_last_response,
honghaiz34b11eb2016-03-16 08:55:44 -070051 int64_t maximum_time,
52 int64_t now) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000053 if (pings_since_last_response.size() == 0)
54 return false;
55
Peter Thatcher1cf6f812015-05-15 10:40:45 -070056 auto first = pings_since_last_response[0];
57 return now > (first.sent_time + maximum_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000058}
59
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000060// We will restrict RTT estimates (when used for determining state) to be
61// within a reasonable range.
honghaiz34b11eb2016-03-16 08:55:44 -070062const int MINIMUM_RTT = 100; // 0.1 seconds
63const int MAXIMUM_RTT = 3000; // 3 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000064
65// When we don't have any RTT data, we have to pick something reasonable. We
66// use a large value just in case the connection is really slow.
honghaiz34b11eb2016-03-16 08:55:44 -070067const int DEFAULT_RTT = MAXIMUM_RTT;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000068
69// Computes our estimate of the RTT given the current estimate.
honghaiz34b11eb2016-03-16 08:55:44 -070070inline int ConservativeRTTEstimate(int rtt) {
andresp@webrtc.orgff689be2015-02-12 11:54:26 +000071 return std::max(MINIMUM_RTT, std::min(MAXIMUM_RTT, 2 * rtt));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000072}
73
74// Weighting of the old rtt value to new data.
75const int RTT_RATIO = 3; // 3 : 1
76
77// The delay before we begin checking if this port is useless.
78const int kPortTimeoutDelay = 30 * 1000; // 30 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000079}
80
81namespace cricket {
82
83// TODO(ronghuawu): Use "host", "srflx", "prflx" and "relay". But this requires
84// the signaling part be updated correspondingly as well.
85const char LOCAL_PORT_TYPE[] = "local";
86const char STUN_PORT_TYPE[] = "stun";
87const char PRFLX_PORT_TYPE[] = "prflx";
88const char RELAY_PORT_TYPE[] = "relay";
89
90const char UDP_PROTOCOL_NAME[] = "udp";
91const char TCP_PROTOCOL_NAME[] = "tcp";
92const char SSLTCP_PROTOCOL_NAME[] = "ssltcp";
93
94static const char* const PROTO_NAMES[] = { UDP_PROTOCOL_NAME,
95 TCP_PROTOCOL_NAME,
96 SSLTCP_PROTOCOL_NAME };
97
98const char* ProtoToString(ProtocolType proto) {
99 return PROTO_NAMES[proto];
100}
101
102bool StringToProto(const char* value, ProtocolType* proto) {
103 for (size_t i = 0; i <= PROTO_LAST; ++i) {
104 if (_stricmp(PROTO_NAMES[i], value) == 0) {
105 *proto = static_cast<ProtocolType>(i);
106 return true;
107 }
108 }
109 return false;
110}
111
112// RFC 6544, TCP candidate encoding rules.
113const int DISCARD_PORT = 9;
114const char TCPTYPE_ACTIVE_STR[] = "active";
115const char TCPTYPE_PASSIVE_STR[] = "passive";
116const char TCPTYPE_SIMOPEN_STR[] = "so";
117
118// Foundation: An arbitrary string that is the same for two candidates
119// that have the same type, base IP address, protocol (UDP, TCP,
120// etc.), and STUN or TURN server. If any of these are different,
121// then the foundation will be different. Two candidate pairs with
122// the same foundation pairs are likely to have similar network
123// characteristics. Foundations are used in the frozen algorithm.
Honghai Zhang80f1db92016-01-27 11:54:45 -0800124static std::string ComputeFoundation(const std::string& type,
125 const std::string& protocol,
126 const std::string& relay_protocol,
127 const rtc::SocketAddress& base_address) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000128 std::ostringstream ost;
Honghai Zhang80f1db92016-01-27 11:54:45 -0800129 ost << type << base_address.ipaddr().ToString() << protocol << relay_protocol;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200130 return rtc::ToString<uint32_t>(rtc::ComputeCrc32(ost.str()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000131}
132
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000133Port::Port(rtc::Thread* thread,
134 rtc::PacketSocketFactory* factory,
135 rtc::Network* network,
136 const rtc::IPAddress& ip,
137 const std::string& username_fragment,
138 const std::string& password)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000139 : thread_(thread),
140 factory_(factory),
141 send_retransmit_count_attribute_(false),
142 network_(network),
143 ip_(ip),
144 min_port_(0),
145 max_port_(0),
146 component_(ICE_CANDIDATE_COMPONENT_DEFAULT),
147 generation_(0),
148 ice_username_fragment_(username_fragment),
149 password_(password),
150 timeout_delay_(kPortTimeoutDelay),
151 enable_port_packets_(false),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000152 ice_role_(ICEROLE_UNKNOWN),
153 tiebreaker_(0),
154 shared_socket_(true),
155 candidate_filter_(CF_ALL) {
156 Construct();
157}
158
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000159Port::Port(rtc::Thread* thread,
160 const std::string& type,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000161 rtc::PacketSocketFactory* factory,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000162 rtc::Network* network,
163 const rtc::IPAddress& ip,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200164 uint16_t min_port,
165 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000166 const std::string& username_fragment,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000167 const std::string& password)
168 : thread_(thread),
169 factory_(factory),
170 type_(type),
171 send_retransmit_count_attribute_(false),
172 network_(network),
173 ip_(ip),
174 min_port_(min_port),
175 max_port_(max_port),
176 component_(ICE_CANDIDATE_COMPONENT_DEFAULT),
177 generation_(0),
178 ice_username_fragment_(username_fragment),
179 password_(password),
180 timeout_delay_(kPortTimeoutDelay),
181 enable_port_packets_(false),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000182 ice_role_(ICEROLE_UNKNOWN),
183 tiebreaker_(0),
184 shared_socket_(false),
185 candidate_filter_(CF_ALL) {
186 ASSERT(factory_ != NULL);
187 Construct();
188}
189
190void Port::Construct() {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700191 // TODO(pthatcher): Remove this old behavior once we're sure no one
192 // relies on it. If the username_fragment and password are empty,
193 // we should just create one.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000194 if (ice_username_fragment_.empty()) {
195 ASSERT(password_.empty());
196 ice_username_fragment_ = rtc::CreateRandomString(ICE_UFRAG_LENGTH);
197 password_ = rtc::CreateRandomString(ICE_PWD_LENGTH);
198 }
honghaize3c6c822016-02-17 13:00:28 -0800199 network_->SignalInactive.connect(this, &Port::OnNetworkInactive);
honghaize1a0c942016-02-16 14:54:56 -0800200 // TODO(honghaiz): Make it configurable from user setting.
201 network_cost_ =
202 (network_->type() == rtc::ADAPTER_TYPE_CELLULAR) ? kMaxNetworkCost : 0;
203
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000204 LOG_J(LS_INFO, this) << "Port created";
205}
206
207Port::~Port() {
208 // Delete all of the remaining connections. We copy the list up front
209 // because each deletion will cause it to be modified.
210
211 std::vector<Connection*> list;
212
213 AddressMap::iterator iter = connections_.begin();
214 while (iter != connections_.end()) {
215 list.push_back(iter->second);
216 ++iter;
217 }
218
Peter Boström0c4e06b2015-10-07 12:23:21 +0200219 for (uint32_t i = 0; i < list.size(); i++)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000220 delete list[i];
221}
222
223Connection* Port::GetConnection(const rtc::SocketAddress& remote_addr) {
224 AddressMap::const_iterator iter = connections_.find(remote_addr);
225 if (iter != connections_.end())
226 return iter->second;
227 else
228 return NULL;
229}
230
231void Port::AddAddress(const rtc::SocketAddress& address,
232 const rtc::SocketAddress& base_address,
233 const rtc::SocketAddress& related_address,
234 const std::string& protocol,
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700235 const std::string& relay_protocol,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000236 const std::string& tcptype,
237 const std::string& type,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200238 uint32_t type_preference,
239 uint32_t relay_preference,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000240 bool final) {
241 if (protocol == TCP_PROTOCOL_NAME && type == LOCAL_PORT_TYPE) {
242 ASSERT(!tcptype.empty());
243 }
244
honghaiza0c44ea2016-03-23 16:07:48 -0700245 std::string foundation =
246 ComputeFoundation(type, protocol, relay_protocol, base_address);
247 Candidate c(component_, protocol, address, 0U, username_fragment(), password_,
248 type, generation_, foundation, network_->id(), network_cost_);
249 c.set_priority(
250 c.GetPriority(type_preference, network_->preference(), relay_preference));
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700251 c.set_relay_protocol(relay_protocol);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000252 c.set_tcptype(tcptype);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000253 c.set_network_name(network_->name());
guoweis@webrtc.org950c5182014-12-16 23:01:31 +0000254 c.set_network_type(network_->type());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000255 c.set_related_address(related_address);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000256 candidates_.push_back(c);
257 SignalCandidateReady(this, c);
258
259 if (final) {
260 SignalPortComplete(this);
261 }
262}
263
264void Port::AddConnection(Connection* conn) {
265 connections_[conn->remote_candidate().address()] = conn;
266 conn->SignalDestroyed.connect(this, &Port::OnConnectionDestroyed);
267 SignalConnectionCreated(this, conn);
268}
269
270void Port::OnReadPacket(
271 const char* data, size_t size, const rtc::SocketAddress& addr,
272 ProtocolType proto) {
273 // If the user has enabled port packets, just hand this over.
274 if (enable_port_packets_) {
275 SignalReadPacket(this, data, size, addr);
276 return;
277 }
278
279 // If this is an authenticated STUN request, then signal unknown address and
280 // send back a proper binding response.
281 rtc::scoped_ptr<IceMessage> msg;
282 std::string remote_username;
kwiberg6baec032016-03-15 11:09:39 -0700283 if (!GetStunMessage(data, size, addr, &msg, &remote_username)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000284 LOG_J(LS_ERROR, this) << "Received non-STUN packet from unknown address ("
285 << addr.ToSensitiveString() << ")";
286 } else if (!msg) {
287 // STUN message handled already
288 } else if (msg->type() == STUN_BINDING_REQUEST) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700289 LOG(LS_INFO) << "Received STUN ping "
290 << " id=" << rtc::hex_encode(msg->transaction_id())
291 << " from unknown address " << addr.ToSensitiveString();
292
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000293 // Check for role conflicts.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700294 if (!MaybeIceRoleConflict(addr, msg.get(), remote_username)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000295 LOG(LS_INFO) << "Received conflicting role from the peer.";
296 return;
297 }
298
299 SignalUnknownAddress(this, addr, proto, msg.get(), remote_username, false);
300 } else {
301 // NOTE(tschmelcher): STUN_BINDING_RESPONSE is benign. It occurs if we
302 // pruned a connection for this port while it had STUN requests in flight,
303 // because we then get back responses for them, which this code correctly
304 // does not handle.
305 if (msg->type() != STUN_BINDING_RESPONSE) {
306 LOG_J(LS_ERROR, this) << "Received unexpected STUN message type ("
307 << msg->type() << ") from unknown address ("
308 << addr.ToSensitiveString() << ")";
309 }
310 }
311}
312
313void Port::OnReadyToSend() {
314 AddressMap::iterator iter = connections_.begin();
315 for (; iter != connections_.end(); ++iter) {
316 iter->second->OnReadyToSend();
317 }
318}
319
320size_t Port::AddPrflxCandidate(const Candidate& local) {
321 candidates_.push_back(local);
322 return (candidates_.size() - 1);
323}
324
kwiberg6baec032016-03-15 11:09:39 -0700325bool Port::GetStunMessage(const char* data,
326 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000327 const rtc::SocketAddress& addr,
kwiberg6baec032016-03-15 11:09:39 -0700328 rtc::scoped_ptr<IceMessage>* out_msg,
329 std::string* out_username) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000330 // NOTE: This could clearly be optimized to avoid allocating any memory.
331 // However, at the data rates we'll be looking at on the client side,
332 // this probably isn't worth worrying about.
333 ASSERT(out_msg != NULL);
334 ASSERT(out_username != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000335 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());
jbauchf1f87202016-03-30 06:43:37 -0700346 rtc::ByteBufferReader buf(data, size);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000347 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.
kwiberg6baec032016-03-15 11:09:39 -0700418 *out_msg = std::move(stun_msg);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000419 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.
jbauchf1f87202016-03-30 06:43:37 -0700568 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000569 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.
jbauchf1f87202016-03-30 06:43:37 -0700616 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000617 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
honghaize3c6c822016-02-17 13:00:28 -0800631void Port::OnNetworkInactive(const rtc::Network* network) {
632 ASSERT(network == network_);
633 SignalNetworkInactive(this);
634}
635
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000636std::string Port::ToString() const {
637 std::stringstream ss;
honghaize3c6c822016-02-17 13:00:28 -0800638 ss << "Port[" << std::hex << this << std::dec << ":" << content_name_ << ":"
639 << component_ << ":" << generation_ << ":" << type_ << ":"
640 << network_->ToString() << "]";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000641 return ss.str();
642}
643
644void Port::EnablePortPackets() {
645 enable_port_packets_ = true;
646}
647
648void Port::OnConnectionDestroyed(Connection* conn) {
649 AddressMap::iterator iter =
650 connections_.find(conn->remote_candidate().address());
651 ASSERT(iter != connections_.end());
652 connections_.erase(iter);
653
honghaizd0b31432015-09-30 12:42:17 -0700654 // On the controlled side, ports time out after all connections fail.
655 // Note: If a new connection is added after this message is posted, but it
656 // fails and is removed before kPortTimeoutDelay, then this message will
657 // still cause the Port to be destroyed.
658 if (dead()) {
659 thread_->PostDelayed(timeout_delay_, this, MSG_DEAD);
660 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000661}
662
663void Port::Destroy() {
664 ASSERT(connections_.empty());
665 LOG_J(LS_INFO, this) << "Port deleted";
666 SignalDestroyed(this);
667 delete this;
668}
669
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000670const std::string Port::username_fragment() const {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700671 return ice_username_fragment_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000672}
673
674// A ConnectionRequest is a simple STUN ping used to determine writability.
675class ConnectionRequest : public StunRequest {
676 public:
677 explicit ConnectionRequest(Connection* connection)
678 : StunRequest(new IceMessage()),
679 connection_(connection) {
680 }
681
682 virtual ~ConnectionRequest() {
683 }
684
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700685 void Prepare(StunMessage* request) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000686 request->SetType(STUN_BINDING_REQUEST);
687 std::string username;
688 connection_->port()->CreateStunUsername(
689 connection_->remote_candidate().username(), &username);
690 request->AddAttribute(
691 new StunByteStringAttribute(STUN_ATTR_USERNAME, username));
692
693 // connection_ already holds this ping, so subtract one from count.
694 if (connection_->port()->send_retransmit_count_attribute()) {
695 request->AddAttribute(new StunUInt32Attribute(
696 STUN_ATTR_RETRANSMIT_COUNT,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200697 static_cast<uint32_t>(connection_->pings_since_last_response_.size() -
698 1)));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000699 }
honghaiza0c44ea2016-03-23 16:07:48 -0700700 uint32_t network_info = connection_->port()->Network()->id();
701 network_info = (network_info << 16) | connection_->port()->network_cost();
702 request->AddAttribute(
703 new StunUInt32Attribute(STUN_ATTR_NETWORK_INFO, network_info));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000704
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700705 // Adding ICE_CONTROLLED or ICE_CONTROLLING attribute based on the role.
706 if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLING) {
707 request->AddAttribute(new StunUInt64Attribute(
708 STUN_ATTR_ICE_CONTROLLING, connection_->port()->IceTiebreaker()));
709 // Since we are trying aggressive nomination, sending USE-CANDIDATE
710 // attribute in every ping.
711 // If we are dealing with a ice-lite end point, nomination flag
712 // in Connection will be set to false by default. Once the connection
713 // becomes "best connection", nomination flag will be turned on.
714 if (connection_->use_candidate_attr()) {
715 request->AddAttribute(new StunByteStringAttribute(
716 STUN_ATTR_USE_CANDIDATE));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000717 }
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700718 } else if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLED) {
719 request->AddAttribute(new StunUInt64Attribute(
720 STUN_ATTR_ICE_CONTROLLED, connection_->port()->IceTiebreaker()));
721 } else {
722 ASSERT(false);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000723 }
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700724
725 // Adding PRIORITY Attribute.
726 // Changing the type preference to Peer Reflexive and local preference
727 // and component id information is unchanged from the original priority.
728 // priority = (2^24)*(type preference) +
729 // (2^8)*(local preference) +
730 // (2^0)*(256 - component ID)
Peter Boström0c4e06b2015-10-07 12:23:21 +0200731 uint32_t prflx_priority =
732 ICE_TYPE_PREFERENCE_PRFLX << 24 |
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700733 (connection_->local_candidate().priority() & 0x00FFFFFF);
734 request->AddAttribute(
735 new StunUInt32Attribute(STUN_ATTR_PRIORITY, prflx_priority));
736
737 // Adding Message Integrity attribute.
738 request->AddMessageIntegrity(connection_->remote_candidate().password());
739 // Adding Fingerprint.
740 request->AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000741 }
742
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700743 void OnResponse(StunMessage* response) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000744 connection_->OnConnectionRequestResponse(this, response);
745 }
746
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700747 void OnErrorResponse(StunMessage* response) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000748 connection_->OnConnectionRequestErrorResponse(this, response);
749 }
750
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700751 void OnTimeout() override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000752 connection_->OnConnectionRequestTimeout(this);
753 }
754
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700755 void OnSent() override {
756 connection_->OnConnectionRequestSent(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000757 // Each request is sent only once. After a single delay , the request will
758 // time out.
759 timeout_ = true;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700760 }
761
762 int resend_delay() override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000763 return CONNECTION_RESPONSE_TIMEOUT;
764 }
765
766 private:
767 Connection* connection_;
768};
769
770//
771// Connection
772//
773
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000774Connection::Connection(Port* port,
775 size_t index,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000776 const Candidate& remote_candidate)
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000777 : port_(port),
778 local_candidate_index_(index),
779 remote_candidate_(remote_candidate),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000780 write_state_(STATE_WRITE_INIT),
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700781 receiving_(false),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000782 connected_(true),
783 pruned_(false),
784 use_candidate_attr_(false),
honghaiz5a3acd82015-08-20 15:53:17 -0700785 nominated_(false),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000786 remote_ice_mode_(ICEMODE_FULL),
787 requests_(port->thread()),
788 rtt_(DEFAULT_RTT),
789 last_ping_sent_(0),
790 last_ping_received_(0),
791 last_data_received_(0),
792 last_ping_response_received_(0),
Tim Psiaki63046262015-09-14 10:38:08 -0700793 recv_rate_tracker_(100u, 10u),
794 send_rate_tracker_(100u, 10u),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000795 sent_packets_discarded_(0),
796 sent_packets_total_(0),
797 reported_(false),
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700798 state_(STATE_WAITING),
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700799 receiving_timeout_(WEAK_CONNECTION_RECEIVE_TIMEOUT),
honghaiz34b11eb2016-03-16 08:55:44 -0700800 time_created_ms_(rtc::Time64()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000801 // All of our connections start in WAITING state.
802 // TODO(mallinath) - Start connections from STATE_FROZEN.
803 // Wire up to send stun packets
804 requests_.SignalSendPacket.connect(this, &Connection::OnSendStunPacket);
805 LOG_J(LS_INFO, this) << "Connection created";
806}
807
808Connection::~Connection() {
809}
810
811const Candidate& Connection::local_candidate() const {
812 ASSERT(local_candidate_index_ < port_->Candidates().size());
813 return port_->Candidates()[local_candidate_index_];
814}
815
Honghai Zhangcc411c02016-03-29 17:27:21 -0700816const Candidate& Connection::remote_candidate() const {
817 return remote_candidate_;
818}
819
Peter Boström0c4e06b2015-10-07 12:23:21 +0200820uint64_t Connection::priority() const {
821 uint64_t priority = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000822 // RFC 5245 - 5.7.2. Computing Pair Priority and Ordering Pairs
823 // Let G be the priority for the candidate provided by the controlling
824 // agent. Let D be the priority for the candidate provided by the
825 // controlled agent.
826 // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)
827 IceRole role = port_->GetIceRole();
828 if (role != ICEROLE_UNKNOWN) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200829 uint32_t g = 0;
830 uint32_t d = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000831 if (role == ICEROLE_CONTROLLING) {
832 g = local_candidate().priority();
833 d = remote_candidate_.priority();
834 } else {
835 g = remote_candidate_.priority();
836 d = local_candidate().priority();
837 }
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000838 priority = std::min(g, d);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000839 priority = priority << 32;
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000840 priority += 2 * std::max(g, d) + (g > d ? 1 : 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000841 }
842 return priority;
843}
844
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000845void Connection::set_write_state(WriteState value) {
846 WriteState old_value = write_state_;
847 write_state_ = value;
848 if (value != old_value) {
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +0000849 LOG_J(LS_VERBOSE, this) << "set_write_state from: " << old_value << " to "
850 << value;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000851 SignalStateChange(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000852 }
853}
854
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700855void Connection::set_receiving(bool value) {
856 if (value != receiving_) {
857 LOG_J(LS_VERBOSE, this) << "set_receiving to " << value;
858 receiving_ = value;
859 SignalStateChange(this);
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700860 }
861}
862
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000863void Connection::set_state(State state) {
864 State old_state = state_;
865 state_ = state;
866 if (state != old_state) {
867 LOG_J(LS_VERBOSE, this) << "set_state";
868 }
869}
870
871void Connection::set_connected(bool value) {
872 bool old_value = connected_;
873 connected_ = value;
874 if (value != old_value) {
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700875 LOG_J(LS_VERBOSE, this) << "set_connected from: " << old_value << " to "
876 << value;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000877 }
878}
879
880void Connection::set_use_candidate_attr(bool enable) {
881 use_candidate_attr_ = enable;
882}
883
884void Connection::OnSendStunPacket(const void* data, size_t size,
885 StunRequest* req) {
886 rtc::PacketOptions options(port_->DefaultDscpValue());
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700887 auto err = port_->SendTo(
888 data, size, remote_candidate_.address(), options, false);
889 if (err < 0) {
890 LOG_J(LS_WARNING, this) << "Failed to send STUN ping "
891 << " err=" << err
892 << " id=" << rtc::hex_encode(req->id());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000893 }
894}
895
896void Connection::OnReadPacket(
897 const char* data, size_t size, const rtc::PacketTime& packet_time) {
898 rtc::scoped_ptr<IceMessage> msg;
899 std::string remote_ufrag;
900 const rtc::SocketAddress& addr(remote_candidate_.address());
kwiberg6baec032016-03-15 11:09:39 -0700901 if (!port_->GetStunMessage(data, size, addr, &msg, &remote_ufrag)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000902 // The packet did not parse as a valid STUN message
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700903 // This is a data packet, pass it along.
904 set_receiving(true);
honghaiz34b11eb2016-03-16 08:55:44 -0700905 last_data_received_ = rtc::Time64();
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700906 recv_rate_tracker_.AddSamples(size);
907 SignalReadPacket(this, data, size, packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000908
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700909 // If timed out sending writability checks, start up again
910 if (!pruned_ && (write_state_ == STATE_WRITE_TIMEOUT)) {
911 LOG(LS_WARNING) << "Received a data packet on a timed-out Connection. "
912 << "Resetting state to STATE_WRITE_INIT.";
913 set_write_state(STATE_WRITE_INIT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000914 }
915 } else if (!msg) {
916 // The packet was STUN, but failed a check and was handled internally.
917 } else {
918 // The packet is STUN and passed the Port checks.
919 // Perform our own checks to ensure this packet is valid.
honghaizd0b31432015-09-30 12:42:17 -0700920 // If this is a STUN request, then update the receiving bit and respond.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000921 // If this is a STUN response, then update the writable bit.
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700922 // Log at LS_INFO if we receive a ping on an unwritable connection.
923 rtc::LoggingSeverity sev = (!writable() ? rtc::LS_INFO : rtc::LS_VERBOSE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000924 switch (msg->type()) {
925 case STUN_BINDING_REQUEST:
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700926 LOG_JV(sev, this) << "Received STUN ping"
927 << ", id=" << rtc::hex_encode(msg->transaction_id());
928
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000929 if (remote_ufrag == remote_candidate_.username()) {
honghaiz9b5ee9c2015-11-11 13:19:17 -0800930 HandleBindingRequest(msg.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000931 } else {
932 // The packet had the right local username, but the remote username
933 // was not the right one for the remote address.
934 LOG_J(LS_ERROR, this)
935 << "Received STUN request with bad remote username "
936 << remote_ufrag;
937 port_->SendBindingErrorResponse(msg.get(), addr,
938 STUN_ERROR_UNAUTHORIZED,
939 STUN_ERROR_REASON_UNAUTHORIZED);
940
941 }
942 break;
943
944 // Response from remote peer. Does it match request sent?
945 // This doesn't just check, it makes callbacks if transaction
946 // id's match.
947 case STUN_BINDING_RESPONSE:
948 case STUN_BINDING_ERROR_RESPONSE:
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700949 if (msg->ValidateMessageIntegrity(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000950 data, size, remote_candidate().password())) {
951 requests_.CheckResponse(msg.get());
952 }
953 // Otherwise silently discard the response message.
954 break;
955
honghaizd0b31432015-09-30 12:42:17 -0700956 // Remote end point sent an STUN indication instead of regular binding
957 // request. In this case |last_ping_received_| will be updated but no
958 // response will be sent.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000959 case STUN_BINDING_INDICATION:
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700960 ReceivedPing();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000961 break;
962
963 default:
964 ASSERT(false);
965 break;
966 }
967 }
968}
969
honghaiz9b5ee9c2015-11-11 13:19:17 -0800970void Connection::HandleBindingRequest(IceMessage* msg) {
971 // This connection should now be receiving.
972 ReceivedPing();
973
974 const rtc::SocketAddress& remote_addr = remote_candidate_.address();
975 const std::string& remote_ufrag = remote_candidate_.username();
976 // Check for role conflicts.
977 if (!port_->MaybeIceRoleConflict(remote_addr, msg, remote_ufrag)) {
978 // Received conflicting role from the peer.
979 LOG(LS_INFO) << "Received conflicting role from the peer.";
980 return;
981 }
982
983 // This is a validated stun request from remote peer.
984 port_->SendBindingResponse(msg, remote_addr);
985
986 // If it timed out on writing check, start up again
987 if (!pruned_ && write_state_ == STATE_WRITE_TIMEOUT) {
988 set_write_state(STATE_WRITE_INIT);
989 }
990
991 if (port_->GetIceRole() == ICEROLE_CONTROLLED) {
992 const StunByteStringAttribute* use_candidate_attr =
993 msg->GetByteString(STUN_ATTR_USE_CANDIDATE);
994 if (use_candidate_attr) {
995 set_nominated(true);
996 SignalNominated(this);
997 }
998 }
999}
1000
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001001void Connection::OnReadyToSend() {
1002 if (write_state_ == STATE_WRITABLE) {
1003 SignalReadyToSend(this);
1004 }
1005}
1006
1007void Connection::Prune() {
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001008 if (!pruned_ || active()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001009 LOG_J(LS_VERBOSE, this) << "Connection pruned";
1010 pruned_ = true;
1011 requests_.Clear();
1012 set_write_state(STATE_WRITE_TIMEOUT);
1013 }
1014}
1015
1016void Connection::Destroy() {
1017 LOG_J(LS_VERBOSE, this) << "Connection destroyed";
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001018 port_->thread()->Post(this, MSG_DELETE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001019}
1020
deadbeef376e1232015-11-25 09:00:08 -08001021void Connection::FailAndDestroy() {
1022 set_state(Connection::STATE_FAILED);
1023 Destroy();
1024}
1025
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001026void Connection::PrintPingsSinceLastResponse(std::string* s, size_t max) {
1027 std::ostringstream oss;
1028 oss << std::boolalpha;
1029 if (pings_since_last_response_.size() > max) {
1030 for (size_t i = 0; i < max; i++) {
1031 const SentPing& ping = pings_since_last_response_[i];
1032 oss << rtc::hex_encode(ping.id) << " ";
1033 }
1034 oss << "... " << (pings_since_last_response_.size() - max) << " more";
1035 } else {
1036 for (const SentPing& ping : pings_since_last_response_) {
1037 oss << rtc::hex_encode(ping.id) << " ";
1038 }
1039 }
1040 *s = oss.str();
1041}
1042
honghaiz34b11eb2016-03-16 08:55:44 -07001043void Connection::UpdateState(int64_t now) {
1044 int rtt = ConservativeRTTEstimate(rtt_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001045
Peter Thatcherb2d26232015-05-15 11:25:14 -07001046 if (LOG_CHECK_LEVEL(LS_VERBOSE)) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001047 std::string pings;
1048 PrintPingsSinceLastResponse(&pings, 5);
1049 LOG_J(LS_VERBOSE, this) << "UpdateState()"
1050 << ", ms since last received response="
1051 << now - last_ping_response_received_
1052 << ", ms since last received data="
1053 << now - last_data_received_
1054 << ", rtt=" << rtt
1055 << ", pings_since_last_response=" << pings;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001056 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001057
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001058 // Check the writable state. (The order of these checks is important.)
1059 //
1060 // Before becoming unwritable, we allow for a fixed number of pings to fail
1061 // (i.e., receive no response). We also have to give the response time to
1062 // get back, so we include a conservative estimate of this.
1063 //
1064 // Before timing out writability, we give a fixed amount of time. This is to
1065 // allow for changes in network conditions.
1066
1067 if ((write_state_ == STATE_WRITABLE) &&
1068 TooManyFailures(pings_since_last_response_,
1069 CONNECTION_WRITE_CONNECT_FAILURES,
1070 rtt,
1071 now) &&
1072 TooLongWithoutResponse(pings_since_last_response_,
1073 CONNECTION_WRITE_CONNECT_TIMEOUT,
1074 now)) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001075 uint32_t max_pings = CONNECTION_WRITE_CONNECT_FAILURES;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001076 LOG_J(LS_INFO, this) << "Unwritable after " << max_pings
1077 << " ping failures and "
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001078 << now - pings_since_last_response_[0].sent_time
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001079 << " ms without a response,"
1080 << " ms since last received ping="
1081 << now - last_ping_received_
1082 << " ms since last received data="
1083 << now - last_data_received_
1084 << " rtt=" << rtt;
1085 set_write_state(STATE_WRITE_UNRELIABLE);
1086 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001087 if ((write_state_ == STATE_WRITE_UNRELIABLE ||
1088 write_state_ == STATE_WRITE_INIT) &&
1089 TooLongWithoutResponse(pings_since_last_response_,
1090 CONNECTION_WRITE_TIMEOUT,
1091 now)) {
1092 LOG_J(LS_INFO, this) << "Timed out after "
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001093 << now - pings_since_last_response_[0].sent_time
1094 << " ms without a response"
1095 << ", rtt=" << rtt;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001096 set_write_state(STATE_WRITE_TIMEOUT);
1097 }
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001098
1099 // Check the receiving state.
honghaiz34b11eb2016-03-16 08:55:44 -07001100 int64_t last_recv_time = last_received();
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001101 bool receiving = now <= last_recv_time + receiving_timeout_;
1102 set_receiving(receiving);
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001103 if (dead(now)) {
1104 Destroy();
1105 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001106}
1107
honghaiz34b11eb2016-03-16 08:55:44 -07001108void Connection::Ping(int64_t now) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001109 last_ping_sent_ = now;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001110 ConnectionRequest *req = new ConnectionRequest(this);
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001111 pings_since_last_response_.push_back(SentPing(req->id(), now));
1112 LOG_J(LS_VERBOSE, this) << "Sending STUN ping "
1113 << ", id=" << rtc::hex_encode(req->id());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001114 requests_.Send(req);
1115 state_ = STATE_INPROGRESS;
1116}
1117
1118void Connection::ReceivedPing() {
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001119 set_receiving(true);
honghaiz34b11eb2016-03-16 08:55:44 -07001120 last_ping_received_ = rtc::Time64();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001121}
1122
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001123void Connection::ReceivedPingResponse() {
1124 // We've already validated that this is a STUN binding response with
1125 // the correct local and remote username for this connection.
1126 // So if we're not already, become writable. We may be bringing a pruned
1127 // connection back to life, but if we don't really want it, we can always
1128 // prune it again.
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001129 set_receiving(true);
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001130 set_write_state(STATE_WRITABLE);
1131 set_state(STATE_SUCCEEDED);
1132 pings_since_last_response_.clear();
honghaiz34b11eb2016-03-16 08:55:44 -07001133 last_ping_response_received_ = rtc::Time64();
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001134}
1135
honghaiz34b11eb2016-03-16 08:55:44 -07001136bool Connection::dead(int64_t now) const {
honghaiz37389b42016-01-04 21:57:33 -08001137 if (last_received() > 0) {
1138 // If it has ever received anything, we keep it alive until it hasn't
1139 // received anything for DEAD_CONNECTION_RECEIVE_TIMEOUT. This covers the
1140 // normal case of a successfully used connection that stops working. This
1141 // also allows a remote peer to continue pinging over a locally inactive
1142 // (pruned) connection.
1143 return (now > (last_received() + DEAD_CONNECTION_RECEIVE_TIMEOUT));
1144 }
1145
1146 if (active()) {
1147 // If it has never received anything, keep it alive as long as it is
1148 // actively pinging and not pruned. Otherwise, the connection might be
1149 // deleted before it has a chance to ping. This is the normal case for a
1150 // new connection that is pinging but hasn't received anything yet.
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001151 return false;
1152 }
1153
honghaiz37389b42016-01-04 21:57:33 -08001154 // If it has never received anything and is not actively pinging (pruned), we
1155 // keep it around for at least MIN_CONNECTION_LIFETIME to prevent connections
1156 // from being pruned too quickly during a network change event when two
1157 // networks would be up simultaneously but only for a brief period.
1158 return now > (time_created_ms_ + MIN_CONNECTION_LIFETIME);
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001159}
1160
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +00001161std::string Connection::ToDebugId() const {
1162 std::stringstream ss;
1163 ss << std::hex << this;
1164 return ss.str();
1165}
1166
honghaize1a0c942016-02-16 14:54:56 -08001167uint32_t Connection::ComputeNetworkCost() const {
1168 // TODO(honghaiz): Will add rtt as part of the network cost.
1169 return local_candidate().network_cost() + remote_candidate_.network_cost();
1170}
1171
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001172std::string Connection::ToString() const {
1173 const char CONNECT_STATE_ABBREV[2] = {
1174 '-', // not connected (false)
1175 'C', // connected (true)
1176 };
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001177 const char RECEIVE_STATE_ABBREV[2] = {
1178 '-', // not receiving (false)
1179 'R', // receiving (true)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001180 };
1181 const char WRITE_STATE_ABBREV[4] = {
1182 'W', // STATE_WRITABLE
1183 'w', // STATE_WRITE_UNRELIABLE
1184 '-', // STATE_WRITE_INIT
1185 'x', // STATE_WRITE_TIMEOUT
1186 };
1187 const std::string ICESTATE[4] = {
1188 "W", // STATE_WAITING
1189 "I", // STATE_INPROGRESS
1190 "S", // STATE_SUCCEEDED
1191 "F" // STATE_FAILED
1192 };
1193 const Candidate& local = local_candidate();
1194 const Candidate& remote = remote_candidate();
1195 std::stringstream ss;
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +00001196 ss << "Conn[" << ToDebugId()
1197 << ":" << port_->content_name()
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001198 << ":" << local.id() << ":" << local.component()
1199 << ":" << local.generation()
1200 << ":" << local.type() << ":" << local.protocol()
1201 << ":" << local.address().ToSensitiveString()
1202 << "->" << remote.id() << ":" << remote.component()
1203 << ":" << remote.priority()
1204 << ":" << remote.type() << ":"
1205 << remote.protocol() << ":" << remote.address().ToSensitiveString() << "|"
1206 << CONNECT_STATE_ABBREV[connected()]
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001207 << RECEIVE_STATE_ABBREV[receiving()]
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001208 << WRITE_STATE_ABBREV[write_state()]
1209 << ICESTATE[state()] << "|"
1210 << priority() << "|";
1211 if (rtt_ < DEFAULT_RTT) {
1212 ss << rtt_ << "]";
1213 } else {
1214 ss << "-]";
1215 }
1216 return ss.str();
1217}
1218
1219std::string Connection::ToSensitiveString() const {
1220 return ToString();
1221}
1222
1223void Connection::OnConnectionRequestResponse(ConnectionRequest* request,
1224 StunMessage* response) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001225 // Log at LS_INFO if we receive a ping response on an unwritable
1226 // connection.
1227 rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1228
honghaiz34b11eb2016-03-16 08:55:44 -07001229 int rtt = request->Elapsed();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001230
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001231 ReceivedPingResponse();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001232
Peter Thatcherb2d26232015-05-15 11:25:14 -07001233 if (LOG_CHECK_LEVEL_V(sev)) {
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001234 bool use_candidate = (
1235 response->GetByteString(STUN_ATTR_USE_CANDIDATE) != nullptr);
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001236 std::string pings;
1237 PrintPingsSinceLastResponse(&pings, 5);
1238 LOG_JV(sev, this) << "Received STUN ping response"
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001239 << ", id=" << rtc::hex_encode(request->id())
1240 << ", code=0" // Makes logging easier to parse.
1241 << ", rtt=" << rtt
1242 << ", use_candidate=" << use_candidate
1243 << ", pings_since_last_response=" << pings;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001244 }
1245
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001246 rtt_ = (RTT_RATIO * rtt_ + rtt) / (RTT_RATIO + 1);
1247
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001248 MaybeAddPrflxCandidate(request, response);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001249}
1250
1251void Connection::OnConnectionRequestErrorResponse(ConnectionRequest* request,
1252 StunMessage* response) {
1253 const StunErrorCodeAttribute* error_attr = response->GetErrorCode();
1254 int error_code = STUN_ERROR_GLOBAL_FAILURE;
1255 if (error_attr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001256 error_code = error_attr->code();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001257 }
1258
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001259 LOG_J(LS_INFO, this) << "Received STUN error response"
1260 << " id=" << rtc::hex_encode(request->id())
1261 << " code=" << error_code
1262 << " rtt=" << request->Elapsed();
1263
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001264 if (error_code == STUN_ERROR_UNKNOWN_ATTRIBUTE ||
1265 error_code == STUN_ERROR_SERVER_ERROR ||
1266 error_code == STUN_ERROR_UNAUTHORIZED) {
1267 // Recoverable error, retry
1268 } else if (error_code == STUN_ERROR_STALE_CREDENTIALS) {
1269 // Race failure, retry
1270 } else if (error_code == STUN_ERROR_ROLE_CONFLICT) {
1271 HandleRoleConflictFromPeer();
1272 } else {
1273 // This is not a valid connection.
1274 LOG_J(LS_ERROR, this) << "Received STUN error response, code="
1275 << error_code << "; killing connection";
deadbeef376e1232015-11-25 09:00:08 -08001276 FailAndDestroy();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001277 }
1278}
1279
1280void Connection::OnConnectionRequestTimeout(ConnectionRequest* request) {
1281 // Log at LS_INFO if we miss a ping on a writable connection.
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001282 rtc::LoggingSeverity sev = writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1283 LOG_JV(sev, this) << "Timing-out STUN ping "
1284 << rtc::hex_encode(request->id())
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001285 << " after " << request->Elapsed() << " ms";
1286}
1287
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001288void Connection::OnConnectionRequestSent(ConnectionRequest* request) {
1289 // Log at LS_INFO if we send a ping on an unwritable connection.
1290 rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001291 bool use_candidate = use_candidate_attr();
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001292 LOG_JV(sev, this) << "Sent STUN ping"
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001293 << ", id=" << rtc::hex_encode(request->id())
1294 << ", use_candidate=" << use_candidate;
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001295}
1296
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001297void Connection::HandleRoleConflictFromPeer() {
1298 port_->SignalRoleConflict(port_);
1299}
1300
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -07001301void Connection::MaybeSetRemoteIceCredentialsAndGeneration(
1302 const std::string& ice_ufrag,
1303 const std::string& ice_pwd,
1304 int generation) {
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +00001305 if (remote_candidate_.username() == ice_ufrag &&
1306 remote_candidate_.password().empty()) {
1307 remote_candidate_.set_password(ice_pwd);
1308 }
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -07001309 // TODO(deadbeef): A value of '0' for the generation is used for both
1310 // generation 0 and "generation unknown". It should be changed to an
1311 // rtc::Optional to fix this.
1312 if (remote_candidate_.username() == ice_ufrag &&
1313 remote_candidate_.password() == ice_pwd &&
1314 remote_candidate_.generation() == 0) {
1315 remote_candidate_.set_generation(generation);
1316 }
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +00001317}
1318
1319void Connection::MaybeUpdatePeerReflexiveCandidate(
1320 const Candidate& new_candidate) {
1321 if (remote_candidate_.type() == PRFLX_PORT_TYPE &&
1322 new_candidate.type() != PRFLX_PORT_TYPE &&
1323 remote_candidate_.protocol() == new_candidate.protocol() &&
1324 remote_candidate_.address() == new_candidate.address() &&
1325 remote_candidate_.username() == new_candidate.username() &&
1326 remote_candidate_.password() == new_candidate.password() &&
1327 remote_candidate_.generation() == new_candidate.generation()) {
1328 remote_candidate_ = new_candidate;
1329 }
1330}
1331
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001332void Connection::OnMessage(rtc::Message *pmsg) {
1333 ASSERT(pmsg->message_id == MSG_DELETE);
honghaizd0b31432015-09-30 12:42:17 -07001334 LOG_J(LS_INFO, this) << "Connection deleted";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001335 SignalDestroyed(this);
1336 delete this;
1337}
1338
honghaiz34b11eb2016-03-16 08:55:44 -07001339int64_t Connection::last_received() const {
Peter Thatcher54360512015-07-08 11:08:35 -07001340 return std::max(last_data_received_,
1341 std::max(last_ping_received_, last_ping_response_received_));
1342}
1343
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001344size_t Connection::recv_bytes_second() {
Tim Psiakiad13d2f2015-11-10 16:34:50 -08001345 return round(recv_rate_tracker_.ComputeRate());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001346}
1347
1348size_t Connection::recv_total_bytes() {
Tim Psiaki63046262015-09-14 10:38:08 -07001349 return recv_rate_tracker_.TotalSampleCount();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001350}
1351
1352size_t Connection::sent_bytes_second() {
Tim Psiakiad13d2f2015-11-10 16:34:50 -08001353 return round(send_rate_tracker_.ComputeRate());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001354}
1355
1356size_t Connection::sent_total_bytes() {
Tim Psiaki63046262015-09-14 10:38:08 -07001357 return send_rate_tracker_.TotalSampleCount();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001358}
1359
guoweis@webrtc.org930e0042014-11-17 19:42:14 +00001360size_t Connection::sent_discarded_packets() {
1361 return sent_packets_discarded_;
1362}
1363
1364size_t Connection::sent_total_packets() {
1365 return sent_packets_total_;
1366}
1367
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001368void Connection::MaybeAddPrflxCandidate(ConnectionRequest* request,
1369 StunMessage* response) {
1370 // RFC 5245
1371 // The agent checks the mapped address from the STUN response. If the
1372 // transport address does not match any of the local candidates that the
1373 // agent knows about, the mapped address represents a new candidate -- a
1374 // peer reflexive candidate.
1375 const StunAddressAttribute* addr =
1376 response->GetAddress(STUN_ATTR_XOR_MAPPED_ADDRESS);
1377 if (!addr) {
1378 LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - "
1379 << "No MAPPED-ADDRESS or XOR-MAPPED-ADDRESS found in the "
1380 << "stun response message";
1381 return;
1382 }
1383
1384 bool known_addr = false;
1385 for (size_t i = 0; i < port_->Candidates().size(); ++i) {
1386 if (port_->Candidates()[i].address() == addr->GetAddress()) {
1387 known_addr = true;
1388 break;
1389 }
1390 }
1391 if (known_addr) {
1392 return;
1393 }
1394
1395 // RFC 5245
1396 // Its priority is set equal to the value of the PRIORITY attribute
1397 // in the Binding request.
1398 const StunUInt32Attribute* priority_attr =
1399 request->msg()->GetUInt32(STUN_ATTR_PRIORITY);
1400 if (!priority_attr) {
1401 LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - "
1402 << "No STUN_ATTR_PRIORITY found in the "
1403 << "stun response message";
1404 return;
1405 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02001406 const uint32_t priority = priority_attr->value();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001407 std::string id = rtc::CreateRandomString(8);
1408
1409 Candidate new_local_candidate;
1410 new_local_candidate.set_id(id);
1411 new_local_candidate.set_component(local_candidate().component());
1412 new_local_candidate.set_type(PRFLX_PORT_TYPE);
1413 new_local_candidate.set_protocol(local_candidate().protocol());
1414 new_local_candidate.set_address(addr->GetAddress());
1415 new_local_candidate.set_priority(priority);
1416 new_local_candidate.set_username(local_candidate().username());
1417 new_local_candidate.set_password(local_candidate().password());
1418 new_local_candidate.set_network_name(local_candidate().network_name());
guoweis@webrtc.org950c5182014-12-16 23:01:31 +00001419 new_local_candidate.set_network_type(local_candidate().network_type());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001420 new_local_candidate.set_related_address(local_candidate().address());
Honghai Zhang80f1db92016-01-27 11:54:45 -08001421 new_local_candidate.set_foundation(ComputeFoundation(
1422 PRFLX_PORT_TYPE, local_candidate().protocol(),
1423 local_candidate().relay_protocol(), local_candidate().address()));
honghaiza0c44ea2016-03-23 16:07:48 -07001424 new_local_candidate.set_network_id(local_candidate().network_id());
1425 new_local_candidate.set_network_cost(local_candidate().network_cost());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001426
1427 // Change the local candidate of this Connection to the new prflx candidate.
1428 local_candidate_index_ = port_->AddPrflxCandidate(new_local_candidate);
1429
1430 // SignalStateChange to force a re-sort in P2PTransportChannel as this
1431 // Connection's local candidate has changed.
1432 SignalStateChange(this);
1433}
1434
deadbeef376e1232015-11-25 09:00:08 -08001435ProxyConnection::ProxyConnection(Port* port,
1436 size_t index,
1437 const Candidate& remote_candidate)
1438 : Connection(port, index, remote_candidate) {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001439
1440int ProxyConnection::Send(const void* data, size_t size,
1441 const rtc::PacketOptions& options) {
1442 if (write_state_ == STATE_WRITE_INIT || write_state_ == STATE_WRITE_TIMEOUT) {
1443 error_ = EWOULDBLOCK;
1444 return SOCKET_ERROR;
1445 }
guoweis@webrtc.org930e0042014-11-17 19:42:14 +00001446 sent_packets_total_++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001447 int sent = port_->SendTo(data, size, remote_candidate_.address(),
1448 options, true);
1449 if (sent <= 0) {
1450 ASSERT(sent < 0);
1451 error_ = port_->GetError();
guoweis@webrtc.org930e0042014-11-17 19:42:14 +00001452 sent_packets_discarded_++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001453 } else {
Tim Psiaki63046262015-09-14 10:38:08 -07001454 send_rate_tracker_.AddSamples(sent);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001455 }
1456 return sent;
1457}
1458
1459} // namespace cricket