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