blob: eba15f69a32a6518766e2a77863d0889c917a02b [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());
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.
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.
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
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
Peter Boström0c4e06b2015-10-07 12:23:21 +0200816uint64_t Connection::priority() const {
817 uint64_t priority = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000818 // RFC 5245 - 5.7.2. Computing Pair Priority and Ordering Pairs
819 // Let G be the priority for the candidate provided by the controlling
820 // agent. Let D be the priority for the candidate provided by the
821 // controlled agent.
822 // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)
823 IceRole role = port_->GetIceRole();
824 if (role != ICEROLE_UNKNOWN) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200825 uint32_t g = 0;
826 uint32_t d = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000827 if (role == ICEROLE_CONTROLLING) {
828 g = local_candidate().priority();
829 d = remote_candidate_.priority();
830 } else {
831 g = remote_candidate_.priority();
832 d = local_candidate().priority();
833 }
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000834 priority = std::min(g, d);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000835 priority = priority << 32;
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000836 priority += 2 * std::max(g, d) + (g > d ? 1 : 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000837 }
838 return priority;
839}
840
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000841void Connection::set_write_state(WriteState value) {
842 WriteState old_value = write_state_;
843 write_state_ = value;
844 if (value != old_value) {
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +0000845 LOG_J(LS_VERBOSE, this) << "set_write_state from: " << old_value << " to "
846 << value;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000847 SignalStateChange(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000848 }
849}
850
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700851void Connection::set_receiving(bool value) {
852 if (value != receiving_) {
853 LOG_J(LS_VERBOSE, this) << "set_receiving to " << value;
854 receiving_ = value;
855 SignalStateChange(this);
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700856 }
857}
858
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000859void Connection::set_state(State state) {
860 State old_state = state_;
861 state_ = state;
862 if (state != old_state) {
863 LOG_J(LS_VERBOSE, this) << "set_state";
864 }
865}
866
867void Connection::set_connected(bool value) {
868 bool old_value = connected_;
869 connected_ = value;
870 if (value != old_value) {
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700871 LOG_J(LS_VERBOSE, this) << "set_connected from: " << old_value << " to "
872 << value;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000873 }
874}
875
876void Connection::set_use_candidate_attr(bool enable) {
877 use_candidate_attr_ = enable;
878}
879
880void Connection::OnSendStunPacket(const void* data, size_t size,
881 StunRequest* req) {
882 rtc::PacketOptions options(port_->DefaultDscpValue());
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700883 auto err = port_->SendTo(
884 data, size, remote_candidate_.address(), options, false);
885 if (err < 0) {
886 LOG_J(LS_WARNING, this) << "Failed to send STUN ping "
887 << " err=" << err
888 << " id=" << rtc::hex_encode(req->id());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000889 }
890}
891
892void Connection::OnReadPacket(
893 const char* data, size_t size, const rtc::PacketTime& packet_time) {
894 rtc::scoped_ptr<IceMessage> msg;
895 std::string remote_ufrag;
896 const rtc::SocketAddress& addr(remote_candidate_.address());
kwiberg6baec032016-03-15 11:09:39 -0700897 if (!port_->GetStunMessage(data, size, addr, &msg, &remote_ufrag)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000898 // The packet did not parse as a valid STUN message
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700899 // This is a data packet, pass it along.
900 set_receiving(true);
honghaiz34b11eb2016-03-16 08:55:44 -0700901 last_data_received_ = rtc::Time64();
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700902 recv_rate_tracker_.AddSamples(size);
903 SignalReadPacket(this, data, size, packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000904
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700905 // If timed out sending writability checks, start up again
906 if (!pruned_ && (write_state_ == STATE_WRITE_TIMEOUT)) {
907 LOG(LS_WARNING) << "Received a data packet on a timed-out Connection. "
908 << "Resetting state to STATE_WRITE_INIT.";
909 set_write_state(STATE_WRITE_INIT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000910 }
911 } else if (!msg) {
912 // The packet was STUN, but failed a check and was handled internally.
913 } else {
914 // The packet is STUN and passed the Port checks.
915 // Perform our own checks to ensure this packet is valid.
honghaizd0b31432015-09-30 12:42:17 -0700916 // If this is a STUN request, then update the receiving bit and respond.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000917 // If this is a STUN response, then update the writable bit.
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700918 // Log at LS_INFO if we receive a ping on an unwritable connection.
919 rtc::LoggingSeverity sev = (!writable() ? rtc::LS_INFO : rtc::LS_VERBOSE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000920 switch (msg->type()) {
921 case STUN_BINDING_REQUEST:
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700922 LOG_JV(sev, this) << "Received STUN ping"
923 << ", id=" << rtc::hex_encode(msg->transaction_id());
924
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000925 if (remote_ufrag == remote_candidate_.username()) {
honghaiz9b5ee9c2015-11-11 13:19:17 -0800926 HandleBindingRequest(msg.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000927 } else {
928 // The packet had the right local username, but the remote username
929 // was not the right one for the remote address.
930 LOG_J(LS_ERROR, this)
931 << "Received STUN request with bad remote username "
932 << remote_ufrag;
933 port_->SendBindingErrorResponse(msg.get(), addr,
934 STUN_ERROR_UNAUTHORIZED,
935 STUN_ERROR_REASON_UNAUTHORIZED);
936
937 }
938 break;
939
940 // Response from remote peer. Does it match request sent?
941 // This doesn't just check, it makes callbacks if transaction
942 // id's match.
943 case STUN_BINDING_RESPONSE:
944 case STUN_BINDING_ERROR_RESPONSE:
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700945 if (msg->ValidateMessageIntegrity(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000946 data, size, remote_candidate().password())) {
947 requests_.CheckResponse(msg.get());
948 }
949 // Otherwise silently discard the response message.
950 break;
951
honghaizd0b31432015-09-30 12:42:17 -0700952 // Remote end point sent an STUN indication instead of regular binding
953 // request. In this case |last_ping_received_| will be updated but no
954 // response will be sent.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000955 case STUN_BINDING_INDICATION:
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700956 ReceivedPing();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000957 break;
958
959 default:
960 ASSERT(false);
961 break;
962 }
963 }
964}
965
honghaiz9b5ee9c2015-11-11 13:19:17 -0800966void Connection::HandleBindingRequest(IceMessage* msg) {
967 // This connection should now be receiving.
968 ReceivedPing();
969
970 const rtc::SocketAddress& remote_addr = remote_candidate_.address();
971 const std::string& remote_ufrag = remote_candidate_.username();
972 // Check for role conflicts.
973 if (!port_->MaybeIceRoleConflict(remote_addr, msg, remote_ufrag)) {
974 // Received conflicting role from the peer.
975 LOG(LS_INFO) << "Received conflicting role from the peer.";
976 return;
977 }
978
979 // This is a validated stun request from remote peer.
980 port_->SendBindingResponse(msg, remote_addr);
981
982 // If it timed out on writing check, start up again
983 if (!pruned_ && write_state_ == STATE_WRITE_TIMEOUT) {
984 set_write_state(STATE_WRITE_INIT);
985 }
986
987 if (port_->GetIceRole() == ICEROLE_CONTROLLED) {
988 const StunByteStringAttribute* use_candidate_attr =
989 msg->GetByteString(STUN_ATTR_USE_CANDIDATE);
990 if (use_candidate_attr) {
991 set_nominated(true);
992 SignalNominated(this);
993 }
994 }
995}
996
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000997void Connection::OnReadyToSend() {
998 if (write_state_ == STATE_WRITABLE) {
999 SignalReadyToSend(this);
1000 }
1001}
1002
1003void Connection::Prune() {
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001004 if (!pruned_ || active()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001005 LOG_J(LS_VERBOSE, this) << "Connection pruned";
1006 pruned_ = true;
1007 requests_.Clear();
1008 set_write_state(STATE_WRITE_TIMEOUT);
1009 }
1010}
1011
1012void Connection::Destroy() {
1013 LOG_J(LS_VERBOSE, this) << "Connection destroyed";
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001014 port_->thread()->Post(this, MSG_DELETE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001015}
1016
deadbeef376e1232015-11-25 09:00:08 -08001017void Connection::FailAndDestroy() {
1018 set_state(Connection::STATE_FAILED);
1019 Destroy();
1020}
1021
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001022void Connection::PrintPingsSinceLastResponse(std::string* s, size_t max) {
1023 std::ostringstream oss;
1024 oss << std::boolalpha;
1025 if (pings_since_last_response_.size() > max) {
1026 for (size_t i = 0; i < max; i++) {
1027 const SentPing& ping = pings_since_last_response_[i];
1028 oss << rtc::hex_encode(ping.id) << " ";
1029 }
1030 oss << "... " << (pings_since_last_response_.size() - max) << " more";
1031 } else {
1032 for (const SentPing& ping : pings_since_last_response_) {
1033 oss << rtc::hex_encode(ping.id) << " ";
1034 }
1035 }
1036 *s = oss.str();
1037}
1038
honghaiz34b11eb2016-03-16 08:55:44 -07001039void Connection::UpdateState(int64_t now) {
1040 int rtt = ConservativeRTTEstimate(rtt_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001041
Peter Thatcherb2d26232015-05-15 11:25:14 -07001042 if (LOG_CHECK_LEVEL(LS_VERBOSE)) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001043 std::string pings;
1044 PrintPingsSinceLastResponse(&pings, 5);
1045 LOG_J(LS_VERBOSE, this) << "UpdateState()"
1046 << ", ms since last received response="
1047 << now - last_ping_response_received_
1048 << ", ms since last received data="
1049 << now - last_data_received_
1050 << ", rtt=" << rtt
1051 << ", pings_since_last_response=" << pings;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001052 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001053
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001054 // Check the writable state. (The order of these checks is important.)
1055 //
1056 // Before becoming unwritable, we allow for a fixed number of pings to fail
1057 // (i.e., receive no response). We also have to give the response time to
1058 // get back, so we include a conservative estimate of this.
1059 //
1060 // Before timing out writability, we give a fixed amount of time. This is to
1061 // allow for changes in network conditions.
1062
1063 if ((write_state_ == STATE_WRITABLE) &&
1064 TooManyFailures(pings_since_last_response_,
1065 CONNECTION_WRITE_CONNECT_FAILURES,
1066 rtt,
1067 now) &&
1068 TooLongWithoutResponse(pings_since_last_response_,
1069 CONNECTION_WRITE_CONNECT_TIMEOUT,
1070 now)) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001071 uint32_t max_pings = CONNECTION_WRITE_CONNECT_FAILURES;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001072 LOG_J(LS_INFO, this) << "Unwritable after " << max_pings
1073 << " ping failures and "
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001074 << now - pings_since_last_response_[0].sent_time
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001075 << " ms without a response,"
1076 << " ms since last received ping="
1077 << now - last_ping_received_
1078 << " ms since last received data="
1079 << now - last_data_received_
1080 << " rtt=" << rtt;
1081 set_write_state(STATE_WRITE_UNRELIABLE);
1082 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001083 if ((write_state_ == STATE_WRITE_UNRELIABLE ||
1084 write_state_ == STATE_WRITE_INIT) &&
1085 TooLongWithoutResponse(pings_since_last_response_,
1086 CONNECTION_WRITE_TIMEOUT,
1087 now)) {
1088 LOG_J(LS_INFO, this) << "Timed out after "
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001089 << now - pings_since_last_response_[0].sent_time
1090 << " ms without a response"
1091 << ", rtt=" << rtt;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001092 set_write_state(STATE_WRITE_TIMEOUT);
1093 }
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001094
1095 // Check the receiving state.
honghaiz34b11eb2016-03-16 08:55:44 -07001096 int64_t last_recv_time = last_received();
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001097 bool receiving = now <= last_recv_time + receiving_timeout_;
1098 set_receiving(receiving);
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001099 if (dead(now)) {
1100 Destroy();
1101 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001102}
1103
honghaiz34b11eb2016-03-16 08:55:44 -07001104void Connection::Ping(int64_t now) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001105 last_ping_sent_ = now;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001106 ConnectionRequest *req = new ConnectionRequest(this);
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001107 pings_since_last_response_.push_back(SentPing(req->id(), now));
1108 LOG_J(LS_VERBOSE, this) << "Sending STUN ping "
1109 << ", id=" << rtc::hex_encode(req->id());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001110 requests_.Send(req);
1111 state_ = STATE_INPROGRESS;
1112}
1113
1114void Connection::ReceivedPing() {
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001115 set_receiving(true);
honghaiz34b11eb2016-03-16 08:55:44 -07001116 last_ping_received_ = rtc::Time64();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001117}
1118
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001119void Connection::ReceivedPingResponse() {
1120 // We've already validated that this is a STUN binding response with
1121 // the correct local and remote username for this connection.
1122 // So if we're not already, become writable. We may be bringing a pruned
1123 // connection back to life, but if we don't really want it, we can always
1124 // prune it again.
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001125 set_receiving(true);
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001126 set_write_state(STATE_WRITABLE);
1127 set_state(STATE_SUCCEEDED);
1128 pings_since_last_response_.clear();
honghaiz34b11eb2016-03-16 08:55:44 -07001129 last_ping_response_received_ = rtc::Time64();
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001130}
1131
honghaiz34b11eb2016-03-16 08:55:44 -07001132bool Connection::dead(int64_t now) const {
honghaiz37389b42016-01-04 21:57:33 -08001133 if (last_received() > 0) {
1134 // If it has ever received anything, we keep it alive until it hasn't
1135 // received anything for DEAD_CONNECTION_RECEIVE_TIMEOUT. This covers the
1136 // normal case of a successfully used connection that stops working. This
1137 // also allows a remote peer to continue pinging over a locally inactive
1138 // (pruned) connection.
1139 return (now > (last_received() + DEAD_CONNECTION_RECEIVE_TIMEOUT));
1140 }
1141
1142 if (active()) {
1143 // If it has never received anything, keep it alive as long as it is
1144 // actively pinging and not pruned. Otherwise, the connection might be
1145 // deleted before it has a chance to ping. This is the normal case for a
1146 // new connection that is pinging but hasn't received anything yet.
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001147 return false;
1148 }
1149
honghaiz37389b42016-01-04 21:57:33 -08001150 // If it has never received anything and is not actively pinging (pruned), we
1151 // keep it around for at least MIN_CONNECTION_LIFETIME to prevent connections
1152 // from being pruned too quickly during a network change event when two
1153 // networks would be up simultaneously but only for a brief period.
1154 return now > (time_created_ms_ + MIN_CONNECTION_LIFETIME);
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001155}
1156
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +00001157std::string Connection::ToDebugId() const {
1158 std::stringstream ss;
1159 ss << std::hex << this;
1160 return ss.str();
1161}
1162
honghaize1a0c942016-02-16 14:54:56 -08001163uint32_t Connection::ComputeNetworkCost() const {
1164 // TODO(honghaiz): Will add rtt as part of the network cost.
1165 return local_candidate().network_cost() + remote_candidate_.network_cost();
1166}
1167
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001168std::string Connection::ToString() const {
1169 const char CONNECT_STATE_ABBREV[2] = {
1170 '-', // not connected (false)
1171 'C', // connected (true)
1172 };
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001173 const char RECEIVE_STATE_ABBREV[2] = {
1174 '-', // not receiving (false)
1175 'R', // receiving (true)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001176 };
1177 const char WRITE_STATE_ABBREV[4] = {
1178 'W', // STATE_WRITABLE
1179 'w', // STATE_WRITE_UNRELIABLE
1180 '-', // STATE_WRITE_INIT
1181 'x', // STATE_WRITE_TIMEOUT
1182 };
1183 const std::string ICESTATE[4] = {
1184 "W", // STATE_WAITING
1185 "I", // STATE_INPROGRESS
1186 "S", // STATE_SUCCEEDED
1187 "F" // STATE_FAILED
1188 };
1189 const Candidate& local = local_candidate();
1190 const Candidate& remote = remote_candidate();
1191 std::stringstream ss;
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +00001192 ss << "Conn[" << ToDebugId()
1193 << ":" << port_->content_name()
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001194 << ":" << local.id() << ":" << local.component()
1195 << ":" << local.generation()
1196 << ":" << local.type() << ":" << local.protocol()
1197 << ":" << local.address().ToSensitiveString()
1198 << "->" << remote.id() << ":" << remote.component()
1199 << ":" << remote.priority()
1200 << ":" << remote.type() << ":"
1201 << remote.protocol() << ":" << remote.address().ToSensitiveString() << "|"
1202 << CONNECT_STATE_ABBREV[connected()]
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001203 << RECEIVE_STATE_ABBREV[receiving()]
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001204 << WRITE_STATE_ABBREV[write_state()]
1205 << ICESTATE[state()] << "|"
1206 << priority() << "|";
1207 if (rtt_ < DEFAULT_RTT) {
1208 ss << rtt_ << "]";
1209 } else {
1210 ss << "-]";
1211 }
1212 return ss.str();
1213}
1214
1215std::string Connection::ToSensitiveString() const {
1216 return ToString();
1217}
1218
1219void Connection::OnConnectionRequestResponse(ConnectionRequest* request,
1220 StunMessage* response) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001221 // Log at LS_INFO if we receive a ping response on an unwritable
1222 // connection.
1223 rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1224
honghaiz34b11eb2016-03-16 08:55:44 -07001225 int rtt = request->Elapsed();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001226
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001227 ReceivedPingResponse();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001228
Peter Thatcherb2d26232015-05-15 11:25:14 -07001229 if (LOG_CHECK_LEVEL_V(sev)) {
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001230 bool use_candidate = (
1231 response->GetByteString(STUN_ATTR_USE_CANDIDATE) != nullptr);
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001232 std::string pings;
1233 PrintPingsSinceLastResponse(&pings, 5);
1234 LOG_JV(sev, this) << "Received STUN ping response"
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001235 << ", id=" << rtc::hex_encode(request->id())
1236 << ", code=0" // Makes logging easier to parse.
1237 << ", rtt=" << rtt
1238 << ", use_candidate=" << use_candidate
1239 << ", pings_since_last_response=" << pings;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001240 }
1241
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001242 rtt_ = (RTT_RATIO * rtt_ + rtt) / (RTT_RATIO + 1);
1243
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001244 MaybeAddPrflxCandidate(request, response);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001245}
1246
1247void Connection::OnConnectionRequestErrorResponse(ConnectionRequest* request,
1248 StunMessage* response) {
1249 const StunErrorCodeAttribute* error_attr = response->GetErrorCode();
1250 int error_code = STUN_ERROR_GLOBAL_FAILURE;
1251 if (error_attr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001252 error_code = error_attr->code();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001253 }
1254
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001255 LOG_J(LS_INFO, this) << "Received STUN error response"
1256 << " id=" << rtc::hex_encode(request->id())
1257 << " code=" << error_code
1258 << " rtt=" << request->Elapsed();
1259
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001260 if (error_code == STUN_ERROR_UNKNOWN_ATTRIBUTE ||
1261 error_code == STUN_ERROR_SERVER_ERROR ||
1262 error_code == STUN_ERROR_UNAUTHORIZED) {
1263 // Recoverable error, retry
1264 } else if (error_code == STUN_ERROR_STALE_CREDENTIALS) {
1265 // Race failure, retry
1266 } else if (error_code == STUN_ERROR_ROLE_CONFLICT) {
1267 HandleRoleConflictFromPeer();
1268 } else {
1269 // This is not a valid connection.
1270 LOG_J(LS_ERROR, this) << "Received STUN error response, code="
1271 << error_code << "; killing connection";
deadbeef376e1232015-11-25 09:00:08 -08001272 FailAndDestroy();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001273 }
1274}
1275
1276void Connection::OnConnectionRequestTimeout(ConnectionRequest* request) {
1277 // Log at LS_INFO if we miss a ping on a writable connection.
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001278 rtc::LoggingSeverity sev = writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1279 LOG_JV(sev, this) << "Timing-out STUN ping "
1280 << rtc::hex_encode(request->id())
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001281 << " after " << request->Elapsed() << " ms";
1282}
1283
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001284void Connection::OnConnectionRequestSent(ConnectionRequest* request) {
1285 // Log at LS_INFO if we send a ping on an unwritable connection.
1286 rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001287 bool use_candidate = use_candidate_attr();
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001288 LOG_JV(sev, this) << "Sent STUN ping"
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001289 << ", id=" << rtc::hex_encode(request->id())
1290 << ", use_candidate=" << use_candidate;
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001291}
1292
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001293void Connection::HandleRoleConflictFromPeer() {
1294 port_->SignalRoleConflict(port_);
1295}
1296
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +00001297void Connection::MaybeSetRemoteIceCredentials(const std::string& ice_ufrag,
1298 const std::string& ice_pwd) {
1299 if (remote_candidate_.username() == ice_ufrag &&
1300 remote_candidate_.password().empty()) {
1301 remote_candidate_.set_password(ice_pwd);
1302 }
1303}
1304
1305void Connection::MaybeUpdatePeerReflexiveCandidate(
1306 const Candidate& new_candidate) {
1307 if (remote_candidate_.type() == PRFLX_PORT_TYPE &&
1308 new_candidate.type() != PRFLX_PORT_TYPE &&
1309 remote_candidate_.protocol() == new_candidate.protocol() &&
1310 remote_candidate_.address() == new_candidate.address() &&
1311 remote_candidate_.username() == new_candidate.username() &&
1312 remote_candidate_.password() == new_candidate.password() &&
1313 remote_candidate_.generation() == new_candidate.generation()) {
1314 remote_candidate_ = new_candidate;
1315 }
1316}
1317
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001318void Connection::OnMessage(rtc::Message *pmsg) {
1319 ASSERT(pmsg->message_id == MSG_DELETE);
honghaizd0b31432015-09-30 12:42:17 -07001320 LOG_J(LS_INFO, this) << "Connection deleted";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001321 SignalDestroyed(this);
1322 delete this;
1323}
1324
honghaiz34b11eb2016-03-16 08:55:44 -07001325int64_t Connection::last_received() const {
Peter Thatcher54360512015-07-08 11:08:35 -07001326 return std::max(last_data_received_,
1327 std::max(last_ping_received_, last_ping_response_received_));
1328}
1329
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001330size_t Connection::recv_bytes_second() {
Tim Psiakiad13d2f2015-11-10 16:34:50 -08001331 return round(recv_rate_tracker_.ComputeRate());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001332}
1333
1334size_t Connection::recv_total_bytes() {
Tim Psiaki63046262015-09-14 10:38:08 -07001335 return recv_rate_tracker_.TotalSampleCount();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001336}
1337
1338size_t Connection::sent_bytes_second() {
Tim Psiakiad13d2f2015-11-10 16:34:50 -08001339 return round(send_rate_tracker_.ComputeRate());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001340}
1341
1342size_t Connection::sent_total_bytes() {
Tim Psiaki63046262015-09-14 10:38:08 -07001343 return send_rate_tracker_.TotalSampleCount();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001344}
1345
guoweis@webrtc.org930e0042014-11-17 19:42:14 +00001346size_t Connection::sent_discarded_packets() {
1347 return sent_packets_discarded_;
1348}
1349
1350size_t Connection::sent_total_packets() {
1351 return sent_packets_total_;
1352}
1353
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001354void Connection::MaybeAddPrflxCandidate(ConnectionRequest* request,
1355 StunMessage* response) {
1356 // RFC 5245
1357 // The agent checks the mapped address from the STUN response. If the
1358 // transport address does not match any of the local candidates that the
1359 // agent knows about, the mapped address represents a new candidate -- a
1360 // peer reflexive candidate.
1361 const StunAddressAttribute* addr =
1362 response->GetAddress(STUN_ATTR_XOR_MAPPED_ADDRESS);
1363 if (!addr) {
1364 LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - "
1365 << "No MAPPED-ADDRESS or XOR-MAPPED-ADDRESS found in the "
1366 << "stun response message";
1367 return;
1368 }
1369
1370 bool known_addr = false;
1371 for (size_t i = 0; i < port_->Candidates().size(); ++i) {
1372 if (port_->Candidates()[i].address() == addr->GetAddress()) {
1373 known_addr = true;
1374 break;
1375 }
1376 }
1377 if (known_addr) {
1378 return;
1379 }
1380
1381 // RFC 5245
1382 // Its priority is set equal to the value of the PRIORITY attribute
1383 // in the Binding request.
1384 const StunUInt32Attribute* priority_attr =
1385 request->msg()->GetUInt32(STUN_ATTR_PRIORITY);
1386 if (!priority_attr) {
1387 LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - "
1388 << "No STUN_ATTR_PRIORITY found in the "
1389 << "stun response message";
1390 return;
1391 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02001392 const uint32_t priority = priority_attr->value();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001393 std::string id = rtc::CreateRandomString(8);
1394
1395 Candidate new_local_candidate;
1396 new_local_candidate.set_id(id);
1397 new_local_candidate.set_component(local_candidate().component());
1398 new_local_candidate.set_type(PRFLX_PORT_TYPE);
1399 new_local_candidate.set_protocol(local_candidate().protocol());
1400 new_local_candidate.set_address(addr->GetAddress());
1401 new_local_candidate.set_priority(priority);
1402 new_local_candidate.set_username(local_candidate().username());
1403 new_local_candidate.set_password(local_candidate().password());
1404 new_local_candidate.set_network_name(local_candidate().network_name());
guoweis@webrtc.org950c5182014-12-16 23:01:31 +00001405 new_local_candidate.set_network_type(local_candidate().network_type());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001406 new_local_candidate.set_related_address(local_candidate().address());
Honghai Zhang80f1db92016-01-27 11:54:45 -08001407 new_local_candidate.set_foundation(ComputeFoundation(
1408 PRFLX_PORT_TYPE, local_candidate().protocol(),
1409 local_candidate().relay_protocol(), local_candidate().address()));
honghaiza0c44ea2016-03-23 16:07:48 -07001410 new_local_candidate.set_network_id(local_candidate().network_id());
1411 new_local_candidate.set_network_cost(local_candidate().network_cost());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001412
1413 // Change the local candidate of this Connection to the new prflx candidate.
1414 local_candidate_index_ = port_->AddPrflxCandidate(new_local_candidate);
1415
1416 // SignalStateChange to force a re-sort in P2PTransportChannel as this
1417 // Connection's local candidate has changed.
1418 SignalStateChange(this);
1419}
1420
deadbeef376e1232015-11-25 09:00:08 -08001421ProxyConnection::ProxyConnection(Port* port,
1422 size_t index,
1423 const Candidate& remote_candidate)
1424 : Connection(port, index, remote_candidate) {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001425
1426int ProxyConnection::Send(const void* data, size_t size,
1427 const rtc::PacketOptions& options) {
1428 if (write_state_ == STATE_WRITE_INIT || write_state_ == STATE_WRITE_TIMEOUT) {
1429 error_ = EWOULDBLOCK;
1430 return SOCKET_ERROR;
1431 }
guoweis@webrtc.org930e0042014-11-17 19:42:14 +00001432 sent_packets_total_++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001433 int sent = port_->SendTo(data, size, remote_candidate_.address(),
1434 options, true);
1435 if (sent <= 0) {
1436 ASSERT(sent < 0);
1437 error_ = port_->GetError();
guoweis@webrtc.org930e0042014-11-17 19:42:14 +00001438 sent_packets_discarded_++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001439 } else {
Tim Psiaki63046262015-09-14 10:38:08 -07001440 send_rate_tracker_.AddSamples(sent);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001441 }
1442 return sent;
1443}
1444
1445} // namespace cricket