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