| OLD | NEW |
| (Empty) |
| 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. | |
| 2 // Use of this source code is governed by a BSD-style license that can be | |
| 3 // found in the LICENSE file. | |
| 4 | |
| 5 #include "net/quic/quic_connection.h" | |
| 6 | |
| 7 #include <string.h> | |
| 8 #include <sys/types.h> | |
| 9 | |
| 10 #include <algorithm> | |
| 11 #include <iterator> | |
| 12 #include <limits> | |
| 13 #include <memory> | |
| 14 #include <set> | |
| 15 #include <utility> | |
| 16 | |
| 17 #include "base/format_macros.h" | |
| 18 #include "base/logging.h" | |
| 19 #include "base/macros.h" | |
| 20 #include "base/memory/ref_counted.h" | |
| 21 #include "base/metrics/histogram_macros.h" | |
| 22 #include "base/stl_util.h" | |
| 23 #include "base/strings/string_number_conversions.h" | |
| 24 #include "base/strings/stringprintf.h" | |
| 25 #include "net/base/address_family.h" | |
| 26 #include "net/base/ip_address.h" | |
| 27 #include "net/base/net_errors.h" | |
| 28 #include "net/quic/crypto/crypto_protocol.h" | |
| 29 #include "net/quic/crypto/quic_decrypter.h" | |
| 30 #include "net/quic/crypto/quic_encrypter.h" | |
| 31 #include "net/quic/proto/cached_network_parameters.pb.h" | |
| 32 #include "net/quic/quic_bandwidth.h" | |
| 33 #include "net/quic/quic_bug_tracker.h" | |
| 34 #include "net/quic/quic_config.h" | |
| 35 #include "net/quic/quic_flags.h" | |
| 36 #include "net/quic/quic_packet_generator.h" | |
| 37 #include "net/quic/quic_sent_packet_manager.h" | |
| 38 #include "net/quic/quic_utils.h" | |
| 39 | |
| 40 using base::StringPiece; | |
| 41 using base::StringPrintf; | |
| 42 using std::list; | |
| 43 using std::make_pair; | |
| 44 using std::max; | |
| 45 using std::min; | |
| 46 using std::numeric_limits; | |
| 47 using std::set; | |
| 48 using std::string; | |
| 49 using std::vector; | |
| 50 | |
| 51 namespace net { | |
| 52 | |
| 53 class QuicDecrypter; | |
| 54 class QuicEncrypter; | |
| 55 | |
| 56 namespace { | |
| 57 | |
| 58 // The largest gap in packets we'll accept without closing the connection. | |
| 59 // This will likely have to be tuned. | |
| 60 const QuicPacketNumber kMaxPacketGap = 5000; | |
| 61 | |
| 62 // Maximum number of acks received before sending an ack in response. | |
| 63 const QuicPacketCount kMaxPacketsReceivedBeforeAckSend = 20; | |
| 64 | |
| 65 // Maximum number of retransmittable packets received before sending an ack. | |
| 66 const QuicPacketCount kDefaultRetransmittablePacketsBeforeAck = 2; | |
| 67 // Minimum number of packets received before ack decimation is enabled. | |
| 68 // This intends to avoid the beginning of slow start, when CWNDs may be | |
| 69 // rapidly increasing. | |
| 70 const QuicPacketCount kMinReceivedBeforeAckDecimation = 100; | |
| 71 // Wait for up to 10 retransmittable packets before sending an ack. | |
| 72 const QuicPacketCount kMaxRetransmittablePacketsBeforeAck = 10; | |
| 73 // One quarter RTT delay when doing ack decimation. | |
| 74 const float kAckDecimationDelay = 0.25; | |
| 75 // One eighth RTT delay when doing ack decimation. | |
| 76 const float kShortAckDecimationDelay = 0.125; | |
| 77 | |
| 78 bool Near(QuicPacketNumber a, QuicPacketNumber b) { | |
| 79 QuicPacketNumber delta = (a > b) ? a - b : b - a; | |
| 80 return delta <= kMaxPacketGap; | |
| 81 } | |
| 82 | |
| 83 bool IsInitializedIPEndPoint(const IPEndPoint& address) { | |
| 84 return net::GetAddressFamily(address.address()) != | |
| 85 net::ADDRESS_FAMILY_UNSPECIFIED; | |
| 86 } | |
| 87 | |
| 88 // An alarm that is scheduled to send an ack if a timeout occurs. | |
| 89 class AckAlarmDelegate : public QuicAlarm::Delegate { | |
| 90 public: | |
| 91 explicit AckAlarmDelegate(QuicConnection* connection) | |
| 92 : connection_(connection) {} | |
| 93 | |
| 94 void OnAlarm() override { | |
| 95 DCHECK(connection_->ack_frame_updated()); | |
| 96 QuicConnection::ScopedPacketBundler bundler(connection_, | |
| 97 QuicConnection::SEND_ACK); | |
| 98 } | |
| 99 | |
| 100 private: | |
| 101 QuicConnection* connection_; | |
| 102 | |
| 103 DISALLOW_COPY_AND_ASSIGN(AckAlarmDelegate); | |
| 104 }; | |
| 105 | |
| 106 // This alarm will be scheduled any time a data-bearing packet is sent out. | |
| 107 // When the alarm goes off, the connection checks to see if the oldest packets | |
| 108 // have been acked, and retransmit them if they have not. | |
| 109 class RetransmissionAlarmDelegate : public QuicAlarm::Delegate { | |
| 110 public: | |
| 111 explicit RetransmissionAlarmDelegate(QuicConnection* connection) | |
| 112 : connection_(connection) {} | |
| 113 | |
| 114 void OnAlarm() override { connection_->OnRetransmissionTimeout(); } | |
| 115 | |
| 116 private: | |
| 117 QuicConnection* connection_; | |
| 118 | |
| 119 DISALLOW_COPY_AND_ASSIGN(RetransmissionAlarmDelegate); | |
| 120 }; | |
| 121 | |
| 122 // An alarm that is scheduled when the SentPacketManager requires a delay | |
| 123 // before sending packets and fires when the packet may be sent. | |
| 124 class SendAlarmDelegate : public QuicAlarm::Delegate { | |
| 125 public: | |
| 126 explicit SendAlarmDelegate(QuicConnection* connection) | |
| 127 : connection_(connection) {} | |
| 128 | |
| 129 void OnAlarm() override { connection_->WriteAndBundleAcksIfNotBlocked(); } | |
| 130 | |
| 131 private: | |
| 132 QuicConnection* connection_; | |
| 133 | |
| 134 DISALLOW_COPY_AND_ASSIGN(SendAlarmDelegate); | |
| 135 }; | |
| 136 | |
| 137 class TimeoutAlarmDelegate : public QuicAlarm::Delegate { | |
| 138 public: | |
| 139 explicit TimeoutAlarmDelegate(QuicConnection* connection) | |
| 140 : connection_(connection) {} | |
| 141 | |
| 142 void OnAlarm() override { connection_->CheckForTimeout(); } | |
| 143 | |
| 144 private: | |
| 145 QuicConnection* connection_; | |
| 146 | |
| 147 DISALLOW_COPY_AND_ASSIGN(TimeoutAlarmDelegate); | |
| 148 }; | |
| 149 | |
| 150 class PingAlarmDelegate : public QuicAlarm::Delegate { | |
| 151 public: | |
| 152 explicit PingAlarmDelegate(QuicConnection* connection) | |
| 153 : connection_(connection) {} | |
| 154 | |
| 155 void OnAlarm() override { connection_->OnPingTimeout(); } | |
| 156 | |
| 157 private: | |
| 158 QuicConnection* connection_; | |
| 159 | |
| 160 DISALLOW_COPY_AND_ASSIGN(PingAlarmDelegate); | |
| 161 }; | |
| 162 | |
| 163 class MtuDiscoveryAlarmDelegate : public QuicAlarm::Delegate { | |
| 164 public: | |
| 165 explicit MtuDiscoveryAlarmDelegate(QuicConnection* connection) | |
| 166 : connection_(connection) {} | |
| 167 | |
| 168 void OnAlarm() override { connection_->DiscoverMtu(); } | |
| 169 | |
| 170 private: | |
| 171 QuicConnection* connection_; | |
| 172 | |
| 173 DISALLOW_COPY_AND_ASSIGN(MtuDiscoveryAlarmDelegate); | |
| 174 }; | |
| 175 | |
| 176 // Listens for acks of MTU discovery packets and raises the maximum packet size | |
| 177 // of the connection if the probe succeeds. | |
| 178 class MtuDiscoveryAckListener : public QuicAckListenerInterface { | |
| 179 public: | |
| 180 MtuDiscoveryAckListener(QuicConnection* connection, QuicByteCount probe_size) | |
| 181 : connection_(connection), probe_size_(probe_size) {} | |
| 182 | |
| 183 void OnPacketAcked(int /*acked_bytes*/, | |
| 184 QuicTime::Delta /*ack delay time*/) override { | |
| 185 // MTU discovery packets are not retransmittable, so it must be acked. | |
| 186 MaybeIncreaseMtu(); | |
| 187 } | |
| 188 | |
| 189 void OnPacketRetransmitted(int /*retransmitted_bytes*/) override {} | |
| 190 | |
| 191 protected: | |
| 192 // MtuDiscoveryAckListener is ref counted. | |
| 193 ~MtuDiscoveryAckListener() override {} | |
| 194 | |
| 195 private: | |
| 196 void MaybeIncreaseMtu() { | |
| 197 if (probe_size_ > connection_->max_packet_length()) { | |
| 198 connection_->SetMaxPacketLength(probe_size_); | |
| 199 } | |
| 200 } | |
| 201 | |
| 202 QuicConnection* connection_; | |
| 203 QuicByteCount probe_size_; | |
| 204 | |
| 205 DISALLOW_COPY_AND_ASSIGN(MtuDiscoveryAckListener); | |
| 206 }; | |
| 207 | |
| 208 } // namespace | |
| 209 | |
| 210 #define ENDPOINT \ | |
| 211 (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ") | |
| 212 | |
| 213 QuicConnection::QuicConnection(QuicConnectionId connection_id, | |
| 214 IPEndPoint address, | |
| 215 QuicConnectionHelperInterface* helper, | |
| 216 QuicAlarmFactory* alarm_factory, | |
| 217 QuicPacketWriter* writer, | |
| 218 bool owns_writer, | |
| 219 Perspective perspective, | |
| 220 const QuicVersionVector& supported_versions) | |
| 221 : framer_(supported_versions, | |
| 222 helper->GetClock()->ApproximateNow(), | |
| 223 perspective), | |
| 224 helper_(helper), | |
| 225 alarm_factory_(alarm_factory), | |
| 226 per_packet_options_(nullptr), | |
| 227 writer_(writer), | |
| 228 owns_writer_(owns_writer), | |
| 229 encryption_level_(ENCRYPTION_NONE), | |
| 230 has_forward_secure_encrypter_(false), | |
| 231 first_required_forward_secure_packet_(0), | |
| 232 clock_(helper->GetClock()), | |
| 233 random_generator_(helper->GetRandomGenerator()), | |
| 234 connection_id_(connection_id), | |
| 235 peer_address_(address), | |
| 236 active_peer_migration_type_(NO_CHANGE), | |
| 237 highest_packet_sent_before_peer_migration_(0), | |
| 238 last_packet_decrypted_(false), | |
| 239 last_size_(0), | |
| 240 current_packet_data_(nullptr), | |
| 241 last_decrypted_packet_level_(ENCRYPTION_NONE), | |
| 242 should_last_packet_instigate_acks_(false), | |
| 243 largest_seen_packet_with_ack_(0), | |
| 244 largest_seen_packet_with_stop_waiting_(0), | |
| 245 max_undecryptable_packets_(0), | |
| 246 pending_version_negotiation_packet_(false), | |
| 247 save_crypto_packets_as_termination_packets_(false), | |
| 248 idle_timeout_connection_close_behavior_( | |
| 249 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET), | |
| 250 close_connection_after_five_rtos_(false), | |
| 251 received_packet_manager_(&stats_), | |
| 252 ack_queued_(false), | |
| 253 num_retransmittable_packets_received_since_last_ack_sent_(0), | |
| 254 last_ack_had_missing_packets_(false), | |
| 255 num_packets_received_since_last_ack_sent_(0), | |
| 256 stop_waiting_count_(0), | |
| 257 ack_mode_(TCP_ACKING), | |
| 258 ack_decimation_delay_(kAckDecimationDelay), | |
| 259 delay_setting_retransmission_alarm_(false), | |
| 260 pending_retransmission_alarm_(false), | |
| 261 defer_send_in_response_to_packets_(false), | |
| 262 arena_(), | |
| 263 ack_alarm_(alarm_factory_->CreateAlarm(arena_.New<AckAlarmDelegate>(this), | |
| 264 &arena_)), | |
| 265 retransmission_alarm_(alarm_factory_->CreateAlarm( | |
| 266 arena_.New<RetransmissionAlarmDelegate>(this), | |
| 267 &arena_)), | |
| 268 send_alarm_( | |
| 269 alarm_factory_->CreateAlarm(arena_.New<SendAlarmDelegate>(this), | |
| 270 &arena_)), | |
| 271 resume_writes_alarm_( | |
| 272 alarm_factory_->CreateAlarm(arena_.New<SendAlarmDelegate>(this), | |
| 273 &arena_)), | |
| 274 timeout_alarm_( | |
| 275 alarm_factory_->CreateAlarm(arena_.New<TimeoutAlarmDelegate>(this), | |
| 276 &arena_)), | |
| 277 ping_alarm_( | |
| 278 alarm_factory_->CreateAlarm(arena_.New<PingAlarmDelegate>(this), | |
| 279 &arena_)), | |
| 280 mtu_discovery_alarm_(alarm_factory_->CreateAlarm( | |
| 281 arena_.New<MtuDiscoveryAlarmDelegate>(this), | |
| 282 &arena_)), | |
| 283 visitor_(nullptr), | |
| 284 debug_visitor_(nullptr), | |
| 285 packet_generator_(connection_id_, | |
| 286 &framer_, | |
| 287 random_generator_, | |
| 288 helper->GetBufferAllocator(), | |
| 289 this), | |
| 290 idle_network_timeout_(QuicTime::Delta::Infinite()), | |
| 291 handshake_timeout_(QuicTime::Delta::Infinite()), | |
| 292 time_of_last_received_packet_(clock_->ApproximateNow()), | |
| 293 time_of_last_sent_new_packet_(clock_->ApproximateNow()), | |
| 294 last_send_for_timeout_(clock_->ApproximateNow()), | |
| 295 packet_number_of_last_sent_packet_(0), | |
| 296 sent_packet_manager_(new QuicSentPacketManager(perspective, | |
| 297 kDefaultPathId, | |
| 298 clock_, | |
| 299 &stats_, | |
| 300 kCubic, | |
| 301 kNack, | |
| 302 /*delegate=*/nullptr)), | |
| 303 version_negotiation_state_(START_NEGOTIATION), | |
| 304 perspective_(perspective), | |
| 305 connected_(true), | |
| 306 can_truncate_connection_ids_(true), | |
| 307 mtu_discovery_target_(0), | |
| 308 mtu_probe_count_(0), | |
| 309 packets_between_mtu_probes_(kPacketsBetweenMtuProbesBase), | |
| 310 next_mtu_probe_at_(kPacketsBetweenMtuProbesBase), | |
| 311 largest_received_packet_size_(0), | |
| 312 goaway_sent_(false), | |
| 313 goaway_received_(false), | |
| 314 multipath_enabled_(false) { | |
| 315 DVLOG(1) << ENDPOINT | |
| 316 << "Created connection with connection_id: " << connection_id; | |
| 317 framer_.set_visitor(this); | |
| 318 framer_.set_received_entropy_calculator(&received_packet_manager_); | |
| 319 last_stop_waiting_frame_.least_unacked = 0; | |
| 320 stats_.connection_creation_time = clock_->ApproximateNow(); | |
| 321 if (FLAGS_quic_enable_multipath) { | |
| 322 sent_packet_manager_.reset(new QuicMultipathSentPacketManager( | |
| 323 sent_packet_manager_.release(), this)); | |
| 324 } | |
| 325 // TODO(ianswett): Supply the NetworkChangeVisitor as a constructor argument | |
| 326 // and make it required non-null, because it's always used. | |
| 327 sent_packet_manager_->SetNetworkChangeVisitor(this); | |
| 328 // Allow the packet writer to potentially reduce the packet size to a value | |
| 329 // even smaller than kDefaultMaxPacketSize. | |
| 330 SetMaxPacketLength(perspective_ == Perspective::IS_SERVER | |
| 331 ? kDefaultServerMaxPacketSize | |
| 332 : kDefaultMaxPacketSize); | |
| 333 received_packet_manager_.SetVersion(version()); | |
| 334 } | |
| 335 | |
| 336 QuicConnection::~QuicConnection() { | |
| 337 if (owns_writer_) { | |
| 338 delete writer_; | |
| 339 } | |
| 340 STLDeleteElements(&undecryptable_packets_); | |
| 341 ClearQueuedPackets(); | |
| 342 } | |
| 343 | |
| 344 void QuicConnection::ClearQueuedPackets() { | |
| 345 for (QueuedPacketList::iterator it = queued_packets_.begin(); | |
| 346 it != queued_packets_.end(); ++it) { | |
| 347 // Delete the buffer before calling ClearSerializedPacket, which sets | |
| 348 // encrypted_buffer to nullptr. | |
| 349 delete[] it->encrypted_buffer; | |
| 350 QuicUtils::ClearSerializedPacket(&(*it)); | |
| 351 } | |
| 352 queued_packets_.clear(); | |
| 353 } | |
| 354 | |
| 355 void QuicConnection::SetFromConfig(const QuicConfig& config) { | |
| 356 if (config.negotiated()) { | |
| 357 // Handshake complete, set handshake timeout to Infinite. | |
| 358 SetNetworkTimeouts(QuicTime::Delta::Infinite(), | |
| 359 config.IdleConnectionStateLifetime()); | |
| 360 if (config.SilentClose()) { | |
| 361 idle_timeout_connection_close_behavior_ = | |
| 362 ConnectionCloseBehavior::SILENT_CLOSE; | |
| 363 } | |
| 364 if (FLAGS_quic_enable_multipath && config.MultipathEnabled()) { | |
| 365 multipath_enabled_ = true; | |
| 366 } | |
| 367 } else { | |
| 368 SetNetworkTimeouts(config.max_time_before_crypto_handshake(), | |
| 369 config.max_idle_time_before_crypto_handshake()); | |
| 370 } | |
| 371 | |
| 372 sent_packet_manager_->SetFromConfig(config); | |
| 373 if (config.HasReceivedBytesForConnectionId() && | |
| 374 can_truncate_connection_ids_) { | |
| 375 packet_generator_.SetConnectionIdLength( | |
| 376 config.ReceivedBytesForConnectionId()); | |
| 377 } | |
| 378 max_undecryptable_packets_ = config.max_undecryptable_packets(); | |
| 379 | |
| 380 if (config.HasClientSentConnectionOption(kMTUH, perspective_)) { | |
| 381 SetMtuDiscoveryTarget(kMtuDiscoveryTargetPacketSizeHigh); | |
| 382 } | |
| 383 if (config.HasClientSentConnectionOption(kMTUL, perspective_)) { | |
| 384 SetMtuDiscoveryTarget(kMtuDiscoveryTargetPacketSizeLow); | |
| 385 } | |
| 386 if (debug_visitor_ != nullptr) { | |
| 387 debug_visitor_->OnSetFromConfig(config); | |
| 388 } | |
| 389 if (config.HasClientSentConnectionOption(kACKD, perspective_)) { | |
| 390 ack_mode_ = ACK_DECIMATION; | |
| 391 } | |
| 392 if (config.HasClientSentConnectionOption(kAKD2, perspective_)) { | |
| 393 ack_mode_ = ACK_DECIMATION_WITH_REORDERING; | |
| 394 } | |
| 395 if (config.HasClientSentConnectionOption(kAKD3, perspective_)) { | |
| 396 ack_mode_ = ACK_DECIMATION; | |
| 397 ack_decimation_delay_ = kShortAckDecimationDelay; | |
| 398 } | |
| 399 if (config.HasClientSentConnectionOption(kAKD4, perspective_)) { | |
| 400 ack_mode_ = ACK_DECIMATION_WITH_REORDERING; | |
| 401 ack_decimation_delay_ = kShortAckDecimationDelay; | |
| 402 } | |
| 403 if (config.HasClientSentConnectionOption(k5RTO, perspective_)) { | |
| 404 close_connection_after_five_rtos_ = true; | |
| 405 } | |
| 406 } | |
| 407 | |
| 408 void QuicConnection::OnSendConnectionState( | |
| 409 const CachedNetworkParameters& cached_network_params) { | |
| 410 if (debug_visitor_ != nullptr) { | |
| 411 debug_visitor_->OnSendConnectionState(cached_network_params); | |
| 412 } | |
| 413 } | |
| 414 | |
| 415 void QuicConnection::OnReceiveConnectionState( | |
| 416 const CachedNetworkParameters& cached_network_params) { | |
| 417 if (debug_visitor_ != nullptr) { | |
| 418 debug_visitor_->OnReceiveConnectionState(cached_network_params); | |
| 419 } | |
| 420 } | |
| 421 | |
| 422 void QuicConnection::ResumeConnectionState( | |
| 423 const CachedNetworkParameters& cached_network_params, | |
| 424 bool max_bandwidth_resumption) { | |
| 425 sent_packet_manager_->ResumeConnectionState(cached_network_params, | |
| 426 max_bandwidth_resumption); | |
| 427 } | |
| 428 | |
| 429 void QuicConnection::SetMaxPacingRate(QuicBandwidth max_pacing_rate) { | |
| 430 sent_packet_manager_->SetMaxPacingRate(max_pacing_rate); | |
| 431 } | |
| 432 | |
| 433 void QuicConnection::SetNumOpenStreams(size_t num_streams) { | |
| 434 sent_packet_manager_->SetNumOpenStreams(num_streams); | |
| 435 } | |
| 436 | |
| 437 bool QuicConnection::SelectMutualVersion( | |
| 438 const QuicVersionVector& available_versions) { | |
| 439 // Try to find the highest mutual version by iterating over supported | |
| 440 // versions, starting with the highest, and breaking out of the loop once we | |
| 441 // find a matching version in the provided available_versions vector. | |
| 442 const QuicVersionVector& supported_versions = framer_.supported_versions(); | |
| 443 for (size_t i = 0; i < supported_versions.size(); ++i) { | |
| 444 const QuicVersion& version = supported_versions[i]; | |
| 445 if (ContainsValue(available_versions, version)) { | |
| 446 framer_.set_version(version); | |
| 447 return true; | |
| 448 } | |
| 449 } | |
| 450 | |
| 451 return false; | |
| 452 } | |
| 453 | |
| 454 void QuicConnection::OnError(QuicFramer* framer) { | |
| 455 // Packets that we can not or have not decrypted are dropped. | |
| 456 // TODO(rch): add stats to measure this. | |
| 457 if (!connected_ || last_packet_decrypted_ == false) { | |
| 458 return; | |
| 459 } | |
| 460 CloseConnection(framer->error(), framer->detailed_error(), | |
| 461 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); | |
| 462 } | |
| 463 | |
| 464 void QuicConnection::OnPacket() { | |
| 465 last_packet_decrypted_ = false; | |
| 466 } | |
| 467 | |
| 468 void QuicConnection::OnPublicResetPacket(const QuicPublicResetPacket& packet) { | |
| 469 // Check that any public reset packet with a different connection ID that was | |
| 470 // routed to this QuicConnection has been redirected before control reaches | |
| 471 // here. (Check for a bug regression.) | |
| 472 DCHECK_EQ(connection_id_, packet.public_header.connection_id); | |
| 473 if (debug_visitor_ != nullptr) { | |
| 474 debug_visitor_->OnPublicResetPacket(packet); | |
| 475 } | |
| 476 const string error_details = "Received public reset."; | |
| 477 DVLOG(1) << ENDPOINT << error_details; | |
| 478 TearDownLocalConnectionState(QUIC_PUBLIC_RESET, error_details, | |
| 479 ConnectionCloseSource::FROM_PEER); | |
| 480 } | |
| 481 | |
| 482 bool QuicConnection::OnProtocolVersionMismatch(QuicVersion received_version) { | |
| 483 DVLOG(1) << ENDPOINT << "Received packet with mismatched version " | |
| 484 << received_version; | |
| 485 // TODO(satyamshekhar): Implement no server state in this mode. | |
| 486 if (perspective_ == Perspective::IS_CLIENT) { | |
| 487 const string error_details = "Protocol version mismatch."; | |
| 488 QUIC_BUG << ENDPOINT << error_details; | |
| 489 TearDownLocalConnectionState(QUIC_INTERNAL_ERROR, error_details, | |
| 490 ConnectionCloseSource::FROM_SELF); | |
| 491 return false; | |
| 492 } | |
| 493 DCHECK_NE(version(), received_version); | |
| 494 | |
| 495 if (debug_visitor_ != nullptr) { | |
| 496 debug_visitor_->OnProtocolVersionMismatch(received_version); | |
| 497 } | |
| 498 | |
| 499 switch (version_negotiation_state_) { | |
| 500 case START_NEGOTIATION: | |
| 501 if (!framer_.IsSupportedVersion(received_version)) { | |
| 502 SendVersionNegotiationPacket(); | |
| 503 version_negotiation_state_ = NEGOTIATION_IN_PROGRESS; | |
| 504 return false; | |
| 505 } | |
| 506 break; | |
| 507 | |
| 508 case NEGOTIATION_IN_PROGRESS: | |
| 509 if (!framer_.IsSupportedVersion(received_version)) { | |
| 510 SendVersionNegotiationPacket(); | |
| 511 return false; | |
| 512 } | |
| 513 break; | |
| 514 | |
| 515 case NEGOTIATED_VERSION: | |
| 516 // Might be old packets that were sent by the client before the version | |
| 517 // was negotiated. Drop these. | |
| 518 return false; | |
| 519 | |
| 520 default: | |
| 521 DCHECK(false); | |
| 522 } | |
| 523 | |
| 524 version_negotiation_state_ = NEGOTIATED_VERSION; | |
| 525 received_packet_manager_.SetVersion(received_version); | |
| 526 visitor_->OnSuccessfulVersionNegotiation(received_version); | |
| 527 if (debug_visitor_ != nullptr) { | |
| 528 debug_visitor_->OnSuccessfulVersionNegotiation(received_version); | |
| 529 } | |
| 530 DVLOG(1) << ENDPOINT << "version negotiated " << received_version; | |
| 531 | |
| 532 // Store the new version. | |
| 533 framer_.set_version(received_version); | |
| 534 | |
| 535 // TODO(satyamshekhar): Store the packet number of this packet and close the | |
| 536 // connection if we ever received a packet with incorrect version and whose | |
| 537 // packet number is greater. | |
| 538 return true; | |
| 539 } | |
| 540 | |
| 541 // Handles version negotiation for client connection. | |
| 542 void QuicConnection::OnVersionNegotiationPacket( | |
| 543 const QuicVersionNegotiationPacket& packet) { | |
| 544 // Check that any public reset packet with a different connection ID that was | |
| 545 // routed to this QuicConnection has been redirected before control reaches | |
| 546 // here. (Check for a bug regression.) | |
| 547 DCHECK_EQ(connection_id_, packet.connection_id); | |
| 548 if (perspective_ == Perspective::IS_SERVER) { | |
| 549 const string error_details = "Server receieved version negotiation packet."; | |
| 550 QUIC_BUG << error_details; | |
| 551 TearDownLocalConnectionState(QUIC_INTERNAL_ERROR, error_details, | |
| 552 ConnectionCloseSource::FROM_SELF); | |
| 553 return; | |
| 554 } | |
| 555 if (debug_visitor_ != nullptr) { | |
| 556 debug_visitor_->OnVersionNegotiationPacket(packet); | |
| 557 } | |
| 558 | |
| 559 if (version_negotiation_state_ != START_NEGOTIATION) { | |
| 560 // Possibly a duplicate version negotiation packet. | |
| 561 return; | |
| 562 } | |
| 563 | |
| 564 if (ContainsValue(packet.versions, version())) { | |
| 565 const string error_details = | |
| 566 "Server already supports client's version and should have accepted the " | |
| 567 "connection."; | |
| 568 DLOG(WARNING) << error_details; | |
| 569 TearDownLocalConnectionState(QUIC_INVALID_VERSION_NEGOTIATION_PACKET, | |
| 570 error_details, | |
| 571 ConnectionCloseSource::FROM_SELF); | |
| 572 return; | |
| 573 } | |
| 574 | |
| 575 if (!SelectMutualVersion(packet.versions)) { | |
| 576 CloseConnection(QUIC_INVALID_VERSION, "No common version found.", | |
| 577 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); | |
| 578 return; | |
| 579 } | |
| 580 | |
| 581 DVLOG(1) << ENDPOINT | |
| 582 << "Negotiated version: " << QuicVersionToString(version()); | |
| 583 received_packet_manager_.SetVersion(version()); | |
| 584 server_supported_versions_ = packet.versions; | |
| 585 version_negotiation_state_ = NEGOTIATION_IN_PROGRESS; | |
| 586 RetransmitUnackedPackets(ALL_UNACKED_RETRANSMISSION); | |
| 587 } | |
| 588 | |
| 589 bool QuicConnection::OnUnauthenticatedPublicHeader( | |
| 590 const QuicPacketPublicHeader& header) { | |
| 591 if (header.connection_id == connection_id_) { | |
| 592 return true; | |
| 593 } | |
| 594 | |
| 595 ++stats_.packets_dropped; | |
| 596 DVLOG(1) << ENDPOINT << "Ignoring packet from unexpected ConnectionId: " | |
| 597 << header.connection_id << " instead of " << connection_id_; | |
| 598 if (debug_visitor_ != nullptr) { | |
| 599 debug_visitor_->OnIncorrectConnectionId(header.connection_id); | |
| 600 } | |
| 601 // If this is a server, the dispatcher routes each packet to the | |
| 602 // QuicConnection responsible for the packet's connection ID. So if control | |
| 603 // arrives here and this is a server, the dispatcher must be malfunctioning. | |
| 604 DCHECK_NE(Perspective::IS_SERVER, perspective_); | |
| 605 return false; | |
| 606 } | |
| 607 | |
| 608 bool QuicConnection::OnUnauthenticatedHeader(const QuicPacketHeader& header) { | |
| 609 if (debug_visitor_ != nullptr) { | |
| 610 debug_visitor_->OnUnauthenticatedHeader(header); | |
| 611 } | |
| 612 | |
| 613 // Check that any public reset packet with a different connection ID that was | |
| 614 // routed to this QuicConnection has been redirected before control reaches | |
| 615 // here. | |
| 616 DCHECK_EQ(connection_id_, header.public_header.connection_id); | |
| 617 | |
| 618 // Multipath is not enabled, but a packet with multipath flag on is received. | |
| 619 if (!multipath_enabled_ && header.public_header.multipath_flag) { | |
| 620 const string error_details = | |
| 621 "Received a packet with multipath flag but multipath is not enabled."; | |
| 622 QUIC_BUG << error_details; | |
| 623 CloseConnection(QUIC_BAD_MULTIPATH_FLAG, error_details, | |
| 624 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); | |
| 625 return false; | |
| 626 } | |
| 627 if (!packet_generator_.IsPendingPacketEmpty()) { | |
| 628 // Incoming packets may change a queued ACK frame. | |
| 629 const string error_details = | |
| 630 "Pending frames must be serialized before incoming packets are " | |
| 631 "processed."; | |
| 632 QUIC_BUG << error_details; | |
| 633 CloseConnection(QUIC_INTERNAL_ERROR, error_details, | |
| 634 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); | |
| 635 return false; | |
| 636 } | |
| 637 | |
| 638 // If this packet has already been seen, or the sender has told us that it | |
| 639 // will not be retransmitted, then stop processing the packet. | |
| 640 if (!received_packet_manager_.IsAwaitingPacket(header.packet_number)) { | |
| 641 DVLOG(1) << ENDPOINT << "Packet " << header.packet_number | |
| 642 << " no longer being waited for. Discarding."; | |
| 643 if (debug_visitor_ != nullptr) { | |
| 644 debug_visitor_->OnDuplicatePacket(header.packet_number); | |
| 645 } | |
| 646 ++stats_.packets_dropped; | |
| 647 return false; | |
| 648 } | |
| 649 | |
| 650 return true; | |
| 651 } | |
| 652 | |
| 653 void QuicConnection::OnDecryptedPacket(EncryptionLevel level) { | |
| 654 last_decrypted_packet_level_ = level; | |
| 655 last_packet_decrypted_ = true; | |
| 656 | |
| 657 // If this packet was foward-secure encrypted and the forward-secure encrypter | |
| 658 // is not being used, start using it. | |
| 659 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE && | |
| 660 has_forward_secure_encrypter_ && level == ENCRYPTION_FORWARD_SECURE) { | |
| 661 SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); | |
| 662 } | |
| 663 | |
| 664 // Once the server receives a forward secure packet, the handshake is | |
| 665 // confirmed. | |
| 666 if (FLAGS_quic_no_shlo_listener && level == ENCRYPTION_FORWARD_SECURE && | |
| 667 perspective_ == Perspective::IS_SERVER) { | |
| 668 sent_packet_manager_->SetHandshakeConfirmed(); | |
| 669 } | |
| 670 } | |
| 671 | |
| 672 bool QuicConnection::OnPacketHeader(const QuicPacketHeader& header) { | |
| 673 if (debug_visitor_ != nullptr) { | |
| 674 debug_visitor_->OnPacketHeader(header); | |
| 675 } | |
| 676 | |
| 677 // Will be decremented below if we fall through to return true. | |
| 678 ++stats_.packets_dropped; | |
| 679 | |
| 680 if (!ProcessValidatedPacket(header)) { | |
| 681 return false; | |
| 682 } | |
| 683 | |
| 684 // Only migrate connection to a new peer address if a change is not underway. | |
| 685 PeerAddressChangeType peer_migration_type = | |
| 686 QuicUtils::DetermineAddressChangeType(peer_address_, | |
| 687 last_packet_source_address_); | |
| 688 // Do not migrate connection if the changed address packet is a reordered | |
| 689 // packet. | |
| 690 if (active_peer_migration_type_ == NO_CHANGE && | |
| 691 peer_migration_type != NO_CHANGE && | |
| 692 (!FLAGS_quic_do_not_migrate_on_old_packet || | |
| 693 header.packet_number > received_packet_manager_.GetLargestObserved())) { | |
| 694 StartPeerMigration(header.path_id, peer_migration_type); | |
| 695 } | |
| 696 | |
| 697 --stats_.packets_dropped; | |
| 698 DVLOG(1) << ENDPOINT << "Received packet header: " << header; | |
| 699 last_header_ = header; | |
| 700 DCHECK(connected_); | |
| 701 return true; | |
| 702 } | |
| 703 | |
| 704 bool QuicConnection::OnStreamFrame(const QuicStreamFrame& frame) { | |
| 705 DCHECK(connected_); | |
| 706 if (debug_visitor_ != nullptr) { | |
| 707 debug_visitor_->OnStreamFrame(frame); | |
| 708 } | |
| 709 if (frame.stream_id != kCryptoStreamId && | |
| 710 last_decrypted_packet_level_ == ENCRYPTION_NONE) { | |
| 711 if (MaybeConsiderAsMemoryCorruption(frame)) { | |
| 712 CloseConnection(QUIC_MAYBE_CORRUPTED_MEMORY, | |
| 713 "Received crypto frame on non crypto stream.", | |
| 714 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); | |
| 715 return false; | |
| 716 } | |
| 717 | |
| 718 QUIC_BUG << ENDPOINT | |
| 719 << "Received an unencrypted data frame: closing connection" | |
| 720 << " packet_number:" << last_header_.packet_number | |
| 721 << " stream_id:" << frame.stream_id | |
| 722 << " received_packets:" << received_packet_manager_.ack_frame(); | |
| 723 CloseConnection(QUIC_UNENCRYPTED_STREAM_DATA, | |
| 724 "Unencrypted stream data seen.", | |
| 725 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); | |
| 726 return false; | |
| 727 } | |
| 728 visitor_->OnStreamFrame(frame); | |
| 729 visitor_->PostProcessAfterData(); | |
| 730 stats_.stream_bytes_received += frame.data_length; | |
| 731 should_last_packet_instigate_acks_ = true; | |
| 732 return connected_; | |
| 733 } | |
| 734 | |
| 735 bool QuicConnection::OnAckFrame(const QuicAckFrame& incoming_ack) { | |
| 736 DCHECK(connected_); | |
| 737 if (debug_visitor_ != nullptr) { | |
| 738 debug_visitor_->OnAckFrame(incoming_ack); | |
| 739 } | |
| 740 DVLOG(1) << ENDPOINT << "OnAckFrame: " << incoming_ack; | |
| 741 | |
| 742 if (last_header_.packet_number <= largest_seen_packet_with_ack_) { | |
| 743 DVLOG(1) << ENDPOINT << "Received an old ack frame: ignoring"; | |
| 744 return true; | |
| 745 } | |
| 746 | |
| 747 const char* error = ValidateAckFrame(incoming_ack); | |
| 748 if (error != nullptr) { | |
| 749 CloseConnection(QUIC_INVALID_ACK_DATA, error, | |
| 750 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); | |
| 751 return false; | |
| 752 } | |
| 753 | |
| 754 if (send_alarm_->IsSet()) { | |
| 755 send_alarm_->Cancel(); | |
| 756 } | |
| 757 ProcessAckFrame(incoming_ack); | |
| 758 if (incoming_ack.is_truncated) { | |
| 759 should_last_packet_instigate_acks_ = true; | |
| 760 } | |
| 761 // If the incoming ack's packets set expresses missing packets: peer is still | |
| 762 // waiting for a packet lower than a packet that we are no longer planning to | |
| 763 // send. | |
| 764 // If the incoming ack's packets set expresses received packets: peer is still | |
| 765 // acking packets which we never care about. | |
| 766 // Send an ack to raise the high water mark. | |
| 767 if (!incoming_ack.packets.Empty() && | |
| 768 GetLeastUnacked(incoming_ack.path_id) > incoming_ack.packets.Min()) { | |
| 769 ++stop_waiting_count_; | |
| 770 } else { | |
| 771 stop_waiting_count_ = 0; | |
| 772 } | |
| 773 | |
| 774 return connected_; | |
| 775 } | |
| 776 | |
| 777 void QuicConnection::ProcessAckFrame(const QuicAckFrame& incoming_ack) { | |
| 778 largest_seen_packet_with_ack_ = last_header_.packet_number; | |
| 779 sent_packet_manager_->OnIncomingAck(incoming_ack, | |
| 780 time_of_last_received_packet_); | |
| 781 if (version() <= QUIC_VERSION_33) { | |
| 782 sent_entropy_manager_.ClearEntropyBefore( | |
| 783 sent_packet_manager_->GetLeastPacketAwaitedByPeer( | |
| 784 incoming_ack.path_id) - | |
| 785 1); | |
| 786 } | |
| 787 // Always reset the retransmission alarm when an ack comes in, since we now | |
| 788 // have a better estimate of the current rtt than when it was set. | |
| 789 SetRetransmissionAlarm(); | |
| 790 } | |
| 791 | |
| 792 void QuicConnection::ProcessStopWaitingFrame( | |
| 793 const QuicStopWaitingFrame& stop_waiting) { | |
| 794 largest_seen_packet_with_stop_waiting_ = last_header_.packet_number; | |
| 795 received_packet_manager_.UpdatePacketInformationSentByPeer(stop_waiting); | |
| 796 } | |
| 797 | |
| 798 bool QuicConnection::OnStopWaitingFrame(const QuicStopWaitingFrame& frame) { | |
| 799 DCHECK(connected_); | |
| 800 | |
| 801 if (last_header_.packet_number <= largest_seen_packet_with_stop_waiting_) { | |
| 802 DVLOG(1) << ENDPOINT << "Received an old stop waiting frame: ignoring"; | |
| 803 return true; | |
| 804 } | |
| 805 | |
| 806 const char* error = ValidateStopWaitingFrame(frame); | |
| 807 if (error != nullptr) { | |
| 808 CloseConnection(QUIC_INVALID_STOP_WAITING_DATA, error, | |
| 809 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); | |
| 810 return false; | |
| 811 } | |
| 812 | |
| 813 if (debug_visitor_ != nullptr) { | |
| 814 debug_visitor_->OnStopWaitingFrame(frame); | |
| 815 } | |
| 816 | |
| 817 last_stop_waiting_frame_ = frame; | |
| 818 return connected_; | |
| 819 } | |
| 820 | |
| 821 bool QuicConnection::OnPaddingFrame(const QuicPaddingFrame& frame) { | |
| 822 DCHECK(connected_); | |
| 823 if (debug_visitor_ != nullptr) { | |
| 824 debug_visitor_->OnPaddingFrame(frame); | |
| 825 } | |
| 826 return true; | |
| 827 } | |
| 828 | |
| 829 bool QuicConnection::OnPingFrame(const QuicPingFrame& frame) { | |
| 830 DCHECK(connected_); | |
| 831 if (debug_visitor_ != nullptr) { | |
| 832 debug_visitor_->OnPingFrame(frame); | |
| 833 } | |
| 834 should_last_packet_instigate_acks_ = true; | |
| 835 return true; | |
| 836 } | |
| 837 | |
| 838 const char* QuicConnection::ValidateAckFrame(const QuicAckFrame& incoming_ack) { | |
| 839 if (incoming_ack.largest_observed > packet_generator_.packet_number()) { | |
| 840 DLOG(WARNING) << ENDPOINT << "Peer's observed unsent packet:" | |
| 841 << incoming_ack.largest_observed << " vs " | |
| 842 << packet_generator_.packet_number(); | |
| 843 // We got an error for data we have not sent. Error out. | |
| 844 return "Largest observed too high."; | |
| 845 } | |
| 846 | |
| 847 if (incoming_ack.largest_observed < | |
| 848 sent_packet_manager_->GetLargestObserved(incoming_ack.path_id)) { | |
| 849 VLOG(1) << ENDPOINT << "Peer's largest_observed packet decreased:" | |
| 850 << incoming_ack.largest_observed << " vs " | |
| 851 << sent_packet_manager_->GetLargestObserved(incoming_ack.path_id) | |
| 852 << " packet_number:" << last_header_.packet_number | |
| 853 << " largest seen with ack:" << largest_seen_packet_with_ack_ | |
| 854 << " connection_id: " << connection_id_; | |
| 855 // A new ack has a diminished largest_observed value. Error out. | |
| 856 // If this was an old packet, we wouldn't even have checked. | |
| 857 return "Largest observed too low."; | |
| 858 } | |
| 859 | |
| 860 if (version() <= QUIC_VERSION_33) { | |
| 861 if (!incoming_ack.packets.Empty() && | |
| 862 incoming_ack.packets.Max() > incoming_ack.largest_observed) { | |
| 863 LOG(WARNING) << ENDPOINT | |
| 864 << "Peer sent missing packet: " << incoming_ack.packets.Max() | |
| 865 << " which is greater than largest observed: " | |
| 866 << incoming_ack.largest_observed; | |
| 867 return "Missing packet higher than largest observed."; | |
| 868 } | |
| 869 | |
| 870 if (!incoming_ack.packets.Empty() && | |
| 871 incoming_ack.packets.Min() < | |
| 872 sent_packet_manager_->GetLeastPacketAwaitedByPeer( | |
| 873 incoming_ack.path_id)) { | |
| 874 LOG(WARNING) << ENDPOINT | |
| 875 << "Peer sent missing packet: " << incoming_ack.packets.Min() | |
| 876 << " which is smaller than least_packet_awaited_by_peer_: " | |
| 877 << sent_packet_manager_->GetLeastPacketAwaitedByPeer( | |
| 878 incoming_ack.path_id); | |
| 879 return "Missing packet smaller than least awaited."; | |
| 880 } | |
| 881 if (!sent_entropy_manager_.IsValidEntropy(incoming_ack.largest_observed, | |
| 882 incoming_ack.packets, | |
| 883 incoming_ack.entropy_hash)) { | |
| 884 DLOG(WARNING) << ENDPOINT << "Peer sent invalid entropy." | |
| 885 << " largest_observed:" << incoming_ack.largest_observed | |
| 886 << " last_received:" << last_header_.packet_number; | |
| 887 return "Invalid entropy."; | |
| 888 } | |
| 889 } else { | |
| 890 if (!incoming_ack.packets.Empty() && | |
| 891 incoming_ack.packets.Max() != incoming_ack.largest_observed) { | |
| 892 QUIC_BUG << ENDPOINT | |
| 893 << "Peer last received packet: " << incoming_ack.packets.Max() | |
| 894 << " which is not equal to largest observed: " | |
| 895 << incoming_ack.largest_observed; | |
| 896 return "Last received packet not equal to largest observed."; | |
| 897 } | |
| 898 } | |
| 899 | |
| 900 return nullptr; | |
| 901 } | |
| 902 | |
| 903 const char* QuicConnection::ValidateStopWaitingFrame( | |
| 904 const QuicStopWaitingFrame& stop_waiting) { | |
| 905 if (stop_waiting.least_unacked < | |
| 906 received_packet_manager_.peer_least_packet_awaiting_ack()) { | |
| 907 DLOG(ERROR) << ENDPOINT << "Peer's sent low least_unacked: " | |
| 908 << stop_waiting.least_unacked << " vs " | |
| 909 << received_packet_manager_.peer_least_packet_awaiting_ack(); | |
| 910 // We never process old ack frames, so this number should only increase. | |
| 911 return "Least unacked too small."; | |
| 912 } | |
| 913 | |
| 914 if (stop_waiting.least_unacked > last_header_.packet_number) { | |
| 915 DLOG(ERROR) << ENDPOINT | |
| 916 << "Peer sent least_unacked:" << stop_waiting.least_unacked | |
| 917 << " greater than the enclosing packet number:" | |
| 918 << last_header_.packet_number; | |
| 919 return "Least unacked too large."; | |
| 920 } | |
| 921 | |
| 922 return nullptr; | |
| 923 } | |
| 924 | |
| 925 bool QuicConnection::OnRstStreamFrame(const QuicRstStreamFrame& frame) { | |
| 926 DCHECK(connected_); | |
| 927 if (debug_visitor_ != nullptr) { | |
| 928 debug_visitor_->OnRstStreamFrame(frame); | |
| 929 } | |
| 930 DVLOG(1) << ENDPOINT | |
| 931 << "RST_STREAM_FRAME received for stream: " << frame.stream_id | |
| 932 << " with error: " | |
| 933 << QuicUtils::StreamErrorToString(frame.error_code); | |
| 934 visitor_->OnRstStream(frame); | |
| 935 visitor_->PostProcessAfterData(); | |
| 936 should_last_packet_instigate_acks_ = true; | |
| 937 return connected_; | |
| 938 } | |
| 939 | |
| 940 bool QuicConnection::OnConnectionCloseFrame( | |
| 941 const QuicConnectionCloseFrame& frame) { | |
| 942 DCHECK(connected_); | |
| 943 if (debug_visitor_ != nullptr) { | |
| 944 debug_visitor_->OnConnectionCloseFrame(frame); | |
| 945 } | |
| 946 DVLOG(1) << ENDPOINT | |
| 947 << "Received ConnectionClose for connection: " << connection_id() | |
| 948 << ", with error: " << QuicUtils::ErrorToString(frame.error_code) | |
| 949 << " (" << frame.error_details << ")"; | |
| 950 TearDownLocalConnectionState(frame.error_code, frame.error_details, | |
| 951 ConnectionCloseSource::FROM_PEER); | |
| 952 return connected_; | |
| 953 } | |
| 954 | |
| 955 bool QuicConnection::OnGoAwayFrame(const QuicGoAwayFrame& frame) { | |
| 956 DCHECK(connected_); | |
| 957 if (debug_visitor_ != nullptr) { | |
| 958 debug_visitor_->OnGoAwayFrame(frame); | |
| 959 } | |
| 960 DVLOG(1) << ENDPOINT << "GOAWAY_FRAME received with last good stream: " | |
| 961 << frame.last_good_stream_id | |
| 962 << " and error: " << QuicUtils::ErrorToString(frame.error_code) | |
| 963 << " and reason: " << frame.reason_phrase; | |
| 964 | |
| 965 goaway_received_ = true; | |
| 966 visitor_->OnGoAway(frame); | |
| 967 visitor_->PostProcessAfterData(); | |
| 968 should_last_packet_instigate_acks_ = true; | |
| 969 return connected_; | |
| 970 } | |
| 971 | |
| 972 bool QuicConnection::OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) { | |
| 973 DCHECK(connected_); | |
| 974 if (debug_visitor_ != nullptr) { | |
| 975 debug_visitor_->OnWindowUpdateFrame(frame); | |
| 976 } | |
| 977 DVLOG(1) << ENDPOINT | |
| 978 << "WINDOW_UPDATE_FRAME received for stream: " << frame.stream_id | |
| 979 << " with byte offset: " << frame.byte_offset; | |
| 980 visitor_->OnWindowUpdateFrame(frame); | |
| 981 visitor_->PostProcessAfterData(); | |
| 982 should_last_packet_instigate_acks_ = true; | |
| 983 return connected_; | |
| 984 } | |
| 985 | |
| 986 bool QuicConnection::OnBlockedFrame(const QuicBlockedFrame& frame) { | |
| 987 DCHECK(connected_); | |
| 988 if (debug_visitor_ != nullptr) { | |
| 989 debug_visitor_->OnBlockedFrame(frame); | |
| 990 } | |
| 991 DVLOG(1) << ENDPOINT | |
| 992 << "BLOCKED_FRAME received for stream: " << frame.stream_id; | |
| 993 visitor_->OnBlockedFrame(frame); | |
| 994 visitor_->PostProcessAfterData(); | |
| 995 should_last_packet_instigate_acks_ = true; | |
| 996 return connected_; | |
| 997 } | |
| 998 | |
| 999 bool QuicConnection::OnPathCloseFrame(const QuicPathCloseFrame& frame) { | |
| 1000 DCHECK(connected_); | |
| 1001 if (debug_visitor_ != nullptr) { | |
| 1002 debug_visitor_->OnPathCloseFrame(frame); | |
| 1003 } | |
| 1004 DVLOG(1) << ENDPOINT | |
| 1005 << "PATH_CLOSE_FRAME received for path: " << frame.path_id; | |
| 1006 OnPathClosed(frame.path_id); | |
| 1007 return connected_; | |
| 1008 } | |
| 1009 | |
| 1010 void QuicConnection::OnPacketComplete() { | |
| 1011 // Don't do anything if this packet closed the connection. | |
| 1012 if (!connected_) { | |
| 1013 ClearLastFrames(); | |
| 1014 return; | |
| 1015 } | |
| 1016 | |
| 1017 DVLOG(1) << ENDPOINT << "Got packet " << last_header_.packet_number << " for " | |
| 1018 << last_header_.public_header.connection_id; | |
| 1019 | |
| 1020 // An ack will be sent if a missing retransmittable packet was received; | |
| 1021 const bool was_missing = | |
| 1022 should_last_packet_instigate_acks_ && | |
| 1023 received_packet_manager_.IsMissing(last_header_.packet_number); | |
| 1024 | |
| 1025 // Record received to populate ack info correctly before processing stream | |
| 1026 // frames, since the processing may result in a response packet with a bundled | |
| 1027 // ack. | |
| 1028 received_packet_manager_.RecordPacketReceived(last_size_, last_header_, | |
| 1029 time_of_last_received_packet_); | |
| 1030 | |
| 1031 // Process stop waiting frames here, instead of inline, because the packet | |
| 1032 // needs to be considered 'received' before the entropy can be updated. | |
| 1033 if (last_stop_waiting_frame_.least_unacked > 0) { | |
| 1034 ProcessStopWaitingFrame(last_stop_waiting_frame_); | |
| 1035 if (!connected_) { | |
| 1036 return; | |
| 1037 } | |
| 1038 } | |
| 1039 | |
| 1040 MaybeQueueAck(was_missing); | |
| 1041 | |
| 1042 ClearLastFrames(); | |
| 1043 MaybeCloseIfTooManyOutstandingPackets(); | |
| 1044 } | |
| 1045 | |
| 1046 void QuicConnection::MaybeQueueAck(bool was_missing) { | |
| 1047 ++num_packets_received_since_last_ack_sent_; | |
| 1048 // Always send an ack every 20 packets in order to allow the peer to discard | |
| 1049 // information from the SentPacketManager and provide an RTT measurement. | |
| 1050 if (num_packets_received_since_last_ack_sent_ >= | |
| 1051 kMaxPacketsReceivedBeforeAckSend) { | |
| 1052 ack_queued_ = true; | |
| 1053 } | |
| 1054 | |
| 1055 // Determine whether the newly received packet was missing before recording | |
| 1056 // the received packet. | |
| 1057 // Ack decimation with reordering relies on the timer to send an ack, but if | |
| 1058 // missing packets we reported in the previous ack, send an ack immediately. | |
| 1059 if (was_missing && (ack_mode_ != ACK_DECIMATION_WITH_REORDERING || | |
| 1060 last_ack_had_missing_packets_)) { | |
| 1061 ack_queued_ = true; | |
| 1062 } | |
| 1063 | |
| 1064 if (should_last_packet_instigate_acks_ && !ack_queued_) { | |
| 1065 ++num_retransmittable_packets_received_since_last_ack_sent_; | |
| 1066 if (ack_mode_ != TCP_ACKING && | |
| 1067 last_header_.packet_number > kMinReceivedBeforeAckDecimation) { | |
| 1068 // Ack up to 10 packets at once. | |
| 1069 if (num_retransmittable_packets_received_since_last_ack_sent_ >= | |
| 1070 kMaxRetransmittablePacketsBeforeAck) { | |
| 1071 ack_queued_ = true; | |
| 1072 } else if (!ack_alarm_->IsSet()) { | |
| 1073 // Wait the minimum of a quarter min_rtt and the delayed ack time. | |
| 1074 QuicTime::Delta ack_delay = std::min( | |
| 1075 DelayedAckTime(), sent_packet_manager_->GetRttStats()->min_rtt() * | |
| 1076 ack_decimation_delay_); | |
| 1077 ack_alarm_->Set(clock_->ApproximateNow() + ack_delay); | |
| 1078 } | |
| 1079 } else { | |
| 1080 // Ack with a timer or every 2 packets by default. | |
| 1081 if (num_retransmittable_packets_received_since_last_ack_sent_ >= | |
| 1082 kDefaultRetransmittablePacketsBeforeAck) { | |
| 1083 ack_queued_ = true; | |
| 1084 } else if (!ack_alarm_->IsSet()) { | |
| 1085 ack_alarm_->Set(clock_->ApproximateNow() + DelayedAckTime()); | |
| 1086 } | |
| 1087 } | |
| 1088 | |
| 1089 // If there are new missing packets to report, send an ack immediately. | |
| 1090 if (received_packet_manager_.HasNewMissingPackets()) { | |
| 1091 if (ack_mode_ == ACK_DECIMATION_WITH_REORDERING) { | |
| 1092 // Wait the minimum of an eighth min_rtt and the existing ack time. | |
| 1093 QuicTime ack_time = | |
| 1094 clock_->ApproximateNow() + | |
| 1095 0.125 * sent_packet_manager_->GetRttStats()->min_rtt(); | |
| 1096 if (!ack_alarm_->IsSet() || ack_alarm_->deadline() > ack_time) { | |
| 1097 ack_alarm_->Update(ack_time, QuicTime::Delta::Zero()); | |
| 1098 } | |
| 1099 } else { | |
| 1100 ack_queued_ = true; | |
| 1101 } | |
| 1102 } | |
| 1103 } | |
| 1104 | |
| 1105 if (ack_queued_) { | |
| 1106 ack_alarm_->Cancel(); | |
| 1107 } | |
| 1108 } | |
| 1109 | |
| 1110 void QuicConnection::ClearLastFrames() { | |
| 1111 should_last_packet_instigate_acks_ = false; | |
| 1112 last_stop_waiting_frame_.least_unacked = 0; | |
| 1113 } | |
| 1114 | |
| 1115 void QuicConnection::MaybeCloseIfTooManyOutstandingPackets() { | |
| 1116 if (version() > QUIC_VERSION_33) { | |
| 1117 return; | |
| 1118 } | |
| 1119 // This occurs if we don't discard old packets we've sent fast enough. | |
| 1120 // It's possible largest observed is less than least unacked. | |
| 1121 if (sent_packet_manager_->GetLargestObserved(last_header_.path_id) > | |
| 1122 (sent_packet_manager_->GetLeastUnacked(last_header_.path_id) + | |
| 1123 kMaxTrackedPackets)) { | |
| 1124 CloseConnection( | |
| 1125 QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS, | |
| 1126 StringPrintf("More than %" PRIu64 " outstanding.", kMaxTrackedPackets), | |
| 1127 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); | |
| 1128 } | |
| 1129 // This occurs if there are received packet gaps and the peer does not raise | |
| 1130 // the least unacked fast enough. | |
| 1131 if (received_packet_manager_.NumTrackedPackets() > kMaxTrackedPackets) { | |
| 1132 CloseConnection( | |
| 1133 QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS, | |
| 1134 StringPrintf("More than %" PRIu64 " outstanding.", kMaxTrackedPackets), | |
| 1135 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); | |
| 1136 } | |
| 1137 } | |
| 1138 | |
| 1139 const QuicFrame QuicConnection::GetUpdatedAckFrame() { | |
| 1140 return received_packet_manager_.GetUpdatedAckFrame(clock_->ApproximateNow()); | |
| 1141 } | |
| 1142 | |
| 1143 void QuicConnection::PopulateStopWaitingFrame( | |
| 1144 QuicStopWaitingFrame* stop_waiting) { | |
| 1145 stop_waiting->least_unacked = GetLeastUnacked(stop_waiting->path_id); | |
| 1146 if (version() <= QUIC_VERSION_33) { | |
| 1147 stop_waiting->entropy_hash = sent_entropy_manager_.GetCumulativeEntropy( | |
| 1148 stop_waiting->least_unacked - 1); | |
| 1149 } | |
| 1150 } | |
| 1151 | |
| 1152 QuicPacketNumber QuicConnection::GetLeastUnacked(QuicPathId path_id) const { | |
| 1153 return sent_packet_manager_->GetLeastUnacked(path_id); | |
| 1154 } | |
| 1155 | |
| 1156 void QuicConnection::MaybeSendInResponseToPacket() { | |
| 1157 if (!connected_) { | |
| 1158 return; | |
| 1159 } | |
| 1160 // Now that we have received an ack, we might be able to send packets which | |
| 1161 // are queued locally, or drain streams which are blocked. | |
| 1162 if (defer_send_in_response_to_packets_) { | |
| 1163 send_alarm_->Update(clock_->ApproximateNow(), QuicTime::Delta::Zero()); | |
| 1164 } else { | |
| 1165 WriteAndBundleAcksIfNotBlocked(); | |
| 1166 } | |
| 1167 } | |
| 1168 | |
| 1169 void QuicConnection::SendVersionNegotiationPacket() { | |
| 1170 // TODO(alyssar): implement zero server state negotiation. | |
| 1171 pending_version_negotiation_packet_ = true; | |
| 1172 if (writer_->IsWriteBlocked()) { | |
| 1173 visitor_->OnWriteBlocked(); | |
| 1174 return; | |
| 1175 } | |
| 1176 DVLOG(1) << ENDPOINT << "Sending version negotiation packet: {" | |
| 1177 << QuicVersionVectorToString(framer_.supported_versions()) << "}"; | |
| 1178 std::unique_ptr<QuicEncryptedPacket> version_packet( | |
| 1179 packet_generator_.SerializeVersionNegotiationPacket( | |
| 1180 framer_.supported_versions())); | |
| 1181 WriteResult result = writer_->WritePacket( | |
| 1182 version_packet->data(), version_packet->length(), | |
| 1183 self_address().address(), peer_address(), per_packet_options_); | |
| 1184 | |
| 1185 if (result.status == WRITE_STATUS_ERROR) { | |
| 1186 OnWriteError(result.error_code); | |
| 1187 return; | |
| 1188 } | |
| 1189 if (result.status == WRITE_STATUS_BLOCKED) { | |
| 1190 visitor_->OnWriteBlocked(); | |
| 1191 if (writer_->IsWriteBlockedDataBuffered()) { | |
| 1192 pending_version_negotiation_packet_ = false; | |
| 1193 } | |
| 1194 return; | |
| 1195 } | |
| 1196 | |
| 1197 pending_version_negotiation_packet_ = false; | |
| 1198 } | |
| 1199 | |
| 1200 QuicConsumedData QuicConnection::SendStreamData( | |
| 1201 QuicStreamId id, | |
| 1202 QuicIOVector iov, | |
| 1203 QuicStreamOffset offset, | |
| 1204 bool fin, | |
| 1205 QuicAckListenerInterface* listener) { | |
| 1206 if (!fin && iov.total_length == 0) { | |
| 1207 QUIC_BUG << "Attempt to send empty stream frame"; | |
| 1208 return QuicConsumedData(0, false); | |
| 1209 } | |
| 1210 | |
| 1211 // Opportunistically bundle an ack with every outgoing packet. | |
| 1212 // Particularly, we want to bundle with handshake packets since we don't know | |
| 1213 // which decrypter will be used on an ack packet following a handshake | |
| 1214 // packet (a handshake packet from client to server could result in a REJ or a | |
| 1215 // SHLO from the server, leading to two different decrypters at the server.) | |
| 1216 ScopedRetransmissionScheduler alarm_delayer(this); | |
| 1217 ScopedPacketBundler ack_bundler(this, SEND_ACK_IF_PENDING); | |
| 1218 // The optimized path may be used for data only packets which fit into a | |
| 1219 // standard buffer and don't need padding. | |
| 1220 if (id != kCryptoStreamId && !packet_generator_.HasQueuedFrames() && | |
| 1221 iov.total_length > kMaxPacketSize) { | |
| 1222 // Use the fast path to send full data packets. | |
| 1223 return packet_generator_.ConsumeDataFastPath(id, iov, offset, fin, | |
| 1224 listener); | |
| 1225 } | |
| 1226 return packet_generator_.ConsumeData(id, iov, offset, fin, listener); | |
| 1227 } | |
| 1228 | |
| 1229 void QuicConnection::SendRstStream(QuicStreamId id, | |
| 1230 QuicRstStreamErrorCode error, | |
| 1231 QuicStreamOffset bytes_written) { | |
| 1232 // Opportunistically bundle an ack with this outgoing packet. | |
| 1233 ScopedPacketBundler ack_bundler(this, SEND_ACK_IF_PENDING); | |
| 1234 packet_generator_.AddControlFrame(QuicFrame(new QuicRstStreamFrame( | |
| 1235 id, AdjustErrorForVersion(error, version()), bytes_written))); | |
| 1236 | |
| 1237 if (error == QUIC_STREAM_NO_ERROR) { | |
| 1238 // All data for streams which are reset with QUIC_STREAM_NO_ERROR must | |
| 1239 // be received by the peer. | |
| 1240 return; | |
| 1241 } | |
| 1242 | |
| 1243 sent_packet_manager_->CancelRetransmissionsForStream(id); | |
| 1244 // Remove all queued packets which only contain data for the reset stream. | |
| 1245 QueuedPacketList::iterator packet_iterator = queued_packets_.begin(); | |
| 1246 while (packet_iterator != queued_packets_.end()) { | |
| 1247 QuicFrames* retransmittable_frames = | |
| 1248 &packet_iterator->retransmittable_frames; | |
| 1249 if (retransmittable_frames->empty()) { | |
| 1250 ++packet_iterator; | |
| 1251 continue; | |
| 1252 } | |
| 1253 QuicUtils::RemoveFramesForStream(retransmittable_frames, id); | |
| 1254 if (!retransmittable_frames->empty()) { | |
| 1255 ++packet_iterator; | |
| 1256 continue; | |
| 1257 } | |
| 1258 delete[] packet_iterator->encrypted_buffer; | |
| 1259 QuicUtils::ClearSerializedPacket(&(*packet_iterator)); | |
| 1260 packet_iterator = queued_packets_.erase(packet_iterator); | |
| 1261 } | |
| 1262 } | |
| 1263 | |
| 1264 void QuicConnection::SendWindowUpdate(QuicStreamId id, | |
| 1265 QuicStreamOffset byte_offset) { | |
| 1266 // Opportunistically bundle an ack with this outgoing packet. | |
| 1267 ScopedPacketBundler ack_bundler(this, SEND_ACK_IF_PENDING); | |
| 1268 packet_generator_.AddControlFrame( | |
| 1269 QuicFrame(new QuicWindowUpdateFrame(id, byte_offset))); | |
| 1270 } | |
| 1271 | |
| 1272 void QuicConnection::SendBlocked(QuicStreamId id) { | |
| 1273 // Opportunistically bundle an ack with this outgoing packet. | |
| 1274 ScopedPacketBundler ack_bundler(this, SEND_ACK_IF_PENDING); | |
| 1275 packet_generator_.AddControlFrame(QuicFrame(new QuicBlockedFrame(id))); | |
| 1276 } | |
| 1277 | |
| 1278 void QuicConnection::SendPathClose(QuicPathId path_id) { | |
| 1279 // Opportunistically bundle an ack with this outgoing packet. | |
| 1280 ScopedPacketBundler ack_bundler(this, SEND_ACK_IF_PENDING); | |
| 1281 packet_generator_.AddControlFrame(QuicFrame(new QuicPathCloseFrame(path_id))); | |
| 1282 OnPathClosed(path_id); | |
| 1283 } | |
| 1284 | |
| 1285 const QuicConnectionStats& QuicConnection::GetStats() { | |
| 1286 const RttStats* rtt_stats = sent_packet_manager_->GetRttStats(); | |
| 1287 | |
| 1288 // Update rtt and estimated bandwidth. | |
| 1289 QuicTime::Delta min_rtt = rtt_stats->min_rtt(); | |
| 1290 if (min_rtt.IsZero()) { | |
| 1291 // If min RTT has not been set, use initial RTT instead. | |
| 1292 min_rtt = QuicTime::Delta::FromMicroseconds(rtt_stats->initial_rtt_us()); | |
| 1293 } | |
| 1294 stats_.min_rtt_us = min_rtt.ToMicroseconds(); | |
| 1295 | |
| 1296 QuicTime::Delta srtt = rtt_stats->smoothed_rtt(); | |
| 1297 if (srtt.IsZero()) { | |
| 1298 // If SRTT has not been set, use initial RTT instead. | |
| 1299 srtt = QuicTime::Delta::FromMicroseconds(rtt_stats->initial_rtt_us()); | |
| 1300 } | |
| 1301 stats_.srtt_us = srtt.ToMicroseconds(); | |
| 1302 | |
| 1303 stats_.estimated_bandwidth = sent_packet_manager_->BandwidthEstimate(); | |
| 1304 stats_.max_packet_size = packet_generator_.GetCurrentMaxPacketLength(); | |
| 1305 stats_.max_received_packet_size = largest_received_packet_size_; | |
| 1306 return stats_; | |
| 1307 } | |
| 1308 | |
| 1309 void QuicConnection::ProcessUdpPacket(const IPEndPoint& self_address, | |
| 1310 const IPEndPoint& peer_address, | |
| 1311 const QuicReceivedPacket& packet) { | |
| 1312 if (!connected_) { | |
| 1313 return; | |
| 1314 } | |
| 1315 if (debug_visitor_ != nullptr) { | |
| 1316 debug_visitor_->OnPacketReceived(self_address, peer_address, packet); | |
| 1317 } | |
| 1318 last_size_ = packet.length(); | |
| 1319 current_packet_data_ = packet.data(); | |
| 1320 | |
| 1321 last_packet_destination_address_ = self_address; | |
| 1322 last_packet_source_address_ = peer_address; | |
| 1323 if (!IsInitializedIPEndPoint(self_address_)) { | |
| 1324 self_address_ = last_packet_destination_address_; | |
| 1325 } | |
| 1326 if (!IsInitializedIPEndPoint(peer_address_)) { | |
| 1327 peer_address_ = last_packet_source_address_; | |
| 1328 } | |
| 1329 | |
| 1330 stats_.bytes_received += packet.length(); | |
| 1331 ++stats_.packets_received; | |
| 1332 | |
| 1333 time_of_last_received_packet_ = packet.receipt_time(); | |
| 1334 DVLOG(1) << ENDPOINT << "time of last received packet: " | |
| 1335 << time_of_last_received_packet_.ToDebuggingValue(); | |
| 1336 | |
| 1337 ScopedRetransmissionScheduler alarm_delayer(this); | |
| 1338 if (!framer_.ProcessPacket(packet)) { | |
| 1339 // If we are unable to decrypt this packet, it might be | |
| 1340 // because the CHLO or SHLO packet was lost. | |
| 1341 if (framer_.error() == QUIC_DECRYPTION_FAILURE) { | |
| 1342 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE && | |
| 1343 undecryptable_packets_.size() < max_undecryptable_packets_) { | |
| 1344 QueueUndecryptablePacket(packet); | |
| 1345 } else if (debug_visitor_ != nullptr) { | |
| 1346 debug_visitor_->OnUndecryptablePacket(); | |
| 1347 } | |
| 1348 } | |
| 1349 DVLOG(1) << ENDPOINT << "Unable to process packet. Last packet processed: " | |
| 1350 << last_header_.packet_number; | |
| 1351 current_packet_data_ = nullptr; | |
| 1352 return; | |
| 1353 } | |
| 1354 | |
| 1355 ++stats_.packets_processed; | |
| 1356 if (active_peer_migration_type_ != NO_CHANGE && | |
| 1357 sent_packet_manager_->GetLargestObserved(last_header_.path_id) > | |
| 1358 highest_packet_sent_before_peer_migration_) { | |
| 1359 OnPeerMigrationValidated(last_header_.path_id); | |
| 1360 } | |
| 1361 MaybeProcessUndecryptablePackets(); | |
| 1362 MaybeSendInResponseToPacket(); | |
| 1363 SetPingAlarm(); | |
| 1364 current_packet_data_ = nullptr; | |
| 1365 } | |
| 1366 | |
| 1367 void QuicConnection::OnCanWrite() { | |
| 1368 DCHECK(!writer_->IsWriteBlocked()); | |
| 1369 | |
| 1370 WriteQueuedPackets(); | |
| 1371 WritePendingRetransmissions(); | |
| 1372 | |
| 1373 // Sending queued packets may have caused the socket to become write blocked, | |
| 1374 // or the congestion manager to prohibit sending. If we've sent everything | |
| 1375 // we had queued and we're still not blocked, let the visitor know it can | |
| 1376 // write more. | |
| 1377 if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) { | |
| 1378 return; | |
| 1379 } | |
| 1380 | |
| 1381 { | |
| 1382 ScopedPacketBundler bundler(this, SEND_ACK_IF_QUEUED); | |
| 1383 visitor_->OnCanWrite(); | |
| 1384 visitor_->PostProcessAfterData(); | |
| 1385 } | |
| 1386 | |
| 1387 // After the visitor writes, it may have caused the socket to become write | |
| 1388 // blocked or the congestion manager to prohibit sending, so check again. | |
| 1389 if (visitor_->WillingAndAbleToWrite() && !resume_writes_alarm_->IsSet() && | |
| 1390 CanWrite(HAS_RETRANSMITTABLE_DATA)) { | |
| 1391 // We're not write blocked, but some stream didn't write out all of its | |
| 1392 // bytes. Register for 'immediate' resumption so we'll keep writing after | |
| 1393 // other connections and events have had a chance to use the thread. | |
| 1394 resume_writes_alarm_->Set(clock_->ApproximateNow()); | |
| 1395 } | |
| 1396 } | |
| 1397 | |
| 1398 void QuicConnection::WriteIfNotBlocked() { | |
| 1399 if (!writer_->IsWriteBlocked()) { | |
| 1400 OnCanWrite(); | |
| 1401 } | |
| 1402 } | |
| 1403 | |
| 1404 void QuicConnection::WriteAndBundleAcksIfNotBlocked() { | |
| 1405 if (!writer_->IsWriteBlocked()) { | |
| 1406 ScopedPacketBundler bundler(this, SEND_ACK_IF_QUEUED); | |
| 1407 OnCanWrite(); | |
| 1408 } | |
| 1409 } | |
| 1410 | |
| 1411 bool QuicConnection::ProcessValidatedPacket(const QuicPacketHeader& header) { | |
| 1412 if (header.fec_flag) { | |
| 1413 // Drop any FEC packet. | |
| 1414 return false; | |
| 1415 } | |
| 1416 | |
| 1417 if (perspective_ == Perspective::IS_SERVER && | |
| 1418 IsInitializedIPEndPoint(self_address_) && | |
| 1419 IsInitializedIPEndPoint(last_packet_destination_address_) && | |
| 1420 (!(self_address_ == last_packet_destination_address_))) { | |
| 1421 CloseConnection(QUIC_ERROR_MIGRATING_ADDRESS, | |
| 1422 "Self address migration is not supported at the server.", | |
| 1423 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); | |
| 1424 return false; | |
| 1425 } | |
| 1426 | |
| 1427 if (!Near(header.packet_number, last_header_.packet_number)) { | |
| 1428 DVLOG(1) << ENDPOINT << "Packet " << header.packet_number | |
| 1429 << " out of bounds. Discarding"; | |
| 1430 CloseConnection(QUIC_INVALID_PACKET_HEADER, "packet number out of bounds.", | |
| 1431 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); | |
| 1432 return false; | |
| 1433 } | |
| 1434 | |
| 1435 if (version_negotiation_state_ != NEGOTIATED_VERSION) { | |
| 1436 if (perspective_ == Perspective::IS_SERVER) { | |
| 1437 if (!header.public_header.version_flag) { | |
| 1438 // Packets should have the version flag till version negotiation is | |
| 1439 // done. | |
| 1440 string error_details = | |
| 1441 StringPrintf("%s Packet %" PRIu64 | |
| 1442 " without version flag before version negotiated.", | |
| 1443 ENDPOINT, header.packet_number); | |
| 1444 DLOG(WARNING) << error_details; | |
| 1445 CloseConnection(QUIC_INVALID_VERSION, error_details, | |
| 1446 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); | |
| 1447 return false; | |
| 1448 } else { | |
| 1449 DCHECK_EQ(1u, header.public_header.versions.size()); | |
| 1450 DCHECK_EQ(header.public_header.versions[0], version()); | |
| 1451 version_negotiation_state_ = NEGOTIATED_VERSION; | |
| 1452 received_packet_manager_.SetVersion(version()); | |
| 1453 visitor_->OnSuccessfulVersionNegotiation(version()); | |
| 1454 if (debug_visitor_ != nullptr) { | |
| 1455 debug_visitor_->OnSuccessfulVersionNegotiation(version()); | |
| 1456 } | |
| 1457 } | |
| 1458 } else { | |
| 1459 DCHECK(!header.public_header.version_flag); | |
| 1460 // If the client gets a packet without the version flag from the server | |
| 1461 // it should stop sending version since the version negotiation is done. | |
| 1462 packet_generator_.StopSendingVersion(); | |
| 1463 version_negotiation_state_ = NEGOTIATED_VERSION; | |
| 1464 received_packet_manager_.SetVersion(version()); | |
| 1465 visitor_->OnSuccessfulVersionNegotiation(version()); | |
| 1466 if (debug_visitor_ != nullptr) { | |
| 1467 debug_visitor_->OnSuccessfulVersionNegotiation(version()); | |
| 1468 } | |
| 1469 } | |
| 1470 } | |
| 1471 | |
| 1472 DCHECK_EQ(NEGOTIATED_VERSION, version_negotiation_state_); | |
| 1473 | |
| 1474 if (last_size_ > largest_received_packet_size_) { | |
| 1475 largest_received_packet_size_ = last_size_; | |
| 1476 } | |
| 1477 | |
| 1478 if (perspective_ == Perspective::IS_SERVER && | |
| 1479 encryption_level_ == ENCRYPTION_NONE && | |
| 1480 last_size_ > packet_generator_.GetCurrentMaxPacketLength()) { | |
| 1481 SetMaxPacketLength(last_size_); | |
| 1482 } | |
| 1483 return true; | |
| 1484 } | |
| 1485 | |
| 1486 void QuicConnection::WriteQueuedPackets() { | |
| 1487 DCHECK(!writer_->IsWriteBlocked()); | |
| 1488 | |
| 1489 if (pending_version_negotiation_packet_) { | |
| 1490 SendVersionNegotiationPacket(); | |
| 1491 } | |
| 1492 | |
| 1493 QueuedPacketList::iterator packet_iterator = queued_packets_.begin(); | |
| 1494 while (packet_iterator != queued_packets_.end() && | |
| 1495 WritePacket(&(*packet_iterator))) { | |
| 1496 delete[] packet_iterator->encrypted_buffer; | |
| 1497 QuicUtils::ClearSerializedPacket(&(*packet_iterator)); | |
| 1498 packet_iterator = queued_packets_.erase(packet_iterator); | |
| 1499 } | |
| 1500 } | |
| 1501 | |
| 1502 void QuicConnection::WritePendingRetransmissions() { | |
| 1503 // Keep writing as long as there's a pending retransmission which can be | |
| 1504 // written. | |
| 1505 while (sent_packet_manager_->HasPendingRetransmissions()) { | |
| 1506 const PendingRetransmission pending = | |
| 1507 sent_packet_manager_->NextPendingRetransmission(); | |
| 1508 if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) { | |
| 1509 break; | |
| 1510 } | |
| 1511 | |
| 1512 // Re-packetize the frames with a new packet number for retransmission. | |
| 1513 // Retransmitted packets use the same packet number length as the | |
| 1514 // original. | |
| 1515 // Flush the packet generator before making a new packet. | |
| 1516 // TODO(ianswett): Implement ReserializeAllFrames as a separate path that | |
| 1517 // does not require the creator to be flushed. | |
| 1518 packet_generator_.FlushAllQueuedFrames(); | |
| 1519 char buffer[kMaxPacketSize]; | |
| 1520 packet_generator_.ReserializeAllFrames(pending, buffer, kMaxPacketSize); | |
| 1521 } | |
| 1522 } | |
| 1523 | |
| 1524 void QuicConnection::RetransmitUnackedPackets( | |
| 1525 TransmissionType retransmission_type) { | |
| 1526 sent_packet_manager_->RetransmitUnackedPackets(retransmission_type); | |
| 1527 | |
| 1528 WriteIfNotBlocked(); | |
| 1529 } | |
| 1530 | |
| 1531 void QuicConnection::NeuterUnencryptedPackets() { | |
| 1532 sent_packet_manager_->NeuterUnencryptedPackets(); | |
| 1533 // This may have changed the retransmission timer, so re-arm it. | |
| 1534 SetRetransmissionAlarm(); | |
| 1535 } | |
| 1536 | |
| 1537 bool QuicConnection::ShouldGeneratePacket( | |
| 1538 HasRetransmittableData retransmittable, | |
| 1539 IsHandshake handshake) { | |
| 1540 // We should serialize handshake packets immediately to ensure that they | |
| 1541 // end up sent at the right encryption level. | |
| 1542 if (handshake == IS_HANDSHAKE) { | |
| 1543 return true; | |
| 1544 } | |
| 1545 | |
| 1546 return CanWrite(retransmittable); | |
| 1547 } | |
| 1548 | |
| 1549 bool QuicConnection::CanWrite(HasRetransmittableData retransmittable) { | |
| 1550 if (!connected_) { | |
| 1551 return false; | |
| 1552 } | |
| 1553 | |
| 1554 if (writer_->IsWriteBlocked()) { | |
| 1555 visitor_->OnWriteBlocked(); | |
| 1556 return false; | |
| 1557 } | |
| 1558 | |
| 1559 // Allow acks to be sent immediately. | |
| 1560 // TODO(ianswett): Remove retransmittable from | |
| 1561 // SendAlgorithmInterface::TimeUntilSend. | |
| 1562 if (retransmittable == NO_RETRANSMITTABLE_DATA) { | |
| 1563 return true; | |
| 1564 } | |
| 1565 // If the send alarm is set, wait for it to fire. | |
| 1566 if (send_alarm_->IsSet()) { | |
| 1567 return false; | |
| 1568 } | |
| 1569 | |
| 1570 // TODO(fayang): If delay is not infinite, the next packet will be created and | |
| 1571 // sent on path_id. | |
| 1572 QuicPathId path_id = kInvalidPathId; | |
| 1573 QuicTime now = clock_->Now(); | |
| 1574 QuicTime::Delta delay = | |
| 1575 sent_packet_manager_->TimeUntilSend(now, retransmittable, &path_id); | |
| 1576 if (delay.IsInfinite()) { | |
| 1577 DCHECK_EQ(kInvalidPathId, path_id); | |
| 1578 send_alarm_->Cancel(); | |
| 1579 return false; | |
| 1580 } | |
| 1581 | |
| 1582 DCHECK_NE(kInvalidPathId, path_id); | |
| 1583 // If the scheduler requires a delay, then we can not send this packet now. | |
| 1584 if (!delay.IsZero()) { | |
| 1585 send_alarm_->Update(now + delay, QuicTime::Delta::FromMilliseconds(1)); | |
| 1586 DVLOG(1) << ENDPOINT << "Delaying sending " << delay.ToMilliseconds() | |
| 1587 << "ms"; | |
| 1588 return false; | |
| 1589 } | |
| 1590 return true; | |
| 1591 } | |
| 1592 | |
| 1593 bool QuicConnection::WritePacket(SerializedPacket* packet) { | |
| 1594 if (packet->packet_number < | |
| 1595 sent_packet_manager_->GetLargestSentPacket(packet->path_id)) { | |
| 1596 QUIC_BUG << "Attempt to write packet:" << packet->packet_number << " after:" | |
| 1597 << sent_packet_manager_->GetLargestSentPacket(packet->path_id); | |
| 1598 CloseConnection(QUIC_INTERNAL_ERROR, "Packet written out of order.", | |
| 1599 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); | |
| 1600 return true; | |
| 1601 } | |
| 1602 if (ShouldDiscardPacket(*packet)) { | |
| 1603 ++stats_.packets_discarded; | |
| 1604 return true; | |
| 1605 } | |
| 1606 // Termination packets are encrypted and saved, so don't exit early. | |
| 1607 const bool is_termination_packet = IsTerminationPacket(*packet); | |
| 1608 if (writer_->IsWriteBlocked() && !is_termination_packet) { | |
| 1609 return false; | |
| 1610 } | |
| 1611 | |
| 1612 QuicPacketNumber packet_number = packet->packet_number; | |
| 1613 DCHECK_LE(packet_number_of_last_sent_packet_, packet_number); | |
| 1614 packet_number_of_last_sent_packet_ = packet_number; | |
| 1615 | |
| 1616 QuicPacketLength encrypted_length = packet->encrypted_length; | |
| 1617 // Termination packets are eventually owned by TimeWaitListManager. | |
| 1618 // Others are deleted at the end of this call. | |
| 1619 if (is_termination_packet) { | |
| 1620 if (termination_packets_.get() == nullptr) { | |
| 1621 termination_packets_.reset( | |
| 1622 new std::vector<std::unique_ptr<QuicEncryptedPacket>>); | |
| 1623 } | |
| 1624 // Copy the buffer so it's owned in the future. | |
| 1625 char* buffer_copy = QuicUtils::CopyBuffer(*packet); | |
| 1626 termination_packets_->push_back(std::unique_ptr<QuicEncryptedPacket>( | |
| 1627 new QuicEncryptedPacket(buffer_copy, encrypted_length, true))); | |
| 1628 // This assures we won't try to write *forced* packets when blocked. | |
| 1629 // Return true to stop processing. | |
| 1630 if (writer_->IsWriteBlocked()) { | |
| 1631 visitor_->OnWriteBlocked(); | |
| 1632 return true; | |
| 1633 } | |
| 1634 } | |
| 1635 | |
| 1636 DCHECK_LE(encrypted_length, kMaxPacketSize); | |
| 1637 DCHECK_LE(encrypted_length, packet_generator_.GetCurrentMaxPacketLength()); | |
| 1638 DVLOG(1) << ENDPOINT << "Sending packet " << packet_number << " : " | |
| 1639 << (IsRetransmittable(*packet) == HAS_RETRANSMITTABLE_DATA | |
| 1640 ? "data bearing " | |
| 1641 : " ack only ") | |
| 1642 << ", encryption level: " | |
| 1643 << QuicUtils::EncryptionLevelToString(packet->encryption_level) | |
| 1644 << ", encrypted length:" << encrypted_length; | |
| 1645 DVLOG(2) << ENDPOINT << "packet(" << packet_number << "): " << std::endl | |
| 1646 << QuicUtils::HexDump( | |
| 1647 StringPiece(packet->encrypted_buffer, encrypted_length)); | |
| 1648 | |
| 1649 // Measure the RTT from before the write begins to avoid underestimating the | |
| 1650 // min_rtt_, especially in cases where the thread blocks or gets swapped out | |
| 1651 // during the WritePacket below. | |
| 1652 QuicTime packet_send_time = clock_->Now(); | |
| 1653 WriteResult result = writer_->WritePacket( | |
| 1654 packet->encrypted_buffer, encrypted_length, self_address().address(), | |
| 1655 peer_address(), per_packet_options_); | |
| 1656 if (result.error_code == ERR_IO_PENDING) { | |
| 1657 DCHECK_EQ(WRITE_STATUS_BLOCKED, result.status); | |
| 1658 } | |
| 1659 | |
| 1660 if (result.status == WRITE_STATUS_BLOCKED) { | |
| 1661 visitor_->OnWriteBlocked(); | |
| 1662 // If the socket buffers the the data, then the packet should not | |
| 1663 // be queued and sent again, which would result in an unnecessary | |
| 1664 // duplicate packet being sent. The helper must call OnCanWrite | |
| 1665 // when the write completes, and OnWriteError if an error occurs. | |
| 1666 if (!writer_->IsWriteBlockedDataBuffered()) { | |
| 1667 return false; | |
| 1668 } | |
| 1669 } | |
| 1670 if (result.status != WRITE_STATUS_ERROR && debug_visitor_ != nullptr) { | |
| 1671 // Pass the write result to the visitor. | |
| 1672 debug_visitor_->OnPacketSent(*packet, packet->original_path_id, | |
| 1673 packet->original_packet_number, | |
| 1674 packet->transmission_type, packet_send_time); | |
| 1675 } | |
| 1676 if (packet->transmission_type == NOT_RETRANSMISSION) { | |
| 1677 time_of_last_sent_new_packet_ = packet_send_time; | |
| 1678 if (IsRetransmittable(*packet) == HAS_RETRANSMITTABLE_DATA && | |
| 1679 last_send_for_timeout_ <= time_of_last_received_packet_) { | |
| 1680 last_send_for_timeout_ = packet_send_time; | |
| 1681 } | |
| 1682 } | |
| 1683 SetPingAlarm(); | |
| 1684 MaybeSetMtuAlarm(); | |
| 1685 DVLOG(1) << ENDPOINT << "time we began writing last sent packet: " | |
| 1686 << packet_send_time.ToDebuggingValue(); | |
| 1687 | |
| 1688 if (!FLAGS_quic_simple_packet_number_length) { | |
| 1689 // TODO(ianswett): Change the packet number length and other packet creator | |
| 1690 // options by a more explicit API than setting a struct value directly, | |
| 1691 // perhaps via the NetworkChangeVisitor. | |
| 1692 packet_generator_.UpdateSequenceNumberLength( | |
| 1693 sent_packet_manager_->GetLeastPacketAwaitedByPeer(packet->path_id), | |
| 1694 sent_packet_manager_->EstimateMaxPacketsInFlight(max_packet_length())); | |
| 1695 } | |
| 1696 | |
| 1697 bool reset_retransmission_alarm = sent_packet_manager_->OnPacketSent( | |
| 1698 packet, packet->original_path_id, packet->original_packet_number, | |
| 1699 packet_send_time, packet->transmission_type, IsRetransmittable(*packet)); | |
| 1700 | |
| 1701 if (reset_retransmission_alarm || !retransmission_alarm_->IsSet()) { | |
| 1702 SetRetransmissionAlarm(); | |
| 1703 } | |
| 1704 | |
| 1705 if (FLAGS_quic_simple_packet_number_length) { | |
| 1706 // The packet number length must be updated after OnPacketSent, because it | |
| 1707 // may change the packet number length in packet. | |
| 1708 packet_generator_.UpdateSequenceNumberLength( | |
| 1709 sent_packet_manager_->GetLeastPacketAwaitedByPeer(packet->path_id), | |
| 1710 sent_packet_manager_->EstimateMaxPacketsInFlight(max_packet_length())); | |
| 1711 } | |
| 1712 | |
| 1713 stats_.bytes_sent += result.bytes_written; | |
| 1714 ++stats_.packets_sent; | |
| 1715 if (packet->transmission_type != NOT_RETRANSMISSION) { | |
| 1716 stats_.bytes_retransmitted += result.bytes_written; | |
| 1717 ++stats_.packets_retransmitted; | |
| 1718 } | |
| 1719 | |
| 1720 if (result.status == WRITE_STATUS_ERROR) { | |
| 1721 OnWriteError(result.error_code); | |
| 1722 DLOG(ERROR) << ENDPOINT << "failed writing " << encrypted_length | |
| 1723 << " bytes " | |
| 1724 << " from host " << (self_address().address().empty() | |
| 1725 ? " empty address " | |
| 1726 : self_address().ToStringWithoutPort()) | |
| 1727 << " to address " << peer_address().ToString(); | |
| 1728 return false; | |
| 1729 } | |
| 1730 | |
| 1731 return true; | |
| 1732 } | |
| 1733 | |
| 1734 bool QuicConnection::ShouldDiscardPacket(const SerializedPacket& packet) { | |
| 1735 if (!connected_) { | |
| 1736 DVLOG(1) << ENDPOINT << "Not sending packet as connection is disconnected."; | |
| 1737 return true; | |
| 1738 } | |
| 1739 | |
| 1740 QuicPacketNumber packet_number = packet.packet_number; | |
| 1741 if (encryption_level_ == ENCRYPTION_FORWARD_SECURE && | |
| 1742 packet.encryption_level == ENCRYPTION_NONE) { | |
| 1743 // Drop packets that are NULL encrypted since the peer won't accept them | |
| 1744 // anymore. | |
| 1745 DVLOG(1) << ENDPOINT << "Dropping NULL encrypted packet: " << packet_number | |
| 1746 << " since the connection is forward secure."; | |
| 1747 return true; | |
| 1748 } | |
| 1749 | |
| 1750 return false; | |
| 1751 } | |
| 1752 | |
| 1753 void QuicConnection::OnWriteError(int error_code) { | |
| 1754 const string error_details = "Write failed with error: " + | |
| 1755 base::IntToString(error_code) + " (" + | |
| 1756 ErrorToString(error_code) + ")"; | |
| 1757 DVLOG(1) << ENDPOINT << error_details; | |
| 1758 // We can't send an error as the socket is presumably borked. | |
| 1759 TearDownLocalConnectionState(QUIC_PACKET_WRITE_ERROR, error_details, | |
| 1760 ConnectionCloseSource::FROM_SELF); | |
| 1761 } | |
| 1762 | |
| 1763 void QuicConnection::OnSerializedPacket(SerializedPacket* serialized_packet) { | |
| 1764 DCHECK_NE(kInvalidPathId, serialized_packet->path_id); | |
| 1765 if (serialized_packet->encrypted_buffer == nullptr) { | |
| 1766 // We failed to serialize the packet, so close the connection. | |
| 1767 // TearDownLocalConnectionState does not send close packet, so no infinite | |
| 1768 // loop here. | |
| 1769 // TODO(ianswett): This is actually an internal error, not an | |
| 1770 // encryption failure. | |
| 1771 TearDownLocalConnectionState( | |
| 1772 QUIC_ENCRYPTION_FAILURE, | |
| 1773 "Serialized packet does not have an encrypted buffer.", | |
| 1774 ConnectionCloseSource::FROM_SELF); | |
| 1775 return; | |
| 1776 } | |
| 1777 SendOrQueuePacket(serialized_packet); | |
| 1778 } | |
| 1779 | |
| 1780 void QuicConnection::OnUnrecoverableError(QuicErrorCode error, | |
| 1781 const string& error_details, | |
| 1782 ConnectionCloseSource source) { | |
| 1783 // The packet creator or generator encountered an unrecoverable error: tear | |
| 1784 // down local connection state immediately. | |
| 1785 TearDownLocalConnectionState(error, error_details, source); | |
| 1786 } | |
| 1787 | |
| 1788 void QuicConnection::OnCongestionChange() { | |
| 1789 visitor_->OnCongestionWindowChange(clock_->ApproximateNow()); | |
| 1790 | |
| 1791 // Uses the connection's smoothed RTT. If zero, uses initial_rtt. | |
| 1792 QuicTime::Delta rtt = sent_packet_manager_->GetRttStats()->smoothed_rtt(); | |
| 1793 if (rtt.IsZero()) { | |
| 1794 rtt = QuicTime::Delta::FromMicroseconds( | |
| 1795 sent_packet_manager_->GetRttStats()->initial_rtt_us()); | |
| 1796 } | |
| 1797 | |
| 1798 if (debug_visitor_) | |
| 1799 debug_visitor_->OnRttChanged(rtt); | |
| 1800 } | |
| 1801 | |
| 1802 void QuicConnection::OnPathDegrading() { | |
| 1803 visitor_->OnPathDegrading(); | |
| 1804 } | |
| 1805 | |
| 1806 void QuicConnection::OnPathMtuIncreased(QuicPacketLength packet_size) { | |
| 1807 DCHECK(FLAGS_quic_no_mtu_discovery_ack_listener); | |
| 1808 if (packet_size > max_packet_length()) { | |
| 1809 SetMaxPacketLength(packet_size); | |
| 1810 } | |
| 1811 } | |
| 1812 | |
| 1813 void QuicConnection::OnHandshakeComplete() { | |
| 1814 sent_packet_manager_->SetHandshakeConfirmed(); | |
| 1815 // The client should immediately ack the SHLO to confirm the handshake is | |
| 1816 // complete with the server. | |
| 1817 if (perspective_ == Perspective::IS_CLIENT && !ack_queued_ && | |
| 1818 ack_frame_updated()) { | |
| 1819 ack_alarm_->Update(clock_->ApproximateNow(), QuicTime::Delta::Zero()); | |
| 1820 } | |
| 1821 } | |
| 1822 | |
| 1823 void QuicConnection::SendOrQueuePacket(SerializedPacket* packet) { | |
| 1824 // The caller of this function is responsible for checking CanWrite(). | |
| 1825 if (packet->encrypted_buffer == nullptr) { | |
| 1826 QUIC_BUG << "packet.encrypted_buffer == nullptr in to SendOrQueuePacket"; | |
| 1827 return; | |
| 1828 } | |
| 1829 if (version() <= QUIC_VERSION_33) { | |
| 1830 sent_entropy_manager_.RecordPacketEntropyHash(packet->packet_number, | |
| 1831 packet->entropy_hash); | |
| 1832 } | |
| 1833 // If there are already queued packets, queue this one immediately to ensure | |
| 1834 // it's written in sequence number order. | |
| 1835 if (!queued_packets_.empty() || !WritePacket(packet)) { | |
| 1836 // Take ownership of the underlying encrypted packet. | |
| 1837 packet->encrypted_buffer = QuicUtils::CopyBuffer(*packet); | |
| 1838 queued_packets_.push_back(*packet); | |
| 1839 packet->retransmittable_frames.clear(); | |
| 1840 } | |
| 1841 | |
| 1842 QuicUtils::ClearSerializedPacket(packet); | |
| 1843 // If a forward-secure encrypter is available but is not being used and the | |
| 1844 // next packet number is the first packet which requires | |
| 1845 // forward security, start using the forward-secure encrypter. | |
| 1846 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE && | |
| 1847 has_forward_secure_encrypter_ && | |
| 1848 packet->packet_number >= first_required_forward_secure_packet_ - 1) { | |
| 1849 SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); | |
| 1850 } | |
| 1851 } | |
| 1852 | |
| 1853 void QuicConnection::OnPingTimeout() { | |
| 1854 if (!retransmission_alarm_->IsSet()) { | |
| 1855 SendPing(); | |
| 1856 } | |
| 1857 } | |
| 1858 | |
| 1859 void QuicConnection::SendPing() { | |
| 1860 ScopedPacketBundler bundler(this, SEND_ACK_IF_QUEUED); | |
| 1861 packet_generator_.AddControlFrame(QuicFrame(QuicPingFrame())); | |
| 1862 // Send PING frame immediately, without checking for congestion window bounds. | |
| 1863 packet_generator_.FlushAllQueuedFrames(); | |
| 1864 } | |
| 1865 | |
| 1866 void QuicConnection::SendAck() { | |
| 1867 ack_alarm_->Cancel(); | |
| 1868 ack_queued_ = false; | |
| 1869 stop_waiting_count_ = 0; | |
| 1870 num_retransmittable_packets_received_since_last_ack_sent_ = 0; | |
| 1871 last_ack_had_missing_packets_ = received_packet_manager_.HasMissingPackets(); | |
| 1872 num_packets_received_since_last_ack_sent_ = 0; | |
| 1873 | |
| 1874 packet_generator_.SetShouldSendAck(true); | |
| 1875 } | |
| 1876 | |
| 1877 void QuicConnection::OnRetransmissionTimeout() { | |
| 1878 DCHECK(sent_packet_manager_->HasUnackedPackets()); | |
| 1879 | |
| 1880 if (close_connection_after_five_rtos_ && | |
| 1881 sent_packet_manager_->GetConsecutiveRtoCount() >= 4) { | |
| 1882 // Close on the 5th consecutive RTO, so after 4 previous RTOs have occurred. | |
| 1883 CloseConnection(QUIC_TOO_MANY_RTOS, "5 consecutive retransmission timeouts", | |
| 1884 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); | |
| 1885 return; | |
| 1886 } | |
| 1887 | |
| 1888 sent_packet_manager_->OnRetransmissionTimeout(); | |
| 1889 WriteIfNotBlocked(); | |
| 1890 | |
| 1891 // A write failure can result in the connection being closed, don't attempt to | |
| 1892 // write further packets, or to set alarms. | |
| 1893 if (!connected_) { | |
| 1894 return; | |
| 1895 } | |
| 1896 | |
| 1897 // In the TLP case, the SentPacketManager gives the connection the opportunity | |
| 1898 // to send new data before retransmitting. | |
| 1899 if (sent_packet_manager_->MaybeRetransmitTailLossProbe()) { | |
| 1900 // Send the pending retransmission now that it's been queued. | |
| 1901 WriteIfNotBlocked(); | |
| 1902 } | |
| 1903 | |
| 1904 // Ensure the retransmission alarm is always set if there are unacked packets | |
| 1905 // and nothing waiting to be sent. | |
| 1906 // This happens if the loss algorithm invokes a timer based loss, but the | |
| 1907 // packet doesn't need to be retransmitted. | |
| 1908 if (!HasQueuedData() && !retransmission_alarm_->IsSet()) { | |
| 1909 SetRetransmissionAlarm(); | |
| 1910 } | |
| 1911 } | |
| 1912 | |
| 1913 void QuicConnection::SetEncrypter(EncryptionLevel level, | |
| 1914 QuicEncrypter* encrypter) { | |
| 1915 packet_generator_.SetEncrypter(level, encrypter); | |
| 1916 if (level == ENCRYPTION_FORWARD_SECURE) { | |
| 1917 has_forward_secure_encrypter_ = true; | |
| 1918 first_required_forward_secure_packet_ = | |
| 1919 packet_number_of_last_sent_packet_ + | |
| 1920 // 3 times the current congestion window (in slow start) should cover | |
| 1921 // about two full round trips worth of packets, which should be | |
| 1922 // sufficient. | |
| 1923 3 * | |
| 1924 sent_packet_manager_->EstimateMaxPacketsInFlight( | |
| 1925 max_packet_length()); | |
| 1926 } | |
| 1927 } | |
| 1928 | |
| 1929 void QuicConnection::SetDiversificationNonce(const DiversificationNonce nonce) { | |
| 1930 DCHECK_EQ(Perspective::IS_SERVER, perspective_); | |
| 1931 packet_generator_.SetDiversificationNonce(nonce); | |
| 1932 } | |
| 1933 | |
| 1934 void QuicConnection::SetDefaultEncryptionLevel(EncryptionLevel level) { | |
| 1935 encryption_level_ = level; | |
| 1936 packet_generator_.set_encryption_level(level); | |
| 1937 } | |
| 1938 | |
| 1939 void QuicConnection::SetDecrypter(EncryptionLevel level, | |
| 1940 QuicDecrypter* decrypter) { | |
| 1941 framer_.SetDecrypter(level, decrypter); | |
| 1942 } | |
| 1943 | |
| 1944 void QuicConnection::SetAlternativeDecrypter(EncryptionLevel level, | |
| 1945 QuicDecrypter* decrypter, | |
| 1946 bool latch_once_used) { | |
| 1947 framer_.SetAlternativeDecrypter(level, decrypter, latch_once_used); | |
| 1948 } | |
| 1949 | |
| 1950 const QuicDecrypter* QuicConnection::decrypter() const { | |
| 1951 return framer_.decrypter(); | |
| 1952 } | |
| 1953 | |
| 1954 const QuicDecrypter* QuicConnection::alternative_decrypter() const { | |
| 1955 return framer_.alternative_decrypter(); | |
| 1956 } | |
| 1957 | |
| 1958 void QuicConnection::QueueUndecryptablePacket( | |
| 1959 const QuicEncryptedPacket& packet) { | |
| 1960 DVLOG(1) << ENDPOINT << "Queueing undecryptable packet."; | |
| 1961 undecryptable_packets_.push_back(packet.Clone()); | |
| 1962 } | |
| 1963 | |
| 1964 void QuicConnection::MaybeProcessUndecryptablePackets() { | |
| 1965 if (undecryptable_packets_.empty() || encryption_level_ == ENCRYPTION_NONE) { | |
| 1966 return; | |
| 1967 } | |
| 1968 | |
| 1969 while (connected_ && !undecryptable_packets_.empty()) { | |
| 1970 DVLOG(1) << ENDPOINT << "Attempting to process undecryptable packet"; | |
| 1971 QuicEncryptedPacket* packet = undecryptable_packets_.front(); | |
| 1972 if (!framer_.ProcessPacket(*packet) && | |
| 1973 framer_.error() == QUIC_DECRYPTION_FAILURE) { | |
| 1974 DVLOG(1) << ENDPOINT << "Unable to process undecryptable packet..."; | |
| 1975 break; | |
| 1976 } | |
| 1977 DVLOG(1) << ENDPOINT << "Processed undecryptable packet!"; | |
| 1978 ++stats_.packets_processed; | |
| 1979 delete packet; | |
| 1980 undecryptable_packets_.pop_front(); | |
| 1981 } | |
| 1982 | |
| 1983 // Once forward secure encryption is in use, there will be no | |
| 1984 // new keys installed and hence any undecryptable packets will | |
| 1985 // never be able to be decrypted. | |
| 1986 if (encryption_level_ == ENCRYPTION_FORWARD_SECURE) { | |
| 1987 if (debug_visitor_ != nullptr) { | |
| 1988 // TODO(rtenneti): perhaps more efficient to pass the number of | |
| 1989 // undecryptable packets as the argument to OnUndecryptablePacket so that | |
| 1990 // we just need to call OnUndecryptablePacket once? | |
| 1991 for (size_t i = 0; i < undecryptable_packets_.size(); ++i) { | |
| 1992 debug_visitor_->OnUndecryptablePacket(); | |
| 1993 } | |
| 1994 } | |
| 1995 STLDeleteElements(&undecryptable_packets_); | |
| 1996 } | |
| 1997 } | |
| 1998 | |
| 1999 void QuicConnection::CloseConnection( | |
| 2000 QuicErrorCode error, | |
| 2001 const string& error_details, | |
| 2002 ConnectionCloseBehavior connection_close_behavior) { | |
| 2003 DCHECK(!error_details.empty()); | |
| 2004 if (!connected_) { | |
| 2005 DVLOG(1) << "Connection is already closed."; | |
| 2006 return; | |
| 2007 } | |
| 2008 | |
| 2009 DVLOG(1) << ENDPOINT << "Closing connection: " << connection_id() | |
| 2010 << ", with error: " << QuicUtils::ErrorToString(error) << " (" | |
| 2011 << error << "), and details: " << error_details; | |
| 2012 | |
| 2013 if (connection_close_behavior == | |
| 2014 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET) { | |
| 2015 SendConnectionClosePacket(error, error_details); | |
| 2016 } | |
| 2017 | |
| 2018 TearDownLocalConnectionState(error, error_details, | |
| 2019 ConnectionCloseSource::FROM_SELF); | |
| 2020 } | |
| 2021 | |
| 2022 void QuicConnection::SendConnectionClosePacket(QuicErrorCode error, | |
| 2023 const string& details) { | |
| 2024 DVLOG(1) << ENDPOINT << "Sending connection close packet."; | |
| 2025 ClearQueuedPackets(); | |
| 2026 ScopedPacketBundler ack_bundler(this, SEND_ACK); | |
| 2027 QuicConnectionCloseFrame* frame = new QuicConnectionCloseFrame(); | |
| 2028 frame->error_code = error; | |
| 2029 frame->error_details = details; | |
| 2030 packet_generator_.AddControlFrame(QuicFrame(frame)); | |
| 2031 packet_generator_.FlushAllQueuedFrames(); | |
| 2032 } | |
| 2033 | |
| 2034 void QuicConnection::TearDownLocalConnectionState( | |
| 2035 QuicErrorCode error, | |
| 2036 const string& error_details, | |
| 2037 ConnectionCloseSource source) { | |
| 2038 if (!connected_) { | |
| 2039 DVLOG(1) << "Connection is already closed."; | |
| 2040 return; | |
| 2041 } | |
| 2042 connected_ = false; | |
| 2043 DCHECK(visitor_ != nullptr); | |
| 2044 // TODO(rtenneti): crbug.com/546668. A temporary fix. Added a check for null | |
| 2045 // |visitor_| to fix crash bug. Delete |visitor_| check and histogram after | |
| 2046 // fix is merged. | |
| 2047 if (visitor_ != nullptr) { | |
| 2048 visitor_->OnConnectionClosed(error, error_details, source); | |
| 2049 } else { | |
| 2050 UMA_HISTOGRAM_BOOLEAN("Net.QuicCloseConnection.NullVisitor", true); | |
| 2051 } | |
| 2052 if (debug_visitor_ != nullptr) { | |
| 2053 debug_visitor_->OnConnectionClosed(error, error_details, source); | |
| 2054 } | |
| 2055 // Cancel the alarms so they don't trigger any action now that the | |
| 2056 // connection is closed. | |
| 2057 CancelAllAlarms(); | |
| 2058 } | |
| 2059 | |
| 2060 void QuicConnection::CancelAllAlarms() { | |
| 2061 ack_alarm_->Cancel(); | |
| 2062 ping_alarm_->Cancel(); | |
| 2063 resume_writes_alarm_->Cancel(); | |
| 2064 retransmission_alarm_->Cancel(); | |
| 2065 send_alarm_->Cancel(); | |
| 2066 timeout_alarm_->Cancel(); | |
| 2067 mtu_discovery_alarm_->Cancel(); | |
| 2068 } | |
| 2069 | |
| 2070 void QuicConnection::SendGoAway(QuicErrorCode error, | |
| 2071 QuicStreamId last_good_stream_id, | |
| 2072 const string& reason) { | |
| 2073 if (goaway_sent_) { | |
| 2074 return; | |
| 2075 } | |
| 2076 goaway_sent_ = true; | |
| 2077 | |
| 2078 DVLOG(1) << ENDPOINT << "Going away with error " | |
| 2079 << QuicUtils::ErrorToString(error) << " (" << error << ")"; | |
| 2080 | |
| 2081 // Opportunistically bundle an ack with this outgoing packet. | |
| 2082 ScopedPacketBundler ack_bundler(this, SEND_ACK_IF_PENDING); | |
| 2083 packet_generator_.AddControlFrame( | |
| 2084 QuicFrame(new QuicGoAwayFrame(error, last_good_stream_id, reason))); | |
| 2085 } | |
| 2086 | |
| 2087 QuicByteCount QuicConnection::max_packet_length() const { | |
| 2088 return packet_generator_.GetCurrentMaxPacketLength(); | |
| 2089 } | |
| 2090 | |
| 2091 void QuicConnection::SetMaxPacketLength(QuicByteCount length) { | |
| 2092 return packet_generator_.SetMaxPacketLength(LimitMaxPacketSize(length)); | |
| 2093 } | |
| 2094 | |
| 2095 bool QuicConnection::HasQueuedData() const { | |
| 2096 return pending_version_negotiation_packet_ || !queued_packets_.empty() || | |
| 2097 packet_generator_.HasQueuedFrames(); | |
| 2098 } | |
| 2099 | |
| 2100 void QuicConnection::EnableSavingCryptoPackets() { | |
| 2101 save_crypto_packets_as_termination_packets_ = true; | |
| 2102 } | |
| 2103 | |
| 2104 bool QuicConnection::CanWriteStreamData() { | |
| 2105 // Don't write stream data if there are negotiation or queued data packets | |
| 2106 // to send. Otherwise, continue and bundle as many frames as possible. | |
| 2107 if (pending_version_negotiation_packet_ || !queued_packets_.empty()) { | |
| 2108 return false; | |
| 2109 } | |
| 2110 | |
| 2111 IsHandshake pending_handshake = | |
| 2112 visitor_->HasPendingHandshake() ? IS_HANDSHAKE : NOT_HANDSHAKE; | |
| 2113 // Sending queued packets may have caused the socket to become write blocked, | |
| 2114 // or the congestion manager to prohibit sending. If we've sent everything | |
| 2115 // we had queued and we're still not blocked, let the visitor know it can | |
| 2116 // write more. | |
| 2117 return ShouldGeneratePacket(HAS_RETRANSMITTABLE_DATA, pending_handshake); | |
| 2118 } | |
| 2119 | |
| 2120 void QuicConnection::SetNetworkTimeouts(QuicTime::Delta handshake_timeout, | |
| 2121 QuicTime::Delta idle_timeout) { | |
| 2122 QUIC_BUG_IF(idle_timeout > handshake_timeout) | |
| 2123 << "idle_timeout:" << idle_timeout.ToMilliseconds() | |
| 2124 << " handshake_timeout:" << handshake_timeout.ToMilliseconds(); | |
| 2125 // Adjust the idle timeout on client and server to prevent clients from | |
| 2126 // sending requests to servers which have already closed the connection. | |
| 2127 if (perspective_ == Perspective::IS_SERVER) { | |
| 2128 idle_timeout = idle_timeout + QuicTime::Delta::FromSeconds(3); | |
| 2129 } else if (idle_timeout > QuicTime::Delta::FromSeconds(1)) { | |
| 2130 idle_timeout = idle_timeout - QuicTime::Delta::FromSeconds(1); | |
| 2131 } | |
| 2132 handshake_timeout_ = handshake_timeout; | |
| 2133 idle_network_timeout_ = idle_timeout; | |
| 2134 | |
| 2135 SetTimeoutAlarm(); | |
| 2136 } | |
| 2137 | |
| 2138 void QuicConnection::CheckForTimeout() { | |
| 2139 QuicTime now = clock_->ApproximateNow(); | |
| 2140 QuicTime time_of_last_packet = | |
| 2141 max(time_of_last_received_packet_, last_send_for_timeout_); | |
| 2142 | |
| 2143 // |delta| can be < 0 as |now| is approximate time but |time_of_last_packet| | |
| 2144 // is accurate time. However, this should not change the behavior of | |
| 2145 // timeout handling. | |
| 2146 QuicTime::Delta idle_duration = now - time_of_last_packet; | |
| 2147 DVLOG(1) << ENDPOINT << "last packet " | |
| 2148 << time_of_last_packet.ToDebuggingValue() | |
| 2149 << " now:" << now.ToDebuggingValue() | |
| 2150 << " idle_duration:" << idle_duration.ToMicroseconds() | |
| 2151 << " idle_network_timeout: " | |
| 2152 << idle_network_timeout_.ToMicroseconds(); | |
| 2153 if (idle_duration >= idle_network_timeout_) { | |
| 2154 const string error_details = "No recent network activity."; | |
| 2155 DVLOG(1) << ENDPOINT << error_details; | |
| 2156 CloseConnection(QUIC_NETWORK_IDLE_TIMEOUT, error_details, | |
| 2157 idle_timeout_connection_close_behavior_); | |
| 2158 return; | |
| 2159 } | |
| 2160 | |
| 2161 if (!handshake_timeout_.IsInfinite()) { | |
| 2162 QuicTime::Delta connected_duration = now - stats_.connection_creation_time; | |
| 2163 DVLOG(1) << ENDPOINT | |
| 2164 << "connection time: " << connected_duration.ToMicroseconds() | |
| 2165 << " handshake timeout: " << handshake_timeout_.ToMicroseconds(); | |
| 2166 if (connected_duration >= handshake_timeout_) { | |
| 2167 const string error_details = "Handshake timeout expired."; | |
| 2168 DVLOG(1) << ENDPOINT << error_details; | |
| 2169 CloseConnection(QUIC_HANDSHAKE_TIMEOUT, error_details, | |
| 2170 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); | |
| 2171 return; | |
| 2172 } | |
| 2173 } | |
| 2174 | |
| 2175 SetTimeoutAlarm(); | |
| 2176 } | |
| 2177 | |
| 2178 void QuicConnection::SetTimeoutAlarm() { | |
| 2179 QuicTime time_of_last_packet = | |
| 2180 max(time_of_last_received_packet_, time_of_last_sent_new_packet_); | |
| 2181 | |
| 2182 QuicTime deadline = time_of_last_packet + idle_network_timeout_; | |
| 2183 if (!handshake_timeout_.IsInfinite()) { | |
| 2184 deadline = | |
| 2185 min(deadline, stats_.connection_creation_time + handshake_timeout_); | |
| 2186 } | |
| 2187 | |
| 2188 timeout_alarm_->Update(deadline, QuicTime::Delta::Zero()); | |
| 2189 } | |
| 2190 | |
| 2191 void QuicConnection::SetPingAlarm() { | |
| 2192 if (perspective_ == Perspective::IS_SERVER) { | |
| 2193 // Only clients send pings. | |
| 2194 return; | |
| 2195 } | |
| 2196 if (!visitor_->HasOpenDynamicStreams()) { | |
| 2197 ping_alarm_->Cancel(); | |
| 2198 // Don't send a ping unless there are open streams. | |
| 2199 return; | |
| 2200 } | |
| 2201 QuicTime::Delta ping_timeout = QuicTime::Delta::FromSeconds(kPingTimeoutSecs); | |
| 2202 ping_alarm_->Update(clock_->ApproximateNow() + ping_timeout, | |
| 2203 QuicTime::Delta::FromSeconds(1)); | |
| 2204 } | |
| 2205 | |
| 2206 void QuicConnection::SetRetransmissionAlarm() { | |
| 2207 if (delay_setting_retransmission_alarm_) { | |
| 2208 pending_retransmission_alarm_ = true; | |
| 2209 return; | |
| 2210 } | |
| 2211 QuicTime retransmission_time = sent_packet_manager_->GetRetransmissionTime(); | |
| 2212 retransmission_alarm_->Update(retransmission_time, | |
| 2213 QuicTime::Delta::FromMilliseconds(1)); | |
| 2214 } | |
| 2215 | |
| 2216 void QuicConnection::MaybeSetMtuAlarm() { | |
| 2217 // Do not set the alarm if the target size is less than the current size. | |
| 2218 // This covers the case when |mtu_discovery_target_| is at its default value, | |
| 2219 // zero. | |
| 2220 if (mtu_discovery_target_ <= max_packet_length()) { | |
| 2221 return; | |
| 2222 } | |
| 2223 | |
| 2224 if (mtu_probe_count_ >= kMtuDiscoveryAttempts) { | |
| 2225 return; | |
| 2226 } | |
| 2227 | |
| 2228 if (mtu_discovery_alarm_->IsSet()) { | |
| 2229 return; | |
| 2230 } | |
| 2231 | |
| 2232 if (packet_number_of_last_sent_packet_ >= next_mtu_probe_at_) { | |
| 2233 // Use an alarm to send the MTU probe to ensure that no ScopedPacketBundlers | |
| 2234 // are active. | |
| 2235 mtu_discovery_alarm_->Set(clock_->ApproximateNow()); | |
| 2236 } | |
| 2237 } | |
| 2238 | |
| 2239 QuicConnection::ScopedPacketBundler::ScopedPacketBundler( | |
| 2240 QuicConnection* connection, | |
| 2241 AckBundling ack_mode) | |
| 2242 : connection_(connection), | |
| 2243 already_in_batch_mode_(connection != nullptr && | |
| 2244 connection->packet_generator_.InBatchMode()) { | |
| 2245 if (connection_ == nullptr) { | |
| 2246 return; | |
| 2247 } | |
| 2248 // Move generator into batch mode. If caller wants us to include an ack, | |
| 2249 // check the delayed-ack timer to see if there's ack info to be sent. | |
| 2250 if (!already_in_batch_mode_) { | |
| 2251 DVLOG(2) << "Entering Batch Mode."; | |
| 2252 connection_->packet_generator_.StartBatchOperations(); | |
| 2253 } | |
| 2254 if (ShouldSendAck(ack_mode)) { | |
| 2255 DVLOG(1) << "Bundling ack with outgoing packet."; | |
| 2256 DCHECK(ack_mode == SEND_ACK || connection_->ack_frame_updated() || | |
| 2257 connection_->stop_waiting_count_ > 1); | |
| 2258 connection_->SendAck(); | |
| 2259 } | |
| 2260 } | |
| 2261 | |
| 2262 bool QuicConnection::ScopedPacketBundler::ShouldSendAck( | |
| 2263 AckBundling ack_mode) const { | |
| 2264 switch (ack_mode) { | |
| 2265 case SEND_ACK: | |
| 2266 return true; | |
| 2267 case SEND_ACK_IF_QUEUED: | |
| 2268 return connection_->ack_queued(); | |
| 2269 case SEND_ACK_IF_PENDING: | |
| 2270 return connection_->ack_alarm_->IsSet() || | |
| 2271 connection_->stop_waiting_count_ > 1; | |
| 2272 default: | |
| 2273 QUIC_BUG << "Unsupported ack_mode."; | |
| 2274 return true; | |
| 2275 } | |
| 2276 } | |
| 2277 | |
| 2278 QuicConnection::ScopedPacketBundler::~ScopedPacketBundler() { | |
| 2279 if (connection_ == nullptr) { | |
| 2280 return; | |
| 2281 } | |
| 2282 // If we changed the generator's batch state, restore original batch state. | |
| 2283 if (!already_in_batch_mode_) { | |
| 2284 DVLOG(2) << "Leaving Batch Mode."; | |
| 2285 connection_->packet_generator_.FinishBatchOperations(); | |
| 2286 } | |
| 2287 DCHECK_EQ(already_in_batch_mode_, | |
| 2288 connection_->packet_generator_.InBatchMode()); | |
| 2289 } | |
| 2290 | |
| 2291 QuicConnection::ScopedRetransmissionScheduler::ScopedRetransmissionScheduler( | |
| 2292 QuicConnection* connection) | |
| 2293 : connection_(connection), | |
| 2294 already_delayed_(connection_->delay_setting_retransmission_alarm_) { | |
| 2295 connection_->delay_setting_retransmission_alarm_ = true; | |
| 2296 } | |
| 2297 | |
| 2298 QuicConnection::ScopedRetransmissionScheduler:: | |
| 2299 ~ScopedRetransmissionScheduler() { | |
| 2300 if (already_delayed_) { | |
| 2301 return; | |
| 2302 } | |
| 2303 connection_->delay_setting_retransmission_alarm_ = false; | |
| 2304 if (connection_->pending_retransmission_alarm_) { | |
| 2305 connection_->SetRetransmissionAlarm(); | |
| 2306 connection_->pending_retransmission_alarm_ = false; | |
| 2307 } | |
| 2308 } | |
| 2309 | |
| 2310 HasRetransmittableData QuicConnection::IsRetransmittable( | |
| 2311 const SerializedPacket& packet) { | |
| 2312 // Retransmitted packets retransmittable frames are owned by the unacked | |
| 2313 // packet map, but are not present in the serialized packet. | |
| 2314 if (packet.transmission_type != NOT_RETRANSMISSION || | |
| 2315 !packet.retransmittable_frames.empty()) { | |
| 2316 return HAS_RETRANSMITTABLE_DATA; | |
| 2317 } else { | |
| 2318 return NO_RETRANSMITTABLE_DATA; | |
| 2319 } | |
| 2320 } | |
| 2321 | |
| 2322 bool QuicConnection::IsTerminationPacket(const SerializedPacket& packet) { | |
| 2323 if (packet.retransmittable_frames.empty()) { | |
| 2324 return false; | |
| 2325 } | |
| 2326 for (const QuicFrame& frame : packet.retransmittable_frames) { | |
| 2327 if (frame.type == CONNECTION_CLOSE_FRAME) { | |
| 2328 return true; | |
| 2329 } | |
| 2330 if (save_crypto_packets_as_termination_packets_ && | |
| 2331 frame.type == STREAM_FRAME && | |
| 2332 frame.stream_frame->stream_id == kCryptoStreamId) { | |
| 2333 return true; | |
| 2334 } | |
| 2335 } | |
| 2336 return false; | |
| 2337 } | |
| 2338 | |
| 2339 void QuicConnection::SetMtuDiscoveryTarget(QuicByteCount target) { | |
| 2340 mtu_discovery_target_ = LimitMaxPacketSize(target); | |
| 2341 } | |
| 2342 | |
| 2343 QuicByteCount QuicConnection::LimitMaxPacketSize( | |
| 2344 QuicByteCount suggested_max_packet_size) { | |
| 2345 if (peer_address_.address().empty()) { | |
| 2346 QUIC_BUG << "Attempted to use a connection without a valid peer address"; | |
| 2347 return suggested_max_packet_size; | |
| 2348 } | |
| 2349 | |
| 2350 const QuicByteCount writer_limit = writer_->GetMaxPacketSize(peer_address()); | |
| 2351 | |
| 2352 QuicByteCount max_packet_size = suggested_max_packet_size; | |
| 2353 if (max_packet_size > writer_limit) { | |
| 2354 max_packet_size = writer_limit; | |
| 2355 } | |
| 2356 if (max_packet_size > kMaxPacketSize) { | |
| 2357 max_packet_size = kMaxPacketSize; | |
| 2358 } | |
| 2359 return max_packet_size; | |
| 2360 } | |
| 2361 | |
| 2362 void QuicConnection::SendMtuDiscoveryPacket(QuicByteCount target_mtu) { | |
| 2363 // Currently, this limit is ensured by the caller. | |
| 2364 DCHECK_EQ(target_mtu, LimitMaxPacketSize(target_mtu)); | |
| 2365 | |
| 2366 // Create a listener for the new probe. The ownership of the listener is | |
| 2367 // transferred to the AckNotifierManager. The notifier will get destroyed | |
| 2368 // before the connection (because it's stored in one of the connection's | |
| 2369 // subfields), hence |this| pointer is guaranteed to stay valid at all times. | |
| 2370 scoped_refptr<MtuDiscoveryAckListener> last_mtu_discovery_ack_listener( | |
| 2371 new MtuDiscoveryAckListener(this, target_mtu)); | |
| 2372 | |
| 2373 // Send the probe. | |
| 2374 packet_generator_.GenerateMtuDiscoveryPacket( | |
| 2375 target_mtu, FLAGS_quic_no_mtu_discovery_ack_listener | |
| 2376 ? nullptr | |
| 2377 : last_mtu_discovery_ack_listener.get()); | |
| 2378 } | |
| 2379 | |
| 2380 void QuicConnection::DiscoverMtu() { | |
| 2381 DCHECK(!mtu_discovery_alarm_->IsSet()); | |
| 2382 | |
| 2383 // Check if the MTU has been already increased. | |
| 2384 if (mtu_discovery_target_ <= max_packet_length()) { | |
| 2385 return; | |
| 2386 } | |
| 2387 | |
| 2388 // Calculate the packet number of the next probe *before* sending the current | |
| 2389 // one. Otherwise, when SendMtuDiscoveryPacket() is called, | |
| 2390 // MaybeSetMtuAlarm() will not realize that the probe has been just sent, and | |
| 2391 // will reschedule this probe again. | |
| 2392 packets_between_mtu_probes_ *= 2; | |
| 2393 next_mtu_probe_at_ = | |
| 2394 packet_number_of_last_sent_packet_ + packets_between_mtu_probes_ + 1; | |
| 2395 ++mtu_probe_count_; | |
| 2396 | |
| 2397 DVLOG(2) << "Sending a path MTU discovery packet #" << mtu_probe_count_; | |
| 2398 SendMtuDiscoveryPacket(mtu_discovery_target_); | |
| 2399 | |
| 2400 DCHECK(!mtu_discovery_alarm_->IsSet()); | |
| 2401 } | |
| 2402 | |
| 2403 void QuicConnection::OnPeerMigrationValidated(QuicPathId path_id) { | |
| 2404 if (active_peer_migration_type_ == NO_CHANGE) { | |
| 2405 QUIC_BUG << "No migration underway."; | |
| 2406 return; | |
| 2407 } | |
| 2408 highest_packet_sent_before_peer_migration_ = 0; | |
| 2409 active_peer_migration_type_ = NO_CHANGE; | |
| 2410 } | |
| 2411 | |
| 2412 // TODO(jri): Modify method to start migration whenever a new IP address is seen | |
| 2413 // from a packet with sequence number > the one that triggered the previous | |
| 2414 // migration. This should happen even if a migration is underway, since the | |
| 2415 // most recent migration is the one that we should pay attention to. | |
| 2416 void QuicConnection::StartPeerMigration( | |
| 2417 QuicPathId path_id, | |
| 2418 PeerAddressChangeType peer_migration_type) { | |
| 2419 // TODO(fayang): Currently, all peer address change type are allowed. Need to | |
| 2420 // add a method ShouldAllowPeerAddressChange(PeerAddressChangeType type) to | |
| 2421 // determine whether |type| is allowed. | |
| 2422 if (active_peer_migration_type_ != NO_CHANGE || | |
| 2423 peer_migration_type == NO_CHANGE) { | |
| 2424 QUIC_BUG << "Migration underway or no new migration started."; | |
| 2425 return; | |
| 2426 } | |
| 2427 DVLOG(1) << ENDPOINT << "Peer's ip:port changed from " | |
| 2428 << peer_address_.ToString() << " to " | |
| 2429 << last_packet_source_address_.ToString() | |
| 2430 << ", migrating connection."; | |
| 2431 | |
| 2432 highest_packet_sent_before_peer_migration_ = | |
| 2433 packet_number_of_last_sent_packet_; | |
| 2434 peer_address_ = last_packet_source_address_; | |
| 2435 active_peer_migration_type_ = peer_migration_type; | |
| 2436 | |
| 2437 // TODO(jri): Move these calls to OnPeerMigrationValidated. Rename | |
| 2438 // OnConnectionMigration methods to OnPeerMigration. | |
| 2439 visitor_->OnConnectionMigration(peer_migration_type); | |
| 2440 sent_packet_manager_->OnConnectionMigration(path_id, peer_migration_type); | |
| 2441 } | |
| 2442 | |
| 2443 void QuicConnection::OnPathClosed(QuicPathId path_id) { | |
| 2444 // Stop receiving packets on this path. | |
| 2445 framer_.OnPathClosed(path_id); | |
| 2446 } | |
| 2447 | |
| 2448 bool QuicConnection::ack_frame_updated() const { | |
| 2449 return received_packet_manager_.ack_frame_updated(); | |
| 2450 } | |
| 2451 | |
| 2452 StringPiece QuicConnection::GetCurrentPacket() { | |
| 2453 if (current_packet_data_ == nullptr) { | |
| 2454 return StringPiece(); | |
| 2455 } | |
| 2456 return StringPiece(current_packet_data_, last_size_); | |
| 2457 } | |
| 2458 | |
| 2459 bool QuicConnection::MaybeConsiderAsMemoryCorruption( | |
| 2460 const QuicStreamFrame& frame) { | |
| 2461 if (frame.stream_id == kCryptoStreamId || | |
| 2462 last_decrypted_packet_level_ != ENCRYPTION_NONE) { | |
| 2463 return false; | |
| 2464 } | |
| 2465 | |
| 2466 if (perspective_ == Perspective::IS_SERVER && | |
| 2467 frame.data_length >= sizeof(kCHLO) && | |
| 2468 strncmp(frame.data_buffer, reinterpret_cast<const char*>(&kCHLO), | |
| 2469 sizeof(kCHLO)) == 0) { | |
| 2470 return true; | |
| 2471 } | |
| 2472 | |
| 2473 if (perspective_ == Perspective::IS_CLIENT && | |
| 2474 frame.data_length >= sizeof(kREJ) && | |
| 2475 strncmp(frame.data_buffer, reinterpret_cast<const char*>(&kREJ), | |
| 2476 sizeof(kREJ)) == 0) { | |
| 2477 return true; | |
| 2478 } | |
| 2479 | |
| 2480 return false; | |
| 2481 } | |
| 2482 | |
| 2483 // Uses a 25ms delayed ack timer. Also helps with better signaling | |
| 2484 // in low-bandwidth (< ~384 kbps), where an ack is sent per packet. | |
| 2485 // Ensures that the Delayed Ack timer is always set to a value lesser | |
| 2486 // than the retransmission timer's minimum value (MinRTO). We want the | |
| 2487 // delayed ack to get back to the QUIC peer before the sender's | |
| 2488 // retransmission timer triggers. Since we do not know the | |
| 2489 // reverse-path one-way delay, we assume equal delays for forward and | |
| 2490 // reverse paths, and ensure that the timer is set to less than half | |
| 2491 // of the MinRTO. | |
| 2492 // There may be a value in making this delay adaptive with the help of | |
| 2493 // the sender and a signaling mechanism -- if the sender uses a | |
| 2494 // different MinRTO, we may get spurious retransmissions. May not have | |
| 2495 // any benefits, but if the delayed ack becomes a significant source | |
| 2496 // of (likely, tail) latency, then consider such a mechanism. | |
| 2497 const QuicTime::Delta QuicConnection::DelayedAckTime() { | |
| 2498 return QuicTime::Delta::FromMilliseconds( | |
| 2499 min(kMaxDelayedAckTimeMs, kMinRetransmissionTimeMs / 2)); | |
| 2500 } | |
| 2501 | |
| 2502 } // namespace net | |
| OLD | NEW |