blob: d71d6fa844fa69a15ebc3179fe00b8f25a189dfd [file] [log] [blame]
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "webrtc/p2p/base/port.h"
12
13#include <algorithm>
14#include <vector>
15
16#include "webrtc/p2p/base/common.h"
17#include "webrtc/p2p/base/portallocator.h"
18#include "webrtc/base/base64.h"
19#include "webrtc/base/crc32.h"
20#include "webrtc/base/helpers.h"
21#include "webrtc/base/logging.h"
22#include "webrtc/base/messagedigest.h"
23#include "webrtc/base/scoped_ptr.h"
24#include "webrtc/base/stringencode.h"
25#include "webrtc/base/stringutils.h"
26
27namespace {
28
29// Determines whether we have seen at least the given maximum number of
30// pings fail to have a response.
31inline bool TooManyFailures(
32 const std::vector<uint32>& pings_since_last_response,
33 uint32 maximum_failures,
34 uint32 rtt_estimate,
35 uint32 now) {
36
37 // 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.
43 return pings_since_last_response[maximum_failures - 1] + rtt_estimate < now;
44}
45
46// Determines whether we have gone too long without seeing any response.
47inline bool TooLongWithoutResponse(
48 const std::vector<uint32>& pings_since_last_response,
49 uint32 maximum_time,
50 uint32 now) {
51
52 if (pings_since_last_response.size() == 0)
53 return false;
54
55 return pings_since_last_response[0] + maximum_time < now;
56}
57
58// GICE(ICEPROTO_GOOGLE) requires different username for RTP and RTCP.
59// This function generates a different username by +1 on the last character of
60// the given username (|rtp_ufrag|).
61std::string GetRtcpUfragFromRtpUfrag(const std::string& rtp_ufrag) {
62 ASSERT(!rtp_ufrag.empty());
63 if (rtp_ufrag.empty()) {
64 return rtp_ufrag;
65 }
66 // Change the last character to the one next to it in the base64 table.
67 char new_last_char;
68 if (!rtc::Base64::GetNextBase64Char(rtp_ufrag[rtp_ufrag.size() - 1],
69 &new_last_char)) {
70 // Should not be here.
71 ASSERT(false);
72 }
73 std::string rtcp_ufrag = rtp_ufrag;
74 rtcp_ufrag[rtcp_ufrag.size() - 1] = new_last_char;
75 ASSERT(rtcp_ufrag != rtp_ufrag);
76 return rtcp_ufrag;
77}
78
79// We will restrict RTT estimates (when used for determining state) to be
80// within a reasonable range.
81const uint32 MINIMUM_RTT = 100; // 0.1 seconds
82const uint32 MAXIMUM_RTT = 3000; // 3 seconds
83
84// When we don't have any RTT data, we have to pick something reasonable. We
85// use a large value just in case the connection is really slow.
86const uint32 DEFAULT_RTT = MAXIMUM_RTT;
87
88// Computes our estimate of the RTT given the current estimate.
89inline uint32 ConservativeRTTEstimate(uint32 rtt) {
90 return rtc::_max(MINIMUM_RTT, rtc::_min(MAXIMUM_RTT, 2 * rtt));
91}
92
93// Weighting of the old rtt value to new data.
94const int RTT_RATIO = 3; // 3 : 1
95
96// The delay before we begin checking if this port is useless.
97const int kPortTimeoutDelay = 30 * 1000; // 30 seconds
98
99// Used by the Connection.
100const uint32 MSG_DELETE = 1;
101}
102
103namespace cricket {
104
105// TODO(ronghuawu): Use "host", "srflx", "prflx" and "relay". But this requires
106// the signaling part be updated correspondingly as well.
107const char LOCAL_PORT_TYPE[] = "local";
108const char STUN_PORT_TYPE[] = "stun";
109const char PRFLX_PORT_TYPE[] = "prflx";
110const char RELAY_PORT_TYPE[] = "relay";
111
112const char UDP_PROTOCOL_NAME[] = "udp";
113const char TCP_PROTOCOL_NAME[] = "tcp";
114const char SSLTCP_PROTOCOL_NAME[] = "ssltcp";
115
116static const char* const PROTO_NAMES[] = { UDP_PROTOCOL_NAME,
117 TCP_PROTOCOL_NAME,
118 SSLTCP_PROTOCOL_NAME };
119
120const char* ProtoToString(ProtocolType proto) {
121 return PROTO_NAMES[proto];
122}
123
124bool StringToProto(const char* value, ProtocolType* proto) {
125 for (size_t i = 0; i <= PROTO_LAST; ++i) {
126 if (_stricmp(PROTO_NAMES[i], value) == 0) {
127 *proto = static_cast<ProtocolType>(i);
128 return true;
129 }
130 }
131 return false;
132}
133
134// RFC 6544, TCP candidate encoding rules.
135const int DISCARD_PORT = 9;
136const char TCPTYPE_ACTIVE_STR[] = "active";
137const char TCPTYPE_PASSIVE_STR[] = "passive";
138const char TCPTYPE_SIMOPEN_STR[] = "so";
139
140// Foundation: An arbitrary string that is the same for two candidates
141// that have the same type, base IP address, protocol (UDP, TCP,
142// etc.), and STUN or TURN server. If any of these are different,
143// then the foundation will be different. Two candidate pairs with
144// the same foundation pairs are likely to have similar network
145// characteristics. Foundations are used in the frozen algorithm.
146static std::string ComputeFoundation(
147 const std::string& type,
148 const std::string& protocol,
149 const rtc::SocketAddress& base_address) {
150 std::ostringstream ost;
151 ost << type << base_address.ipaddr().ToString() << protocol;
152 return rtc::ToString<uint32>(rtc::ComputeCrc32(ost.str()));
153}
154
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000155Port::Port(rtc::Thread* thread,
156 rtc::PacketSocketFactory* factory,
157 rtc::Network* network,
158 const rtc::IPAddress& ip,
159 const std::string& username_fragment,
160 const std::string& password)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000161 : thread_(thread),
162 factory_(factory),
163 send_retransmit_count_attribute_(false),
164 network_(network),
165 ip_(ip),
166 min_port_(0),
167 max_port_(0),
168 component_(ICE_CANDIDATE_COMPONENT_DEFAULT),
169 generation_(0),
170 ice_username_fragment_(username_fragment),
171 password_(password),
172 timeout_delay_(kPortTimeoutDelay),
173 enable_port_packets_(false),
174 ice_protocol_(ICEPROTO_HYBRID),
175 ice_role_(ICEROLE_UNKNOWN),
176 tiebreaker_(0),
177 shared_socket_(true),
178 candidate_filter_(CF_ALL) {
179 Construct();
180}
181
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000182Port::Port(rtc::Thread* thread,
183 const std::string& type,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000184 rtc::PacketSocketFactory* factory,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000185 rtc::Network* network,
186 const rtc::IPAddress& ip,
187 uint16 min_port,
188 uint16 max_port,
189 const std::string& username_fragment,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000190 const std::string& password)
191 : thread_(thread),
192 factory_(factory),
193 type_(type),
194 send_retransmit_count_attribute_(false),
195 network_(network),
196 ip_(ip),
197 min_port_(min_port),
198 max_port_(max_port),
199 component_(ICE_CANDIDATE_COMPONENT_DEFAULT),
200 generation_(0),
201 ice_username_fragment_(username_fragment),
202 password_(password),
203 timeout_delay_(kPortTimeoutDelay),
204 enable_port_packets_(false),
205 ice_protocol_(ICEPROTO_HYBRID),
206 ice_role_(ICEROLE_UNKNOWN),
207 tiebreaker_(0),
208 shared_socket_(false),
209 candidate_filter_(CF_ALL) {
210 ASSERT(factory_ != NULL);
211 Construct();
212}
213
214void Port::Construct() {
215 // If the username_fragment and password are empty, we should just create one.
216 if (ice_username_fragment_.empty()) {
217 ASSERT(password_.empty());
218 ice_username_fragment_ = rtc::CreateRandomString(ICE_UFRAG_LENGTH);
219 password_ = rtc::CreateRandomString(ICE_PWD_LENGTH);
220 }
221 LOG_J(LS_INFO, this) << "Port created";
222}
223
224Port::~Port() {
225 // Delete all of the remaining connections. We copy the list up front
226 // because each deletion will cause it to be modified.
227
228 std::vector<Connection*> list;
229
230 AddressMap::iterator iter = connections_.begin();
231 while (iter != connections_.end()) {
232 list.push_back(iter->second);
233 ++iter;
234 }
235
236 for (uint32 i = 0; i < list.size(); i++)
237 delete list[i];
238}
239
240Connection* Port::GetConnection(const rtc::SocketAddress& remote_addr) {
241 AddressMap::const_iterator iter = connections_.find(remote_addr);
242 if (iter != connections_.end())
243 return iter->second;
244 else
245 return NULL;
246}
247
248void Port::AddAddress(const rtc::SocketAddress& address,
249 const rtc::SocketAddress& base_address,
250 const rtc::SocketAddress& related_address,
251 const std::string& protocol,
252 const std::string& tcptype,
253 const std::string& type,
254 uint32 type_preference,
255 uint32 relay_preference,
256 bool final) {
257 if (protocol == TCP_PROTOCOL_NAME && type == LOCAL_PORT_TYPE) {
258 ASSERT(!tcptype.empty());
259 }
260
261 Candidate c;
262 c.set_id(rtc::CreateRandomString(8));
263 c.set_component(component_);
264 c.set_type(type);
265 c.set_protocol(protocol);
266 c.set_tcptype(tcptype);
267 c.set_address(address);
268 c.set_priority(c.GetPriority(type_preference, network_->preference(),
269 relay_preference));
270 c.set_username(username_fragment());
271 c.set_password(password_);
272 c.set_network_name(network_->name());
273 c.set_generation(generation_);
274 c.set_related_address(related_address);
275 c.set_foundation(ComputeFoundation(type, protocol, base_address));
276 candidates_.push_back(c);
277 SignalCandidateReady(this, c);
278
279 if (final) {
280 SignalPortComplete(this);
281 }
282}
283
284void Port::AddConnection(Connection* conn) {
285 connections_[conn->remote_candidate().address()] = conn;
286 conn->SignalDestroyed.connect(this, &Port::OnConnectionDestroyed);
287 SignalConnectionCreated(this, conn);
288}
289
290void Port::OnReadPacket(
291 const char* data, size_t size, const rtc::SocketAddress& addr,
292 ProtocolType proto) {
293 // If the user has enabled port packets, just hand this over.
294 if (enable_port_packets_) {
295 SignalReadPacket(this, data, size, addr);
296 return;
297 }
298
299 // If this is an authenticated STUN request, then signal unknown address and
300 // send back a proper binding response.
301 rtc::scoped_ptr<IceMessage> msg;
302 std::string remote_username;
303 if (!GetStunMessage(data, size, addr, msg.accept(), &remote_username)) {
304 LOG_J(LS_ERROR, this) << "Received non-STUN packet from unknown address ("
305 << addr.ToSensitiveString() << ")";
306 } else if (!msg) {
307 // STUN message handled already
308 } else if (msg->type() == STUN_BINDING_REQUEST) {
309 // Check for role conflicts.
310 if (IsStandardIce() &&
311 !MaybeIceRoleConflict(addr, msg.get(), remote_username)) {
312 LOG(LS_INFO) << "Received conflicting role from the peer.";
313 return;
314 }
315
316 SignalUnknownAddress(this, addr, proto, msg.get(), remote_username, false);
317 } else {
318 // NOTE(tschmelcher): STUN_BINDING_RESPONSE is benign. It occurs if we
319 // pruned a connection for this port while it had STUN requests in flight,
320 // because we then get back responses for them, which this code correctly
321 // does not handle.
322 if (msg->type() != STUN_BINDING_RESPONSE) {
323 LOG_J(LS_ERROR, this) << "Received unexpected STUN message type ("
324 << msg->type() << ") from unknown address ("
325 << addr.ToSensitiveString() << ")";
326 }
327 }
328}
329
330void Port::OnReadyToSend() {
331 AddressMap::iterator iter = connections_.begin();
332 for (; iter != connections_.end(); ++iter) {
333 iter->second->OnReadyToSend();
334 }
335}
336
337size_t Port::AddPrflxCandidate(const Candidate& local) {
338 candidates_.push_back(local);
339 return (candidates_.size() - 1);
340}
341
342bool Port::IsStandardIce() const {
343 return (ice_protocol_ == ICEPROTO_RFC5245);
344}
345
346bool Port::IsGoogleIce() const {
347 return (ice_protocol_ == ICEPROTO_GOOGLE);
348}
349
350bool Port::IsHybridIce() const {
351 return (ice_protocol_ == ICEPROTO_HYBRID);
352}
353
354bool Port::GetStunMessage(const char* data, size_t size,
355 const rtc::SocketAddress& addr,
356 IceMessage** out_msg, std::string* out_username) {
357 // NOTE: This could clearly be optimized to avoid allocating any memory.
358 // However, at the data rates we'll be looking at on the client side,
359 // this probably isn't worth worrying about.
360 ASSERT(out_msg != NULL);
361 ASSERT(out_username != NULL);
362 *out_msg = NULL;
363 out_username->clear();
364
365 // Don't bother parsing the packet if we can tell it's not STUN.
366 // In ICE mode, all STUN packets will have a valid fingerprint.
367 if (IsStandardIce() && !StunMessage::ValidateFingerprint(data, size)) {
368 return false;
369 }
370
371 // Parse the request message. If the packet is not a complete and correct
372 // STUN message, then ignore it.
373 rtc::scoped_ptr<IceMessage> stun_msg(new IceMessage());
374 rtc::ByteBuffer buf(data, size);
375 if (!stun_msg->Read(&buf) || (buf.Length() > 0)) {
376 return false;
377 }
378
379 if (stun_msg->type() == STUN_BINDING_REQUEST) {
380 // Check for the presence of USERNAME and MESSAGE-INTEGRITY (if ICE) first.
381 // If not present, fail with a 400 Bad Request.
382 if (!stun_msg->GetByteString(STUN_ATTR_USERNAME) ||
383 (IsStandardIce() &&
384 !stun_msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY))) {
385 LOG_J(LS_ERROR, this) << "Received STUN request without username/M-I "
386 << "from " << addr.ToSensitiveString();
387 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_BAD_REQUEST,
388 STUN_ERROR_REASON_BAD_REQUEST);
389 return true;
390 }
391
392 // If the username is bad or unknown, fail with a 401 Unauthorized.
393 std::string local_ufrag;
394 std::string remote_ufrag;
395 IceProtocolType remote_protocol_type;
396 if (!ParseStunUsername(stun_msg.get(), &local_ufrag, &remote_ufrag,
397 &remote_protocol_type) ||
398 local_ufrag != username_fragment()) {
399 LOG_J(LS_ERROR, this) << "Received STUN request with bad local username "
400 << local_ufrag << " from "
401 << addr.ToSensitiveString();
402 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED,
403 STUN_ERROR_REASON_UNAUTHORIZED);
404 return true;
405 }
406
407 // Port is initialized to GOOGLE-ICE protocol type. If pings from remote
408 // are received before the signal message, protocol type may be different.
409 // Based on the STUN username, we can determine what's the remote protocol.
410 // This also enables us to send the response back using the same protocol
411 // as the request.
412 if (IsHybridIce()) {
413 SetIceProtocolType(remote_protocol_type);
414 }
415
416 // If ICE, and the MESSAGE-INTEGRITY is bad, fail with a 401 Unauthorized
417 if (IsStandardIce() &&
418 !stun_msg->ValidateMessageIntegrity(data, size, password_)) {
419 LOG_J(LS_ERROR, this) << "Received STUN request with bad M-I "
420 << "from " << addr.ToSensitiveString();
421 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED,
422 STUN_ERROR_REASON_UNAUTHORIZED);
423 return true;
424 }
425 out_username->assign(remote_ufrag);
426 } else if ((stun_msg->type() == STUN_BINDING_RESPONSE) ||
427 (stun_msg->type() == STUN_BINDING_ERROR_RESPONSE)) {
428 if (stun_msg->type() == STUN_BINDING_ERROR_RESPONSE) {
429 if (const StunErrorCodeAttribute* error_code = stun_msg->GetErrorCode()) {
430 LOG_J(LS_ERROR, this) << "Received STUN binding error:"
431 << " class=" << error_code->eclass()
432 << " number=" << error_code->number()
433 << " reason='" << error_code->reason() << "'"
434 << " from " << addr.ToSensitiveString();
435 // Return message to allow error-specific processing
436 } else {
437 LOG_J(LS_ERROR, this) << "Received STUN binding error without a error "
438 << "code from " << addr.ToSensitiveString();
439 return true;
440 }
441 }
442 // NOTE: Username should not be used in verifying response messages.
443 out_username->clear();
444 } else if (stun_msg->type() == STUN_BINDING_INDICATION) {
445 LOG_J(LS_VERBOSE, this) << "Received STUN binding indication:"
446 << " from " << addr.ToSensitiveString();
447 out_username->clear();
448 // No stun attributes will be verified, if it's stun indication message.
449 // Returning from end of the this method.
450 } else {
451 LOG_J(LS_ERROR, this) << "Received STUN packet with invalid type ("
452 << stun_msg->type() << ") from "
453 << addr.ToSensitiveString();
454 return true;
455 }
456
457 // Return the STUN message found.
458 *out_msg = stun_msg.release();
459 return true;
460}
461
462bool Port::IsCompatibleAddress(const rtc::SocketAddress& addr) {
463 int family = ip().family();
464 // We use single-stack sockets, so families must match.
465 if (addr.family() != family) {
466 return false;
467 }
468 // Link-local IPv6 ports can only connect to other link-local IPv6 ports.
469 if (family == AF_INET6 && (IPIsPrivate(ip()) != IPIsPrivate(addr.ipaddr()))) {
470 return false;
471 }
472 return true;
473}
474
475bool Port::ParseStunUsername(const StunMessage* stun_msg,
476 std::string* local_ufrag,
477 std::string* remote_ufrag,
478 IceProtocolType* remote_protocol_type) const {
479 // The packet must include a username that either begins or ends with our
480 // fragment. It should begin with our fragment if it is a request and it
481 // should end with our fragment if it is a response.
482 local_ufrag->clear();
483 remote_ufrag->clear();
484 const StunByteStringAttribute* username_attr =
485 stun_msg->GetByteString(STUN_ATTR_USERNAME);
486 if (username_attr == NULL)
487 return false;
488
489 const std::string username_attr_str = username_attr->GetString();
490 size_t colon_pos = username_attr_str.find(":");
491 // If we are in hybrid mode set the appropriate ice protocol type based on
492 // the username argument style.
493 if (IsHybridIce()) {
494 *remote_protocol_type = (colon_pos != std::string::npos) ?
495 ICEPROTO_RFC5245 : ICEPROTO_GOOGLE;
496 } else {
497 *remote_protocol_type = ice_protocol_;
498 }
499 if (*remote_protocol_type == ICEPROTO_RFC5245) {
500 if (colon_pos != std::string::npos) { // RFRAG:LFRAG
501 *local_ufrag = username_attr_str.substr(0, colon_pos);
502 *remote_ufrag = username_attr_str.substr(
503 colon_pos + 1, username_attr_str.size());
504 } else {
505 return false;
506 }
507 } else if (*remote_protocol_type == ICEPROTO_GOOGLE) {
508 int remote_frag_len = static_cast<int>(username_attr_str.size());
509 remote_frag_len -= static_cast<int>(username_fragment().size());
510 if (remote_frag_len < 0)
511 return false;
512
513 *local_ufrag = username_attr_str.substr(0, username_fragment().size());
514 *remote_ufrag = username_attr_str.substr(
515 username_fragment().size(), username_attr_str.size());
516 }
517 return true;
518}
519
520bool Port::MaybeIceRoleConflict(
521 const rtc::SocketAddress& addr, IceMessage* stun_msg,
522 const std::string& remote_ufrag) {
523 // Validate ICE_CONTROLLING or ICE_CONTROLLED attributes.
524 bool ret = true;
525 IceRole remote_ice_role = ICEROLE_UNKNOWN;
526 uint64 remote_tiebreaker = 0;
527 const StunUInt64Attribute* stun_attr =
528 stun_msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
529 if (stun_attr) {
530 remote_ice_role = ICEROLE_CONTROLLING;
531 remote_tiebreaker = stun_attr->value();
532 }
533
534 // If |remote_ufrag| is same as port local username fragment and
535 // tie breaker value received in the ping message matches port
536 // tiebreaker value this must be a loopback call.
537 // We will treat this as valid scenario.
538 if (remote_ice_role == ICEROLE_CONTROLLING &&
539 username_fragment() == remote_ufrag &&
540 remote_tiebreaker == IceTiebreaker()) {
541 return true;
542 }
543
544 stun_attr = stun_msg->GetUInt64(STUN_ATTR_ICE_CONTROLLED);
545 if (stun_attr) {
546 remote_ice_role = ICEROLE_CONTROLLED;
547 remote_tiebreaker = stun_attr->value();
548 }
549
550 switch (ice_role_) {
551 case ICEROLE_CONTROLLING:
552 if (ICEROLE_CONTROLLING == remote_ice_role) {
553 if (remote_tiebreaker >= tiebreaker_) {
554 SignalRoleConflict(this);
555 } else {
556 // Send Role Conflict (487) error response.
557 SendBindingErrorResponse(stun_msg, addr,
558 STUN_ERROR_ROLE_CONFLICT, STUN_ERROR_REASON_ROLE_CONFLICT);
559 ret = false;
560 }
561 }
562 break;
563 case ICEROLE_CONTROLLED:
564 if (ICEROLE_CONTROLLED == remote_ice_role) {
565 if (remote_tiebreaker < tiebreaker_) {
566 SignalRoleConflict(this);
567 } else {
568 // Send Role Conflict (487) error response.
569 SendBindingErrorResponse(stun_msg, addr,
570 STUN_ERROR_ROLE_CONFLICT, STUN_ERROR_REASON_ROLE_CONFLICT);
571 ret = false;
572 }
573 }
574 break;
575 default:
576 ASSERT(false);
577 }
578 return ret;
579}
580
581void Port::CreateStunUsername(const std::string& remote_username,
582 std::string* stun_username_attr_str) const {
583 stun_username_attr_str->clear();
584 *stun_username_attr_str = remote_username;
585 if (IsStandardIce()) {
586 // Connectivity checks from L->R will have username RFRAG:LFRAG.
587 stun_username_attr_str->append(":");
588 }
589 stun_username_attr_str->append(username_fragment());
590}
591
592void Port::SendBindingResponse(StunMessage* request,
593 const rtc::SocketAddress& addr) {
594 ASSERT(request->type() == STUN_BINDING_REQUEST);
595
596 // Retrieve the username from the request.
597 const StunByteStringAttribute* username_attr =
598 request->GetByteString(STUN_ATTR_USERNAME);
599 ASSERT(username_attr != NULL);
600 if (username_attr == NULL) {
601 // No valid username, skip the response.
602 return;
603 }
604
605 // Fill in the response message.
606 StunMessage response;
607 response.SetType(STUN_BINDING_RESPONSE);
608 response.SetTransactionID(request->transaction_id());
609 const StunUInt32Attribute* retransmit_attr =
610 request->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
611 if (retransmit_attr) {
612 // Inherit the incoming retransmit value in the response so the other side
613 // can see our view of lost pings.
614 response.AddAttribute(new StunUInt32Attribute(
615 STUN_ATTR_RETRANSMIT_COUNT, retransmit_attr->value()));
616
617 if (retransmit_attr->value() > CONNECTION_WRITE_CONNECT_FAILURES) {
618 LOG_J(LS_INFO, this)
619 << "Received a remote ping with high retransmit count: "
620 << retransmit_attr->value();
621 }
622 }
623
624 // Only GICE messages have USERNAME and MAPPED-ADDRESS in the response.
625 // ICE messages use XOR-MAPPED-ADDRESS, and add MESSAGE-INTEGRITY.
626 if (IsStandardIce()) {
627 response.AddAttribute(
628 new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, addr));
629 response.AddMessageIntegrity(password_);
630 response.AddFingerprint();
631 } else if (IsGoogleIce()) {
632 response.AddAttribute(
633 new StunAddressAttribute(STUN_ATTR_MAPPED_ADDRESS, addr));
634 response.AddAttribute(new StunByteStringAttribute(
635 STUN_ATTR_USERNAME, username_attr->GetString()));
636 }
637
638 // Send the response message.
639 rtc::ByteBuffer buf;
640 response.Write(&buf);
641 rtc::PacketOptions options(DefaultDscpValue());
642 if (SendTo(buf.Data(), buf.Length(), addr, options, false) < 0) {
643 LOG_J(LS_ERROR, this) << "Failed to send STUN ping response to "
644 << addr.ToSensitiveString();
645 }
646
647 // The fact that we received a successful request means that this connection
648 // (if one exists) should now be readable.
649 Connection* conn = GetConnection(addr);
650 ASSERT(conn != NULL);
651 if (conn)
652 conn->ReceivedPing();
653}
654
655void Port::SendBindingErrorResponse(StunMessage* request,
656 const rtc::SocketAddress& addr,
657 int error_code, const std::string& reason) {
658 ASSERT(request->type() == STUN_BINDING_REQUEST);
659
660 // Fill in the response message.
661 StunMessage response;
662 response.SetType(STUN_BINDING_ERROR_RESPONSE);
663 response.SetTransactionID(request->transaction_id());
664
665 // When doing GICE, we need to write out the error code incorrectly to
666 // maintain backwards compatiblility.
667 StunErrorCodeAttribute* error_attr = StunAttribute::CreateErrorCode();
668 if (IsStandardIce()) {
669 error_attr->SetCode(error_code);
670 } else if (IsGoogleIce()) {
671 error_attr->SetClass(error_code / 256);
672 error_attr->SetNumber(error_code % 256);
673 }
674 error_attr->SetReason(reason);
675 response.AddAttribute(error_attr);
676
677 if (IsStandardIce()) {
678 // Per Section 10.1.2, certain error cases don't get a MESSAGE-INTEGRITY,
679 // because we don't have enough information to determine the shared secret.
680 if (error_code != STUN_ERROR_BAD_REQUEST &&
681 error_code != STUN_ERROR_UNAUTHORIZED)
682 response.AddMessageIntegrity(password_);
683 response.AddFingerprint();
684 } else if (IsGoogleIce()) {
685 // GICE responses include a username, if one exists.
686 const StunByteStringAttribute* username_attr =
687 request->GetByteString(STUN_ATTR_USERNAME);
688 if (username_attr)
689 response.AddAttribute(new StunByteStringAttribute(
690 STUN_ATTR_USERNAME, username_attr->GetString()));
691 }
692
693 // Send the response message.
694 rtc::ByteBuffer buf;
695 response.Write(&buf);
696 rtc::PacketOptions options(DefaultDscpValue());
697 SendTo(buf.Data(), buf.Length(), addr, options, false);
698 LOG_J(LS_INFO, this) << "Sending STUN binding error: reason=" << reason
699 << " to " << addr.ToSensitiveString();
700}
701
702void Port::OnMessage(rtc::Message *pmsg) {
703 ASSERT(pmsg->message_id == MSG_CHECKTIMEOUT);
704 CheckTimeout();
705}
706
707std::string Port::ToString() const {
708 std::stringstream ss;
709 ss << "Port[" << content_name_ << ":" << component_
710 << ":" << generation_ << ":" << type_
711 << ":" << network_->ToString() << "]";
712 return ss.str();
713}
714
715void Port::EnablePortPackets() {
716 enable_port_packets_ = true;
717}
718
719void Port::OnConnectionDestroyed(Connection* conn) {
720 AddressMap::iterator iter =
721 connections_.find(conn->remote_candidate().address());
722 ASSERT(iter != connections_.end());
723 connections_.erase(iter);
724
725 // On the controlled side, ports time out, but only after all connections
726 // fail. Note: If a new connection is added after this message is posted,
727 // but it fails and is removed before kPortTimeoutDelay, then this message
728 // will still cause the Port to be destroyed.
729 if (ice_role_ == ICEROLE_CONTROLLED)
730 thread_->PostDelayed(timeout_delay_, this, MSG_CHECKTIMEOUT);
731}
732
733void Port::Destroy() {
734 ASSERT(connections_.empty());
735 LOG_J(LS_INFO, this) << "Port deleted";
736 SignalDestroyed(this);
737 delete this;
738}
739
740void Port::CheckTimeout() {
741 ASSERT(ice_role_ == ICEROLE_CONTROLLED);
742 // If this port has no connections, then there's no reason to keep it around.
743 // When the connections time out (both read and write), they will delete
744 // themselves, so if we have any connections, they are either readable or
745 // writable (or still connecting).
746 if (connections_.empty())
747 Destroy();
748}
749
750const std::string Port::username_fragment() const {
751 if (!IsStandardIce() &&
752 component_ == ICE_CANDIDATE_COMPONENT_RTCP) {
753 // In GICE mode, we should adjust username fragment for rtcp component.
754 return GetRtcpUfragFromRtpUfrag(ice_username_fragment_);
755 } else {
756 return ice_username_fragment_;
757 }
758}
759
760// A ConnectionRequest is a simple STUN ping used to determine writability.
761class ConnectionRequest : public StunRequest {
762 public:
763 explicit ConnectionRequest(Connection* connection)
764 : StunRequest(new IceMessage()),
765 connection_(connection) {
766 }
767
768 virtual ~ConnectionRequest() {
769 }
770
771 virtual void Prepare(StunMessage* request) {
772 request->SetType(STUN_BINDING_REQUEST);
773 std::string username;
774 connection_->port()->CreateStunUsername(
775 connection_->remote_candidate().username(), &username);
776 request->AddAttribute(
777 new StunByteStringAttribute(STUN_ATTR_USERNAME, username));
778
779 // connection_ already holds this ping, so subtract one from count.
780 if (connection_->port()->send_retransmit_count_attribute()) {
781 request->AddAttribute(new StunUInt32Attribute(
782 STUN_ATTR_RETRANSMIT_COUNT,
783 static_cast<uint32>(
784 connection_->pings_since_last_response_.size() - 1)));
785 }
786
787 // Adding ICE-specific attributes to the STUN request message.
788 if (connection_->port()->IsStandardIce()) {
789 // Adding ICE_CONTROLLED or ICE_CONTROLLING attribute based on the role.
790 if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLING) {
791 request->AddAttribute(new StunUInt64Attribute(
792 STUN_ATTR_ICE_CONTROLLING, connection_->port()->IceTiebreaker()));
793 // Since we are trying aggressive nomination, sending USE-CANDIDATE
794 // attribute in every ping.
795 // If we are dealing with a ice-lite end point, nomination flag
796 // in Connection will be set to false by default. Once the connection
797 // becomes "best connection", nomination flag will be turned on.
798 if (connection_->use_candidate_attr()) {
799 request->AddAttribute(new StunByteStringAttribute(
800 STUN_ATTR_USE_CANDIDATE));
801 }
802 } else if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLED) {
803 request->AddAttribute(new StunUInt64Attribute(
804 STUN_ATTR_ICE_CONTROLLED, connection_->port()->IceTiebreaker()));
805 } else {
806 ASSERT(false);
807 }
808
809 // Adding PRIORITY Attribute.
810 // Changing the type preference to Peer Reflexive and local preference
811 // and component id information is unchanged from the original priority.
812 // priority = (2^24)*(type preference) +
813 // (2^8)*(local preference) +
814 // (2^0)*(256 - component ID)
815 uint32 prflx_priority = ICE_TYPE_PREFERENCE_PRFLX << 24 |
816 (connection_->local_candidate().priority() & 0x00FFFFFF);
817 request->AddAttribute(
818 new StunUInt32Attribute(STUN_ATTR_PRIORITY, prflx_priority));
819
820 // Adding Message Integrity attribute.
821 request->AddMessageIntegrity(connection_->remote_candidate().password());
822 // Adding Fingerprint.
823 request->AddFingerprint();
824 }
825 }
826
827 virtual void OnResponse(StunMessage* response) {
828 connection_->OnConnectionRequestResponse(this, response);
829 }
830
831 virtual void OnErrorResponse(StunMessage* response) {
832 connection_->OnConnectionRequestErrorResponse(this, response);
833 }
834
835 virtual void OnTimeout() {
836 connection_->OnConnectionRequestTimeout(this);
837 }
838
839 virtual int GetNextDelay() {
840 // Each request is sent only once. After a single delay , the request will
841 // time out.
842 timeout_ = true;
843 return CONNECTION_RESPONSE_TIMEOUT;
844 }
845
846 private:
847 Connection* connection_;
848};
849
850//
851// Connection
852//
853
854Connection::Connection(Port* port, size_t index,
855 const Candidate& remote_candidate)
856 : port_(port), local_candidate_index_(index),
857 remote_candidate_(remote_candidate), read_state_(STATE_READ_INIT),
858 write_state_(STATE_WRITE_INIT), connected_(true), pruned_(false),
859 use_candidate_attr_(false), remote_ice_mode_(ICEMODE_FULL),
860 requests_(port->thread()), rtt_(DEFAULT_RTT), last_ping_sent_(0),
861 last_ping_received_(0), last_data_received_(0),
862 last_ping_response_received_(0), reported_(false), state_(STATE_WAITING) {
863 // All of our connections start in WAITING state.
864 // TODO(mallinath) - Start connections from STATE_FROZEN.
865 // Wire up to send stun packets
866 requests_.SignalSendPacket.connect(this, &Connection::OnSendStunPacket);
867 LOG_J(LS_INFO, this) << "Connection created";
868}
869
870Connection::~Connection() {
871}
872
873const Candidate& Connection::local_candidate() const {
874 ASSERT(local_candidate_index_ < port_->Candidates().size());
875 return port_->Candidates()[local_candidate_index_];
876}
877
878uint64 Connection::priority() const {
879 uint64 priority = 0;
880 // RFC 5245 - 5.7.2. Computing Pair Priority and Ordering Pairs
881 // Let G be the priority for the candidate provided by the controlling
882 // agent. Let D be the priority for the candidate provided by the
883 // controlled agent.
884 // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)
885 IceRole role = port_->GetIceRole();
886 if (role != ICEROLE_UNKNOWN) {
887 uint32 g = 0;
888 uint32 d = 0;
889 if (role == ICEROLE_CONTROLLING) {
890 g = local_candidate().priority();
891 d = remote_candidate_.priority();
892 } else {
893 g = remote_candidate_.priority();
894 d = local_candidate().priority();
895 }
896 priority = rtc::_min(g, d);
897 priority = priority << 32;
898 priority += 2 * rtc::_max(g, d) + (g > d ? 1 : 0);
899 }
900 return priority;
901}
902
903void Connection::set_read_state(ReadState value) {
904 ReadState old_value = read_state_;
905 read_state_ = value;
906 if (value != old_value) {
907 LOG_J(LS_VERBOSE, this) << "set_read_state";
908 SignalStateChange(this);
909 CheckTimeout();
910 }
911}
912
913void Connection::set_write_state(WriteState value) {
914 WriteState old_value = write_state_;
915 write_state_ = value;
916 if (value != old_value) {
917 LOG_J(LS_VERBOSE, this) << "set_write_state";
918 SignalStateChange(this);
919 CheckTimeout();
920 }
921}
922
923void Connection::set_state(State state) {
924 State old_state = state_;
925 state_ = state;
926 if (state != old_state) {
927 LOG_J(LS_VERBOSE, this) << "set_state";
928 }
929}
930
931void Connection::set_connected(bool value) {
932 bool old_value = connected_;
933 connected_ = value;
934 if (value != old_value) {
935 LOG_J(LS_VERBOSE, this) << "set_connected";
936 }
937}
938
939void Connection::set_use_candidate_attr(bool enable) {
940 use_candidate_attr_ = enable;
941}
942
943void Connection::OnSendStunPacket(const void* data, size_t size,
944 StunRequest* req) {
945 rtc::PacketOptions options(port_->DefaultDscpValue());
946 if (port_->SendTo(data, size, remote_candidate_.address(),
947 options, false) < 0) {
948 LOG_J(LS_WARNING, this) << "Failed to send STUN ping " << req->id();
949 }
950}
951
952void Connection::OnReadPacket(
953 const char* data, size_t size, const rtc::PacketTime& packet_time) {
954 rtc::scoped_ptr<IceMessage> msg;
955 std::string remote_ufrag;
956 const rtc::SocketAddress& addr(remote_candidate_.address());
957 if (!port_->GetStunMessage(data, size, addr, msg.accept(), &remote_ufrag)) {
958 // The packet did not parse as a valid STUN message
959
960 // If this connection is readable, then pass along the packet.
961 if (read_state_ == STATE_READABLE) {
962 // readable means data from this address is acceptable
963 // Send it on!
964
965 last_data_received_ = rtc::Time();
966 recv_rate_tracker_.Update(size);
967 SignalReadPacket(this, data, size, packet_time);
968
969 // If timed out sending writability checks, start up again
970 if (!pruned_ && (write_state_ == STATE_WRITE_TIMEOUT)) {
971 LOG(LS_WARNING) << "Received a data packet on a timed-out Connection. "
972 << "Resetting state to STATE_WRITE_INIT.";
973 set_write_state(STATE_WRITE_INIT);
974 }
975 } else {
976 // Not readable means the remote address hasn't sent a valid
977 // binding request yet.
978
979 LOG_J(LS_WARNING, this)
980 << "Received non-STUN packet from an unreadable connection.";
981 }
982 } else if (!msg) {
983 // The packet was STUN, but failed a check and was handled internally.
984 } else {
985 // The packet is STUN and passed the Port checks.
986 // Perform our own checks to ensure this packet is valid.
987 // If this is a STUN request, then update the readable bit and respond.
988 // If this is a STUN response, then update the writable bit.
989 switch (msg->type()) {
990 case STUN_BINDING_REQUEST:
991 if (remote_ufrag == remote_candidate_.username()) {
992 // Check for role conflicts.
993 if (port_->IsStandardIce() &&
994 !port_->MaybeIceRoleConflict(addr, msg.get(), remote_ufrag)) {
995 // Received conflicting role from the peer.
996 LOG(LS_INFO) << "Received conflicting role from the peer.";
997 return;
998 }
999
1000 // Incoming, validated stun request from remote peer.
1001 // This call will also set the connection readable.
1002 port_->SendBindingResponse(msg.get(), addr);
1003
1004 // If timed out sending writability checks, start up again
1005 if (!pruned_ && (write_state_ == STATE_WRITE_TIMEOUT))
1006 set_write_state(STATE_WRITE_INIT);
1007
1008 if ((port_->IsStandardIce()) &&
1009 (port_->GetIceRole() == ICEROLE_CONTROLLED)) {
1010 const StunByteStringAttribute* use_candidate_attr =
1011 msg->GetByteString(STUN_ATTR_USE_CANDIDATE);
1012 if (use_candidate_attr)
1013 SignalUseCandidate(this);
1014 }
1015 } else {
1016 // The packet had the right local username, but the remote username
1017 // was not the right one for the remote address.
1018 LOG_J(LS_ERROR, this)
1019 << "Received STUN request with bad remote username "
1020 << remote_ufrag;
1021 port_->SendBindingErrorResponse(msg.get(), addr,
1022 STUN_ERROR_UNAUTHORIZED,
1023 STUN_ERROR_REASON_UNAUTHORIZED);
1024
1025 }
1026 break;
1027
1028 // Response from remote peer. Does it match request sent?
1029 // This doesn't just check, it makes callbacks if transaction
1030 // id's match.
1031 case STUN_BINDING_RESPONSE:
1032 case STUN_BINDING_ERROR_RESPONSE:
1033 if (port_->IsGoogleIce() ||
1034 msg->ValidateMessageIntegrity(
1035 data, size, remote_candidate().password())) {
1036 requests_.CheckResponse(msg.get());
1037 }
1038 // Otherwise silently discard the response message.
1039 break;
1040
1041 // Remote end point sent an STUN indication instead of regular
1042 // binding request. In this case |last_ping_received_| will be updated.
1043 // Otherwise we can mark connection to read timeout. No response will be
1044 // sent in this scenario.
1045 case STUN_BINDING_INDICATION:
1046 if (port_->IsStandardIce() && read_state_ == STATE_READABLE) {
1047 ReceivedPing();
1048 } else {
1049 LOG_J(LS_WARNING, this) << "Received STUN binding indication "
1050 << "from an unreadable connection.";
1051 }
1052 break;
1053
1054 default:
1055 ASSERT(false);
1056 break;
1057 }
1058 }
1059}
1060
1061void Connection::OnReadyToSend() {
1062 if (write_state_ == STATE_WRITABLE) {
1063 SignalReadyToSend(this);
1064 }
1065}
1066
1067void Connection::Prune() {
1068 if (!pruned_) {
1069 LOG_J(LS_VERBOSE, this) << "Connection pruned";
1070 pruned_ = true;
1071 requests_.Clear();
1072 set_write_state(STATE_WRITE_TIMEOUT);
1073 }
1074}
1075
1076void Connection::Destroy() {
1077 LOG_J(LS_VERBOSE, this) << "Connection destroyed";
1078 set_read_state(STATE_READ_TIMEOUT);
1079 set_write_state(STATE_WRITE_TIMEOUT);
1080}
1081
1082void Connection::UpdateState(uint32 now) {
1083 uint32 rtt = ConservativeRTTEstimate(rtt_);
1084
1085 std::string pings;
1086 for (size_t i = 0; i < pings_since_last_response_.size(); ++i) {
1087 char buf[32];
1088 rtc::sprintfn(buf, sizeof(buf), "%u",
1089 pings_since_last_response_[i]);
1090 pings.append(buf).append(" ");
1091 }
1092 LOG_J(LS_VERBOSE, this) << "UpdateState(): pings_since_last_response_=" <<
1093 pings << ", rtt=" << rtt << ", now=" << now;
1094
1095 // Check the readable state.
1096 //
1097 // Since we don't know how many pings the other side has attempted, the best
1098 // test we can do is a simple window.
1099 // If other side has not sent ping after connection has become readable, use
1100 // |last_data_received_| as the indication.
1101 // If remote endpoint is doing RFC 5245, it's not required to send ping
1102 // after connection is established. If this connection is serving a data
1103 // channel, it may not be in a position to send media continuously. Do not
1104 // mark connection timeout if it's in RFC5245 mode.
1105 // Below check will be performed with end point if it's doing google-ice.
1106 if (port_->IsGoogleIce() && (read_state_ == STATE_READABLE) &&
1107 (last_ping_received_ + CONNECTION_READ_TIMEOUT <= now) &&
1108 (last_data_received_ + CONNECTION_READ_TIMEOUT <= now)) {
1109 LOG_J(LS_INFO, this) << "Unreadable after "
1110 << now - last_ping_received_
1111 << " ms without a ping,"
1112 << " ms since last received response="
1113 << now - last_ping_response_received_
1114 << " ms since last received data="
1115 << now - last_data_received_
1116 << " rtt=" << rtt;
1117 set_read_state(STATE_READ_TIMEOUT);
1118 }
1119
1120 // Check the writable state. (The order of these checks is important.)
1121 //
1122 // Before becoming unwritable, we allow for a fixed number of pings to fail
1123 // (i.e., receive no response). We also have to give the response time to
1124 // get back, so we include a conservative estimate of this.
1125 //
1126 // Before timing out writability, we give a fixed amount of time. This is to
1127 // allow for changes in network conditions.
1128
1129 if ((write_state_ == STATE_WRITABLE) &&
1130 TooManyFailures(pings_since_last_response_,
1131 CONNECTION_WRITE_CONNECT_FAILURES,
1132 rtt,
1133 now) &&
1134 TooLongWithoutResponse(pings_since_last_response_,
1135 CONNECTION_WRITE_CONNECT_TIMEOUT,
1136 now)) {
1137 uint32 max_pings = CONNECTION_WRITE_CONNECT_FAILURES;
1138 LOG_J(LS_INFO, this) << "Unwritable after " << max_pings
1139 << " ping failures and "
1140 << now - pings_since_last_response_[0]
1141 << " ms without a response,"
1142 << " ms since last received ping="
1143 << now - last_ping_received_
1144 << " ms since last received data="
1145 << now - last_data_received_
1146 << " rtt=" << rtt;
1147 set_write_state(STATE_WRITE_UNRELIABLE);
1148 }
1149
1150 if ((write_state_ == STATE_WRITE_UNRELIABLE ||
1151 write_state_ == STATE_WRITE_INIT) &&
1152 TooLongWithoutResponse(pings_since_last_response_,
1153 CONNECTION_WRITE_TIMEOUT,
1154 now)) {
1155 LOG_J(LS_INFO, this) << "Timed out after "
1156 << now - pings_since_last_response_[0]
1157 << " ms without a response, rtt=" << rtt;
1158 set_write_state(STATE_WRITE_TIMEOUT);
1159 }
1160}
1161
1162void Connection::Ping(uint32 now) {
1163 ASSERT(connected_);
1164 last_ping_sent_ = now;
1165 pings_since_last_response_.push_back(now);
1166 ConnectionRequest *req = new ConnectionRequest(this);
1167 LOG_J(LS_VERBOSE, this) << "Sending STUN ping " << req->id() << " at " << now;
1168 requests_.Send(req);
1169 state_ = STATE_INPROGRESS;
1170}
1171
1172void Connection::ReceivedPing() {
1173 last_ping_received_ = rtc::Time();
1174 set_read_state(STATE_READABLE);
1175}
1176
1177std::string Connection::ToString() const {
1178 const char CONNECT_STATE_ABBREV[2] = {
1179 '-', // not connected (false)
1180 'C', // connected (true)
1181 };
1182 const char READ_STATE_ABBREV[3] = {
1183 '-', // STATE_READ_INIT
1184 'R', // STATE_READABLE
1185 'x', // STATE_READ_TIMEOUT
1186 };
1187 const char WRITE_STATE_ABBREV[4] = {
1188 'W', // STATE_WRITABLE
1189 'w', // STATE_WRITE_UNRELIABLE
1190 '-', // STATE_WRITE_INIT
1191 'x', // STATE_WRITE_TIMEOUT
1192 };
1193 const std::string ICESTATE[4] = {
1194 "W", // STATE_WAITING
1195 "I", // STATE_INPROGRESS
1196 "S", // STATE_SUCCEEDED
1197 "F" // STATE_FAILED
1198 };
1199 const Candidate& local = local_candidate();
1200 const Candidate& remote = remote_candidate();
1201 std::stringstream ss;
1202 ss << "Conn[" << port_->content_name()
1203 << ":" << local.id() << ":" << local.component()
1204 << ":" << local.generation()
1205 << ":" << local.type() << ":" << local.protocol()
1206 << ":" << local.address().ToSensitiveString()
1207 << "->" << remote.id() << ":" << remote.component()
1208 << ":" << remote.priority()
1209 << ":" << remote.type() << ":"
1210 << remote.protocol() << ":" << remote.address().ToSensitiveString() << "|"
1211 << CONNECT_STATE_ABBREV[connected()]
1212 << READ_STATE_ABBREV[read_state()]
1213 << WRITE_STATE_ABBREV[write_state()]
1214 << ICESTATE[state()] << "|"
1215 << priority() << "|";
1216 if (rtt_ < DEFAULT_RTT) {
1217 ss << rtt_ << "]";
1218 } else {
1219 ss << "-]";
1220 }
1221 return ss.str();
1222}
1223
1224std::string Connection::ToSensitiveString() const {
1225 return ToString();
1226}
1227
1228void Connection::OnConnectionRequestResponse(ConnectionRequest* request,
1229 StunMessage* response) {
1230 // We've already validated that this is a STUN binding response with
1231 // the correct local and remote username for this connection.
1232 // So if we're not already, become writable. We may be bringing a pruned
1233 // connection back to life, but if we don't really want it, we can always
1234 // prune it again.
1235 uint32 rtt = request->Elapsed();
1236 set_write_state(STATE_WRITABLE);
1237 set_state(STATE_SUCCEEDED);
1238
1239 if (remote_ice_mode_ == ICEMODE_LITE) {
1240 // A ice-lite end point never initiates ping requests. This will allow
1241 // us to move to STATE_READABLE.
1242 ReceivedPing();
1243 }
1244
1245 std::string pings;
1246 for (size_t i = 0; i < pings_since_last_response_.size(); ++i) {
1247 char buf[32];
1248 rtc::sprintfn(buf, sizeof(buf), "%u",
1249 pings_since_last_response_[i]);
1250 pings.append(buf).append(" ");
1251 }
1252
1253 rtc::LoggingSeverity level =
1254 (pings_since_last_response_.size() > CONNECTION_WRITE_CONNECT_FAILURES) ?
1255 rtc::LS_INFO : rtc::LS_VERBOSE;
1256
1257 LOG_JV(level, this) << "Received STUN ping response " << request->id()
1258 << ", pings_since_last_response_=" << pings
1259 << ", rtt=" << rtt;
1260
1261 pings_since_last_response_.clear();
1262 last_ping_response_received_ = rtc::Time();
1263 rtt_ = (RTT_RATIO * rtt_ + rtt) / (RTT_RATIO + 1);
1264
1265 // Peer reflexive candidate is only for RFC 5245 ICE.
1266 if (port_->IsStandardIce()) {
1267 MaybeAddPrflxCandidate(request, response);
1268 }
1269}
1270
1271void Connection::OnConnectionRequestErrorResponse(ConnectionRequest* request,
1272 StunMessage* response) {
1273 const StunErrorCodeAttribute* error_attr = response->GetErrorCode();
1274 int error_code = STUN_ERROR_GLOBAL_FAILURE;
1275 if (error_attr) {
1276 if (port_->IsGoogleIce()) {
1277 // When doing GICE, the error code is written out incorrectly, so we need
1278 // to unmunge it here.
1279 error_code = error_attr->eclass() * 256 + error_attr->number();
1280 } else {
1281 error_code = error_attr->code();
1282 }
1283 }
1284
1285 if (error_code == STUN_ERROR_UNKNOWN_ATTRIBUTE ||
1286 error_code == STUN_ERROR_SERVER_ERROR ||
1287 error_code == STUN_ERROR_UNAUTHORIZED) {
1288 // Recoverable error, retry
1289 } else if (error_code == STUN_ERROR_STALE_CREDENTIALS) {
1290 // Race failure, retry
1291 } else if (error_code == STUN_ERROR_ROLE_CONFLICT) {
1292 HandleRoleConflictFromPeer();
1293 } else {
1294 // This is not a valid connection.
1295 LOG_J(LS_ERROR, this) << "Received STUN error response, code="
1296 << error_code << "; killing connection";
1297 set_state(STATE_FAILED);
1298 set_write_state(STATE_WRITE_TIMEOUT);
1299 }
1300}
1301
1302void Connection::OnConnectionRequestTimeout(ConnectionRequest* request) {
1303 // Log at LS_INFO if we miss a ping on a writable connection.
1304 rtc::LoggingSeverity sev = (write_state_ == STATE_WRITABLE) ?
1305 rtc::LS_INFO : rtc::LS_VERBOSE;
1306 LOG_JV(sev, this) << "Timing-out STUN ping " << request->id()
1307 << " after " << request->Elapsed() << " ms";
1308}
1309
1310void Connection::CheckTimeout() {
1311 // If both read and write have timed out or read has never initialized, then
1312 // this connection can contribute no more to p2p socket unless at some later
1313 // date readability were to come back. However, we gave readability a long
1314 // time to timeout, so at this point, it seems fair to get rid of this
1315 // connection.
1316 if ((read_state_ == STATE_READ_TIMEOUT ||
1317 read_state_ == STATE_READ_INIT) &&
1318 write_state_ == STATE_WRITE_TIMEOUT) {
1319 port_->thread()->Post(this, MSG_DELETE);
1320 }
1321}
1322
1323void Connection::HandleRoleConflictFromPeer() {
1324 port_->SignalRoleConflict(port_);
1325}
1326
1327void Connection::OnMessage(rtc::Message *pmsg) {
1328 ASSERT(pmsg->message_id == MSG_DELETE);
1329
henrike@webrtc.org43e033e2014-11-10 19:40:29 +00001330 LOG_J(LS_INFO, this) << "Connection deleted due to read or write timeout";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001331 SignalDestroyed(this);
1332 delete this;
1333}
1334
1335size_t Connection::recv_bytes_second() {
1336 return recv_rate_tracker_.units_second();
1337}
1338
1339size_t Connection::recv_total_bytes() {
1340 return recv_rate_tracker_.total_units();
1341}
1342
1343size_t Connection::sent_bytes_second() {
1344 return send_rate_tracker_.units_second();
1345}
1346
1347size_t Connection::sent_total_bytes() {
1348 return send_rate_tracker_.total_units();
1349}
1350
1351void Connection::MaybeAddPrflxCandidate(ConnectionRequest* request,
1352 StunMessage* response) {
1353 // RFC 5245
1354 // The agent checks the mapped address from the STUN response. If the
1355 // transport address does not match any of the local candidates that the
1356 // agent knows about, the mapped address represents a new candidate -- a
1357 // peer reflexive candidate.
1358 const StunAddressAttribute* addr =
1359 response->GetAddress(STUN_ATTR_XOR_MAPPED_ADDRESS);
1360 if (!addr) {
1361 LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - "
1362 << "No MAPPED-ADDRESS or XOR-MAPPED-ADDRESS found in the "
1363 << "stun response message";
1364 return;
1365 }
1366
1367 bool known_addr = false;
1368 for (size_t i = 0; i < port_->Candidates().size(); ++i) {
1369 if (port_->Candidates()[i].address() == addr->GetAddress()) {
1370 known_addr = true;
1371 break;
1372 }
1373 }
1374 if (known_addr) {
1375 return;
1376 }
1377
1378 // RFC 5245
1379 // Its priority is set equal to the value of the PRIORITY attribute
1380 // in the Binding request.
1381 const StunUInt32Attribute* priority_attr =
1382 request->msg()->GetUInt32(STUN_ATTR_PRIORITY);
1383 if (!priority_attr) {
1384 LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - "
1385 << "No STUN_ATTR_PRIORITY found in the "
1386 << "stun response message";
1387 return;
1388 }
1389 const uint32 priority = priority_attr->value();
1390 std::string id = rtc::CreateRandomString(8);
1391
1392 Candidate new_local_candidate;
1393 new_local_candidate.set_id(id);
1394 new_local_candidate.set_component(local_candidate().component());
1395 new_local_candidate.set_type(PRFLX_PORT_TYPE);
1396 new_local_candidate.set_protocol(local_candidate().protocol());
1397 new_local_candidate.set_address(addr->GetAddress());
1398 new_local_candidate.set_priority(priority);
1399 new_local_candidate.set_username(local_candidate().username());
1400 new_local_candidate.set_password(local_candidate().password());
1401 new_local_candidate.set_network_name(local_candidate().network_name());
1402 new_local_candidate.set_related_address(local_candidate().address());
1403 new_local_candidate.set_foundation(
1404 ComputeFoundation(PRFLX_PORT_TYPE, local_candidate().protocol(),
1405 local_candidate().address()));
1406
1407 // Change the local candidate of this Connection to the new prflx candidate.
1408 local_candidate_index_ = port_->AddPrflxCandidate(new_local_candidate);
1409
1410 // SignalStateChange to force a re-sort in P2PTransportChannel as this
1411 // Connection's local candidate has changed.
1412 SignalStateChange(this);
1413}
1414
1415ProxyConnection::ProxyConnection(Port* port, size_t index,
1416 const Candidate& candidate)
1417 : Connection(port, index, candidate), error_(0) {
1418}
1419
1420int ProxyConnection::Send(const void* data, size_t size,
1421 const rtc::PacketOptions& options) {
1422 if (write_state_ == STATE_WRITE_INIT || write_state_ == STATE_WRITE_TIMEOUT) {
1423 error_ = EWOULDBLOCK;
1424 return SOCKET_ERROR;
1425 }
1426 int sent = port_->SendTo(data, size, remote_candidate_.address(),
1427 options, true);
1428 if (sent <= 0) {
1429 ASSERT(sent < 0);
1430 error_ = port_->GetError();
1431 } else {
1432 send_rate_tracker_.Update(sent);
1433 }
1434 return sent;
1435}
1436
1437} // namespace cricket