forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquic_connection.cc
2077 lines (1823 loc) · 72.1 KB
/
quic_connection.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/quic/quic_connection.h"
#include <string.h>
#include <sys/types.h>
#include <algorithm>
#include <iterator>
#include <limits>
#include <memory>
#include <set>
#include <utility>
#include "base/debug/stack_trace.h"
#include "base/logging.h"
#include "base/stl_util.h"
#include "base/strings/stringprintf.h"
#include "net/base/net_errors.h"
#include "net/quic/crypto/quic_decrypter.h"
#include "net/quic/crypto/quic_encrypter.h"
#include "net/quic/iovector.h"
#include "net/quic/quic_bandwidth.h"
#include "net/quic/quic_config.h"
#include "net/quic/quic_fec_group.h"
#include "net/quic/quic_flags.h"
#include "net/quic/quic_utils.h"
using base::StringPiece;
using base::StringPrintf;
using base::hash_map;
using base::hash_set;
using std::list;
using std::make_pair;
using std::max;
using std::min;
using std::numeric_limits;
using std::set;
using std::string;
using std::vector;
namespace net {
class QuicDecrypter;
class QuicEncrypter;
namespace {
// The largest gap in packets we'll accept without closing the connection.
// This will likely have to be tuned.
const QuicPacketSequenceNumber kMaxPacketGap = 5000;
// Limit the number of FEC groups to two. If we get enough out of order packets
// that this becomes limiting, we can revisit.
const size_t kMaxFecGroups = 2;
// Maximum number of acks received before sending an ack in response.
const size_t kMaxPacketsReceivedBeforeAckSend = 20;
// Maximum number of tracked packets.
const size_t kMaxTrackedPackets = 5 * kMaxTcpCongestionWindow;;
bool Near(QuicPacketSequenceNumber a, QuicPacketSequenceNumber b) {
QuicPacketSequenceNumber delta = (a > b) ? a - b : b - a;
return delta <= kMaxPacketGap;
}
// An alarm that is scheduled to send an ack if a timeout occurs.
class AckAlarm : public QuicAlarm::Delegate {
public:
explicit AckAlarm(QuicConnection* connection)
: connection_(connection) {
}
QuicTime OnAlarm() override {
connection_->SendAck();
return QuicTime::Zero();
}
private:
QuicConnection* connection_;
DISALLOW_COPY_AND_ASSIGN(AckAlarm);
};
// This alarm will be scheduled any time a data-bearing packet is sent out.
// When the alarm goes off, the connection checks to see if the oldest packets
// have been acked, and retransmit them if they have not.
class RetransmissionAlarm : public QuicAlarm::Delegate {
public:
explicit RetransmissionAlarm(QuicConnection* connection)
: connection_(connection) {
}
QuicTime OnAlarm() override {
connection_->OnRetransmissionTimeout();
return QuicTime::Zero();
}
private:
QuicConnection* connection_;
DISALLOW_COPY_AND_ASSIGN(RetransmissionAlarm);
};
// An alarm that is scheduled when the sent scheduler requires a
// a delay before sending packets and fires when the packet may be sent.
class SendAlarm : public QuicAlarm::Delegate {
public:
explicit SendAlarm(QuicConnection* connection)
: connection_(connection) {
}
QuicTime OnAlarm() override {
connection_->WriteIfNotBlocked();
// Never reschedule the alarm, since CanWrite does that.
return QuicTime::Zero();
}
private:
QuicConnection* connection_;
DISALLOW_COPY_AND_ASSIGN(SendAlarm);
};
class TimeoutAlarm : public QuicAlarm::Delegate {
public:
explicit TimeoutAlarm(QuicConnection* connection)
: connection_(connection) {
}
QuicTime OnAlarm() override {
connection_->CheckForTimeout();
// Never reschedule the alarm, since CheckForTimeout does that.
return QuicTime::Zero();
}
private:
QuicConnection* connection_;
DISALLOW_COPY_AND_ASSIGN(TimeoutAlarm);
};
class PingAlarm : public QuicAlarm::Delegate {
public:
explicit PingAlarm(QuicConnection* connection)
: connection_(connection) {
}
QuicTime OnAlarm() override {
connection_->SendPing();
return QuicTime::Zero();
}
private:
QuicConnection* connection_;
DISALLOW_COPY_AND_ASSIGN(PingAlarm);
};
} // namespace
QuicConnection::QueuedPacket::QueuedPacket(SerializedPacket packet,
EncryptionLevel level)
: serialized_packet(packet),
encryption_level(level),
transmission_type(NOT_RETRANSMISSION),
original_sequence_number(0) {
}
QuicConnection::QueuedPacket::QueuedPacket(
SerializedPacket packet,
EncryptionLevel level,
TransmissionType transmission_type,
QuicPacketSequenceNumber original_sequence_number)
: serialized_packet(packet),
encryption_level(level),
transmission_type(transmission_type),
original_sequence_number(original_sequence_number) {
}
#define ENDPOINT (is_server_ ? "Server: " : " Client: ")
QuicConnection::QuicConnection(QuicConnectionId connection_id,
IPEndPoint address,
QuicConnectionHelperInterface* helper,
const PacketWriterFactory& writer_factory,
bool owns_writer,
bool is_server,
bool is_secure,
const QuicVersionVector& supported_versions)
: framer_(supported_versions, helper->GetClock()->ApproximateNow(),
is_server),
helper_(helper),
writer_(writer_factory.Create(this)),
owns_writer_(owns_writer),
encryption_level_(ENCRYPTION_NONE),
has_forward_secure_encrypter_(false),
first_required_forward_secure_packet_(0),
clock_(helper->GetClock()),
random_generator_(helper->GetRandomGenerator()),
connection_id_(connection_id),
peer_address_(address),
migrating_peer_port_(0),
last_packet_decrypted_(false),
last_packet_revived_(false),
last_size_(0),
last_decrypted_packet_level_(ENCRYPTION_NONE),
largest_seen_packet_with_ack_(0),
largest_seen_packet_with_stop_waiting_(0),
max_undecryptable_packets_(0),
pending_version_negotiation_packet_(false),
received_packet_manager_(&stats_),
ack_queued_(false),
num_packets_received_since_last_ack_sent_(0),
stop_waiting_count_(0),
ack_alarm_(helper->CreateAlarm(new AckAlarm(this))),
retransmission_alarm_(helper->CreateAlarm(new RetransmissionAlarm(this))),
send_alarm_(helper->CreateAlarm(new SendAlarm(this))),
resume_writes_alarm_(helper->CreateAlarm(new SendAlarm(this))),
timeout_alarm_(helper->CreateAlarm(new TimeoutAlarm(this))),
ping_alarm_(helper->CreateAlarm(new PingAlarm(this))),
packet_generator_(connection_id_, &framer_, random_generator_, this),
idle_network_timeout_(QuicTime::Delta::Infinite()),
overall_connection_timeout_(QuicTime::Delta::Infinite()),
time_of_last_received_packet_(clock_->ApproximateNow()),
time_of_last_sent_new_packet_(clock_->ApproximateNow()),
sequence_number_of_last_sent_packet_(0),
sent_packet_manager_(
is_server, clock_, &stats_,
FLAGS_quic_use_bbr_congestion_control ? kBBR : kCubic,
FLAGS_quic_use_time_loss_detection ? kTime : kNack,
is_secure),
version_negotiation_state_(START_NEGOTIATION),
is_server_(is_server),
connected_(true),
peer_ip_changed_(false),
peer_port_changed_(false),
self_ip_changed_(false),
self_port_changed_(false),
can_truncate_connection_ids_(true),
is_secure_(is_secure) {
DVLOG(1) << ENDPOINT << "Created connection with connection_id: "
<< connection_id;
framer_.set_visitor(this);
framer_.set_received_entropy_calculator(&received_packet_manager_);
stats_.connection_creation_time = clock_->ApproximateNow();
sent_packet_manager_.set_network_change_visitor(this);
}
QuicConnection::~QuicConnection() {
if (owns_writer_) {
delete writer_;
}
STLDeleteElements(&undecryptable_packets_);
STLDeleteValues(&group_map_);
for (QueuedPacketList::iterator it = queued_packets_.begin();
it != queued_packets_.end(); ++it) {
delete it->serialized_packet.retransmittable_frames;
delete it->serialized_packet.packet;
}
}
void QuicConnection::SetFromConfig(const QuicConfig& config) {
if (config.negotiated()) {
SetNetworkTimeouts(QuicTime::Delta::Infinite(),
config.IdleConnectionStateLifetime());
} else {
SetNetworkTimeouts(config.max_time_before_crypto_handshake(),
config.max_idle_time_before_crypto_handshake());
}
sent_packet_manager_.SetFromConfig(config);
if (FLAGS_allow_truncated_connection_ids_for_quic &&
config.HasReceivedBytesForConnectionId() &&
can_truncate_connection_ids_) {
packet_generator_.SetConnectionIdLength(
config.ReceivedBytesForConnectionId());
}
max_undecryptable_packets_ = config.max_undecryptable_packets();
}
void QuicConnection::SetNumOpenStreams(size_t num_streams) {
sent_packet_manager_.SetNumOpenStreams(num_streams);
}
bool QuicConnection::SelectMutualVersion(
const QuicVersionVector& available_versions) {
// Try to find the highest mutual version by iterating over supported
// versions, starting with the highest, and breaking out of the loop once we
// find a matching version in the provided available_versions vector.
const QuicVersionVector& supported_versions = framer_.supported_versions();
for (size_t i = 0; i < supported_versions.size(); ++i) {
const QuicVersion& version = supported_versions[i];
if (std::find(available_versions.begin(), available_versions.end(),
version) != available_versions.end()) {
framer_.set_version(version);
return true;
}
}
return false;
}
void QuicConnection::OnError(QuicFramer* framer) {
// Packets that we can not or have not decrypted are dropped.
// TODO(rch): add stats to measure this.
if (FLAGS_quic_drop_junk_packets) {
if (!connected_ || last_packet_decrypted_ == false) {
return;
}
} else {
if (!connected_ || framer->error() == QUIC_DECRYPTION_FAILURE) {
return;
}
}
SendConnectionCloseWithDetails(framer->error(), framer->detailed_error());
}
void QuicConnection::OnPacket() {
DCHECK(last_stream_frames_.empty() &&
last_ack_frames_.empty() &&
last_congestion_frames_.empty() &&
last_stop_waiting_frames_.empty() &&
last_rst_frames_.empty() &&
last_goaway_frames_.empty() &&
last_window_update_frames_.empty() &&
last_blocked_frames_.empty() &&
last_ping_frames_.empty() &&
last_close_frames_.empty());
last_packet_decrypted_ = false;
last_packet_revived_ = false;
}
void QuicConnection::OnPublicResetPacket(
const QuicPublicResetPacket& packet) {
if (debug_visitor_.get() != nullptr) {
debug_visitor_->OnPublicResetPacket(packet);
}
CloseConnection(QUIC_PUBLIC_RESET, true);
DVLOG(1) << ENDPOINT << "Connection " << connection_id()
<< " closed via QUIC_PUBLIC_RESET from peer.";
}
bool QuicConnection::OnProtocolVersionMismatch(QuicVersion received_version) {
DVLOG(1) << ENDPOINT << "Received packet with mismatched version "
<< received_version;
// TODO(satyamshekhar): Implement no server state in this mode.
if (!is_server_) {
LOG(DFATAL) << ENDPOINT << "Framer called OnProtocolVersionMismatch. "
<< "Closing connection.";
CloseConnection(QUIC_INTERNAL_ERROR, false);
return false;
}
DCHECK_NE(version(), received_version);
if (debug_visitor_.get() != nullptr) {
debug_visitor_->OnProtocolVersionMismatch(received_version);
}
switch (version_negotiation_state_) {
case START_NEGOTIATION:
if (!framer_.IsSupportedVersion(received_version)) {
SendVersionNegotiationPacket();
version_negotiation_state_ = NEGOTIATION_IN_PROGRESS;
return false;
}
break;
case NEGOTIATION_IN_PROGRESS:
if (!framer_.IsSupportedVersion(received_version)) {
SendVersionNegotiationPacket();
return false;
}
break;
case NEGOTIATED_VERSION:
// Might be old packets that were sent by the client before the version
// was negotiated. Drop these.
return false;
default:
DCHECK(false);
}
version_negotiation_state_ = NEGOTIATED_VERSION;
visitor_->OnSuccessfulVersionNegotiation(received_version);
if (debug_visitor_.get() != nullptr) {
debug_visitor_->OnSuccessfulVersionNegotiation(received_version);
}
DVLOG(1) << ENDPOINT << "version negotiated " << received_version;
// Store the new version.
framer_.set_version(received_version);
// TODO(satyamshekhar): Store the sequence number of this packet and close the
// connection if we ever received a packet with incorrect version and whose
// sequence number is greater.
return true;
}
// Handles version negotiation for client connection.
void QuicConnection::OnVersionNegotiationPacket(
const QuicVersionNegotiationPacket& packet) {
if (is_server_) {
LOG(DFATAL) << ENDPOINT << "Framer parsed VersionNegotiationPacket."
<< " Closing connection.";
CloseConnection(QUIC_INTERNAL_ERROR, false);
return;
}
if (debug_visitor_.get() != nullptr) {
debug_visitor_->OnVersionNegotiationPacket(packet);
}
if (version_negotiation_state_ != START_NEGOTIATION) {
// Possibly a duplicate version negotiation packet.
return;
}
if (std::find(packet.versions.begin(),
packet.versions.end(), version()) !=
packet.versions.end()) {
DLOG(WARNING) << ENDPOINT << "The server already supports our version. "
<< "It should have accepted our connection.";
// Just drop the connection.
CloseConnection(QUIC_INVALID_VERSION_NEGOTIATION_PACKET, false);
return;
}
if (!SelectMutualVersion(packet.versions)) {
SendConnectionCloseWithDetails(QUIC_INVALID_VERSION,
"no common version found");
return;
}
DVLOG(1) << ENDPOINT
<< "Negotiated version: " << QuicVersionToString(version());
server_supported_versions_ = packet.versions;
version_negotiation_state_ = NEGOTIATION_IN_PROGRESS;
RetransmitUnackedPackets(ALL_UNACKED_RETRANSMISSION);
}
void QuicConnection::OnRevivedPacket() {
}
bool QuicConnection::OnUnauthenticatedPublicHeader(
const QuicPacketPublicHeader& header) {
return true;
}
bool QuicConnection::OnUnauthenticatedHeader(const QuicPacketHeader& header) {
return true;
}
void QuicConnection::OnDecryptedPacket(EncryptionLevel level) {
last_decrypted_packet_level_ = level;
last_packet_decrypted_ = true;
// If this packet was foward-secure encrypted and the forward-secure encrypter
// is not being used, start using it.
if (FLAGS_enable_quic_delay_forward_security &&
encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
has_forward_secure_encrypter_ &&
level == ENCRYPTION_FORWARD_SECURE) {
SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
}
}
bool QuicConnection::OnPacketHeader(const QuicPacketHeader& header) {
if (debug_visitor_.get() != nullptr) {
debug_visitor_->OnPacketHeader(header);
}
if (!ProcessValidatedPacket()) {
return false;
}
// Will be decrement below if we fall through to return true;
++stats_.packets_dropped;
if (header.public_header.connection_id != connection_id_) {
DVLOG(1) << ENDPOINT << "Ignoring packet from unexpected ConnectionId: "
<< header.public_header.connection_id << " instead of "
<< connection_id_;
if (debug_visitor_.get() != nullptr) {
debug_visitor_->OnIncorrectConnectionId(
header.public_header.connection_id);
}
return false;
}
if (!Near(header.packet_sequence_number,
last_header_.packet_sequence_number)) {
DVLOG(1) << ENDPOINT << "Packet " << header.packet_sequence_number
<< " out of bounds. Discarding";
SendConnectionCloseWithDetails(QUIC_INVALID_PACKET_HEADER,
"Packet sequence number out of bounds");
return false;
}
// If this packet has already been seen, or that the sender
// has told us will not be retransmitted, then stop processing the packet.
if (!received_packet_manager_.IsAwaitingPacket(
header.packet_sequence_number)) {
DVLOG(1) << ENDPOINT << "Packet " << header.packet_sequence_number
<< " no longer being waited for. Discarding.";
if (debug_visitor_.get() != nullptr) {
debug_visitor_->OnDuplicatePacket(header.packet_sequence_number);
}
return false;
}
if (version_negotiation_state_ != NEGOTIATED_VERSION) {
if (is_server_) {
if (!header.public_header.version_flag) {
DLOG(WARNING) << ENDPOINT << "Packet " << header.packet_sequence_number
<< " without version flag before version negotiated.";
// Packets should have the version flag till version negotiation is
// done.
CloseConnection(QUIC_INVALID_VERSION, false);
return false;
} else {
DCHECK_EQ(1u, header.public_header.versions.size());
DCHECK_EQ(header.public_header.versions[0], version());
version_negotiation_state_ = NEGOTIATED_VERSION;
visitor_->OnSuccessfulVersionNegotiation(version());
if (debug_visitor_.get() != nullptr) {
debug_visitor_->OnSuccessfulVersionNegotiation(version());
}
}
} else {
DCHECK(!header.public_header.version_flag);
// If the client gets a packet without the version flag from the server
// it should stop sending version since the version negotiation is done.
packet_generator_.StopSendingVersion();
version_negotiation_state_ = NEGOTIATED_VERSION;
visitor_->OnSuccessfulVersionNegotiation(version());
if (debug_visitor_.get() != nullptr) {
debug_visitor_->OnSuccessfulVersionNegotiation(version());
}
}
}
DCHECK_EQ(NEGOTIATED_VERSION, version_negotiation_state_);
--stats_.packets_dropped;
DVLOG(1) << ENDPOINT << "Received packet header: " << header;
last_header_ = header;
DCHECK(connected_);
return true;
}
void QuicConnection::OnFecProtectedPayload(StringPiece payload) {
DCHECK_EQ(IN_FEC_GROUP, last_header_.is_in_fec_group);
DCHECK_NE(0u, last_header_.fec_group);
QuicFecGroup* group = GetFecGroup();
if (group != nullptr) {
group->Update(last_decrypted_packet_level_, last_header_, payload);
}
}
bool QuicConnection::OnStreamFrame(const QuicStreamFrame& frame) {
DCHECK(connected_);
if (debug_visitor_.get() != nullptr) {
debug_visitor_->OnStreamFrame(frame);
}
if (frame.stream_id != kCryptoStreamId &&
last_decrypted_packet_level_ == ENCRYPTION_NONE) {
DLOG(WARNING) << ENDPOINT
<< "Received an unencrypted data frame: closing connection";
SendConnectionClose(QUIC_UNENCRYPTED_STREAM_DATA);
return false;
}
last_stream_frames_.push_back(frame);
return true;
}
bool QuicConnection::OnAckFrame(const QuicAckFrame& incoming_ack) {
DCHECK(connected_);
if (debug_visitor_.get() != nullptr) {
debug_visitor_->OnAckFrame(incoming_ack);
}
DVLOG(1) << ENDPOINT << "OnAckFrame: " << incoming_ack;
if (last_header_.packet_sequence_number <= largest_seen_packet_with_ack_) {
DVLOG(1) << ENDPOINT << "Received an old ack frame: ignoring";
return true;
}
if (!ValidateAckFrame(incoming_ack)) {
SendConnectionClose(QUIC_INVALID_ACK_DATA);
return false;
}
last_ack_frames_.push_back(incoming_ack);
return connected_;
}
void QuicConnection::ProcessAckFrame(const QuicAckFrame& incoming_ack) {
largest_seen_packet_with_ack_ = last_header_.packet_sequence_number;
sent_packet_manager_.OnIncomingAck(incoming_ack,
time_of_last_received_packet_);
sent_entropy_manager_.ClearEntropyBefore(
sent_packet_manager_.least_packet_awaited_by_peer() - 1);
if (sent_packet_manager_.HasPendingRetransmissions()) {
WriteIfNotBlocked();
}
// Always reset the retransmission alarm when an ack comes in, since we now
// have a better estimate of the current rtt than when it was set.
QuicTime retransmission_time = sent_packet_manager_.GetRetransmissionTime();
retransmission_alarm_->Update(retransmission_time,
QuicTime::Delta::FromMilliseconds(1));
}
void QuicConnection::ProcessStopWaitingFrame(
const QuicStopWaitingFrame& stop_waiting) {
largest_seen_packet_with_stop_waiting_ = last_header_.packet_sequence_number;
received_packet_manager_.UpdatePacketInformationSentByPeer(stop_waiting);
// Possibly close any FecGroups which are now irrelevant.
CloseFecGroupsBefore(stop_waiting.least_unacked + 1);
}
bool QuicConnection::OnCongestionFeedbackFrame(
const QuicCongestionFeedbackFrame& feedback) {
DCHECK(connected_);
if (debug_visitor_.get() != nullptr) {
debug_visitor_->OnCongestionFeedbackFrame(feedback);
}
last_congestion_frames_.push_back(feedback);
return connected_;
}
bool QuicConnection::OnStopWaitingFrame(const QuicStopWaitingFrame& frame) {
DCHECK(connected_);
if (last_header_.packet_sequence_number <=
largest_seen_packet_with_stop_waiting_) {
DVLOG(1) << ENDPOINT << "Received an old stop waiting frame: ignoring";
return true;
}
if (!ValidateStopWaitingFrame(frame)) {
SendConnectionClose(QUIC_INVALID_STOP_WAITING_DATA);
return false;
}
if (debug_visitor_.get() != nullptr) {
debug_visitor_->OnStopWaitingFrame(frame);
}
last_stop_waiting_frames_.push_back(frame);
return connected_;
}
bool QuicConnection::OnPingFrame(const QuicPingFrame& frame) {
DCHECK(connected_);
if (debug_visitor_.get() != nullptr) {
debug_visitor_->OnPingFrame(frame);
}
last_ping_frames_.push_back(frame);
return true;
}
bool QuicConnection::ValidateAckFrame(const QuicAckFrame& incoming_ack) {
if (incoming_ack.largest_observed > packet_generator_.sequence_number()) {
DLOG(ERROR) << ENDPOINT << "Peer's observed unsent packet:"
<< incoming_ack.largest_observed << " vs "
<< packet_generator_.sequence_number();
// We got an error for data we have not sent. Error out.
return false;
}
if (incoming_ack.largest_observed < sent_packet_manager_.largest_observed()) {
DLOG(ERROR) << ENDPOINT << "Peer's largest_observed packet decreased:"
<< incoming_ack.largest_observed << " vs "
<< sent_packet_manager_.largest_observed();
// A new ack has a diminished largest_observed value. Error out.
// If this was an old packet, we wouldn't even have checked.
return false;
}
if (!incoming_ack.missing_packets.empty() &&
*incoming_ack.missing_packets.rbegin() > incoming_ack.largest_observed) {
DLOG(ERROR) << ENDPOINT << "Peer sent missing packet: "
<< *incoming_ack.missing_packets.rbegin()
<< " which is greater than largest observed: "
<< incoming_ack.largest_observed;
return false;
}
if (!incoming_ack.missing_packets.empty() &&
*incoming_ack.missing_packets.begin() <
sent_packet_manager_.least_packet_awaited_by_peer()) {
DLOG(ERROR) << ENDPOINT << "Peer sent missing packet: "
<< *incoming_ack.missing_packets.begin()
<< " which is smaller than least_packet_awaited_by_peer_: "
<< sent_packet_manager_.least_packet_awaited_by_peer();
return false;
}
if (!sent_entropy_manager_.IsValidEntropy(
incoming_ack.largest_observed,
incoming_ack.missing_packets,
incoming_ack.entropy_hash)) {
DLOG(ERROR) << ENDPOINT << "Peer sent invalid entropy.";
return false;
}
for (SequenceNumberSet::const_iterator iter =
incoming_ack.revived_packets.begin();
iter != incoming_ack.revived_packets.end(); ++iter) {
if (!ContainsKey(incoming_ack.missing_packets, *iter)) {
DLOG(ERROR) << ENDPOINT
<< "Peer specified revived packet which was not missing.";
return false;
}
}
return true;
}
bool QuicConnection::ValidateStopWaitingFrame(
const QuicStopWaitingFrame& stop_waiting) {
if (stop_waiting.least_unacked <
received_packet_manager_.peer_least_packet_awaiting_ack()) {
DLOG(ERROR) << ENDPOINT << "Peer's sent low least_unacked: "
<< stop_waiting.least_unacked << " vs "
<< received_packet_manager_.peer_least_packet_awaiting_ack();
// We never process old ack frames, so this number should only increase.
return false;
}
if (stop_waiting.least_unacked >
last_header_.packet_sequence_number) {
DLOG(ERROR) << ENDPOINT << "Peer sent least_unacked:"
<< stop_waiting.least_unacked
<< " greater than the enclosing packet sequence number:"
<< last_header_.packet_sequence_number;
return false;
}
return true;
}
void QuicConnection::OnFecData(const QuicFecData& fec) {
DCHECK_EQ(IN_FEC_GROUP, last_header_.is_in_fec_group);
DCHECK_NE(0u, last_header_.fec_group);
QuicFecGroup* group = GetFecGroup();
if (group != nullptr) {
group->UpdateFec(last_decrypted_packet_level_,
last_header_.packet_sequence_number, fec);
}
}
bool QuicConnection::OnRstStreamFrame(const QuicRstStreamFrame& frame) {
DCHECK(connected_);
if (debug_visitor_.get() != nullptr) {
debug_visitor_->OnRstStreamFrame(frame);
}
DVLOG(1) << ENDPOINT << "Stream reset with error "
<< QuicUtils::StreamErrorToString(frame.error_code);
last_rst_frames_.push_back(frame);
return connected_;
}
bool QuicConnection::OnConnectionCloseFrame(
const QuicConnectionCloseFrame& frame) {
DCHECK(connected_);
if (debug_visitor_.get() != nullptr) {
debug_visitor_->OnConnectionCloseFrame(frame);
}
DVLOG(1) << ENDPOINT << "Connection " << connection_id()
<< " closed with error "
<< QuicUtils::ErrorToString(frame.error_code)
<< " " << frame.error_details;
last_close_frames_.push_back(frame);
return connected_;
}
bool QuicConnection::OnGoAwayFrame(const QuicGoAwayFrame& frame) {
DCHECK(connected_);
if (debug_visitor_.get() != nullptr) {
debug_visitor_->OnGoAwayFrame(frame);
}
DVLOG(1) << ENDPOINT << "Go away received with error "
<< QuicUtils::ErrorToString(frame.error_code)
<< " and reason:" << frame.reason_phrase;
last_goaway_frames_.push_back(frame);
return connected_;
}
bool QuicConnection::OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) {
DCHECK(connected_);
if (debug_visitor_.get() != nullptr) {
debug_visitor_->OnWindowUpdateFrame(frame);
}
DVLOG(1) << ENDPOINT << "WindowUpdate received for stream: "
<< frame.stream_id << " with byte offset: " << frame.byte_offset;
last_window_update_frames_.push_back(frame);
return connected_;
}
bool QuicConnection::OnBlockedFrame(const QuicBlockedFrame& frame) {
DCHECK(connected_);
if (debug_visitor_.get() != nullptr) {
debug_visitor_->OnBlockedFrame(frame);
}
DVLOG(1) << ENDPOINT << "Blocked frame received for stream: "
<< frame.stream_id;
last_blocked_frames_.push_back(frame);
return connected_;
}
void QuicConnection::OnPacketComplete() {
// Don't do anything if this packet closed the connection.
if (!connected_) {
ClearLastFrames();
return;
}
DVLOG(1) << ENDPOINT << (last_packet_revived_ ? "Revived" : "Got")
<< " packet " << last_header_.packet_sequence_number
<< " with " << last_stream_frames_.size()<< " stream frames "
<< last_ack_frames_.size() << " acks, "
<< last_congestion_frames_.size() << " congestions, "
<< last_stop_waiting_frames_.size() << " stop_waiting, "
<< last_rst_frames_.size() << " rsts, "
<< last_goaway_frames_.size() << " goaways, "
<< last_window_update_frames_.size() << " window updates, "
<< last_blocked_frames_.size() << " blocked, "
<< last_ping_frames_.size() << " pings, "
<< last_close_frames_.size() << " closes, "
<< "for " << last_header_.public_header.connection_id;
++num_packets_received_since_last_ack_sent_;
// Call MaybeQueueAck() before recording the received packet, since we want
// to trigger an ack if the newly received packet was previously missing.
MaybeQueueAck();
// Record received or revived packet to populate ack info correctly before
// processing stream frames, since the processing may result in a response
// packet with a bundled ack.
if (last_packet_revived_) {
received_packet_manager_.RecordPacketRevived(
last_header_.packet_sequence_number);
} else {
received_packet_manager_.RecordPacketReceived(
last_size_, last_header_, time_of_last_received_packet_);
}
if (!last_stream_frames_.empty()) {
visitor_->OnStreamFrames(last_stream_frames_);
}
for (size_t i = 0; i < last_stream_frames_.size(); ++i) {
stats_.stream_bytes_received +=
last_stream_frames_[i].data.TotalBufferSize();
}
// Process window updates, blocked, stream resets, acks, then congestion
// feedback.
if (!last_window_update_frames_.empty()) {
visitor_->OnWindowUpdateFrames(last_window_update_frames_);
}
if (!last_blocked_frames_.empty()) {
visitor_->OnBlockedFrames(last_blocked_frames_);
}
for (size_t i = 0; i < last_goaway_frames_.size(); ++i) {
visitor_->OnGoAway(last_goaway_frames_[i]);
}
for (size_t i = 0; i < last_rst_frames_.size(); ++i) {
visitor_->OnRstStream(last_rst_frames_[i]);
}
for (size_t i = 0; i < last_ack_frames_.size(); ++i) {
ProcessAckFrame(last_ack_frames_[i]);
}
for (size_t i = 0; i < last_congestion_frames_.size(); ++i) {
sent_packet_manager_.OnIncomingQuicCongestionFeedbackFrame(
last_congestion_frames_[i], time_of_last_received_packet_);
}
for (size_t i = 0; i < last_stop_waiting_frames_.size(); ++i) {
ProcessStopWaitingFrame(last_stop_waiting_frames_[i]);
}
if (!last_close_frames_.empty()) {
CloseConnection(last_close_frames_[0].error_code, true);
DCHECK(!connected_);
}
// If there are new missing packets to report, send an ack immediately.
if (received_packet_manager_.HasNewMissingPackets()) {
ack_queued_ = true;
ack_alarm_->Cancel();
}
UpdateStopWaitingCount();
ClearLastFrames();
MaybeCloseIfTooManyOutstandingPackets();
}
void QuicConnection::MaybeQueueAck() {
// If the incoming packet was missing, send an ack immediately.
ack_queued_ = received_packet_manager_.IsMissing(
last_header_.packet_sequence_number);
if (!ack_queued_ && ShouldLastPacketInstigateAck()) {
if (ack_alarm_->IsSet()) {
ack_queued_ = true;
} else {
// Send an ack much more quickly for crypto handshake packets.
QuicTime::Delta delayed_ack_time = sent_packet_manager_.DelayedAckTime();
if (last_stream_frames_.size() == 1 &&
last_stream_frames_[0].stream_id == kCryptoStreamId) {
delayed_ack_time = QuicTime::Delta::Zero();
}
ack_alarm_->Set(clock_->ApproximateNow().Add(delayed_ack_time));
DVLOG(1) << "Ack timer set; next packet or timer will trigger ACK.";
}
}
if (ack_queued_) {
ack_alarm_->Cancel();
}
}
void QuicConnection::ClearLastFrames() {
last_stream_frames_.clear();
last_ack_frames_.clear();
last_congestion_frames_.clear();
last_stop_waiting_frames_.clear();
last_rst_frames_.clear();
last_goaway_frames_.clear();
last_window_update_frames_.clear();
last_blocked_frames_.clear();
last_ping_frames_.clear();
last_close_frames_.clear();
}
void QuicConnection::MaybeCloseIfTooManyOutstandingPackets() {
if (!FLAGS_quic_too_many_outstanding_packets) {
return;
}
// This occurs if we don't discard old packets we've sent fast enough.
// It's possible largest observed is less than least unacked.
if (sent_packet_manager_.largest_observed() >
(sent_packet_manager_.GetLeastUnacked() + kMaxTrackedPackets)) {
SendConnectionCloseWithDetails(
QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS,
StringPrintf("More than %zu outstanding.", kMaxTrackedPackets));
}
// This occurs if there are received packet gaps and the peer does not raise
// the least unacked fast enough.
if (received_packet_manager_.NumTrackedPackets() > kMaxTrackedPackets) {
SendConnectionCloseWithDetails(
QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS,
StringPrintf("More than %zu outstanding.", kMaxTrackedPackets));
}
}
QuicAckFrame* QuicConnection::CreateAckFrame() {
QuicAckFrame* outgoing_ack = new QuicAckFrame();
received_packet_manager_.UpdateReceivedPacketInfo(
outgoing_ack, clock_->ApproximateNow());
DVLOG(1) << ENDPOINT << "Creating ack frame: " << *outgoing_ack;
return outgoing_ack;
}
QuicCongestionFeedbackFrame* QuicConnection::CreateFeedbackFrame() {
return new QuicCongestionFeedbackFrame(outgoing_congestion_feedback_);
}
QuicStopWaitingFrame* QuicConnection::CreateStopWaitingFrame() {
QuicStopWaitingFrame stop_waiting;
UpdateStopWaiting(&stop_waiting);
return new QuicStopWaitingFrame(stop_waiting);
}
bool QuicConnection::ShouldLastPacketInstigateAck() const {
if (!last_stream_frames_.empty() ||
!last_goaway_frames_.empty() ||
!last_rst_frames_.empty() ||
!last_window_update_frames_.empty() ||
!last_blocked_frames_.empty() ||
!last_ping_frames_.empty()) {
return true;
}
if (!last_ack_frames_.empty() && last_ack_frames_.back().is_truncated) {
return true;
}
// Always send an ack every 20 packets in order to allow the peer to discard
// information from the SentPacketManager and provide an RTT measurement.
if (num_packets_received_since_last_ack_sent_ >=
kMaxPacketsReceivedBeforeAckSend) {
return true;
}
return false;
}