| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 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> |
| James Robinson | e2ac7e8 | 2014-10-15 13:21:59 -0700 | [diff] [blame] | 9 | |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 10 | #include <algorithm> |
| 11 | #include <iterator> |
| 12 | #include <limits> |
| 13 | #include <memory> |
| 14 | #include <set> |
| 15 | #include <utility> |
| 16 | |
| 17 | #include "base/debug/stack_trace.h" |
| James Robinson | 6a64b81 | 2014-12-03 13:38:42 -0800 | [diff] [blame^] | 18 | #include "base/format_macros.h" |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 19 | #include "base/logging.h" |
| 20 | #include "base/stl_util.h" |
| James Robinson | 7f48021 | 2014-10-31 10:28:08 -0700 | [diff] [blame] | 21 | #include "base/strings/stringprintf.h" |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 22 | #include "net/base/net_errors.h" |
| 23 | #include "net/quic/crypto/quic_decrypter.h" |
| 24 | #include "net/quic/crypto/quic_encrypter.h" |
| 25 | #include "net/quic/iovector.h" |
| 26 | #include "net/quic/quic_bandwidth.h" |
| 27 | #include "net/quic/quic_config.h" |
| 28 | #include "net/quic/quic_fec_group.h" |
| 29 | #include "net/quic/quic_flags.h" |
| 30 | #include "net/quic/quic_utils.h" |
| 31 | |
| 32 | using base::StringPiece; |
| James Robinson | 7f48021 | 2014-10-31 10:28:08 -0700 | [diff] [blame] | 33 | using base::StringPrintf; |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 34 | using base::hash_map; |
| 35 | using base::hash_set; |
| 36 | using std::list; |
| 37 | using std::make_pair; |
| 38 | using std::max; |
| 39 | using std::min; |
| 40 | using std::numeric_limits; |
| 41 | using std::set; |
| 42 | using std::string; |
| 43 | using std::vector; |
| 44 | |
| 45 | namespace net { |
| 46 | |
| 47 | class QuicDecrypter; |
| 48 | class QuicEncrypter; |
| 49 | |
| 50 | namespace { |
| 51 | |
| 52 | // The largest gap in packets we'll accept without closing the connection. |
| 53 | // This will likely have to be tuned. |
| 54 | const QuicPacketSequenceNumber kMaxPacketGap = 5000; |
| 55 | |
| 56 | // Limit the number of FEC groups to two. If we get enough out of order packets |
| 57 | // that this becomes limiting, we can revisit. |
| 58 | const size_t kMaxFecGroups = 2; |
| 59 | |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 60 | // Maximum number of acks received before sending an ack in response. |
| James Robinson | 6a64b81 | 2014-12-03 13:38:42 -0800 | [diff] [blame^] | 61 | const QuicPacketCount kMaxPacketsReceivedBeforeAckSend = 20; |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 62 | |
| James Robinson | 7f48021 | 2014-10-31 10:28:08 -0700 | [diff] [blame] | 63 | // Maximum number of tracked packets. |
| James Robinson | 6a64b81 | 2014-12-03 13:38:42 -0800 | [diff] [blame^] | 64 | const QuicPacketCount kMaxTrackedPackets = 5 * kMaxTcpCongestionWindow; |
| James Robinson | 7f48021 | 2014-10-31 10:28:08 -0700 | [diff] [blame] | 65 | |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 66 | bool Near(QuicPacketSequenceNumber a, QuicPacketSequenceNumber b) { |
| 67 | QuicPacketSequenceNumber delta = (a > b) ? a - b : b - a; |
| 68 | return delta <= kMaxPacketGap; |
| 69 | } |
| 70 | |
| 71 | // An alarm that is scheduled to send an ack if a timeout occurs. |
| 72 | class AckAlarm : public QuicAlarm::Delegate { |
| 73 | public: |
| 74 | explicit AckAlarm(QuicConnection* connection) |
| 75 | : connection_(connection) { |
| 76 | } |
| 77 | |
| James Robinson | e1b30cf | 2014-10-21 12:25:40 -0700 | [diff] [blame] | 78 | QuicTime OnAlarm() override { |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 79 | connection_->SendAck(); |
| 80 | return QuicTime::Zero(); |
| 81 | } |
| 82 | |
| 83 | private: |
| 84 | QuicConnection* connection_; |
| 85 | |
| 86 | DISALLOW_COPY_AND_ASSIGN(AckAlarm); |
| 87 | }; |
| 88 | |
| 89 | // This alarm will be scheduled any time a data-bearing packet is sent out. |
| 90 | // When the alarm goes off, the connection checks to see if the oldest packets |
| 91 | // have been acked, and retransmit them if they have not. |
| 92 | class RetransmissionAlarm : public QuicAlarm::Delegate { |
| 93 | public: |
| 94 | explicit RetransmissionAlarm(QuicConnection* connection) |
| 95 | : connection_(connection) { |
| 96 | } |
| 97 | |
| James Robinson | e1b30cf | 2014-10-21 12:25:40 -0700 | [diff] [blame] | 98 | QuicTime OnAlarm() override { |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 99 | connection_->OnRetransmissionTimeout(); |
| 100 | return QuicTime::Zero(); |
| 101 | } |
| 102 | |
| 103 | private: |
| 104 | QuicConnection* connection_; |
| 105 | |
| 106 | DISALLOW_COPY_AND_ASSIGN(RetransmissionAlarm); |
| 107 | }; |
| 108 | |
| 109 | // An alarm that is scheduled when the sent scheduler requires a |
| 110 | // a delay before sending packets and fires when the packet may be sent. |
| 111 | class SendAlarm : public QuicAlarm::Delegate { |
| 112 | public: |
| 113 | explicit SendAlarm(QuicConnection* connection) |
| 114 | : connection_(connection) { |
| 115 | } |
| 116 | |
| James Robinson | e1b30cf | 2014-10-21 12:25:40 -0700 | [diff] [blame] | 117 | QuicTime OnAlarm() override { |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 118 | connection_->WriteIfNotBlocked(); |
| 119 | // Never reschedule the alarm, since CanWrite does that. |
| 120 | return QuicTime::Zero(); |
| 121 | } |
| 122 | |
| 123 | private: |
| 124 | QuicConnection* connection_; |
| 125 | |
| 126 | DISALLOW_COPY_AND_ASSIGN(SendAlarm); |
| 127 | }; |
| 128 | |
| 129 | class TimeoutAlarm : public QuicAlarm::Delegate { |
| 130 | public: |
| 131 | explicit TimeoutAlarm(QuicConnection* connection) |
| 132 | : connection_(connection) { |
| 133 | } |
| 134 | |
| James Robinson | e1b30cf | 2014-10-21 12:25:40 -0700 | [diff] [blame] | 135 | QuicTime OnAlarm() override { |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 136 | connection_->CheckForTimeout(); |
| 137 | // Never reschedule the alarm, since CheckForTimeout does that. |
| 138 | return QuicTime::Zero(); |
| 139 | } |
| 140 | |
| 141 | private: |
| 142 | QuicConnection* connection_; |
| 143 | |
| 144 | DISALLOW_COPY_AND_ASSIGN(TimeoutAlarm); |
| 145 | }; |
| 146 | |
| 147 | class PingAlarm : public QuicAlarm::Delegate { |
| 148 | public: |
| 149 | explicit PingAlarm(QuicConnection* connection) |
| 150 | : connection_(connection) { |
| 151 | } |
| 152 | |
| James Robinson | e1b30cf | 2014-10-21 12:25:40 -0700 | [diff] [blame] | 153 | QuicTime OnAlarm() override { |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 154 | connection_->SendPing(); |
| 155 | return QuicTime::Zero(); |
| 156 | } |
| 157 | |
| 158 | private: |
| 159 | QuicConnection* connection_; |
| 160 | |
| 161 | DISALLOW_COPY_AND_ASSIGN(PingAlarm); |
| 162 | }; |
| 163 | |
| 164 | } // namespace |
| 165 | |
| 166 | QuicConnection::QueuedPacket::QueuedPacket(SerializedPacket packet, |
| 167 | EncryptionLevel level) |
| James Robinson | e2ac7e8 | 2014-10-15 13:21:59 -0700 | [diff] [blame] | 168 | : serialized_packet(packet), |
| 169 | encryption_level(level), |
| 170 | transmission_type(NOT_RETRANSMISSION), |
| 171 | original_sequence_number(0) { |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 172 | } |
| 173 | |
| 174 | QuicConnection::QueuedPacket::QueuedPacket( |
| 175 | SerializedPacket packet, |
| 176 | EncryptionLevel level, |
| 177 | TransmissionType transmission_type, |
| 178 | QuicPacketSequenceNumber original_sequence_number) |
| 179 | : serialized_packet(packet), |
| 180 | encryption_level(level), |
| 181 | transmission_type(transmission_type), |
| 182 | original_sequence_number(original_sequence_number) { |
| 183 | } |
| 184 | |
| 185 | #define ENDPOINT (is_server_ ? "Server: " : " Client: ") |
| 186 | |
| 187 | QuicConnection::QuicConnection(QuicConnectionId connection_id, |
| 188 | IPEndPoint address, |
| 189 | QuicConnectionHelperInterface* helper, |
| 190 | const PacketWriterFactory& writer_factory, |
| 191 | bool owns_writer, |
| 192 | bool is_server, |
| Benjamin Lerman | 5799890 | 2014-11-18 16:06:02 +0100 | [diff] [blame] | 193 | bool is_secure, |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 194 | const QuicVersionVector& supported_versions) |
| 195 | : framer_(supported_versions, helper->GetClock()->ApproximateNow(), |
| 196 | is_server), |
| 197 | helper_(helper), |
| 198 | writer_(writer_factory.Create(this)), |
| 199 | owns_writer_(owns_writer), |
| 200 | encryption_level_(ENCRYPTION_NONE), |
| James Robinson | 74f9f1f | 2014-11-04 11:17:49 -0800 | [diff] [blame] | 201 | has_forward_secure_encrypter_(false), |
| 202 | first_required_forward_secure_packet_(0), |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 203 | clock_(helper->GetClock()), |
| 204 | random_generator_(helper->GetRandomGenerator()), |
| 205 | connection_id_(connection_id), |
| 206 | peer_address_(address), |
| 207 | migrating_peer_port_(0), |
| James Robinson | e1b30cf | 2014-10-21 12:25:40 -0700 | [diff] [blame] | 208 | last_packet_decrypted_(false), |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 209 | last_packet_revived_(false), |
| 210 | last_size_(0), |
| 211 | last_decrypted_packet_level_(ENCRYPTION_NONE), |
| 212 | largest_seen_packet_with_ack_(0), |
| 213 | largest_seen_packet_with_stop_waiting_(0), |
| James Robinson | e2ac7e8 | 2014-10-15 13:21:59 -0700 | [diff] [blame] | 214 | max_undecryptable_packets_(0), |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 215 | pending_version_negotiation_packet_(false), |
| 216 | received_packet_manager_(&stats_), |
| 217 | ack_queued_(false), |
| 218 | num_packets_received_since_last_ack_sent_(0), |
| 219 | stop_waiting_count_(0), |
| 220 | ack_alarm_(helper->CreateAlarm(new AckAlarm(this))), |
| 221 | retransmission_alarm_(helper->CreateAlarm(new RetransmissionAlarm(this))), |
| 222 | send_alarm_(helper->CreateAlarm(new SendAlarm(this))), |
| 223 | resume_writes_alarm_(helper->CreateAlarm(new SendAlarm(this))), |
| 224 | timeout_alarm_(helper->CreateAlarm(new TimeoutAlarm(this))), |
| 225 | ping_alarm_(helper->CreateAlarm(new PingAlarm(this))), |
| 226 | packet_generator_(connection_id_, &framer_, random_generator_, this), |
| Benjamin Lerman | 5799890 | 2014-11-18 16:06:02 +0100 | [diff] [blame] | 227 | idle_network_timeout_(QuicTime::Delta::Infinite()), |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 228 | overall_connection_timeout_(QuicTime::Delta::Infinite()), |
| 229 | time_of_last_received_packet_(clock_->ApproximateNow()), |
| 230 | time_of_last_sent_new_packet_(clock_->ApproximateNow()), |
| 231 | sequence_number_of_last_sent_packet_(0), |
| 232 | sent_packet_manager_( |
| 233 | is_server, clock_, &stats_, |
| 234 | FLAGS_quic_use_bbr_congestion_control ? kBBR : kCubic, |
| Benjamin Lerman | 5799890 | 2014-11-18 16:06:02 +0100 | [diff] [blame] | 235 | FLAGS_quic_use_time_loss_detection ? kTime : kNack, |
| 236 | is_secure), |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 237 | version_negotiation_state_(START_NEGOTIATION), |
| 238 | is_server_(is_server), |
| 239 | connected_(true), |
| 240 | peer_ip_changed_(false), |
| 241 | peer_port_changed_(false), |
| 242 | self_ip_changed_(false), |
| James Robinson | 7f48021 | 2014-10-31 10:28:08 -0700 | [diff] [blame] | 243 | self_port_changed_(false), |
| Benjamin Lerman | 5799890 | 2014-11-18 16:06:02 +0100 | [diff] [blame] | 244 | can_truncate_connection_ids_(true), |
| 245 | is_secure_(is_secure) { |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 246 | DVLOG(1) << ENDPOINT << "Created connection with connection_id: " |
| 247 | << connection_id; |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 248 | framer_.set_visitor(this); |
| 249 | framer_.set_received_entropy_calculator(&received_packet_manager_); |
| 250 | stats_.connection_creation_time = clock_->ApproximateNow(); |
| 251 | sent_packet_manager_.set_network_change_visitor(this); |
| 252 | } |
| 253 | |
| 254 | QuicConnection::~QuicConnection() { |
| 255 | if (owns_writer_) { |
| 256 | delete writer_; |
| 257 | } |
| 258 | STLDeleteElements(&undecryptable_packets_); |
| 259 | STLDeleteValues(&group_map_); |
| 260 | for (QueuedPacketList::iterator it = queued_packets_.begin(); |
| 261 | it != queued_packets_.end(); ++it) { |
| 262 | delete it->serialized_packet.retransmittable_frames; |
| 263 | delete it->serialized_packet.packet; |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | void QuicConnection::SetFromConfig(const QuicConfig& config) { |
| Benjamin Lerman | 5799890 | 2014-11-18 16:06:02 +0100 | [diff] [blame] | 268 | if (config.negotiated()) { |
| 269 | SetNetworkTimeouts(QuicTime::Delta::Infinite(), |
| 270 | config.IdleConnectionStateLifetime()); |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 271 | } else { |
| Benjamin Lerman | 5799890 | 2014-11-18 16:06:02 +0100 | [diff] [blame] | 272 | SetNetworkTimeouts(config.max_time_before_crypto_handshake(), |
| 273 | config.max_idle_time_before_crypto_handshake()); |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 274 | } |
| Benjamin Lerman | 5799890 | 2014-11-18 16:06:02 +0100 | [diff] [blame] | 275 | |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 276 | sent_packet_manager_.SetFromConfig(config); |
| James Robinson | 7f48021 | 2014-10-31 10:28:08 -0700 | [diff] [blame] | 277 | if (FLAGS_allow_truncated_connection_ids_for_quic && |
| 278 | config.HasReceivedBytesForConnectionId() && |
| 279 | can_truncate_connection_ids_) { |
| 280 | packet_generator_.SetConnectionIdLength( |
| 281 | config.ReceivedBytesForConnectionId()); |
| 282 | } |
| James Robinson | e2ac7e8 | 2014-10-15 13:21:59 -0700 | [diff] [blame] | 283 | max_undecryptable_packets_ = config.max_undecryptable_packets(); |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 284 | } |
| 285 | |
| James Robinson | 6a64b81 | 2014-12-03 13:38:42 -0800 | [diff] [blame^] | 286 | bool QuicConnection::ResumeConnectionState( |
| James Robinson | c4c1c59 | 2014-11-21 18:27:04 -0800 | [diff] [blame] | 287 | const CachedNetworkParameters& cached_network_params) { |
| James Robinson | 6a64b81 | 2014-12-03 13:38:42 -0800 | [diff] [blame^] | 288 | return sent_packet_manager_.ResumeConnectionState(cached_network_params); |
| James Robinson | c4c1c59 | 2014-11-21 18:27:04 -0800 | [diff] [blame] | 289 | } |
| 290 | |
| James Robinson | 74f9f1f | 2014-11-04 11:17:49 -0800 | [diff] [blame] | 291 | void QuicConnection::SetNumOpenStreams(size_t num_streams) { |
| 292 | sent_packet_manager_.SetNumOpenStreams(num_streams); |
| 293 | } |
| 294 | |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 295 | bool QuicConnection::SelectMutualVersion( |
| 296 | const QuicVersionVector& available_versions) { |
| 297 | // Try to find the highest mutual version by iterating over supported |
| 298 | // versions, starting with the highest, and breaking out of the loop once we |
| 299 | // find a matching version in the provided available_versions vector. |
| 300 | const QuicVersionVector& supported_versions = framer_.supported_versions(); |
| 301 | for (size_t i = 0; i < supported_versions.size(); ++i) { |
| 302 | const QuicVersion& version = supported_versions[i]; |
| 303 | if (std::find(available_versions.begin(), available_versions.end(), |
| 304 | version) != available_versions.end()) { |
| 305 | framer_.set_version(version); |
| 306 | return true; |
| 307 | } |
| 308 | } |
| 309 | |
| 310 | return false; |
| 311 | } |
| 312 | |
| 313 | void QuicConnection::OnError(QuicFramer* framer) { |
| James Robinson | e1b30cf | 2014-10-21 12:25:40 -0700 | [diff] [blame] | 314 | // Packets that we can not or have not decrypted are dropped. |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 315 | // TODO(rch): add stats to measure this. |
| James Robinson | e1b30cf | 2014-10-21 12:25:40 -0700 | [diff] [blame] | 316 | if (FLAGS_quic_drop_junk_packets) { |
| 317 | if (!connected_ || last_packet_decrypted_ == false) { |
| 318 | return; |
| 319 | } |
| 320 | } else { |
| 321 | if (!connected_ || framer->error() == QUIC_DECRYPTION_FAILURE) { |
| 322 | return; |
| 323 | } |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 324 | } |
| 325 | SendConnectionCloseWithDetails(framer->error(), framer->detailed_error()); |
| 326 | } |
| 327 | |
| 328 | void QuicConnection::OnPacket() { |
| 329 | DCHECK(last_stream_frames_.empty() && |
| 330 | last_ack_frames_.empty() && |
| 331 | last_congestion_frames_.empty() && |
| 332 | last_stop_waiting_frames_.empty() && |
| 333 | last_rst_frames_.empty() && |
| 334 | last_goaway_frames_.empty() && |
| 335 | last_window_update_frames_.empty() && |
| 336 | last_blocked_frames_.empty() && |
| 337 | last_ping_frames_.empty() && |
| 338 | last_close_frames_.empty()); |
| James Robinson | e1b30cf | 2014-10-21 12:25:40 -0700 | [diff] [blame] | 339 | last_packet_decrypted_ = false; |
| 340 | last_packet_revived_ = false; |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 341 | } |
| 342 | |
| 343 | void QuicConnection::OnPublicResetPacket( |
| 344 | const QuicPublicResetPacket& packet) { |
| 345 | if (debug_visitor_.get() != nullptr) { |
| 346 | debug_visitor_->OnPublicResetPacket(packet); |
| 347 | } |
| 348 | CloseConnection(QUIC_PUBLIC_RESET, true); |
| 349 | |
| 350 | DVLOG(1) << ENDPOINT << "Connection " << connection_id() |
| 351 | << " closed via QUIC_PUBLIC_RESET from peer."; |
| 352 | } |
| 353 | |
| 354 | bool QuicConnection::OnProtocolVersionMismatch(QuicVersion received_version) { |
| 355 | DVLOG(1) << ENDPOINT << "Received packet with mismatched version " |
| 356 | << received_version; |
| 357 | // TODO(satyamshekhar): Implement no server state in this mode. |
| 358 | if (!is_server_) { |
| 359 | LOG(DFATAL) << ENDPOINT << "Framer called OnProtocolVersionMismatch. " |
| 360 | << "Closing connection."; |
| 361 | CloseConnection(QUIC_INTERNAL_ERROR, false); |
| 362 | return false; |
| 363 | } |
| 364 | DCHECK_NE(version(), received_version); |
| 365 | |
| 366 | if (debug_visitor_.get() != nullptr) { |
| 367 | debug_visitor_->OnProtocolVersionMismatch(received_version); |
| 368 | } |
| 369 | |
| 370 | switch (version_negotiation_state_) { |
| 371 | case START_NEGOTIATION: |
| 372 | if (!framer_.IsSupportedVersion(received_version)) { |
| 373 | SendVersionNegotiationPacket(); |
| 374 | version_negotiation_state_ = NEGOTIATION_IN_PROGRESS; |
| 375 | return false; |
| 376 | } |
| 377 | break; |
| 378 | |
| 379 | case NEGOTIATION_IN_PROGRESS: |
| 380 | if (!framer_.IsSupportedVersion(received_version)) { |
| 381 | SendVersionNegotiationPacket(); |
| 382 | return false; |
| 383 | } |
| 384 | break; |
| 385 | |
| 386 | case NEGOTIATED_VERSION: |
| 387 | // Might be old packets that were sent by the client before the version |
| 388 | // was negotiated. Drop these. |
| 389 | return false; |
| 390 | |
| 391 | default: |
| 392 | DCHECK(false); |
| 393 | } |
| 394 | |
| 395 | version_negotiation_state_ = NEGOTIATED_VERSION; |
| 396 | visitor_->OnSuccessfulVersionNegotiation(received_version); |
| 397 | if (debug_visitor_.get() != nullptr) { |
| 398 | debug_visitor_->OnSuccessfulVersionNegotiation(received_version); |
| 399 | } |
| 400 | DVLOG(1) << ENDPOINT << "version negotiated " << received_version; |
| 401 | |
| 402 | // Store the new version. |
| 403 | framer_.set_version(received_version); |
| 404 | |
| 405 | // TODO(satyamshekhar): Store the sequence number of this packet and close the |
| 406 | // connection if we ever received a packet with incorrect version and whose |
| 407 | // sequence number is greater. |
| 408 | return true; |
| 409 | } |
| 410 | |
| 411 | // Handles version negotiation for client connection. |
| 412 | void QuicConnection::OnVersionNegotiationPacket( |
| 413 | const QuicVersionNegotiationPacket& packet) { |
| 414 | if (is_server_) { |
| 415 | LOG(DFATAL) << ENDPOINT << "Framer parsed VersionNegotiationPacket." |
| 416 | << " Closing connection."; |
| 417 | CloseConnection(QUIC_INTERNAL_ERROR, false); |
| 418 | return; |
| 419 | } |
| 420 | if (debug_visitor_.get() != nullptr) { |
| 421 | debug_visitor_->OnVersionNegotiationPacket(packet); |
| 422 | } |
| 423 | |
| 424 | if (version_negotiation_state_ != START_NEGOTIATION) { |
| 425 | // Possibly a duplicate version negotiation packet. |
| 426 | return; |
| 427 | } |
| 428 | |
| 429 | if (std::find(packet.versions.begin(), |
| 430 | packet.versions.end(), version()) != |
| 431 | packet.versions.end()) { |
| 432 | DLOG(WARNING) << ENDPOINT << "The server already supports our version. " |
| 433 | << "It should have accepted our connection."; |
| 434 | // Just drop the connection. |
| 435 | CloseConnection(QUIC_INVALID_VERSION_NEGOTIATION_PACKET, false); |
| 436 | return; |
| 437 | } |
| 438 | |
| 439 | if (!SelectMutualVersion(packet.versions)) { |
| 440 | SendConnectionCloseWithDetails(QUIC_INVALID_VERSION, |
| 441 | "no common version found"); |
| 442 | return; |
| 443 | } |
| 444 | |
| 445 | DVLOG(1) << ENDPOINT |
| 446 | << "Negotiated version: " << QuicVersionToString(version()); |
| 447 | server_supported_versions_ = packet.versions; |
| 448 | version_negotiation_state_ = NEGOTIATION_IN_PROGRESS; |
| 449 | RetransmitUnackedPackets(ALL_UNACKED_RETRANSMISSION); |
| 450 | } |
| 451 | |
| 452 | void QuicConnection::OnRevivedPacket() { |
| 453 | } |
| 454 | |
| 455 | bool QuicConnection::OnUnauthenticatedPublicHeader( |
| 456 | const QuicPacketPublicHeader& header) { |
| 457 | return true; |
| 458 | } |
| 459 | |
| 460 | bool QuicConnection::OnUnauthenticatedHeader(const QuicPacketHeader& header) { |
| 461 | return true; |
| 462 | } |
| 463 | |
| 464 | void QuicConnection::OnDecryptedPacket(EncryptionLevel level) { |
| 465 | last_decrypted_packet_level_ = level; |
| James Robinson | e1b30cf | 2014-10-21 12:25:40 -0700 | [diff] [blame] | 466 | last_packet_decrypted_ = true; |
| James Robinson | 74f9f1f | 2014-11-04 11:17:49 -0800 | [diff] [blame] | 467 | // If this packet was foward-secure encrypted and the forward-secure encrypter |
| 468 | // is not being used, start using it. |
| 469 | if (FLAGS_enable_quic_delay_forward_security && |
| 470 | encryption_level_ != ENCRYPTION_FORWARD_SECURE && |
| 471 | has_forward_secure_encrypter_ && |
| 472 | level == ENCRYPTION_FORWARD_SECURE) { |
| 473 | SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); |
| 474 | } |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 475 | } |
| 476 | |
| 477 | bool QuicConnection::OnPacketHeader(const QuicPacketHeader& header) { |
| 478 | if (debug_visitor_.get() != nullptr) { |
| 479 | debug_visitor_->OnPacketHeader(header); |
| 480 | } |
| 481 | |
| 482 | if (!ProcessValidatedPacket()) { |
| 483 | return false; |
| 484 | } |
| 485 | |
| 486 | // Will be decrement below if we fall through to return true; |
| 487 | ++stats_.packets_dropped; |
| 488 | |
| 489 | if (header.public_header.connection_id != connection_id_) { |
| 490 | DVLOG(1) << ENDPOINT << "Ignoring packet from unexpected ConnectionId: " |
| 491 | << header.public_header.connection_id << " instead of " |
| 492 | << connection_id_; |
| 493 | if (debug_visitor_.get() != nullptr) { |
| 494 | debug_visitor_->OnIncorrectConnectionId( |
| 495 | header.public_header.connection_id); |
| 496 | } |
| 497 | return false; |
| 498 | } |
| 499 | |
| 500 | if (!Near(header.packet_sequence_number, |
| 501 | last_header_.packet_sequence_number)) { |
| 502 | DVLOG(1) << ENDPOINT << "Packet " << header.packet_sequence_number |
| 503 | << " out of bounds. Discarding"; |
| 504 | SendConnectionCloseWithDetails(QUIC_INVALID_PACKET_HEADER, |
| 505 | "Packet sequence number out of bounds"); |
| 506 | return false; |
| 507 | } |
| 508 | |
| 509 | // If this packet has already been seen, or that the sender |
| 510 | // has told us will not be retransmitted, then stop processing the packet. |
| 511 | if (!received_packet_manager_.IsAwaitingPacket( |
| 512 | header.packet_sequence_number)) { |
| 513 | DVLOG(1) << ENDPOINT << "Packet " << header.packet_sequence_number |
| 514 | << " no longer being waited for. Discarding."; |
| 515 | if (debug_visitor_.get() != nullptr) { |
| 516 | debug_visitor_->OnDuplicatePacket(header.packet_sequence_number); |
| 517 | } |
| 518 | return false; |
| 519 | } |
| 520 | |
| 521 | if (version_negotiation_state_ != NEGOTIATED_VERSION) { |
| 522 | if (is_server_) { |
| 523 | if (!header.public_header.version_flag) { |
| 524 | DLOG(WARNING) << ENDPOINT << "Packet " << header.packet_sequence_number |
| 525 | << " without version flag before version negotiated."; |
| 526 | // Packets should have the version flag till version negotiation is |
| 527 | // done. |
| 528 | CloseConnection(QUIC_INVALID_VERSION, false); |
| 529 | return false; |
| 530 | } else { |
| 531 | DCHECK_EQ(1u, header.public_header.versions.size()); |
| 532 | DCHECK_EQ(header.public_header.versions[0], version()); |
| 533 | version_negotiation_state_ = NEGOTIATED_VERSION; |
| 534 | visitor_->OnSuccessfulVersionNegotiation(version()); |
| 535 | if (debug_visitor_.get() != nullptr) { |
| 536 | debug_visitor_->OnSuccessfulVersionNegotiation(version()); |
| 537 | } |
| 538 | } |
| 539 | } else { |
| 540 | DCHECK(!header.public_header.version_flag); |
| 541 | // If the client gets a packet without the version flag from the server |
| 542 | // it should stop sending version since the version negotiation is done. |
| 543 | packet_generator_.StopSendingVersion(); |
| 544 | version_negotiation_state_ = NEGOTIATED_VERSION; |
| 545 | visitor_->OnSuccessfulVersionNegotiation(version()); |
| 546 | if (debug_visitor_.get() != nullptr) { |
| 547 | debug_visitor_->OnSuccessfulVersionNegotiation(version()); |
| 548 | } |
| 549 | } |
| 550 | } |
| 551 | |
| 552 | DCHECK_EQ(NEGOTIATED_VERSION, version_negotiation_state_); |
| 553 | |
| 554 | --stats_.packets_dropped; |
| 555 | DVLOG(1) << ENDPOINT << "Received packet header: " << header; |
| 556 | last_header_ = header; |
| 557 | DCHECK(connected_); |
| 558 | return true; |
| 559 | } |
| 560 | |
| 561 | void QuicConnection::OnFecProtectedPayload(StringPiece payload) { |
| 562 | DCHECK_EQ(IN_FEC_GROUP, last_header_.is_in_fec_group); |
| 563 | DCHECK_NE(0u, last_header_.fec_group); |
| 564 | QuicFecGroup* group = GetFecGroup(); |
| 565 | if (group != nullptr) { |
| 566 | group->Update(last_decrypted_packet_level_, last_header_, payload); |
| 567 | } |
| 568 | } |
| 569 | |
| 570 | bool QuicConnection::OnStreamFrame(const QuicStreamFrame& frame) { |
| 571 | DCHECK(connected_); |
| 572 | if (debug_visitor_.get() != nullptr) { |
| 573 | debug_visitor_->OnStreamFrame(frame); |
| 574 | } |
| 575 | if (frame.stream_id != kCryptoStreamId && |
| 576 | last_decrypted_packet_level_ == ENCRYPTION_NONE) { |
| 577 | DLOG(WARNING) << ENDPOINT |
| 578 | << "Received an unencrypted data frame: closing connection"; |
| 579 | SendConnectionClose(QUIC_UNENCRYPTED_STREAM_DATA); |
| 580 | return false; |
| 581 | } |
| 582 | last_stream_frames_.push_back(frame); |
| 583 | return true; |
| 584 | } |
| 585 | |
| 586 | bool QuicConnection::OnAckFrame(const QuicAckFrame& incoming_ack) { |
| 587 | DCHECK(connected_); |
| 588 | if (debug_visitor_.get() != nullptr) { |
| 589 | debug_visitor_->OnAckFrame(incoming_ack); |
| 590 | } |
| 591 | DVLOG(1) << ENDPOINT << "OnAckFrame: " << incoming_ack; |
| 592 | |
| 593 | if (last_header_.packet_sequence_number <= largest_seen_packet_with_ack_) { |
| 594 | DVLOG(1) << ENDPOINT << "Received an old ack frame: ignoring"; |
| 595 | return true; |
| 596 | } |
| 597 | |
| 598 | if (!ValidateAckFrame(incoming_ack)) { |
| 599 | SendConnectionClose(QUIC_INVALID_ACK_DATA); |
| 600 | return false; |
| 601 | } |
| 602 | |
| 603 | last_ack_frames_.push_back(incoming_ack); |
| 604 | return connected_; |
| 605 | } |
| 606 | |
| 607 | void QuicConnection::ProcessAckFrame(const QuicAckFrame& incoming_ack) { |
| 608 | largest_seen_packet_with_ack_ = last_header_.packet_sequence_number; |
| 609 | sent_packet_manager_.OnIncomingAck(incoming_ack, |
| 610 | time_of_last_received_packet_); |
| 611 | sent_entropy_manager_.ClearEntropyBefore( |
| 612 | sent_packet_manager_.least_packet_awaited_by_peer() - 1); |
| 613 | if (sent_packet_manager_.HasPendingRetransmissions()) { |
| 614 | WriteIfNotBlocked(); |
| 615 | } |
| 616 | |
| 617 | // Always reset the retransmission alarm when an ack comes in, since we now |
| 618 | // have a better estimate of the current rtt than when it was set. |
| 619 | QuicTime retransmission_time = sent_packet_manager_.GetRetransmissionTime(); |
| 620 | retransmission_alarm_->Update(retransmission_time, |
| 621 | QuicTime::Delta::FromMilliseconds(1)); |
| 622 | } |
| 623 | |
| 624 | void QuicConnection::ProcessStopWaitingFrame( |
| 625 | const QuicStopWaitingFrame& stop_waiting) { |
| 626 | largest_seen_packet_with_stop_waiting_ = last_header_.packet_sequence_number; |
| 627 | received_packet_manager_.UpdatePacketInformationSentByPeer(stop_waiting); |
| 628 | // Possibly close any FecGroups which are now irrelevant. |
| 629 | CloseFecGroupsBefore(stop_waiting.least_unacked + 1); |
| 630 | } |
| 631 | |
| 632 | bool QuicConnection::OnCongestionFeedbackFrame( |
| 633 | const QuicCongestionFeedbackFrame& feedback) { |
| 634 | DCHECK(connected_); |
| 635 | if (debug_visitor_.get() != nullptr) { |
| 636 | debug_visitor_->OnCongestionFeedbackFrame(feedback); |
| 637 | } |
| 638 | last_congestion_frames_.push_back(feedback); |
| 639 | return connected_; |
| 640 | } |
| 641 | |
| 642 | bool QuicConnection::OnStopWaitingFrame(const QuicStopWaitingFrame& frame) { |
| 643 | DCHECK(connected_); |
| 644 | |
| 645 | if (last_header_.packet_sequence_number <= |
| 646 | largest_seen_packet_with_stop_waiting_) { |
| 647 | DVLOG(1) << ENDPOINT << "Received an old stop waiting frame: ignoring"; |
| 648 | return true; |
| 649 | } |
| 650 | |
| 651 | if (!ValidateStopWaitingFrame(frame)) { |
| 652 | SendConnectionClose(QUIC_INVALID_STOP_WAITING_DATA); |
| 653 | return false; |
| 654 | } |
| 655 | |
| 656 | if (debug_visitor_.get() != nullptr) { |
| 657 | debug_visitor_->OnStopWaitingFrame(frame); |
| 658 | } |
| 659 | |
| 660 | last_stop_waiting_frames_.push_back(frame); |
| 661 | return connected_; |
| 662 | } |
| 663 | |
| 664 | bool QuicConnection::OnPingFrame(const QuicPingFrame& frame) { |
| 665 | DCHECK(connected_); |
| 666 | if (debug_visitor_.get() != nullptr) { |
| 667 | debug_visitor_->OnPingFrame(frame); |
| 668 | } |
| 669 | last_ping_frames_.push_back(frame); |
| 670 | return true; |
| 671 | } |
| 672 | |
| 673 | bool QuicConnection::ValidateAckFrame(const QuicAckFrame& incoming_ack) { |
| 674 | if (incoming_ack.largest_observed > packet_generator_.sequence_number()) { |
| 675 | DLOG(ERROR) << ENDPOINT << "Peer's observed unsent packet:" |
| 676 | << incoming_ack.largest_observed << " vs " |
| 677 | << packet_generator_.sequence_number(); |
| 678 | // We got an error for data we have not sent. Error out. |
| 679 | return false; |
| 680 | } |
| 681 | |
| 682 | if (incoming_ack.largest_observed < sent_packet_manager_.largest_observed()) { |
| 683 | DLOG(ERROR) << ENDPOINT << "Peer's largest_observed packet decreased:" |
| 684 | << incoming_ack.largest_observed << " vs " |
| 685 | << sent_packet_manager_.largest_observed(); |
| 686 | // A new ack has a diminished largest_observed value. Error out. |
| 687 | // If this was an old packet, we wouldn't even have checked. |
| 688 | return false; |
| 689 | } |
| 690 | |
| 691 | if (!incoming_ack.missing_packets.empty() && |
| 692 | *incoming_ack.missing_packets.rbegin() > incoming_ack.largest_observed) { |
| 693 | DLOG(ERROR) << ENDPOINT << "Peer sent missing packet: " |
| 694 | << *incoming_ack.missing_packets.rbegin() |
| 695 | << " which is greater than largest observed: " |
| 696 | << incoming_ack.largest_observed; |
| 697 | return false; |
| 698 | } |
| 699 | |
| 700 | if (!incoming_ack.missing_packets.empty() && |
| 701 | *incoming_ack.missing_packets.begin() < |
| 702 | sent_packet_manager_.least_packet_awaited_by_peer()) { |
| 703 | DLOG(ERROR) << ENDPOINT << "Peer sent missing packet: " |
| 704 | << *incoming_ack.missing_packets.begin() |
| 705 | << " which is smaller than least_packet_awaited_by_peer_: " |
| 706 | << sent_packet_manager_.least_packet_awaited_by_peer(); |
| 707 | return false; |
| 708 | } |
| 709 | |
| 710 | if (!sent_entropy_manager_.IsValidEntropy( |
| 711 | incoming_ack.largest_observed, |
| 712 | incoming_ack.missing_packets, |
| 713 | incoming_ack.entropy_hash)) { |
| 714 | DLOG(ERROR) << ENDPOINT << "Peer sent invalid entropy."; |
| 715 | return false; |
| 716 | } |
| 717 | |
| 718 | for (SequenceNumberSet::const_iterator iter = |
| 719 | incoming_ack.revived_packets.begin(); |
| 720 | iter != incoming_ack.revived_packets.end(); ++iter) { |
| 721 | if (!ContainsKey(incoming_ack.missing_packets, *iter)) { |
| 722 | DLOG(ERROR) << ENDPOINT |
| 723 | << "Peer specified revived packet which was not missing."; |
| 724 | return false; |
| 725 | } |
| 726 | } |
| 727 | return true; |
| 728 | } |
| 729 | |
| 730 | bool QuicConnection::ValidateStopWaitingFrame( |
| 731 | const QuicStopWaitingFrame& stop_waiting) { |
| 732 | if (stop_waiting.least_unacked < |
| 733 | received_packet_manager_.peer_least_packet_awaiting_ack()) { |
| 734 | DLOG(ERROR) << ENDPOINT << "Peer's sent low least_unacked: " |
| 735 | << stop_waiting.least_unacked << " vs " |
| 736 | << received_packet_manager_.peer_least_packet_awaiting_ack(); |
| 737 | // We never process old ack frames, so this number should only increase. |
| 738 | return false; |
| 739 | } |
| 740 | |
| 741 | if (stop_waiting.least_unacked > |
| 742 | last_header_.packet_sequence_number) { |
| 743 | DLOG(ERROR) << ENDPOINT << "Peer sent least_unacked:" |
| 744 | << stop_waiting.least_unacked |
| 745 | << " greater than the enclosing packet sequence number:" |
| 746 | << last_header_.packet_sequence_number; |
| 747 | return false; |
| 748 | } |
| 749 | |
| 750 | return true; |
| 751 | } |
| 752 | |
| 753 | void QuicConnection::OnFecData(const QuicFecData& fec) { |
| 754 | DCHECK_EQ(IN_FEC_GROUP, last_header_.is_in_fec_group); |
| 755 | DCHECK_NE(0u, last_header_.fec_group); |
| 756 | QuicFecGroup* group = GetFecGroup(); |
| 757 | if (group != nullptr) { |
| 758 | group->UpdateFec(last_decrypted_packet_level_, |
| 759 | last_header_.packet_sequence_number, fec); |
| 760 | } |
| 761 | } |
| 762 | |
| 763 | bool QuicConnection::OnRstStreamFrame(const QuicRstStreamFrame& frame) { |
| 764 | DCHECK(connected_); |
| 765 | if (debug_visitor_.get() != nullptr) { |
| 766 | debug_visitor_->OnRstStreamFrame(frame); |
| 767 | } |
| 768 | DVLOG(1) << ENDPOINT << "Stream reset with error " |
| 769 | << QuicUtils::StreamErrorToString(frame.error_code); |
| 770 | last_rst_frames_.push_back(frame); |
| 771 | return connected_; |
| 772 | } |
| 773 | |
| 774 | bool QuicConnection::OnConnectionCloseFrame( |
| 775 | const QuicConnectionCloseFrame& frame) { |
| 776 | DCHECK(connected_); |
| 777 | if (debug_visitor_.get() != nullptr) { |
| 778 | debug_visitor_->OnConnectionCloseFrame(frame); |
| 779 | } |
| 780 | DVLOG(1) << ENDPOINT << "Connection " << connection_id() |
| 781 | << " closed with error " |
| 782 | << QuicUtils::ErrorToString(frame.error_code) |
| 783 | << " " << frame.error_details; |
| 784 | last_close_frames_.push_back(frame); |
| 785 | return connected_; |
| 786 | } |
| 787 | |
| 788 | bool QuicConnection::OnGoAwayFrame(const QuicGoAwayFrame& frame) { |
| 789 | DCHECK(connected_); |
| 790 | if (debug_visitor_.get() != nullptr) { |
| 791 | debug_visitor_->OnGoAwayFrame(frame); |
| 792 | } |
| 793 | DVLOG(1) << ENDPOINT << "Go away received with error " |
| 794 | << QuicUtils::ErrorToString(frame.error_code) |
| 795 | << " and reason:" << frame.reason_phrase; |
| 796 | last_goaway_frames_.push_back(frame); |
| 797 | return connected_; |
| 798 | } |
| 799 | |
| 800 | bool QuicConnection::OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) { |
| 801 | DCHECK(connected_); |
| 802 | if (debug_visitor_.get() != nullptr) { |
| 803 | debug_visitor_->OnWindowUpdateFrame(frame); |
| 804 | } |
| 805 | DVLOG(1) << ENDPOINT << "WindowUpdate received for stream: " |
| 806 | << frame.stream_id << " with byte offset: " << frame.byte_offset; |
| 807 | last_window_update_frames_.push_back(frame); |
| 808 | return connected_; |
| 809 | } |
| 810 | |
| 811 | bool QuicConnection::OnBlockedFrame(const QuicBlockedFrame& frame) { |
| 812 | DCHECK(connected_); |
| 813 | if (debug_visitor_.get() != nullptr) { |
| 814 | debug_visitor_->OnBlockedFrame(frame); |
| 815 | } |
| 816 | DVLOG(1) << ENDPOINT << "Blocked frame received for stream: " |
| 817 | << frame.stream_id; |
| 818 | last_blocked_frames_.push_back(frame); |
| 819 | return connected_; |
| 820 | } |
| 821 | |
| 822 | void QuicConnection::OnPacketComplete() { |
| 823 | // Don't do anything if this packet closed the connection. |
| 824 | if (!connected_) { |
| 825 | ClearLastFrames(); |
| 826 | return; |
| 827 | } |
| 828 | |
| 829 | DVLOG(1) << ENDPOINT << (last_packet_revived_ ? "Revived" : "Got") |
| 830 | << " packet " << last_header_.packet_sequence_number |
| 831 | << " with " << last_stream_frames_.size()<< " stream frames " |
| 832 | << last_ack_frames_.size() << " acks, " |
| 833 | << last_congestion_frames_.size() << " congestions, " |
| 834 | << last_stop_waiting_frames_.size() << " stop_waiting, " |
| 835 | << last_rst_frames_.size() << " rsts, " |
| 836 | << last_goaway_frames_.size() << " goaways, " |
| 837 | << last_window_update_frames_.size() << " window updates, " |
| 838 | << last_blocked_frames_.size() << " blocked, " |
| 839 | << last_ping_frames_.size() << " pings, " |
| 840 | << last_close_frames_.size() << " closes, " |
| 841 | << "for " << last_header_.public_header.connection_id; |
| 842 | |
| 843 | ++num_packets_received_since_last_ack_sent_; |
| 844 | |
| 845 | // Call MaybeQueueAck() before recording the received packet, since we want |
| 846 | // to trigger an ack if the newly received packet was previously missing. |
| 847 | MaybeQueueAck(); |
| 848 | |
| 849 | // Record received or revived packet to populate ack info correctly before |
| 850 | // processing stream frames, since the processing may result in a response |
| 851 | // packet with a bundled ack. |
| 852 | if (last_packet_revived_) { |
| 853 | received_packet_manager_.RecordPacketRevived( |
| 854 | last_header_.packet_sequence_number); |
| 855 | } else { |
| 856 | received_packet_manager_.RecordPacketReceived( |
| 857 | last_size_, last_header_, time_of_last_received_packet_); |
| 858 | } |
| 859 | |
| 860 | if (!last_stream_frames_.empty()) { |
| 861 | visitor_->OnStreamFrames(last_stream_frames_); |
| 862 | } |
| 863 | |
| 864 | for (size_t i = 0; i < last_stream_frames_.size(); ++i) { |
| 865 | stats_.stream_bytes_received += |
| 866 | last_stream_frames_[i].data.TotalBufferSize(); |
| 867 | } |
| 868 | |
| 869 | // Process window updates, blocked, stream resets, acks, then congestion |
| 870 | // feedback. |
| 871 | if (!last_window_update_frames_.empty()) { |
| 872 | visitor_->OnWindowUpdateFrames(last_window_update_frames_); |
| 873 | } |
| 874 | if (!last_blocked_frames_.empty()) { |
| 875 | visitor_->OnBlockedFrames(last_blocked_frames_); |
| 876 | } |
| 877 | for (size_t i = 0; i < last_goaway_frames_.size(); ++i) { |
| 878 | visitor_->OnGoAway(last_goaway_frames_[i]); |
| 879 | } |
| 880 | for (size_t i = 0; i < last_rst_frames_.size(); ++i) { |
| 881 | visitor_->OnRstStream(last_rst_frames_[i]); |
| 882 | } |
| 883 | for (size_t i = 0; i < last_ack_frames_.size(); ++i) { |
| 884 | ProcessAckFrame(last_ack_frames_[i]); |
| 885 | } |
| 886 | for (size_t i = 0; i < last_congestion_frames_.size(); ++i) { |
| 887 | sent_packet_manager_.OnIncomingQuicCongestionFeedbackFrame( |
| 888 | last_congestion_frames_[i], time_of_last_received_packet_); |
| 889 | } |
| 890 | for (size_t i = 0; i < last_stop_waiting_frames_.size(); ++i) { |
| 891 | ProcessStopWaitingFrame(last_stop_waiting_frames_[i]); |
| 892 | } |
| 893 | if (!last_close_frames_.empty()) { |
| 894 | CloseConnection(last_close_frames_[0].error_code, true); |
| 895 | DCHECK(!connected_); |
| 896 | } |
| 897 | |
| 898 | // If there are new missing packets to report, send an ack immediately. |
| 899 | if (received_packet_manager_.HasNewMissingPackets()) { |
| 900 | ack_queued_ = true; |
| 901 | ack_alarm_->Cancel(); |
| 902 | } |
| 903 | |
| 904 | UpdateStopWaitingCount(); |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 905 | ClearLastFrames(); |
| James Robinson | 7f48021 | 2014-10-31 10:28:08 -0700 | [diff] [blame] | 906 | MaybeCloseIfTooManyOutstandingPackets(); |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 907 | } |
| 908 | |
| 909 | void QuicConnection::MaybeQueueAck() { |
| 910 | // If the incoming packet was missing, send an ack immediately. |
| 911 | ack_queued_ = received_packet_manager_.IsMissing( |
| 912 | last_header_.packet_sequence_number); |
| 913 | |
| 914 | if (!ack_queued_ && ShouldLastPacketInstigateAck()) { |
| 915 | if (ack_alarm_->IsSet()) { |
| 916 | ack_queued_ = true; |
| 917 | } else { |
| 918 | // Send an ack much more quickly for crypto handshake packets. |
| 919 | QuicTime::Delta delayed_ack_time = sent_packet_manager_.DelayedAckTime(); |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 920 | ack_alarm_->Set(clock_->ApproximateNow().Add(delayed_ack_time)); |
| 921 | DVLOG(1) << "Ack timer set; next packet or timer will trigger ACK."; |
| 922 | } |
| 923 | } |
| 924 | |
| 925 | if (ack_queued_) { |
| 926 | ack_alarm_->Cancel(); |
| 927 | } |
| 928 | } |
| 929 | |
| 930 | void QuicConnection::ClearLastFrames() { |
| 931 | last_stream_frames_.clear(); |
| 932 | last_ack_frames_.clear(); |
| 933 | last_congestion_frames_.clear(); |
| 934 | last_stop_waiting_frames_.clear(); |
| 935 | last_rst_frames_.clear(); |
| 936 | last_goaway_frames_.clear(); |
| 937 | last_window_update_frames_.clear(); |
| 938 | last_blocked_frames_.clear(); |
| 939 | last_ping_frames_.clear(); |
| 940 | last_close_frames_.clear(); |
| 941 | } |
| 942 | |
| James Robinson | 7f48021 | 2014-10-31 10:28:08 -0700 | [diff] [blame] | 943 | void QuicConnection::MaybeCloseIfTooManyOutstandingPackets() { |
| 944 | if (!FLAGS_quic_too_many_outstanding_packets) { |
| 945 | return; |
| 946 | } |
| 947 | // This occurs if we don't discard old packets we've sent fast enough. |
| 948 | // It's possible largest observed is less than least unacked. |
| 949 | if (sent_packet_manager_.largest_observed() > |
| 950 | (sent_packet_manager_.GetLeastUnacked() + kMaxTrackedPackets)) { |
| 951 | SendConnectionCloseWithDetails( |
| 952 | QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS, |
| James Robinson | 6a64b81 | 2014-12-03 13:38:42 -0800 | [diff] [blame^] | 953 | StringPrintf("More than %" PRIu64 " outstanding.", kMaxTrackedPackets)); |
| James Robinson | 7f48021 | 2014-10-31 10:28:08 -0700 | [diff] [blame] | 954 | } |
| 955 | // This occurs if there are received packet gaps and the peer does not raise |
| 956 | // the least unacked fast enough. |
| 957 | if (received_packet_manager_.NumTrackedPackets() > kMaxTrackedPackets) { |
| 958 | SendConnectionCloseWithDetails( |
| 959 | QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS, |
| James Robinson | 6a64b81 | 2014-12-03 13:38:42 -0800 | [diff] [blame^] | 960 | StringPrintf("More than %" PRIu64 " outstanding.", kMaxTrackedPackets)); |
| James Robinson | 7f48021 | 2014-10-31 10:28:08 -0700 | [diff] [blame] | 961 | } |
| 962 | } |
| 963 | |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 964 | QuicAckFrame* QuicConnection::CreateAckFrame() { |
| 965 | QuicAckFrame* outgoing_ack = new QuicAckFrame(); |
| 966 | received_packet_manager_.UpdateReceivedPacketInfo( |
| 967 | outgoing_ack, clock_->ApproximateNow()); |
| 968 | DVLOG(1) << ENDPOINT << "Creating ack frame: " << *outgoing_ack; |
| 969 | return outgoing_ack; |
| 970 | } |
| 971 | |
| 972 | QuicCongestionFeedbackFrame* QuicConnection::CreateFeedbackFrame() { |
| 973 | return new QuicCongestionFeedbackFrame(outgoing_congestion_feedback_); |
| 974 | } |
| 975 | |
| 976 | QuicStopWaitingFrame* QuicConnection::CreateStopWaitingFrame() { |
| 977 | QuicStopWaitingFrame stop_waiting; |
| 978 | UpdateStopWaiting(&stop_waiting); |
| 979 | return new QuicStopWaitingFrame(stop_waiting); |
| 980 | } |
| 981 | |
| 982 | bool QuicConnection::ShouldLastPacketInstigateAck() const { |
| 983 | if (!last_stream_frames_.empty() || |
| 984 | !last_goaway_frames_.empty() || |
| 985 | !last_rst_frames_.empty() || |
| 986 | !last_window_update_frames_.empty() || |
| 987 | !last_blocked_frames_.empty() || |
| 988 | !last_ping_frames_.empty()) { |
| 989 | return true; |
| 990 | } |
| 991 | |
| 992 | if (!last_ack_frames_.empty() && last_ack_frames_.back().is_truncated) { |
| 993 | return true; |
| 994 | } |
| 995 | // Always send an ack every 20 packets in order to allow the peer to discard |
| 996 | // information from the SentPacketManager and provide an RTT measurement. |
| 997 | if (num_packets_received_since_last_ack_sent_ >= |
| 998 | kMaxPacketsReceivedBeforeAckSend) { |
| 999 | return true; |
| 1000 | } |
| 1001 | return false; |
| 1002 | } |
| 1003 | |
| 1004 | void QuicConnection::UpdateStopWaitingCount() { |
| 1005 | if (last_ack_frames_.empty()) { |
| 1006 | return; |
| 1007 | } |
| 1008 | |
| 1009 | // If the peer is still waiting for a packet that we are no longer planning to |
| 1010 | // send, send an ack to raise the high water mark. |
| 1011 | if (!last_ack_frames_.back().missing_packets.empty() && |
| 1012 | GetLeastUnacked() > *last_ack_frames_.back().missing_packets.begin()) { |
| 1013 | ++stop_waiting_count_; |
| 1014 | } else { |
| 1015 | stop_waiting_count_ = 0; |
| 1016 | } |
| 1017 | } |
| 1018 | |
| 1019 | QuicPacketSequenceNumber QuicConnection::GetLeastUnacked() const { |
| 1020 | return sent_packet_manager_.GetLeastUnacked(); |
| 1021 | } |
| 1022 | |
| 1023 | void QuicConnection::MaybeSendInResponseToPacket() { |
| 1024 | if (!connected_) { |
| 1025 | return; |
| 1026 | } |
| 1027 | ScopedPacketBundler bundler(this, ack_queued_ ? SEND_ACK : NO_ACK); |
| 1028 | |
| 1029 | // Now that we have received an ack, we might be able to send packets which |
| 1030 | // are queued locally, or drain streams which are blocked. |
| 1031 | if (CanWrite(HAS_RETRANSMITTABLE_DATA)) { |
| 1032 | OnCanWrite(); |
| 1033 | } |
| 1034 | } |
| 1035 | |
| 1036 | void QuicConnection::SendVersionNegotiationPacket() { |
| 1037 | // TODO(alyssar): implement zero server state negotiation. |
| 1038 | pending_version_negotiation_packet_ = true; |
| 1039 | if (writer_->IsWriteBlocked()) { |
| 1040 | visitor_->OnWriteBlocked(); |
| 1041 | return; |
| 1042 | } |
| 1043 | DVLOG(1) << ENDPOINT << "Sending version negotiation packet: {" |
| 1044 | << QuicVersionVectorToString(framer_.supported_versions()) << "}"; |
| 1045 | scoped_ptr<QuicEncryptedPacket> version_packet( |
| 1046 | packet_generator_.SerializeVersionNegotiationPacket( |
| 1047 | framer_.supported_versions())); |
| 1048 | WriteResult result = writer_->WritePacket( |
| 1049 | version_packet->data(), version_packet->length(), |
| 1050 | self_address().address(), peer_address()); |
| 1051 | |
| 1052 | if (result.status == WRITE_STATUS_ERROR) { |
| 1053 | // We can't send an error as the socket is presumably borked. |
| 1054 | CloseConnection(QUIC_PACKET_WRITE_ERROR, false); |
| 1055 | return; |
| 1056 | } |
| 1057 | if (result.status == WRITE_STATUS_BLOCKED) { |
| 1058 | visitor_->OnWriteBlocked(); |
| 1059 | if (writer_->IsWriteBlockedDataBuffered()) { |
| 1060 | pending_version_negotiation_packet_ = false; |
| 1061 | } |
| 1062 | return; |
| 1063 | } |
| 1064 | |
| 1065 | pending_version_negotiation_packet_ = false; |
| 1066 | } |
| 1067 | |
| 1068 | QuicConsumedData QuicConnection::SendStreamData( |
| 1069 | QuicStreamId id, |
| 1070 | const IOVector& data, |
| 1071 | QuicStreamOffset offset, |
| 1072 | bool fin, |
| 1073 | FecProtection fec_protection, |
| 1074 | QuicAckNotifier::DelegateInterface* delegate) { |
| 1075 | if (!fin && data.Empty()) { |
| 1076 | LOG(DFATAL) << "Attempt to send empty stream frame"; |
| 1077 | } |
| 1078 | |
| 1079 | // This notifier will be owned by the AckNotifierManager (or deleted below if |
| 1080 | // no data or FIN was consumed). |
| 1081 | QuicAckNotifier* notifier = nullptr; |
| 1082 | if (delegate) { |
| 1083 | notifier = new QuicAckNotifier(delegate); |
| 1084 | } |
| 1085 | |
| 1086 | // Opportunistically bundle an ack with every outgoing packet. |
| 1087 | // Particularly, we want to bundle with handshake packets since we don't know |
| 1088 | // which decrypter will be used on an ack packet following a handshake |
| 1089 | // packet (a handshake packet from client to server could result in a REJ or a |
| 1090 | // SHLO from the server, leading to two different decrypters at the server.) |
| 1091 | // |
| 1092 | // TODO(jri): Note that ConsumeData may cause a response packet to be sent. |
| 1093 | // We may end up sending stale ack information if there are undecryptable |
| 1094 | // packets hanging around and/or there are revivable packets which may get |
| 1095 | // handled after this packet is sent. Change ScopedPacketBundler to do the |
| 1096 | // right thing: check ack_queued_, and then check undecryptable packets and |
| 1097 | // also if there is possibility of revival. Only bundle an ack if there's no |
| 1098 | // processing left that may cause received_info_ to change. |
| 1099 | ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK); |
| 1100 | QuicConsumedData consumed_data = |
| 1101 | packet_generator_.ConsumeData(id, data, offset, fin, fec_protection, |
| 1102 | notifier); |
| 1103 | |
| 1104 | if (notifier && |
| 1105 | (consumed_data.bytes_consumed == 0 && !consumed_data.fin_consumed)) { |
| 1106 | // No data was consumed, nor was a fin consumed, so delete the notifier. |
| 1107 | delete notifier; |
| 1108 | } |
| 1109 | |
| 1110 | return consumed_data; |
| 1111 | } |
| 1112 | |
| 1113 | void QuicConnection::SendRstStream(QuicStreamId id, |
| 1114 | QuicRstStreamErrorCode error, |
| 1115 | QuicStreamOffset bytes_written) { |
| 1116 | // Opportunistically bundle an ack with this outgoing packet. |
| 1117 | ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK); |
| 1118 | packet_generator_.AddControlFrame(QuicFrame(new QuicRstStreamFrame( |
| 1119 | id, AdjustErrorForVersion(error, version()), bytes_written))); |
| 1120 | } |
| 1121 | |
| 1122 | void QuicConnection::SendWindowUpdate(QuicStreamId id, |
| 1123 | QuicStreamOffset byte_offset) { |
| 1124 | // Opportunistically bundle an ack with this outgoing packet. |
| 1125 | ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK); |
| 1126 | packet_generator_.AddControlFrame( |
| 1127 | QuicFrame(new QuicWindowUpdateFrame(id, byte_offset))); |
| 1128 | } |
| 1129 | |
| 1130 | void QuicConnection::SendBlocked(QuicStreamId id) { |
| 1131 | // Opportunistically bundle an ack with this outgoing packet. |
| 1132 | ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK); |
| 1133 | packet_generator_.AddControlFrame(QuicFrame(new QuicBlockedFrame(id))); |
| 1134 | } |
| 1135 | |
| 1136 | const QuicConnectionStats& QuicConnection::GetStats() { |
| 1137 | // Update rtt and estimated bandwidth. |
| 1138 | stats_.min_rtt_us = |
| James Robinson | 1ae030a | 2014-11-07 08:32:47 -0800 | [diff] [blame] | 1139 | sent_packet_manager_.GetRttStats()->min_rtt().ToMicroseconds(); |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 1140 | stats_.srtt_us = |
| James Robinson | 1ae030a | 2014-11-07 08:32:47 -0800 | [diff] [blame] | 1141 | sent_packet_manager_.GetRttStats()->smoothed_rtt().ToMicroseconds(); |
| James Robinson | 6a64b81 | 2014-12-03 13:38:42 -0800 | [diff] [blame^] | 1142 | stats_.estimated_bandwidth = sent_packet_manager_.BandwidthEstimate(); |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 1143 | stats_.max_packet_size = packet_generator_.max_packet_length(); |
| 1144 | return stats_; |
| 1145 | } |
| 1146 | |
| 1147 | void QuicConnection::ProcessUdpPacket(const IPEndPoint& self_address, |
| 1148 | const IPEndPoint& peer_address, |
| 1149 | const QuicEncryptedPacket& packet) { |
| 1150 | if (!connected_) { |
| 1151 | return; |
| 1152 | } |
| 1153 | if (debug_visitor_.get() != nullptr) { |
| 1154 | debug_visitor_->OnPacketReceived(self_address, peer_address, packet); |
| 1155 | } |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 1156 | last_size_ = packet.length(); |
| 1157 | |
| 1158 | CheckForAddressMigration(self_address, peer_address); |
| 1159 | |
| 1160 | stats_.bytes_received += packet.length(); |
| 1161 | ++stats_.packets_received; |
| 1162 | |
| 1163 | if (!framer_.ProcessPacket(packet)) { |
| 1164 | // If we are unable to decrypt this packet, it might be |
| 1165 | // because the CHLO or SHLO packet was lost. |
| 1166 | if (framer_.error() == QUIC_DECRYPTION_FAILURE) { |
| 1167 | if (encryption_level_ != ENCRYPTION_FORWARD_SECURE && |
| James Robinson | e2ac7e8 | 2014-10-15 13:21:59 -0700 | [diff] [blame] | 1168 | undecryptable_packets_.size() < max_undecryptable_packets_) { |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 1169 | QueueUndecryptablePacket(packet); |
| 1170 | } else if (debug_visitor_.get() != nullptr) { |
| 1171 | debug_visitor_->OnUndecryptablePacket(); |
| 1172 | } |
| 1173 | } |
| 1174 | DVLOG(1) << ENDPOINT << "Unable to process packet. Last packet processed: " |
| 1175 | << last_header_.packet_sequence_number; |
| 1176 | return; |
| 1177 | } |
| 1178 | |
| 1179 | ++stats_.packets_processed; |
| 1180 | MaybeProcessUndecryptablePackets(); |
| 1181 | MaybeProcessRevivedPacket(); |
| 1182 | MaybeSendInResponseToPacket(); |
| 1183 | SetPingAlarm(); |
| 1184 | } |
| 1185 | |
| 1186 | void QuicConnection::CheckForAddressMigration( |
| 1187 | const IPEndPoint& self_address, const IPEndPoint& peer_address) { |
| 1188 | peer_ip_changed_ = false; |
| 1189 | peer_port_changed_ = false; |
| 1190 | self_ip_changed_ = false; |
| 1191 | self_port_changed_ = false; |
| 1192 | |
| 1193 | if (peer_address_.address().empty()) { |
| 1194 | peer_address_ = peer_address; |
| 1195 | } |
| 1196 | if (self_address_.address().empty()) { |
| 1197 | self_address_ = self_address; |
| 1198 | } |
| 1199 | |
| 1200 | if (!peer_address.address().empty() && !peer_address_.address().empty()) { |
| 1201 | peer_ip_changed_ = (peer_address.address() != peer_address_.address()); |
| 1202 | peer_port_changed_ = (peer_address.port() != peer_address_.port()); |
| 1203 | |
| 1204 | // Store in case we want to migrate connection in ProcessValidatedPacket. |
| 1205 | migrating_peer_port_ = peer_address.port(); |
| 1206 | } |
| 1207 | |
| 1208 | if (!self_address.address().empty() && !self_address_.address().empty()) { |
| 1209 | self_ip_changed_ = (self_address.address() != self_address_.address()); |
| 1210 | self_port_changed_ = (self_address.port() != self_address_.port()); |
| 1211 | } |
| 1212 | } |
| 1213 | |
| 1214 | void QuicConnection::OnCanWrite() { |
| 1215 | DCHECK(!writer_->IsWriteBlocked()); |
| 1216 | |
| 1217 | WriteQueuedPackets(); |
| 1218 | WritePendingRetransmissions(); |
| 1219 | |
| 1220 | // Sending queued packets may have caused the socket to become write blocked, |
| 1221 | // or the congestion manager to prohibit sending. If we've sent everything |
| 1222 | // we had queued and we're still not blocked, let the visitor know it can |
| 1223 | // write more. |
| 1224 | if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) { |
| 1225 | return; |
| 1226 | } |
| 1227 | |
| James Robinson | e2ac7e8 | 2014-10-15 13:21:59 -0700 | [diff] [blame] | 1228 | { // Limit the scope of the bundler. ACK inclusion happens elsewhere. |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 1229 | ScopedPacketBundler bundler(this, NO_ACK); |
| 1230 | visitor_->OnCanWrite(); |
| 1231 | } |
| 1232 | |
| 1233 | // After the visitor writes, it may have caused the socket to become write |
| 1234 | // blocked or the congestion manager to prohibit sending, so check again. |
| 1235 | if (visitor_->WillingAndAbleToWrite() && |
| 1236 | !resume_writes_alarm_->IsSet() && |
| 1237 | CanWrite(HAS_RETRANSMITTABLE_DATA)) { |
| 1238 | // We're not write blocked, but some stream didn't write out all of its |
| 1239 | // bytes. Register for 'immediate' resumption so we'll keep writing after |
| 1240 | // other connections and events have had a chance to use the thread. |
| 1241 | resume_writes_alarm_->Set(clock_->ApproximateNow()); |
| 1242 | } |
| 1243 | } |
| 1244 | |
| 1245 | void QuicConnection::WriteIfNotBlocked() { |
| 1246 | if (!writer_->IsWriteBlocked()) { |
| 1247 | OnCanWrite(); |
| 1248 | } |
| 1249 | } |
| 1250 | |
| 1251 | bool QuicConnection::ProcessValidatedPacket() { |
| 1252 | if (peer_ip_changed_ || self_ip_changed_ || self_port_changed_) { |
| 1253 | SendConnectionCloseWithDetails( |
| 1254 | QUIC_ERROR_MIGRATING_ADDRESS, |
| 1255 | "Neither IP address migration, nor self port migration are supported."); |
| 1256 | return false; |
| 1257 | } |
| 1258 | |
| 1259 | // Peer port migration is supported, do it now if port has changed. |
| 1260 | if (peer_port_changed_) { |
| 1261 | DVLOG(1) << ENDPOINT << "Peer's port changed from " |
| 1262 | << peer_address_.port() << " to " << migrating_peer_port_ |
| 1263 | << ", migrating connection."; |
| 1264 | peer_address_ = IPEndPoint(peer_address_.address(), migrating_peer_port_); |
| 1265 | } |
| 1266 | |
| 1267 | time_of_last_received_packet_ = clock_->Now(); |
| 1268 | DVLOG(1) << ENDPOINT << "time of last received packet: " |
| 1269 | << time_of_last_received_packet_.ToDebuggingValue(); |
| 1270 | |
| 1271 | if (is_server_ && encryption_level_ == ENCRYPTION_NONE && |
| 1272 | last_size_ > packet_generator_.max_packet_length()) { |
| James Robinson | 1ae030a | 2014-11-07 08:32:47 -0800 | [diff] [blame] | 1273 | set_max_packet_length(last_size_); |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 1274 | } |
| 1275 | return true; |
| 1276 | } |
| 1277 | |
| 1278 | void QuicConnection::WriteQueuedPackets() { |
| 1279 | DCHECK(!writer_->IsWriteBlocked()); |
| 1280 | |
| 1281 | if (pending_version_negotiation_packet_) { |
| 1282 | SendVersionNegotiationPacket(); |
| 1283 | } |
| 1284 | |
| 1285 | QueuedPacketList::iterator packet_iterator = queued_packets_.begin(); |
| 1286 | while (packet_iterator != queued_packets_.end() && |
| 1287 | WritePacket(&(*packet_iterator))) { |
| 1288 | packet_iterator = queued_packets_.erase(packet_iterator); |
| 1289 | } |
| 1290 | } |
| 1291 | |
| 1292 | void QuicConnection::WritePendingRetransmissions() { |
| 1293 | // Keep writing as long as there's a pending retransmission which can be |
| 1294 | // written. |
| 1295 | while (sent_packet_manager_.HasPendingRetransmissions()) { |
| 1296 | const QuicSentPacketManager::PendingRetransmission pending = |
| 1297 | sent_packet_manager_.NextPendingRetransmission(); |
| 1298 | if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) { |
| 1299 | break; |
| 1300 | } |
| 1301 | |
| 1302 | // Re-packetize the frames with a new sequence number for retransmission. |
| 1303 | // Retransmitted data packets do not use FEC, even when it's enabled. |
| 1304 | // Retransmitted packets use the same sequence number length as the |
| 1305 | // original. |
| 1306 | // Flush the packet generator before making a new packet. |
| 1307 | // TODO(ianswett): Implement ReserializeAllFrames as a separate path that |
| 1308 | // does not require the creator to be flushed. |
| 1309 | packet_generator_.FlushAllQueuedFrames(); |
| 1310 | SerializedPacket serialized_packet = packet_generator_.ReserializeAllFrames( |
| 1311 | pending.retransmittable_frames.frames(), |
| 1312 | pending.sequence_number_length); |
| 1313 | |
| 1314 | DVLOG(1) << ENDPOINT << "Retransmitting " << pending.sequence_number |
| 1315 | << " as " << serialized_packet.sequence_number; |
| 1316 | SendOrQueuePacket( |
| 1317 | QueuedPacket(serialized_packet, |
| 1318 | pending.retransmittable_frames.encryption_level(), |
| 1319 | pending.transmission_type, |
| 1320 | pending.sequence_number)); |
| 1321 | } |
| 1322 | } |
| 1323 | |
| 1324 | void QuicConnection::RetransmitUnackedPackets( |
| 1325 | TransmissionType retransmission_type) { |
| 1326 | sent_packet_manager_.RetransmitUnackedPackets(retransmission_type); |
| 1327 | |
| 1328 | WriteIfNotBlocked(); |
| 1329 | } |
| 1330 | |
| 1331 | void QuicConnection::NeuterUnencryptedPackets() { |
| 1332 | sent_packet_manager_.NeuterUnencryptedPackets(); |
| 1333 | // This may have changed the retransmission timer, so re-arm it. |
| 1334 | QuicTime retransmission_time = sent_packet_manager_.GetRetransmissionTime(); |
| 1335 | retransmission_alarm_->Update(retransmission_time, |
| 1336 | QuicTime::Delta::FromMilliseconds(1)); |
| 1337 | } |
| 1338 | |
| 1339 | bool QuicConnection::ShouldGeneratePacket( |
| 1340 | TransmissionType transmission_type, |
| 1341 | HasRetransmittableData retransmittable, |
| 1342 | IsHandshake handshake) { |
| 1343 | // We should serialize handshake packets immediately to ensure that they |
| 1344 | // end up sent at the right encryption level. |
| 1345 | if (handshake == IS_HANDSHAKE) { |
| 1346 | return true; |
| 1347 | } |
| 1348 | |
| 1349 | return CanWrite(retransmittable); |
| 1350 | } |
| 1351 | |
| 1352 | bool QuicConnection::CanWrite(HasRetransmittableData retransmittable) { |
| 1353 | if (!connected_) { |
| 1354 | return false; |
| 1355 | } |
| 1356 | |
| 1357 | if (writer_->IsWriteBlocked()) { |
| 1358 | visitor_->OnWriteBlocked(); |
| 1359 | return false; |
| 1360 | } |
| 1361 | |
| 1362 | QuicTime now = clock_->Now(); |
| 1363 | QuicTime::Delta delay = sent_packet_manager_.TimeUntilSend( |
| 1364 | now, retransmittable); |
| 1365 | if (delay.IsInfinite()) { |
| 1366 | send_alarm_->Cancel(); |
| 1367 | return false; |
| 1368 | } |
| 1369 | |
| 1370 | // If the scheduler requires a delay, then we can not send this packet now. |
| 1371 | if (!delay.IsZero()) { |
| 1372 | send_alarm_->Update(now.Add(delay), QuicTime::Delta::FromMilliseconds(1)); |
| James Robinson | e2ac7e8 | 2014-10-15 13:21:59 -0700 | [diff] [blame] | 1373 | DVLOG(1) << ENDPOINT << "Delaying sending " << delay.ToMilliseconds() |
| 1374 | << "ms"; |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 1375 | return false; |
| 1376 | } |
| 1377 | send_alarm_->Cancel(); |
| 1378 | return true; |
| 1379 | } |
| 1380 | |
| 1381 | bool QuicConnection::WritePacket(QueuedPacket* packet) { |
| 1382 | if (!WritePacketInner(packet)) { |
| 1383 | return false; |
| 1384 | } |
| 1385 | delete packet->serialized_packet.retransmittable_frames; |
| 1386 | delete packet->serialized_packet.packet; |
| 1387 | packet->serialized_packet.retransmittable_frames = nullptr; |
| 1388 | packet->serialized_packet.packet = nullptr; |
| 1389 | return true; |
| 1390 | } |
| 1391 | |
| 1392 | bool QuicConnection::WritePacketInner(QueuedPacket* packet) { |
| 1393 | if (ShouldDiscardPacket(*packet)) { |
| 1394 | ++stats_.packets_discarded; |
| 1395 | return true; |
| 1396 | } |
| 1397 | // Connection close packets are encrypted and saved, so don't exit early. |
| 1398 | if (writer_->IsWriteBlocked() && !IsConnectionClose(*packet)) { |
| 1399 | return false; |
| 1400 | } |
| 1401 | |
| 1402 | QuicPacketSequenceNumber sequence_number = |
| 1403 | packet->serialized_packet.sequence_number; |
| 1404 | DCHECK_LE(sequence_number_of_last_sent_packet_, sequence_number); |
| 1405 | sequence_number_of_last_sent_packet_ = sequence_number; |
| 1406 | |
| 1407 | QuicEncryptedPacket* encrypted = framer_.EncryptPacket( |
| 1408 | packet->encryption_level, |
| 1409 | sequence_number, |
| 1410 | *packet->serialized_packet.packet); |
| 1411 | if (encrypted == nullptr) { |
| 1412 | LOG(DFATAL) << ENDPOINT << "Failed to encrypt packet number " |
| 1413 | << sequence_number; |
| 1414 | // CloseConnection does not send close packet, so no infinite loop here. |
| 1415 | CloseConnection(QUIC_ENCRYPTION_FAILURE, false); |
| 1416 | return false; |
| 1417 | } |
| 1418 | |
| 1419 | // Connection close packets are eventually owned by TimeWaitListManager. |
| 1420 | // Others are deleted at the end of this call. |
| 1421 | scoped_ptr<QuicEncryptedPacket> encrypted_deleter; |
| 1422 | if (IsConnectionClose(*packet)) { |
| 1423 | DCHECK(connection_close_packet_.get() == nullptr); |
| 1424 | connection_close_packet_.reset(encrypted); |
| 1425 | // This assures we won't try to write *forced* packets when blocked. |
| 1426 | // Return true to stop processing. |
| 1427 | if (writer_->IsWriteBlocked()) { |
| 1428 | visitor_->OnWriteBlocked(); |
| 1429 | return true; |
| 1430 | } |
| 1431 | } else { |
| 1432 | encrypted_deleter.reset(encrypted); |
| 1433 | } |
| 1434 | |
| 1435 | if (!FLAGS_quic_allow_oversized_packets_for_test) { |
| 1436 | DCHECK_LE(encrypted->length(), kMaxPacketSize); |
| 1437 | } |
| 1438 | DCHECK_LE(encrypted->length(), packet_generator_.max_packet_length()); |
| 1439 | DVLOG(1) << ENDPOINT << "Sending packet " << sequence_number << " : " |
| 1440 | << (packet->serialized_packet.packet->is_fec_packet() ? "FEC " : |
| 1441 | (IsRetransmittable(*packet) == HAS_RETRANSMITTABLE_DATA |
| 1442 | ? "data bearing " : " ack only ")) |
| 1443 | << ", encryption level: " |
| 1444 | << QuicUtils::EncryptionLevelToString(packet->encryption_level) |
| 1445 | << ", length:" |
| 1446 | << packet->serialized_packet.packet->length() |
| 1447 | << ", encrypted length:" |
| 1448 | << encrypted->length(); |
| 1449 | DVLOG(2) << ENDPOINT << "packet(" << sequence_number << "): " << std::endl |
| 1450 | << QuicUtils::StringToHexASCIIDump( |
| 1451 | packet->serialized_packet.packet->AsStringPiece()); |
| 1452 | |
| James Robinson | c4c1c59 | 2014-11-21 18:27:04 -0800 | [diff] [blame] | 1453 | QuicTime packet_send_time = QuicTime::Zero(); |
| 1454 | if (FLAGS_quic_record_send_time_before_write) { |
| 1455 | // Measure the RTT from before the write begins to avoid underestimating the |
| 1456 | // min_rtt_, especially in cases where the thread blocks or gets swapped out |
| 1457 | // during the WritePacket below. |
| 1458 | packet_send_time = clock_->Now(); |
| 1459 | } |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 1460 | WriteResult result = writer_->WritePacket(encrypted->data(), |
| 1461 | encrypted->length(), |
| 1462 | self_address().address(), |
| 1463 | peer_address()); |
| 1464 | if (result.error_code == ERR_IO_PENDING) { |
| 1465 | DCHECK_EQ(WRITE_STATUS_BLOCKED, result.status); |
| 1466 | } |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 1467 | |
| 1468 | if (result.status == WRITE_STATUS_BLOCKED) { |
| 1469 | visitor_->OnWriteBlocked(); |
| 1470 | // If the socket buffers the the data, then the packet should not |
| 1471 | // be queued and sent again, which would result in an unnecessary |
| 1472 | // duplicate packet being sent. The helper must call OnCanWrite |
| 1473 | // when the write completes, and OnWriteError if an error occurs. |
| 1474 | if (!writer_->IsWriteBlockedDataBuffered()) { |
| 1475 | return false; |
| 1476 | } |
| 1477 | } |
| James Robinson | c4c1c59 | 2014-11-21 18:27:04 -0800 | [diff] [blame] | 1478 | if (!FLAGS_quic_record_send_time_before_write) { |
| 1479 | packet_send_time = clock_->Now(); |
| 1480 | } |
| 1481 | if (!packet_send_time.IsInitialized()) { |
| 1482 | // TODO(jokulik): This is only needed because of the two code paths for |
| 1483 | // initializing packet_send_time. Once "quic_record_send_time_before_write" |
| 1484 | // is deprecated, this check can be removed. |
| 1485 | LOG(DFATAL) << "The packet send time should never be zero. " |
| 1486 | << "This is a programming bug, please report it."; |
| 1487 | } |
| James Robinson | e2ac7e8 | 2014-10-15 13:21:59 -0700 | [diff] [blame] | 1488 | if (result.status != WRITE_STATUS_ERROR && debug_visitor_.get() != nullptr) { |
| 1489 | // Pass the write result to the visitor. |
| 1490 | debug_visitor_->OnPacketSent(packet->serialized_packet, |
| 1491 | packet->original_sequence_number, |
| 1492 | packet->encryption_level, |
| 1493 | packet->transmission_type, |
| 1494 | *encrypted, |
| James Robinson | c4c1c59 | 2014-11-21 18:27:04 -0800 | [diff] [blame] | 1495 | packet_send_time); |
| James Robinson | e2ac7e8 | 2014-10-15 13:21:59 -0700 | [diff] [blame] | 1496 | } |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 1497 | if (packet->transmission_type == NOT_RETRANSMISSION) { |
| James Robinson | c4c1c59 | 2014-11-21 18:27:04 -0800 | [diff] [blame] | 1498 | time_of_last_sent_new_packet_ = packet_send_time; |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 1499 | } |
| 1500 | SetPingAlarm(); |
| James Robinson | c4c1c59 | 2014-11-21 18:27:04 -0800 | [diff] [blame] | 1501 | DVLOG(1) << ENDPOINT << "time " |
| 1502 | << (FLAGS_quic_record_send_time_before_write ? |
| 1503 | "we began writing " : "we finished writing ") |
| 1504 | << "last sent packet: " |
| 1505 | << packet_send_time.ToDebuggingValue(); |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 1506 | |
| 1507 | // TODO(ianswett): Change the sequence number length and other packet creator |
| 1508 | // options by a more explicit API than setting a struct value directly, |
| 1509 | // perhaps via the NetworkChangeVisitor. |
| 1510 | packet_generator_.UpdateSequenceNumberLength( |
| 1511 | sent_packet_manager_.least_packet_awaited_by_peer(), |
| James Robinson | 1ae030a | 2014-11-07 08:32:47 -0800 | [diff] [blame] | 1512 | sent_packet_manager_.EstimateMaxPacketsInFlight(max_packet_length())); |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 1513 | |
| 1514 | bool reset_retransmission_alarm = sent_packet_manager_.OnPacketSent( |
| 1515 | &packet->serialized_packet, |
| 1516 | packet->original_sequence_number, |
| James Robinson | c4c1c59 | 2014-11-21 18:27:04 -0800 | [diff] [blame] | 1517 | packet_send_time, |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 1518 | encrypted->length(), |
| 1519 | packet->transmission_type, |
| 1520 | IsRetransmittable(*packet)); |
| 1521 | |
| 1522 | if (reset_retransmission_alarm || !retransmission_alarm_->IsSet()) { |
| 1523 | retransmission_alarm_->Update(sent_packet_manager_.GetRetransmissionTime(), |
| 1524 | QuicTime::Delta::FromMilliseconds(1)); |
| 1525 | } |
| 1526 | |
| 1527 | stats_.bytes_sent += result.bytes_written; |
| 1528 | ++stats_.packets_sent; |
| 1529 | if (packet->transmission_type != NOT_RETRANSMISSION) { |
| 1530 | stats_.bytes_retransmitted += result.bytes_written; |
| 1531 | ++stats_.packets_retransmitted; |
| 1532 | } |
| 1533 | |
| 1534 | if (result.status == WRITE_STATUS_ERROR) { |
| 1535 | OnWriteError(result.error_code); |
| 1536 | return false; |
| 1537 | } |
| 1538 | |
| 1539 | return true; |
| 1540 | } |
| 1541 | |
| 1542 | bool QuicConnection::ShouldDiscardPacket(const QueuedPacket& packet) { |
| 1543 | if (!connected_) { |
| 1544 | DVLOG(1) << ENDPOINT |
| 1545 | << "Not sending packet as connection is disconnected."; |
| 1546 | return true; |
| 1547 | } |
| 1548 | |
| 1549 | QuicPacketSequenceNumber sequence_number = |
| 1550 | packet.serialized_packet.sequence_number; |
| 1551 | if (encryption_level_ == ENCRYPTION_FORWARD_SECURE && |
| 1552 | packet.encryption_level == ENCRYPTION_NONE) { |
| 1553 | // Drop packets that are NULL encrypted since the peer won't accept them |
| 1554 | // anymore. |
| 1555 | DVLOG(1) << ENDPOINT << "Dropping NULL encrypted packet: " |
| 1556 | << sequence_number << " since the connection is forward secure."; |
| 1557 | return true; |
| 1558 | } |
| 1559 | |
| 1560 | // If a retransmission has been acked before sending, don't send it. |
| 1561 | // This occurs if a packet gets serialized, queued, then discarded. |
| 1562 | if (packet.transmission_type != NOT_RETRANSMISSION && |
| 1563 | (!sent_packet_manager_.IsUnacked(packet.original_sequence_number) || |
| 1564 | !sent_packet_manager_.HasRetransmittableFrames( |
| 1565 | packet.original_sequence_number))) { |
| 1566 | DVLOG(1) << ENDPOINT << "Dropping unacked packet: " << sequence_number |
| 1567 | << " A previous transmission was acked while write blocked."; |
| 1568 | return true; |
| 1569 | } |
| 1570 | |
| 1571 | return false; |
| 1572 | } |
| 1573 | |
| 1574 | void QuicConnection::OnWriteError(int error_code) { |
| 1575 | DVLOG(1) << ENDPOINT << "Write failed with error: " << error_code |
| 1576 | << " (" << ErrorToString(error_code) << ")"; |
| 1577 | // We can't send an error as the socket is presumably borked. |
| 1578 | CloseConnection(QUIC_PACKET_WRITE_ERROR, false); |
| 1579 | } |
| 1580 | |
| 1581 | void QuicConnection::OnSerializedPacket( |
| 1582 | const SerializedPacket& serialized_packet) { |
| James Robinson | 74f9f1f | 2014-11-04 11:17:49 -0800 | [diff] [blame] | 1583 | // If a forward-secure encrypter is available but is not being used and this |
| 1584 | // packet's sequence number is after the first packet which requires |
| 1585 | // forward security, start using the forward-secure encrypter. |
| 1586 | if (FLAGS_enable_quic_delay_forward_security && |
| 1587 | encryption_level_ != ENCRYPTION_FORWARD_SECURE && |
| 1588 | has_forward_secure_encrypter_ && |
| 1589 | serialized_packet.sequence_number >= |
| 1590 | first_required_forward_secure_packet_) { |
| 1591 | SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); |
| 1592 | } |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 1593 | if (serialized_packet.retransmittable_frames) { |
| 1594 | serialized_packet.retransmittable_frames-> |
| 1595 | set_encryption_level(encryption_level_); |
| 1596 | } |
| 1597 | SendOrQueuePacket(QueuedPacket(serialized_packet, encryption_level_)); |
| 1598 | } |
| 1599 | |
| James Robinson | 74f9f1f | 2014-11-04 11:17:49 -0800 | [diff] [blame] | 1600 | void QuicConnection::OnCongestionWindowChange() { |
| 1601 | packet_generator_.OnCongestionWindowChange( |
| James Robinson | 1ae030a | 2014-11-07 08:32:47 -0800 | [diff] [blame] | 1602 | sent_packet_manager_.EstimateMaxPacketsInFlight(max_packet_length())); |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 1603 | visitor_->OnCongestionWindowChange(clock_->ApproximateNow()); |
| 1604 | } |
| 1605 | |
| 1606 | void QuicConnection::OnHandshakeComplete() { |
| 1607 | sent_packet_manager_.SetHandshakeConfirmed(); |
| James Robinson | c4c1c59 | 2014-11-21 18:27:04 -0800 | [diff] [blame] | 1608 | // The client should immediately ack the SHLO to confirm the handshake is |
| 1609 | // complete with the server. |
| 1610 | if (!is_server_ && !ack_queued_) { |
| 1611 | ack_alarm_->Cancel(); |
| 1612 | ack_alarm_->Set(clock_->ApproximateNow()); |
| 1613 | } |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 1614 | } |
| 1615 | |
| 1616 | void QuicConnection::SendOrQueuePacket(QueuedPacket packet) { |
| 1617 | // The caller of this function is responsible for checking CanWrite(). |
| 1618 | if (packet.serialized_packet.packet == nullptr) { |
| 1619 | LOG(DFATAL) |
| 1620 | << "packet.serialized_packet.packet == nullptr in to SendOrQueuePacket"; |
| 1621 | return; |
| 1622 | } |
| 1623 | |
| 1624 | sent_entropy_manager_.RecordPacketEntropyHash( |
| 1625 | packet.serialized_packet.sequence_number, |
| 1626 | packet.serialized_packet.entropy_hash); |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 1627 | if (!WritePacket(&packet)) { |
| 1628 | queued_packets_.push_back(packet); |
| 1629 | } |
| 1630 | } |
| 1631 | |
| 1632 | void QuicConnection::UpdateStopWaiting(QuicStopWaitingFrame* stop_waiting) { |
| 1633 | stop_waiting->least_unacked = GetLeastUnacked(); |
| 1634 | stop_waiting->entropy_hash = sent_entropy_manager_.GetCumulativeEntropy( |
| 1635 | stop_waiting->least_unacked - 1); |
| 1636 | } |
| 1637 | |
| 1638 | void QuicConnection::SendPing() { |
| 1639 | if (retransmission_alarm_->IsSet()) { |
| 1640 | return; |
| 1641 | } |
| 1642 | packet_generator_.AddControlFrame(QuicFrame(new QuicPingFrame)); |
| 1643 | } |
| 1644 | |
| 1645 | void QuicConnection::SendAck() { |
| 1646 | ack_alarm_->Cancel(); |
| 1647 | stop_waiting_count_ = 0; |
| 1648 | num_packets_received_since_last_ack_sent_ = 0; |
| 1649 | bool send_feedback = false; |
| 1650 | |
| 1651 | // Deprecating the Congestion Feedback Frame after QUIC_VERSION_22. |
| 1652 | if (version() <= QUIC_VERSION_22) { |
| 1653 | if (received_packet_manager_.GenerateCongestionFeedback( |
| 1654 | &outgoing_congestion_feedback_)) { |
| 1655 | DVLOG(1) << ENDPOINT << "Sending feedback: " |
| 1656 | << outgoing_congestion_feedback_; |
| 1657 | send_feedback = true; |
| 1658 | } |
| 1659 | } |
| 1660 | |
| 1661 | packet_generator_.SetShouldSendAck(send_feedback, true); |
| 1662 | } |
| 1663 | |
| 1664 | void QuicConnection::OnRetransmissionTimeout() { |
| 1665 | if (!sent_packet_manager_.HasUnackedPackets()) { |
| 1666 | return; |
| 1667 | } |
| 1668 | |
| 1669 | sent_packet_manager_.OnRetransmissionTimeout(); |
| 1670 | WriteIfNotBlocked(); |
| 1671 | |
| 1672 | // A write failure can result in the connection being closed, don't attempt to |
| 1673 | // write further packets, or to set alarms. |
| 1674 | if (!connected_) { |
| 1675 | return; |
| 1676 | } |
| 1677 | |
| 1678 | // In the TLP case, the SentPacketManager gives the connection the opportunity |
| 1679 | // to send new data before retransmitting. |
| 1680 | if (sent_packet_manager_.MaybeRetransmitTailLossProbe()) { |
| 1681 | // Send the pending retransmission now that it's been queued. |
| 1682 | WriteIfNotBlocked(); |
| 1683 | } |
| 1684 | |
| 1685 | // Ensure the retransmission alarm is always set if there are unacked packets |
| 1686 | // and nothing waiting to be sent. |
| 1687 | if (!HasQueuedData() && !retransmission_alarm_->IsSet()) { |
| 1688 | QuicTime rto_timeout = sent_packet_manager_.GetRetransmissionTime(); |
| 1689 | if (rto_timeout.IsInitialized()) { |
| 1690 | retransmission_alarm_->Set(rto_timeout); |
| 1691 | } |
| 1692 | } |
| 1693 | } |
| 1694 | |
| 1695 | void QuicConnection::SetEncrypter(EncryptionLevel level, |
| 1696 | QuicEncrypter* encrypter) { |
| 1697 | framer_.SetEncrypter(level, encrypter); |
| James Robinson | 74f9f1f | 2014-11-04 11:17:49 -0800 | [diff] [blame] | 1698 | if (FLAGS_enable_quic_delay_forward_security && |
| 1699 | level == ENCRYPTION_FORWARD_SECURE) { |
| 1700 | has_forward_secure_encrypter_ = true; |
| 1701 | first_required_forward_secure_packet_ = |
| 1702 | sequence_number_of_last_sent_packet_ + |
| 1703 | // 3 times the current congestion window (in slow start) should cover |
| 1704 | // about two full round trips worth of packets, which should be |
| 1705 | // sufficient. |
| James Robinson | 1ae030a | 2014-11-07 08:32:47 -0800 | [diff] [blame] | 1706 | 3 * sent_packet_manager_.EstimateMaxPacketsInFlight( |
| 1707 | max_packet_length()); |
| James Robinson | 74f9f1f | 2014-11-04 11:17:49 -0800 | [diff] [blame] | 1708 | } |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 1709 | } |
| 1710 | |
| 1711 | const QuicEncrypter* QuicConnection::encrypter(EncryptionLevel level) const { |
| 1712 | return framer_.encrypter(level); |
| 1713 | } |
| 1714 | |
| 1715 | void QuicConnection::SetDefaultEncryptionLevel(EncryptionLevel level) { |
| 1716 | encryption_level_ = level; |
| 1717 | packet_generator_.set_encryption_level(level); |
| 1718 | } |
| 1719 | |
| 1720 | void QuicConnection::SetDecrypter(QuicDecrypter* decrypter, |
| 1721 | EncryptionLevel level) { |
| 1722 | framer_.SetDecrypter(decrypter, level); |
| 1723 | } |
| 1724 | |
| 1725 | void QuicConnection::SetAlternativeDecrypter(QuicDecrypter* decrypter, |
| 1726 | EncryptionLevel level, |
| 1727 | bool latch_once_used) { |
| 1728 | framer_.SetAlternativeDecrypter(decrypter, level, latch_once_used); |
| 1729 | } |
| 1730 | |
| 1731 | const QuicDecrypter* QuicConnection::decrypter() const { |
| 1732 | return framer_.decrypter(); |
| 1733 | } |
| 1734 | |
| 1735 | const QuicDecrypter* QuicConnection::alternative_decrypter() const { |
| 1736 | return framer_.alternative_decrypter(); |
| 1737 | } |
| 1738 | |
| 1739 | void QuicConnection::QueueUndecryptablePacket( |
| 1740 | const QuicEncryptedPacket& packet) { |
| 1741 | DVLOG(1) << ENDPOINT << "Queueing undecryptable packet."; |
| 1742 | undecryptable_packets_.push_back(packet.Clone()); |
| 1743 | } |
| 1744 | |
| 1745 | void QuicConnection::MaybeProcessUndecryptablePackets() { |
| 1746 | if (undecryptable_packets_.empty() || encryption_level_ == ENCRYPTION_NONE) { |
| 1747 | return; |
| 1748 | } |
| 1749 | |
| 1750 | while (connected_ && !undecryptable_packets_.empty()) { |
| 1751 | DVLOG(1) << ENDPOINT << "Attempting to process undecryptable packet"; |
| 1752 | QuicEncryptedPacket* packet = undecryptable_packets_.front(); |
| 1753 | if (!framer_.ProcessPacket(*packet) && |
| 1754 | framer_.error() == QUIC_DECRYPTION_FAILURE) { |
| 1755 | DVLOG(1) << ENDPOINT << "Unable to process undecryptable packet..."; |
| 1756 | break; |
| 1757 | } |
| 1758 | DVLOG(1) << ENDPOINT << "Processed undecryptable packet!"; |
| 1759 | ++stats_.packets_processed; |
| 1760 | delete packet; |
| 1761 | undecryptable_packets_.pop_front(); |
| 1762 | } |
| 1763 | |
| 1764 | // Once forward secure encryption is in use, there will be no |
| 1765 | // new keys installed and hence any undecryptable packets will |
| 1766 | // never be able to be decrypted. |
| 1767 | if (encryption_level_ == ENCRYPTION_FORWARD_SECURE) { |
| 1768 | if (debug_visitor_.get() != nullptr) { |
| 1769 | // TODO(rtenneti): perhaps more efficient to pass the number of |
| 1770 | // undecryptable packets as the argument to OnUndecryptablePacket so that |
| 1771 | // we just need to call OnUndecryptablePacket once? |
| 1772 | for (size_t i = 0; i < undecryptable_packets_.size(); ++i) { |
| 1773 | debug_visitor_->OnUndecryptablePacket(); |
| 1774 | } |
| 1775 | } |
| 1776 | STLDeleteElements(&undecryptable_packets_); |
| 1777 | } |
| 1778 | } |
| 1779 | |
| 1780 | void QuicConnection::MaybeProcessRevivedPacket() { |
| 1781 | QuicFecGroup* group = GetFecGroup(); |
| 1782 | if (!connected_ || group == nullptr || !group->CanRevive()) { |
| 1783 | return; |
| 1784 | } |
| 1785 | QuicPacketHeader revived_header; |
| 1786 | char revived_payload[kMaxPacketSize]; |
| 1787 | size_t len = group->Revive(&revived_header, revived_payload, kMaxPacketSize); |
| 1788 | revived_header.public_header.connection_id = connection_id_; |
| 1789 | revived_header.public_header.connection_id_length = |
| 1790 | last_header_.public_header.connection_id_length; |
| 1791 | revived_header.public_header.version_flag = false; |
| 1792 | revived_header.public_header.reset_flag = false; |
| 1793 | revived_header.public_header.sequence_number_length = |
| 1794 | last_header_.public_header.sequence_number_length; |
| 1795 | revived_header.fec_flag = false; |
| 1796 | revived_header.is_in_fec_group = NOT_IN_FEC_GROUP; |
| 1797 | revived_header.fec_group = 0; |
| 1798 | group_map_.erase(last_header_.fec_group); |
| 1799 | last_decrypted_packet_level_ = group->effective_encryption_level(); |
| 1800 | DCHECK_LT(last_decrypted_packet_level_, NUM_ENCRYPTION_LEVELS); |
| 1801 | delete group; |
| 1802 | |
| 1803 | last_packet_revived_ = true; |
| 1804 | if (debug_visitor_.get() != nullptr) { |
| 1805 | debug_visitor_->OnRevivedPacket(revived_header, |
| 1806 | StringPiece(revived_payload, len)); |
| 1807 | } |
| 1808 | |
| 1809 | ++stats_.packets_revived; |
| 1810 | framer_.ProcessRevivedPacket(&revived_header, |
| 1811 | StringPiece(revived_payload, len)); |
| 1812 | } |
| 1813 | |
| 1814 | QuicFecGroup* QuicConnection::GetFecGroup() { |
| 1815 | QuicFecGroupNumber fec_group_num = last_header_.fec_group; |
| 1816 | if (fec_group_num == 0) { |
| 1817 | return nullptr; |
| 1818 | } |
| James Robinson | e1b30cf | 2014-10-21 12:25:40 -0700 | [diff] [blame] | 1819 | if (!ContainsKey(group_map_, fec_group_num)) { |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 1820 | if (group_map_.size() >= kMaxFecGroups) { // Too many groups |
| 1821 | if (fec_group_num < group_map_.begin()->first) { |
| 1822 | // The group being requested is a group we've seen before and deleted. |
| 1823 | // Don't recreate it. |
| 1824 | return nullptr; |
| 1825 | } |
| 1826 | // Clear the lowest group number. |
| 1827 | delete group_map_.begin()->second; |
| 1828 | group_map_.erase(group_map_.begin()); |
| 1829 | } |
| 1830 | group_map_[fec_group_num] = new QuicFecGroup(); |
| 1831 | } |
| 1832 | return group_map_[fec_group_num]; |
| 1833 | } |
| 1834 | |
| 1835 | void QuicConnection::SendConnectionClose(QuicErrorCode error) { |
| 1836 | SendConnectionCloseWithDetails(error, string()); |
| 1837 | } |
| 1838 | |
| 1839 | void QuicConnection::SendConnectionCloseWithDetails(QuicErrorCode error, |
| 1840 | const string& details) { |
| 1841 | // If we're write blocked, WritePacket() will not send, but will capture the |
| 1842 | // serialized packet. |
| 1843 | SendConnectionClosePacket(error, details); |
| 1844 | if (connected_) { |
| 1845 | // It's possible that while sending the connection close packet, we get a |
| 1846 | // socket error and disconnect right then and there. Avoid a double |
| 1847 | // disconnect in that case. |
| 1848 | CloseConnection(error, false); |
| 1849 | } |
| 1850 | } |
| 1851 | |
| 1852 | void QuicConnection::SendConnectionClosePacket(QuicErrorCode error, |
| 1853 | const string& details) { |
| 1854 | DVLOG(1) << ENDPOINT << "Force closing " << connection_id() |
| 1855 | << " with error " << QuicUtils::ErrorToString(error) |
| 1856 | << " (" << error << ") " << details; |
| 1857 | ScopedPacketBundler ack_bundler(this, SEND_ACK); |
| 1858 | QuicConnectionCloseFrame* frame = new QuicConnectionCloseFrame(); |
| 1859 | frame->error_code = error; |
| 1860 | frame->error_details = details; |
| 1861 | packet_generator_.AddControlFrame(QuicFrame(frame)); |
| 1862 | packet_generator_.FlushAllQueuedFrames(); |
| 1863 | } |
| 1864 | |
| 1865 | void QuicConnection::CloseConnection(QuicErrorCode error, bool from_peer) { |
| 1866 | if (!connected_) { |
| 1867 | DLOG(DFATAL) << "Error: attempt to close an already closed connection" |
| 1868 | << base::debug::StackTrace().ToString(); |
| 1869 | return; |
| 1870 | } |
| 1871 | connected_ = false; |
| 1872 | if (debug_visitor_.get() != nullptr) { |
| 1873 | debug_visitor_->OnConnectionClosed(error, from_peer); |
| 1874 | } |
| 1875 | visitor_->OnConnectionClosed(error, from_peer); |
| 1876 | // Cancel the alarms so they don't trigger any action now that the |
| 1877 | // connection is closed. |
| 1878 | ack_alarm_->Cancel(); |
| 1879 | ping_alarm_->Cancel(); |
| 1880 | resume_writes_alarm_->Cancel(); |
| 1881 | retransmission_alarm_->Cancel(); |
| 1882 | send_alarm_->Cancel(); |
| 1883 | timeout_alarm_->Cancel(); |
| 1884 | } |
| 1885 | |
| 1886 | void QuicConnection::SendGoAway(QuicErrorCode error, |
| 1887 | QuicStreamId last_good_stream_id, |
| 1888 | const string& reason) { |
| 1889 | DVLOG(1) << ENDPOINT << "Going away with error " |
| 1890 | << QuicUtils::ErrorToString(error) |
| 1891 | << " (" << error << ")"; |
| 1892 | |
| 1893 | // Opportunistically bundle an ack with this outgoing packet. |
| 1894 | ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK); |
| 1895 | packet_generator_.AddControlFrame( |
| 1896 | QuicFrame(new QuicGoAwayFrame(error, last_good_stream_id, reason))); |
| 1897 | } |
| 1898 | |
| 1899 | void QuicConnection::CloseFecGroupsBefore( |
| 1900 | QuicPacketSequenceNumber sequence_number) { |
| 1901 | FecGroupMap::iterator it = group_map_.begin(); |
| 1902 | while (it != group_map_.end()) { |
| 1903 | // If this is the current group or the group doesn't protect this packet |
| 1904 | // we can ignore it. |
| 1905 | if (last_header_.fec_group == it->first || |
| 1906 | !it->second->ProtectsPacketsBefore(sequence_number)) { |
| 1907 | ++it; |
| 1908 | continue; |
| 1909 | } |
| 1910 | QuicFecGroup* fec_group = it->second; |
| 1911 | DCHECK(!fec_group->CanRevive()); |
| 1912 | FecGroupMap::iterator next = it; |
| 1913 | ++next; |
| 1914 | group_map_.erase(it); |
| 1915 | delete fec_group; |
| 1916 | it = next; |
| 1917 | } |
| 1918 | } |
| 1919 | |
| Benjamin Lerman | 5799890 | 2014-11-18 16:06:02 +0100 | [diff] [blame] | 1920 | QuicByteCount QuicConnection::max_packet_length() const { |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 1921 | return packet_generator_.max_packet_length(); |
| 1922 | } |
| 1923 | |
| Benjamin Lerman | 5799890 | 2014-11-18 16:06:02 +0100 | [diff] [blame] | 1924 | void QuicConnection::set_max_packet_length(QuicByteCount length) { |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 1925 | return packet_generator_.set_max_packet_length(length); |
| 1926 | } |
| 1927 | |
| 1928 | bool QuicConnection::HasQueuedData() const { |
| 1929 | return pending_version_negotiation_packet_ || |
| 1930 | !queued_packets_.empty() || packet_generator_.HasQueuedFrames(); |
| 1931 | } |
| 1932 | |
| 1933 | bool QuicConnection::CanWriteStreamData() { |
| 1934 | // Don't write stream data if there are negotiation or queued data packets |
| 1935 | // to send. Otherwise, continue and bundle as many frames as possible. |
| 1936 | if (pending_version_negotiation_packet_ || !queued_packets_.empty()) { |
| 1937 | return false; |
| 1938 | } |
| 1939 | |
| 1940 | IsHandshake pending_handshake = visitor_->HasPendingHandshake() ? |
| 1941 | IS_HANDSHAKE : NOT_HANDSHAKE; |
| 1942 | // Sending queued packets may have caused the socket to become write blocked, |
| 1943 | // or the congestion manager to prohibit sending. If we've sent everything |
| 1944 | // we had queued and we're still not blocked, let the visitor know it can |
| 1945 | // write more. |
| 1946 | return ShouldGeneratePacket(NOT_RETRANSMISSION, HAS_RETRANSMITTABLE_DATA, |
| 1947 | pending_handshake); |
| 1948 | } |
| 1949 | |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 1950 | void QuicConnection::SetNetworkTimeouts(QuicTime::Delta overall_timeout, |
| 1951 | QuicTime::Delta idle_timeout) { |
| 1952 | LOG_IF(DFATAL, idle_timeout > overall_timeout) |
| 1953 | << "idle_timeout:" << idle_timeout.ToMilliseconds() |
| 1954 | << " overall_timeout:" << overall_timeout.ToMilliseconds(); |
| 1955 | // Adjust the idle timeout on client and server to prevent clients from |
| 1956 | // sending requests to servers which have already closed the connection. |
| 1957 | if (is_server_) { |
| James Robinson | e2ac7e8 | 2014-10-15 13:21:59 -0700 | [diff] [blame] | 1958 | idle_timeout = idle_timeout.Add(QuicTime::Delta::FromSeconds(3)); |
| James Robinson | 646469d | 2014-10-03 15:33:28 -0700 | [diff] [blame] | 1959 | } else if (idle_timeout > QuicTime::Delta::FromSeconds(1)) { |
| 1960 | idle_timeout = idle_timeout.Subtract(QuicTime::Delta::FromSeconds(1)); |
| 1961 | } |
| 1962 | overall_connection_timeout_ = overall_timeout; |
| 1963 | idle_network_timeout_ = idle_timeout; |
| 1964 | |
| 1965 | SetTimeoutAlarm(); |
| 1966 | } |
| 1967 | |
| 1968 | void QuicConnection::CheckForTimeout() { |
| 1969 | QuicTime now = clock_->ApproximateNow(); |
| 1970 | QuicTime time_of_last_packet = max(time_of_last_received_packet_, |
| 1971 | time_of_last_sent_new_packet_); |
| 1972 | |
| 1973 | // |delta| can be < 0 as |now| is approximate time but |time_of_last_packet| |
| 1974 | // is accurate time. However, this should not change the behavior of |
| 1975 | // timeout handling. |
| 1976 | QuicTime::Delta idle_duration = now.Subtract(time_of_last_packet); |
| 1977 | DVLOG(1) << ENDPOINT << "last packet " |
| 1978 | << time_of_last_packet.ToDebuggingValue() |
| 1979 | << " now:" << now.ToDebuggingValue() |
| 1980 | << " idle_duration:" << idle_duration.ToMicroseconds() |
| 1981 | << " idle_network_timeout: " |
| 1982 | << idle_network_timeout_.ToMicroseconds(); |
| 1983 | if (idle_duration >= idle_network_timeout_) { |
| 1984 | DVLOG(1) << ENDPOINT << "Connection timedout due to no network activity."; |
| 1985 | SendConnectionClose(QUIC_CONNECTION_TIMED_OUT); |
| 1986 | return; |
| 1987 | } |
| 1988 | |
| 1989 | if (!overall_connection_timeout_.IsInfinite()) { |
| 1990 | QuicTime::Delta connected_duration = |
| 1991 | now.Subtract(stats_.connection_creation_time); |
| 1992 | DVLOG(1) << ENDPOINT << "connection time: " |
| 1993 | << connected_duration.ToMicroseconds() << " overall timeout: " |
| 1994 | << overall_connection_timeout_.ToMicroseconds(); |
| 1995 | if (connected_duration >= overall_connection_timeout_) { |
| 1996 | DVLOG(1) << ENDPOINT << |
| 1997 | "Connection timedout due to overall connection timeout."; |
| 1998 | SendConnectionClose(QUIC_CONNECTION_OVERALL_TIMED_OUT); |
| 1999 | return; |
| 2000 | } |
| 2001 | } |
| 2002 | |
| 2003 | SetTimeoutAlarm(); |
| 2004 | } |
| 2005 | |
| 2006 | void QuicConnection::SetTimeoutAlarm() { |
| 2007 | QuicTime time_of_last_packet = max(time_of_last_received_packet_, |
| 2008 | time_of_last_sent_new_packet_); |
| 2009 | |
| 2010 | QuicTime deadline = time_of_last_packet.Add(idle_network_timeout_); |
| 2011 | if (!overall_connection_timeout_.IsInfinite()) { |
| 2012 | deadline = min(deadline, |
| 2013 | stats_.connection_creation_time.Add( |
| 2014 | overall_connection_timeout_)); |
| 2015 | } |
| 2016 | |
| 2017 | timeout_alarm_->Cancel(); |
| 2018 | timeout_alarm_->Set(deadline); |
| 2019 | } |
| 2020 | |
| 2021 | void QuicConnection::SetPingAlarm() { |
| 2022 | if (is_server_) { |
| 2023 | // Only clients send pings. |
| 2024 | return; |
| 2025 | } |
| 2026 | if (!visitor_->HasOpenDataStreams()) { |
| 2027 | ping_alarm_->Cancel(); |
| 2028 | // Don't send a ping unless there are open streams. |
| 2029 | return; |
| 2030 | } |
| 2031 | QuicTime::Delta ping_timeout = QuicTime::Delta::FromSeconds(kPingTimeoutSecs); |
| 2032 | ping_alarm_->Update(clock_->ApproximateNow().Add(ping_timeout), |
| 2033 | QuicTime::Delta::FromSeconds(1)); |
| 2034 | } |
| 2035 | |
| 2036 | QuicConnection::ScopedPacketBundler::ScopedPacketBundler( |
| 2037 | QuicConnection* connection, |
| 2038 | AckBundling send_ack) |
| 2039 | : connection_(connection), |
| 2040 | already_in_batch_mode_(connection != nullptr && |
| 2041 | connection->packet_generator_.InBatchMode()) { |
| 2042 | if (connection_ == nullptr) { |
| 2043 | return; |
| 2044 | } |
| 2045 | // Move generator into batch mode. If caller wants us to include an ack, |
| 2046 | // check the delayed-ack timer to see if there's ack info to be sent. |
| 2047 | if (!already_in_batch_mode_) { |
| 2048 | DVLOG(1) << "Entering Batch Mode."; |
| 2049 | connection_->packet_generator_.StartBatchOperations(); |
| 2050 | } |
| 2051 | // Bundle an ack if the alarm is set or with every second packet if we need to |
| 2052 | // raise the peer's least unacked. |
| 2053 | bool ack_pending = |
| 2054 | connection_->ack_alarm_->IsSet() || connection_->stop_waiting_count_ > 1; |
| 2055 | if (send_ack == SEND_ACK || (send_ack == BUNDLE_PENDING_ACK && ack_pending)) { |
| 2056 | DVLOG(1) << "Bundling ack with outgoing packet."; |
| 2057 | connection_->SendAck(); |
| 2058 | } |
| 2059 | } |
| 2060 | |
| 2061 | QuicConnection::ScopedPacketBundler::~ScopedPacketBundler() { |
| 2062 | if (connection_ == nullptr) { |
| 2063 | return; |
| 2064 | } |
| 2065 | // If we changed the generator's batch state, restore original batch state. |
| 2066 | if (!already_in_batch_mode_) { |
| 2067 | DVLOG(1) << "Leaving Batch Mode."; |
| 2068 | connection_->packet_generator_.FinishBatchOperations(); |
| 2069 | } |
| 2070 | DCHECK_EQ(already_in_batch_mode_, |
| 2071 | connection_->packet_generator_.InBatchMode()); |
| 2072 | } |
| 2073 | |
| 2074 | HasRetransmittableData QuicConnection::IsRetransmittable( |
| 2075 | const QueuedPacket& packet) { |
| 2076 | // Retransmitted packets retransmittable frames are owned by the unacked |
| 2077 | // packet map, but are not present in the serialized packet. |
| 2078 | if (packet.transmission_type != NOT_RETRANSMISSION || |
| 2079 | packet.serialized_packet.retransmittable_frames != nullptr) { |
| 2080 | return HAS_RETRANSMITTABLE_DATA; |
| 2081 | } else { |
| 2082 | return NO_RETRANSMITTABLE_DATA; |
| 2083 | } |
| 2084 | } |
| 2085 | |
| 2086 | bool QuicConnection::IsConnectionClose( |
| 2087 | QueuedPacket packet) { |
| 2088 | RetransmittableFrames* retransmittable_frames = |
| 2089 | packet.serialized_packet.retransmittable_frames; |
| 2090 | if (!retransmittable_frames) { |
| 2091 | return false; |
| 2092 | } |
| 2093 | for (size_t i = 0; i < retransmittable_frames->frames().size(); ++i) { |
| 2094 | if (retransmittable_frames->frames()[i].type == CONNECTION_CLOSE_FRAME) { |
| 2095 | return true; |
| 2096 | } |
| 2097 | } |
| 2098 | return false; |
| 2099 | } |
| 2100 | |
| 2101 | } // namespace net |