blob: c1786e6b72dd8a4832e95fe0a7c2cd99242c2a3b [file] [log] [blame]
QUICHE teama6ef0a62019-03-07 20:34:33 -05001// 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/third_party/quiche/src/quic/core/quic_dispatcher.h"
6
vasilvv872e7a32019-03-12 16:42:44 -07007#include <string>
QUICHE teama6ef0a62019-03-07 20:34:33 -05008#include <utility>
9
QUICHE teama6ef0a62019-03-07 20:34:33 -050010#include "net/third_party/quiche/src/quic/core/chlo_extractor.h"
11#include "net/third_party/quiche/src/quic/core/crypto/crypto_protocol.h"
12#include "net/third_party/quiche/src/quic/core/crypto/quic_random.h"
fayangccbab732019-05-13 10:11:25 -070013#include "net/third_party/quiche/src/quic/core/quic_error_codes.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050014#include "net/third_party/quiche/src/quic/core/quic_time_wait_list_manager.h"
15#include "net/third_party/quiche/src/quic/core/quic_types.h"
16#include "net/third_party/quiche/src/quic/core/quic_utils.h"
dschinazi76992e72019-07-17 20:40:40 -070017#include "net/third_party/quiche/src/quic/core/quic_versions.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050018#include "net/third_party/quiche/src/quic/platform/api/quic_bug_tracker.h"
19#include "net/third_party/quiche/src/quic/platform/api/quic_flag_utils.h"
20#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
21#include "net/third_party/quiche/src/quic/platform/api/quic_logging.h"
22#include "net/third_party/quiche/src/quic/platform/api/quic_ptr_util.h"
23#include "net/third_party/quiche/src/quic/platform/api/quic_stack_trace.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050024#include "net/third_party/quiche/src/quic/platform/api/quic_string_piece.h"
dschinazi965ce092019-05-23 06:29:01 -070025#include "net/third_party/quiche/src/quic/platform/api/quic_text_utils.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050026
27namespace quic {
28
29typedef QuicBufferedPacketStore::BufferedPacket BufferedPacket;
30typedef QuicBufferedPacketStore::BufferedPacketList BufferedPacketList;
31typedef QuicBufferedPacketStore::EnqueuePacketResult EnqueuePacketResult;
32
33namespace {
34
fayange3f2f7b2019-09-19 17:01:57 -070035// Minimal INITIAL packet length sent by clients is 1200.
36const QuicPacketLength kMinClientInitialPacketLength = 1200;
37
QUICHE teama6ef0a62019-03-07 20:34:33 -050038// An alarm that informs the QuicDispatcher to delete old sessions.
39class DeleteSessionsAlarm : public QuicAlarm::Delegate {
40 public:
41 explicit DeleteSessionsAlarm(QuicDispatcher* dispatcher)
42 : dispatcher_(dispatcher) {}
43 DeleteSessionsAlarm(const DeleteSessionsAlarm&) = delete;
44 DeleteSessionsAlarm& operator=(const DeleteSessionsAlarm&) = delete;
45
46 void OnAlarm() override { dispatcher_->DeleteSessions(); }
47
48 private:
49 // Not owned.
50 QuicDispatcher* dispatcher_;
51};
52
53// Collects packets serialized by a QuicPacketCreator in order
54// to be handed off to the time wait list manager.
55class PacketCollector : public QuicPacketCreator::DelegateInterface,
56 public QuicStreamFrameDataProducer {
57 public:
58 explicit PacketCollector(QuicBufferAllocator* allocator)
59 : send_buffer_(allocator) {}
60 ~PacketCollector() override = default;
61
62 // QuicPacketCreator::DelegateInterface methods:
63 void OnSerializedPacket(SerializedPacket* serialized_packet) override {
64 // Make a copy of the serialized packet to send later.
65 packets_.emplace_back(
66 new QuicEncryptedPacket(CopyBuffer(*serialized_packet),
67 serialized_packet->encrypted_length, true));
68 serialized_packet->encrypted_buffer = nullptr;
69 DeleteFrames(&(serialized_packet->retransmittable_frames));
70 serialized_packet->retransmittable_frames.clear();
71 }
72
73 char* GetPacketBuffer() override {
74 // Let QuicPacketCreator to serialize packets on stack buffer.
75 return nullptr;
76 }
77
dschinazi17d42422019-06-18 16:35:07 -070078 void OnUnrecoverableError(QuicErrorCode /*error*/,
79 const std::string& /*error_details*/) override {}
QUICHE teama6ef0a62019-03-07 20:34:33 -050080
fayangcad11792019-09-16 13:11:44 -070081 bool ShouldGeneratePacket(HasRetransmittableData /*retransmittable*/,
82 IsHandshake /*handshake*/) override {
83 DCHECK(false);
84 return true;
85 }
86
87 const QuicFrames MaybeBundleAckOpportunistically() override {
88 DCHECK(false);
89 return {};
90 }
91
QUICHE teama6ef0a62019-03-07 20:34:33 -050092 // QuicStreamFrameDataProducer
dschinazi17d42422019-06-18 16:35:07 -070093 WriteStreamDataResult WriteStreamData(QuicStreamId /*id*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -050094 QuicStreamOffset offset,
95 QuicByteCount data_length,
96 QuicDataWriter* writer) override {
97 if (send_buffer_.WriteStreamData(offset, data_length, writer)) {
98 return WRITE_SUCCESS;
99 }
100 return WRITE_FAILED;
101 }
dschinazi17d42422019-06-18 16:35:07 -0700102 bool WriteCryptoData(EncryptionLevel /*level*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500103 QuicStreamOffset offset,
104 QuicByteCount data_length,
105 QuicDataWriter* writer) override {
106 return send_buffer_.WriteStreamData(offset, data_length, writer);
107 }
108
109 std::vector<std::unique_ptr<QuicEncryptedPacket>>* packets() {
110 return &packets_;
111 }
112
113 private:
114 std::vector<std::unique_ptr<QuicEncryptedPacket>> packets_;
115 // This is only needed until the packets are encrypted. Once packets are
116 // encrypted, the stream data is no longer required.
117 QuicStreamSendBuffer send_buffer_;
118};
119
120// Helper for statelessly closing connections by generating the
121// correct termination packets and adding the connection to the time wait
122// list manager.
123class StatelessConnectionTerminator {
124 public:
dschinazi7b9278c2019-05-20 07:36:21 -0700125 StatelessConnectionTerminator(QuicConnectionId server_connection_id,
fayangf7c569c2019-05-07 11:56:51 -0700126 const ParsedQuicVersion version,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500127 QuicConnectionHelperInterface* helper,
128 QuicTimeWaitListManager* time_wait_list_manager)
dschinazi7b9278c2019-05-20 07:36:21 -0700129 : server_connection_id_(server_connection_id),
fayangf7c569c2019-05-07 11:56:51 -0700130 framer_(ParsedQuicVersionVector{version},
131 /*unused*/ QuicTime::Zero(),
132 Perspective::IS_SERVER,
133 /*unused*/ kQuicDefaultConnectionIdLength),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500134 collector_(helper->GetStreamSendBufferAllocator()),
dschinazi7b9278c2019-05-20 07:36:21 -0700135 creator_(server_connection_id, &framer_, &collector_),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500136 time_wait_list_manager_(time_wait_list_manager) {
fayangf7c569c2019-05-07 11:56:51 -0700137 framer_.set_data_producer(&collector_);
nharper965e5922019-09-23 22:33:54 -0700138 if (framer_.framer_doesnt_create_initial_encrypter() ||
139 version.UsesInitialObfuscators()) {
nharperc6b99512019-09-19 11:13:48 -0700140 framer_.SetInitialObfuscators(server_connection_id);
141 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500142 }
143
144 ~StatelessConnectionTerminator() {
145 // Clear framer's producer.
fayangf7c569c2019-05-07 11:56:51 -0700146 framer_.set_data_producer(nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500147 }
148
fayange3f2f7b2019-09-19 17:01:57 -0700149 // Serializes a packet containing CONNECTION_CLOSE frame and send it (without
150 // adding connection to the time wait).
151 void StatelesslyCloseConnection(const QuicSocketAddress& self_address,
152 const QuicSocketAddress& peer_address,
153 QuicErrorCode error_code,
154 const std::string& error_details) {
155 SerializeConnectionClosePacket(error_code, error_details);
156
157 for (const auto& packet : *collector_.packets()) {
158 time_wait_list_manager_->SendPacket(self_address, peer_address, *packet);
159 }
160 }
161
QUICHE teama6ef0a62019-03-07 20:34:33 -0500162 // Generates a packet containing a CONNECTION_CLOSE frame specifying
163 // |error_code| and |error_details| and add the connection to time wait.
164 void CloseConnection(QuicErrorCode error_code,
vasilvvc48c8712019-03-11 13:38:16 -0700165 const std::string& error_details,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500166 bool ietf_quic) {
fayange3f2f7b2019-09-19 17:01:57 -0700167 SerializeConnectionClosePacket(error_code, error_details);
168
169 time_wait_list_manager_->AddConnectionIdToTimeWait(
170 server_connection_id_, ietf_quic,
171 QuicTimeWaitListManager::SEND_TERMINATION_PACKETS,
172 quic::ENCRYPTION_INITIAL, collector_.packets());
173 }
174
175 private:
176 void SerializeConnectionClosePacket(QuicErrorCode error_code,
177 const std::string& error_details) {
fkastenholz591814c2019-09-06 12:11:46 -0700178 QuicConnectionCloseFrame* frame = new QuicConnectionCloseFrame(
179 framer_.transport_version(), error_code, error_details,
180 /*transport_close_frame_type=*/0);
fkastenholz72f509b2019-04-10 09:17:49 -0700181
QUICHE teama6ef0a62019-03-07 20:34:33 -0500182 if (!creator_.AddSavedFrame(QuicFrame(frame), NOT_RETRANSMISSION)) {
183 QUIC_BUG << "Unable to add frame to an empty packet";
184 delete frame;
185 return;
186 }
fayang62b637b2019-09-16 08:40:49 -0700187 creator_.FlushCurrentPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -0500188 DCHECK_EQ(1u, collector_.packets()->size());
QUICHE teama6ef0a62019-03-07 20:34:33 -0500189 }
190
dschinazi7b9278c2019-05-20 07:36:21 -0700191 QuicConnectionId server_connection_id_;
fayangf7c569c2019-05-07 11:56:51 -0700192 QuicFramer framer_;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500193 // Set as the visitor of |creator_| to collect any generated packets.
194 PacketCollector collector_;
195 QuicPacketCreator creator_;
196 QuicTimeWaitListManager* time_wait_list_manager_;
197};
198
199// Class which extracts the ALPN from a CHLO packet.
200class ChloAlpnExtractor : public ChloExtractor::Delegate {
201 public:
dschinazi17d42422019-06-18 16:35:07 -0700202 void OnChlo(QuicTransportVersion /*version*/,
203 QuicConnectionId /*server_connection_id*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500204 const CryptoHandshakeMessage& chlo) override {
205 QuicStringPiece alpn_value;
206 if (chlo.GetStringPiece(kALPN, &alpn_value)) {
vasilvvc48c8712019-03-11 13:38:16 -0700207 alpn_ = std::string(alpn_value);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500208 }
209 }
210
vasilvvc48c8712019-03-11 13:38:16 -0700211 std::string&& ConsumeAlpn() { return std::move(alpn_); }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500212
213 private:
vasilvvc48c8712019-03-11 13:38:16 -0700214 std::string alpn_;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500215};
216
QUICHE teama6ef0a62019-03-07 20:34:33 -0500217} // namespace
218
219QuicDispatcher::QuicDispatcher(
220 const QuicConfig* config,
221 const QuicCryptoServerConfig* crypto_config,
222 QuicVersionManager* version_manager,
223 std::unique_ptr<QuicConnectionHelperInterface> helper,
224 std::unique_ptr<QuicCryptoServerStream::Helper> session_helper,
225 std::unique_ptr<QuicAlarmFactory> alarm_factory,
dschinazi8ff74822019-05-28 16:37:20 -0700226 uint8_t expected_server_connection_id_length)
QUICHE teama6ef0a62019-03-07 20:34:33 -0500227 : config_(config),
228 crypto_config_(crypto_config),
229 compressed_certs_cache_(
230 QuicCompressedCertsCache::kQuicCompressedCertsCacheSize),
231 helper_(std::move(helper)),
232 session_helper_(std::move(session_helper)),
233 alarm_factory_(std::move(alarm_factory)),
234 delete_sessions_alarm_(
235 alarm_factory_->CreateAlarm(new DeleteSessionsAlarm(this))),
236 buffered_packets_(this, helper_->GetClock(), alarm_factory_.get()),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500237 version_manager_(version_manager),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500238 last_error_(QUIC_NO_ERROR),
239 new_sessions_allowed_per_event_loop_(0u),
QUICHE team963d57e2019-03-21 10:58:47 -0700240 accept_new_connections_(true),
dschinazi7b9278c2019-05-20 07:36:21 -0700241 allow_short_initial_server_connection_ids_(false),
dschinazi8ff74822019-05-28 16:37:20 -0700242 expected_server_connection_id_length_(
243 expected_server_connection_id_length),
dschinazic5589bd2019-09-12 14:50:11 -0700244 should_update_expected_server_connection_id_length_(false) {
245 QUIC_DLOG(INFO) << "Created QuicDispatcher with versions: "
246 << ParsedQuicVersionVectorToString(GetSupportedVersions());
247}
QUICHE teama6ef0a62019-03-07 20:34:33 -0500248
249QuicDispatcher::~QuicDispatcher() {
250 session_map_.clear();
251 closed_session_list_.clear();
252}
253
254void QuicDispatcher::InitializeWithWriter(QuicPacketWriter* writer) {
255 DCHECK(writer_ == nullptr);
256 writer_.reset(writer);
257 time_wait_list_manager_.reset(CreateQuicTimeWaitListManager());
258}
259
260void QuicDispatcher::ProcessPacket(const QuicSocketAddress& self_address,
261 const QuicSocketAddress& peer_address,
262 const QuicReceivedPacket& packet) {
dschinazi965ce092019-05-23 06:29:01 -0700263 QUIC_DVLOG(2) << "Dispatcher received encrypted " << packet.length()
264 << " bytes:" << std::endl
265 << QuicTextUtils::HexDump(
266 QuicStringPiece(packet.data(), packet.length()));
fayang1ed1f762019-06-24 11:40:04 -0700267 ReceivedPacketInfo packet_info(self_address, peer_address, packet);
fayang1f123502019-05-14 08:05:16 -0700268 std::string detailed_error;
dschinazibf0413d2019-10-07 14:19:53 -0700269 bool retry_token_present;
270 QuicStringPiece retry_token;
271 const QuicErrorCode error = QuicFramer::ParsePublicHeaderDispatcher(
272 packet, expected_server_connection_id_length_, &packet_info.form,
273 &packet_info.long_packet_type, &packet_info.version_flag,
274 &packet_info.use_length_prefix, &packet_info.version_label,
275 &packet_info.version, &packet_info.destination_connection_id,
276 &packet_info.source_connection_id, &retry_token_present, &retry_token,
277 &detailed_error);
fayangccbab732019-05-13 10:11:25 -0700278 if (error != QUIC_NO_ERROR) {
279 // Packet has framing error.
280 SetLastError(error);
281 QUIC_DLOG(ERROR) << detailed_error;
282 return;
283 }
fayang1ed1f762019-06-24 11:40:04 -0700284 if (packet_info.destination_connection_id.length() !=
dschinazi8ff74822019-05-28 16:37:20 -0700285 expected_server_connection_id_length_ &&
286 !should_update_expected_server_connection_id_length_ &&
fayangccbab732019-05-13 10:11:25 -0700287 !QuicUtils::VariableLengthConnectionIdAllowedForVersion(
fayang1ed1f762019-06-24 11:40:04 -0700288 packet_info.version.transport_version)) {
fayangccbab732019-05-13 10:11:25 -0700289 SetLastError(QUIC_INVALID_PACKET_HEADER);
290 QUIC_DLOG(ERROR) << "Invalid Connection Id Length";
291 return;
292 }
dschinazib953d022019-08-01 18:05:58 -0700293
294 if (packet_info.version_flag && IsSupportedVersion(packet_info.version)) {
295 if (!QuicUtils::IsConnectionIdValidForVersion(
296 packet_info.destination_connection_id,
297 packet_info.version.transport_version)) {
298 SetLastError(QUIC_INVALID_PACKET_HEADER);
299 QUIC_DLOG(ERROR)
300 << "Invalid destination connection ID length for version";
301 return;
302 }
303 if (packet_info.version.SupportsClientConnectionIds() &&
304 !QuicUtils::IsConnectionIdValidForVersion(
305 packet_info.source_connection_id,
306 packet_info.version.transport_version)) {
307 SetLastError(QUIC_INVALID_PACKET_HEADER);
308 QUIC_DLOG(ERROR) << "Invalid source connection ID length for version";
309 return;
310 }
311 }
312
dschinazi8ff74822019-05-28 16:37:20 -0700313 if (should_update_expected_server_connection_id_length_) {
fayang1ed1f762019-06-24 11:40:04 -0700314 expected_server_connection_id_length_ =
315 packet_info.destination_connection_id.length();
fayangccbab732019-05-13 10:11:25 -0700316 }
fayang91475c42019-06-19 08:04:26 -0700317
fayang1ed1f762019-06-24 11:40:04 -0700318 if (MaybeDispatchPacket(packet_info)) {
fayang91475c42019-06-19 08:04:26 -0700319 // Packet has been dropped or successfully dispatched, stop processing.
fayangccbab732019-05-13 10:11:25 -0700320 return;
321 }
fayang1ed1f762019-06-24 11:40:04 -0700322 ProcessHeader(&packet_info);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500323}
324
dschinazi7b9278c2019-05-20 07:36:21 -0700325QuicConnectionId QuicDispatcher::MaybeReplaceServerConnectionId(
326 QuicConnectionId server_connection_id,
QUICHE teamc65d1d12019-03-19 20:58:04 -0700327 ParsedQuicVersion version) {
fayang91475c42019-06-19 08:04:26 -0700328 if (server_connection_id.length() == expected_server_connection_id_length_) {
dschinazi7b9278c2019-05-20 07:36:21 -0700329 return server_connection_id;
QUICHE teamc65d1d12019-03-19 20:58:04 -0700330 }
331 DCHECK(QuicUtils::VariableLengthConnectionIdAllowedForVersion(
332 version.transport_version));
dschinaziadc75072019-08-19 10:54:45 -0700333
QUICHE teamc65d1d12019-03-19 20:58:04 -0700334 QuicConnectionId new_connection_id =
wub662a3d62019-08-16 14:10:50 -0700335 GenerateNewServerConnectionId(version, server_connection_id);
fayang91475c42019-06-19 08:04:26 -0700336 DCHECK_EQ(expected_server_connection_id_length_, new_connection_id.length());
dschinazi28c1bf32019-08-19 11:54:46 -0700337
338 // Verify that GenerateNewServerConnectionId is deterministic.
339 DCHECK_EQ(new_connection_id,
340 GenerateNewServerConnectionId(version, server_connection_id));
341
dschinazi7b9278c2019-05-20 07:36:21 -0700342 QUIC_DLOG(INFO) << "Replacing incoming connection ID " << server_connection_id
QUICHE teamc65d1d12019-03-19 20:58:04 -0700343 << " with " << new_connection_id;
344 return new_connection_id;
345}
346
wub662a3d62019-08-16 14:10:50 -0700347QuicConnectionId QuicDispatcher::GenerateNewServerConnectionId(
348 ParsedQuicVersion /*version*/,
dschinaziadc75072019-08-19 10:54:45 -0700349 QuicConnectionId connection_id) const {
dschinaziadc75072019-08-19 10:54:45 -0700350 return QuicUtils::CreateReplacementConnectionId(connection_id);
wub662a3d62019-08-16 14:10:50 -0700351}
352
fayang91475c42019-06-19 08:04:26 -0700353bool QuicDispatcher::MaybeDispatchPacket(
fayang1ed1f762019-06-24 11:40:04 -0700354 const ReceivedPacketInfo& packet_info) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500355 // Port zero is only allowed for unidirectional UDP, so is disallowed by QUIC.
356 // Given that we can't even send a reply rejecting the packet, just drop the
357 // packet.
fayang1ed1f762019-06-24 11:40:04 -0700358 if (packet_info.peer_address.port() == 0) {
fayang91475c42019-06-19 08:04:26 -0700359 return true;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500360 }
361
fayang1ed1f762019-06-24 11:40:04 -0700362 QuicConnectionId server_connection_id = packet_info.destination_connection_id;
QUICHE team8e2e4532019-03-14 14:37:56 -0700363
QUICHE team963d57e2019-03-21 10:58:47 -0700364 // The IETF spec requires the client to generate an initial server
365 // connection ID that is at least 64 bits long. After that initial
366 // connection ID, the dispatcher picks a new one of its expected length.
367 // Therefore we should never receive a connection ID that is smaller
368 // than 64 bits and smaller than what we expect.
dschinazi7b9278c2019-05-20 07:36:21 -0700369 if (server_connection_id.length() < kQuicMinimumInitialConnectionIdLength &&
fayang91475c42019-06-19 08:04:26 -0700370 server_connection_id.length() < expected_server_connection_id_length_ &&
dschinazi7b9278c2019-05-20 07:36:21 -0700371 !allow_short_initial_server_connection_ids_) {
fayang1ed1f762019-06-24 11:40:04 -0700372 DCHECK(packet_info.version_flag);
QUICHE team963d57e2019-03-21 10:58:47 -0700373 DCHECK(QuicUtils::VariableLengthConnectionIdAllowedForVersion(
fayang1ed1f762019-06-24 11:40:04 -0700374 packet_info.version.transport_version));
QUICHE team963d57e2019-03-21 10:58:47 -0700375 QUIC_DLOG(INFO) << "Packet with short destination connection ID "
dschinazi7b9278c2019-05-20 07:36:21 -0700376 << server_connection_id << " expected "
fayang91475c42019-06-19 08:04:26 -0700377 << static_cast<int>(expected_server_connection_id_length_);
dschinazi95025bf2019-09-06 15:08:47 -0700378 // Drop the packet silently.
379 QUIC_CODE_COUNT(quic_dropped_invalid_small_initial_connection_id);
fayang91475c42019-06-19 08:04:26 -0700380 return true;
QUICHE team963d57e2019-03-21 10:58:47 -0700381 }
382
QUICHE teama6ef0a62019-03-07 20:34:33 -0500383 // Packets with connection IDs for active connections are processed
384 // immediately.
dschinazi7b9278c2019-05-20 07:36:21 -0700385 auto it = session_map_.find(server_connection_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500386 if (it != session_map_.end()) {
dschinazi7b9278c2019-05-20 07:36:21 -0700387 DCHECK(!buffered_packets_.HasBufferedPackets(server_connection_id));
fayang1ed1f762019-06-24 11:40:04 -0700388 it->second->ProcessUdpPacket(packet_info.self_address,
389 packet_info.peer_address, packet_info.packet);
fayang91475c42019-06-19 08:04:26 -0700390 return true;
dschinazicc5a54c2019-09-24 08:30:14 -0700391 } else if (packet_info.version.transport_version !=
392 QUIC_VERSION_UNSUPPORTED) {
dschinazi5c030852019-07-11 15:45:53 -0700393 // We did not find the connection ID, check if we've replaced it.
dschinazicc5a54c2019-09-24 08:30:14 -0700394 // This is only performed for supported versions because packets with
395 // unsupported versions can flow through this function in order to send
396 // a version negotiation packet, but we know that their connection ID
397 // did not get replaced since that is performed on connection creation,
398 // and that only happens for known verions.
dschinazi5c030852019-07-11 15:45:53 -0700399 QuicConnectionId replaced_connection_id = MaybeReplaceServerConnectionId(
400 server_connection_id, packet_info.version);
401 if (replaced_connection_id != server_connection_id) {
402 // Search for the replacement.
403 auto it2 = session_map_.find(replaced_connection_id);
404 if (it2 != session_map_.end()) {
405 DCHECK(!buffered_packets_.HasBufferedPackets(replaced_connection_id));
406 it2->second->ProcessUdpPacket(packet_info.self_address,
407 packet_info.peer_address,
408 packet_info.packet);
409 return true;
410 }
411 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500412 }
413
dschinazi7b9278c2019-05-20 07:36:21 -0700414 if (buffered_packets_.HasChloForConnection(server_connection_id)) {
fayang1ed1f762019-06-24 11:40:04 -0700415 BufferEarlyPacket(packet_info);
fayang91475c42019-06-19 08:04:26 -0700416 return true;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500417 }
418
fayang1ed1f762019-06-24 11:40:04 -0700419 if (OnFailedToDispatchPacket(packet_info)) {
fayang91475c42019-06-19 08:04:26 -0700420 return true;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500421 }
422
dschinazi7b9278c2019-05-20 07:36:21 -0700423 if (time_wait_list_manager_->IsConnectionIdInTimeWait(server_connection_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500424 // This connection ID is already in time-wait state.
425 time_wait_list_manager_->ProcessPacket(
fayang1ed1f762019-06-24 11:40:04 -0700426 packet_info.self_address, packet_info.peer_address,
427 packet_info.destination_connection_id, packet_info.form,
428 GetPerPacketContext());
fayang91475c42019-06-19 08:04:26 -0700429 return true;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500430 }
431
432 // The packet has an unknown connection ID.
433
434 // Unless the packet provides a version, assume that we can continue
435 // processing using our preferred version.
fayang1ed1f762019-06-24 11:40:04 -0700436 if (packet_info.version_flag) {
437 if (!IsSupportedVersion(packet_info.version)) {
438 if (ShouldCreateSessionForUnknownVersion(packet_info.version_label)) {
fayang91475c42019-06-19 08:04:26 -0700439 return false;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500440 }
441 if (!crypto_config()->validate_chlo_size() ||
fayang1ed1f762019-06-24 11:40:04 -0700442 packet_info.packet.length() >= kMinPacketSizeForVersionNegotiation) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500443 // Since the version is not supported, send a version negotiation
444 // packet and stop processing the current packet.
fayang1ed1f762019-06-24 11:40:04 -0700445 QuicConnectionId client_connection_id =
446 packet_info.source_connection_id;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500447 time_wait_list_manager()->SendVersionNegotiationPacket(
dschinazi346b7ce2019-06-05 01:38:18 -0700448 server_connection_id, client_connection_id,
dschinazibf6a7832019-10-08 18:03:52 -0700449 packet_info.form != GOOGLE_QUIC_PACKET,
450 packet_info.use_length_prefix, GetSupportedVersions(),
451 packet_info.self_address, packet_info.peer_address,
452 GetPerPacketContext());
QUICHE teama6ef0a62019-03-07 20:34:33 -0500453 }
fayang91475c42019-06-19 08:04:26 -0700454 return true;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500455 }
fayange3f2f7b2019-09-19 17:01:57 -0700456
dschinazibf0413d2019-10-07 14:19:53 -0700457 if (GetQuicReloadableFlag(quic_donot_process_small_initial_packets) &&
fayange3f2f7b2019-09-19 17:01:57 -0700458 crypto_config()->validate_chlo_size() &&
459 packet_info.form == IETF_QUIC_LONG_HEADER_PACKET &&
460 packet_info.long_packet_type == INITIAL &&
461 packet_info.packet.length() < kMinClientInitialPacketLength) {
462 QUIC_RELOADABLE_FLAG_COUNT(quic_donot_process_small_initial_packets);
463 StatelessConnectionTerminator terminator(
464 packet_info.destination_connection_id, packet_info.version,
465 helper_.get(), time_wait_list_manager_.get());
466 QUIC_DVLOG(1) << "Initial packet too small: "
467 << packet_info.packet.length();
468 terminator.StatelesslyCloseConnection(
469 packet_info.self_address, packet_info.peer_address,
470 IETF_QUIC_PROTOCOL_VIOLATION, "Initial packet too small");
471 return true;
472 }
fayangccbab732019-05-13 10:11:25 -0700473 }
nharper55fa6132019-05-07 19:37:21 -0700474
nharper55fa6132019-05-07 19:37:21 -0700475 return false;
476}
477
fayang1ed1f762019-06-24 11:40:04 -0700478void QuicDispatcher::ProcessHeader(ReceivedPacketInfo* packet_info) {
479 QuicConnectionId server_connection_id =
480 packet_info->destination_connection_id;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500481 // Packet's connection ID is unknown. Apply the validity checks.
wub2a5670f2019-06-13 13:39:16 -0700482 // TODO(wub): Determine the fate completely in ValidityChecks, then call
483 // ProcessUnauthenticatedHeaderFate in one place.
fayang1ed1f762019-06-24 11:40:04 -0700484 QuicPacketFate fate = ValidityChecks(*packet_info);
fayang17230ac2019-06-21 06:28:28 -0700485 ChloAlpnExtractor alpn_extractor;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500486 switch (fate) {
dschinazi76992e72019-07-17 20:40:40 -0700487 case kFateProcess: {
fayang1ed1f762019-06-24 11:40:04 -0700488 if (packet_info->version.handshake_protocol == PROTOCOL_TLS1_3) {
fayang17230ac2019-06-21 06:28:28 -0700489 // TODO(nharper): Support buffering non-ClientHello packets when using
490 // TLS.
fayang1ed1f762019-06-24 11:40:04 -0700491 ProcessChlo(/*alpn=*/"", packet_info);
fayang17230ac2019-06-21 06:28:28 -0700492 break;
493 }
494 if (GetQuicFlag(FLAGS_quic_allow_chlo_buffering) &&
dschinazi4fd8cb12019-09-09 16:31:06 -0700495 !ChloExtractor::Extract(packet_info->packet, packet_info->version,
fayang17230ac2019-06-21 06:28:28 -0700496 config_->create_session_tag_indicators(),
497 &alpn_extractor,
498 server_connection_id.length())) {
499 // Buffer non-CHLO packets.
fayang1ed1f762019-06-24 11:40:04 -0700500 BufferEarlyPacket(*packet_info);
fayang17230ac2019-06-21 06:28:28 -0700501 break;
502 }
fayang1ed1f762019-06-24 11:40:04 -0700503 ProcessChlo(alpn_extractor.ConsumeAlpn(), packet_info);
dschinazi76992e72019-07-17 20:40:40 -0700504 } break;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500505 case kFateTimeWait:
wub0a4b9c52019-05-28 13:18:58 -0700506 // Add this connection_id to the time-wait state, to safely reject
507 // future packets.
508 QUIC_DLOG(INFO) << "Adding connection ID " << server_connection_id
509 << " to time-wait list.";
510 QUIC_CODE_COUNT(quic_reject_fate_time_wait);
511 StatelesslyTerminateConnection(
fayang1ed1f762019-06-24 11:40:04 -0700512 server_connection_id, packet_info->form, packet_info->version_flag,
dschinazi48ac9192019-07-31 00:07:26 -0700513 packet_info->use_length_prefix, packet_info->version,
514 QUIC_HANDSHAKE_FAILED, "Reject connection",
wub0a4b9c52019-05-28 13:18:58 -0700515 quic::QuicTimeWaitListManager::SEND_STATELESS_RESET);
516
dschinazi7b9278c2019-05-20 07:36:21 -0700517 DCHECK(time_wait_list_manager_->IsConnectionIdInTimeWait(
518 server_connection_id));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500519 time_wait_list_manager_->ProcessPacket(
fayang1ed1f762019-06-24 11:40:04 -0700520 packet_info->self_address, packet_info->peer_address,
521 server_connection_id, packet_info->form, GetPerPacketContext());
QUICHE teama6ef0a62019-03-07 20:34:33 -0500522
dschinazi7b9278c2019-05-20 07:36:21 -0700523 buffered_packets_.DiscardPackets(server_connection_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500524 break;
fayangd057e662019-07-10 13:29:41 -0700525 case kFateDrop:
526 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500527 }
528}
529
530QuicDispatcher::QuicPacketFate QuicDispatcher::ValidityChecks(
fayang1ed1f762019-06-24 11:40:04 -0700531 const ReceivedPacketInfo& packet_info) {
fayang1ed1f762019-06-24 11:40:04 -0700532 if (!packet_info.version_flag) {
dschinazi5b236be2019-08-19 14:55:22 -0700533 // The Android network conformance test contains a UDP test that sends a
534 // 12-byte packet with the following format:
535 // - 0x0c (public flags: 8-byte connection ID, 1-byte packet number)
536 // - randomized 8-byte connection ID
537 // - 0x01 (1-byte packet number)
538 // - 0x00 (private flags)
539 // - 0x07 (PING frame).
540 // That packet is invalid and we would normally drop it but in order to
541 // unblock this conformance testing we have the following workaround that
542 // will be removed once the fixed test is deployed.
543 // TODO(b/139691956) Remove this workaround once fixed test is deployed.
544 if (packet_info.packet.length() == 12 &&
545 packet_info.packet.data()[0] == 0x0c &&
546 packet_info.packet.data()[9] == 0x01 &&
547 packet_info.packet.data()[10] == 0x00 &&
548 packet_info.packet.data()[11] == 0x07) {
549 QUIC_DLOG(INFO) << "Received Android UDP network conformance test "
550 "packet with connection ID "
551 << packet_info.destination_connection_id;
552 // Respond with a public reset that the test will know how to parse
553 // then return kFateDrop to stop processing of this packet.
554 time_wait_list_manager()->SendPublicReset(
555 packet_info.self_address, packet_info.peer_address,
556 packet_info.destination_connection_id,
557 /*ietf_quic=*/false, GetPerPacketContext());
558 return kFateDrop;
559 }
dschinazi5b236be2019-08-19 14:55:22 -0700560
QUICHE teama6ef0a62019-03-07 20:34:33 -0500561 QUIC_DLOG(INFO)
562 << "Packet without version arrived for unknown connection ID "
fayang1ed1f762019-06-24 11:40:04 -0700563 << packet_info.destination_connection_id;
fayangd057e662019-07-10 13:29:41 -0700564 if (GetQuicReloadableFlag(quic_reject_unprocessable_packets_statelessly)) {
565 QUIC_RELOADABLE_FLAG_COUNT(quic_reject_unprocessable_packets_statelessly);
566 MaybeResetPacketsWithNoVersion(packet_info);
567 return kFateDrop;
568 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500569 return kFateTimeWait;
570 }
571
fayang91475c42019-06-19 08:04:26 -0700572 // Let the connection parse and validate packet number.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500573 return kFateProcess;
574}
575
576void QuicDispatcher::CleanUpSession(SessionMap::iterator it,
577 QuicConnection* connection,
dschinazi17d42422019-06-18 16:35:07 -0700578 ConnectionCloseSource /*source*/) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500579 write_blocked_list_.erase(connection);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500580 QuicTimeWaitListManager::TimeWaitAction action =
581 QuicTimeWaitListManager::SEND_STATELESS_RESET;
582 if (connection->termination_packets() != nullptr &&
583 !connection->termination_packets()->empty()) {
584 action = QuicTimeWaitListManager::SEND_TERMINATION_PACKETS;
fayang51c23732019-06-24 06:59:55 -0700585 } else {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500586 if (!connection->IsHandshakeConfirmed()) {
fayangd4291e42019-05-30 10:31:21 -0700587 if (!VersionHasIetfInvariantHeader(connection->transport_version())) {
fayang1de67892019-04-19 05:59:45 -0700588 QUIC_CODE_COUNT(gquic_add_to_time_wait_list_with_handshake_failed);
589 } else {
590 QUIC_CODE_COUNT(quic_v44_add_to_time_wait_list_with_handshake_failed);
591 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500592 action = QuicTimeWaitListManager::SEND_TERMINATION_PACKETS;
593 // This serializes a connection close termination packet with error code
594 // QUIC_HANDSHAKE_FAILED and adds the connection to the time wait list.
595 StatelesslyTerminateConnection(
fayang1de67892019-04-19 05:59:45 -0700596 connection->connection_id(),
fayangd4291e42019-05-30 10:31:21 -0700597 VersionHasIetfInvariantHeader(connection->transport_version())
fayang1de67892019-04-19 05:59:45 -0700598 ? IETF_QUIC_LONG_HEADER_PACKET
599 : GOOGLE_QUIC_PACKET,
dschinazi48ac9192019-07-31 00:07:26 -0700600 /*version_flag=*/true,
601 connection->version().HasLengthPrefixedConnectionIds(),
602 connection->version(), QUIC_HANDSHAKE_FAILED,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500603 "Connection is closed by server before handshake confirmed",
604 // Although it is our intention to send termination packets, the
605 // |action| argument is not used by this call to
606 // StatelesslyTerminateConnection().
607 action);
608 session_map_.erase(it);
609 return;
610 }
611 QUIC_CODE_COUNT(quic_v44_add_to_time_wait_list_with_stateless_reset);
612 }
613 time_wait_list_manager_->AddConnectionIdToTimeWait(
fayangd4291e42019-05-30 10:31:21 -0700614 it->first, VersionHasIetfInvariantHeader(connection->transport_version()),
615 action, connection->encryption_level(),
616 connection->termination_packets());
QUICHE teama6ef0a62019-03-07 20:34:33 -0500617 session_map_.erase(it);
618}
619
620void QuicDispatcher::StopAcceptingNewConnections() {
621 accept_new_connections_ = false;
622}
623
624std::unique_ptr<QuicPerPacketContext> QuicDispatcher::GetPerPacketContext()
625 const {
626 return nullptr;
627}
628
629void QuicDispatcher::DeleteSessions() {
QUICHE teamaa1d6a82019-03-13 09:14:13 -0700630 if (!write_blocked_list_.empty()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500631 for (const std::unique_ptr<QuicSession>& session : closed_session_list_) {
632 if (write_blocked_list_.erase(session->connection()) != 0) {
633 QUIC_BUG << "QuicConnection was in WriteBlockedList before destruction";
634 }
635 }
636 }
637 closed_session_list_.clear();
638}
639
640void QuicDispatcher::OnCanWrite() {
641 // The socket is now writable.
642 writer_->SetWritable();
643
644 // Move every blocked writer in |write_blocked_list_| to a temporary list.
645 const size_t num_blocked_writers_before = write_blocked_list_.size();
646 WriteBlockedList temp_list;
647 temp_list.swap(write_blocked_list_);
648 DCHECK(write_blocked_list_.empty());
649
650 // Give each blocked writer a chance to write what they indended to write.
651 // If they are blocked again, they will call |OnWriteBlocked| to add
652 // themselves back into |write_blocked_list_|.
653 while (!temp_list.empty()) {
654 QuicBlockedWriterInterface* blocked_writer = temp_list.begin()->first;
655 temp_list.erase(temp_list.begin());
656 blocked_writer->OnBlockedWriterCanWrite();
657 }
658 const size_t num_blocked_writers_after = write_blocked_list_.size();
659 if (num_blocked_writers_after != 0) {
660 if (num_blocked_writers_before == num_blocked_writers_after) {
661 QUIC_CODE_COUNT(quic_zero_progress_on_can_write);
662 } else {
663 QUIC_CODE_COUNT(quic_blocked_again_on_can_write);
664 }
665 }
666}
667
668bool QuicDispatcher::HasPendingWrites() const {
669 return !write_blocked_list_.empty();
670}
671
672void QuicDispatcher::Shutdown() {
673 while (!session_map_.empty()) {
674 QuicSession* session = session_map_.begin()->second.get();
675 session->connection()->CloseConnection(
676 QUIC_PEER_GOING_AWAY, "Server shutdown imminent",
677 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
678 // Validate that the session removes itself from the session map on close.
679 DCHECK(session_map_.empty() ||
680 session_map_.begin()->second.get() != session);
681 }
682 DeleteSessions();
683}
684
dschinazi7b9278c2019-05-20 07:36:21 -0700685void QuicDispatcher::OnConnectionClosed(QuicConnectionId server_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500686 QuicErrorCode error,
vasilvvc48c8712019-03-11 13:38:16 -0700687 const std::string& error_details,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500688 ConnectionCloseSource source) {
dschinazi7b9278c2019-05-20 07:36:21 -0700689 auto it = session_map_.find(server_connection_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500690 if (it == session_map_.end()) {
dschinazi7b9278c2019-05-20 07:36:21 -0700691 QUIC_BUG << "ConnectionId " << server_connection_id
QUICHE teama6ef0a62019-03-07 20:34:33 -0500692 << " does not exist in the session map. Error: "
693 << QuicErrorCodeToString(error);
694 QUIC_BUG << QuicStackTrace();
695 return;
696 }
697
698 QUIC_DLOG_IF(INFO, error != QUIC_NO_ERROR)
dschinazi7b9278c2019-05-20 07:36:21 -0700699 << "Closing connection (" << server_connection_id
QUICHE teama6ef0a62019-03-07 20:34:33 -0500700 << ") due to error: " << QuicErrorCodeToString(error)
701 << ", with details: " << error_details;
702
703 QuicConnection* connection = it->second->connection();
704 if (ShouldDestroySessionAsynchronously()) {
705 // Set up alarm to fire immediately to bring destruction of this session
706 // out of current call stack.
707 if (closed_session_list_.empty()) {
708 delete_sessions_alarm_->Update(helper()->GetClock()->ApproximateNow(),
709 QuicTime::Delta::Zero());
710 }
711 closed_session_list_.push_back(std::move(it->second));
712 }
wub5f64ec42019-06-06 07:31:19 -0700713 CleanUpSession(it, connection, source);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500714}
715
716void QuicDispatcher::OnWriteBlocked(
717 QuicBlockedWriterInterface* blocked_writer) {
718 if (!blocked_writer->IsWriterBlocked()) {
719 // It is a programming error if this ever happens. When we are sure it is
720 // not happening, replace it with a DCHECK.
721 QUIC_BUG
722 << "Tried to add writer into blocked list when it shouldn't be added";
723 // Return without adding the connection to the blocked list, to avoid
724 // infinite loops in OnCanWrite.
725 return;
726 }
727
728 write_blocked_list_.insert(std::make_pair(blocked_writer, true));
729}
730
dschinazi17d42422019-06-18 16:35:07 -0700731void QuicDispatcher::OnRstStreamReceived(const QuicRstStreamFrame& /*frame*/) {}
QUICHE teama6ef0a62019-03-07 20:34:33 -0500732
dschinazi17d42422019-06-18 16:35:07 -0700733void QuicDispatcher::OnStopSendingReceived(
734 const QuicStopSendingFrame& /*frame*/) {}
QUICHE teama6ef0a62019-03-07 20:34:33 -0500735
736void QuicDispatcher::OnConnectionAddedToTimeWaitList(
dschinazi7b9278c2019-05-20 07:36:21 -0700737 QuicConnectionId server_connection_id) {
738 QUIC_DLOG(INFO) << "Connection " << server_connection_id
QUICHE teama6ef0a62019-03-07 20:34:33 -0500739 << " added to time wait list.";
740}
741
742void QuicDispatcher::StatelesslyTerminateConnection(
dschinazi7b9278c2019-05-20 07:36:21 -0700743 QuicConnectionId server_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500744 PacketHeaderFormat format,
fayang1de67892019-04-19 05:59:45 -0700745 bool version_flag,
dschinazi48ac9192019-07-31 00:07:26 -0700746 bool use_length_prefix,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500747 ParsedQuicVersion version,
748 QuicErrorCode error_code,
vasilvvc48c8712019-03-11 13:38:16 -0700749 const std::string& error_details,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500750 QuicTimeWaitListManager::TimeWaitAction action) {
fayang51c23732019-06-24 06:59:55 -0700751 if (format != IETF_QUIC_LONG_HEADER_PACKET && !version_flag) {
dschinazi7b9278c2019-05-20 07:36:21 -0700752 QUIC_DVLOG(1) << "Statelessly terminating " << server_connection_id
QUICHE teama6ef0a62019-03-07 20:34:33 -0500753 << " based on a non-ietf-long packet, action:" << action
754 << ", error_code:" << error_code
755 << ", error_details:" << error_details;
756 time_wait_list_manager_->AddConnectionIdToTimeWait(
dschinazi7b9278c2019-05-20 07:36:21 -0700757 server_connection_id, format != GOOGLE_QUIC_PACKET, action,
758 ENCRYPTION_INITIAL, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500759 return;
760 }
761
762 // If the version is known and supported by framer, send a connection close.
fayangccbab732019-05-13 10:11:25 -0700763 if (IsSupportedVersion(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500764 QUIC_DVLOG(1)
dschinazi7b9278c2019-05-20 07:36:21 -0700765 << "Statelessly terminating " << server_connection_id
QUICHE teama6ef0a62019-03-07 20:34:33 -0500766 << " based on an ietf-long packet, which has a supported version:"
767 << version << ", error_code:" << error_code
768 << ", error_details:" << error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500769
dschinazi7b9278c2019-05-20 07:36:21 -0700770 StatelessConnectionTerminator terminator(server_connection_id, version,
771 helper_.get(),
772 time_wait_list_manager_.get());
QUICHE teama6ef0a62019-03-07 20:34:33 -0500773 // This also adds the connection to time wait list.
fayang1de67892019-04-19 05:59:45 -0700774 terminator.CloseConnection(error_code, error_details,
775 format != GOOGLE_QUIC_PACKET);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500776 return;
777 }
778
779 QUIC_DVLOG(1)
dschinazi7b9278c2019-05-20 07:36:21 -0700780 << "Statelessly terminating " << server_connection_id
QUICHE teama6ef0a62019-03-07 20:34:33 -0500781 << " based on an ietf-long packet, which has an unsupported version:"
782 << version << ", error_code:" << error_code
783 << ", error_details:" << error_details;
784 // Version is unknown or unsupported by framer, send a version negotiation
785 // with an empty version list, which can be understood by the client.
786 std::vector<std::unique_ptr<QuicEncryptedPacket>> termination_packets;
787 termination_packets.push_back(QuicFramer::BuildVersionNegotiationPacket(
dschinazib417d602019-05-29 13:08:45 -0700788 server_connection_id, EmptyQuicConnectionId(),
dschinazi48ac9192019-07-31 00:07:26 -0700789 /*ietf_quic=*/format != GOOGLE_QUIC_PACKET, use_length_prefix,
dschinazi1ac22cc2019-06-25 11:47:50 -0700790 /*versions=*/{}));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500791 time_wait_list_manager()->AddConnectionIdToTimeWait(
dschinazi7b9278c2019-05-20 07:36:21 -0700792 server_connection_id, /*ietf_quic=*/format != GOOGLE_QUIC_PACKET,
QUICHE team6987b4a2019-03-15 16:23:04 -0700793 QuicTimeWaitListManager::SEND_TERMINATION_PACKETS, ENCRYPTION_INITIAL,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500794 &termination_packets);
795}
796
QUICHE teama6ef0a62019-03-07 20:34:33 -0500797bool QuicDispatcher::ShouldCreateSessionForUnknownVersion(
798 QuicVersionLabel /*version_label*/) {
799 return false;
800}
801
QUICHE teama6ef0a62019-03-07 20:34:33 -0500802void QuicDispatcher::OnExpiredPackets(
dschinazi7b9278c2019-05-20 07:36:21 -0700803 QuicConnectionId server_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500804 BufferedPacketList early_arrived_packets) {
805 QUIC_CODE_COUNT(quic_reject_buffered_packets_expired);
806 StatelesslyTerminateConnection(
dschinazi7b9278c2019-05-20 07:36:21 -0700807 server_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500808 early_arrived_packets.ietf_quic ? IETF_QUIC_LONG_HEADER_PACKET
809 : GOOGLE_QUIC_PACKET,
dschinazi48ac9192019-07-31 00:07:26 -0700810 /*version_flag=*/true,
811 early_arrived_packets.version.HasLengthPrefixedConnectionIds(),
812 early_arrived_packets.version, QUIC_HANDSHAKE_FAILED,
813 "Packets buffered for too long",
QUICHE teama6ef0a62019-03-07 20:34:33 -0500814 quic::QuicTimeWaitListManager::SEND_STATELESS_RESET);
815}
816
817void QuicDispatcher::ProcessBufferedChlos(size_t max_connections_to_create) {
818 // Reset the counter before starting creating connections.
819 new_sessions_allowed_per_event_loop_ = max_connections_to_create;
820 for (; new_sessions_allowed_per_event_loop_ > 0;
821 --new_sessions_allowed_per_event_loop_) {
dschinazi7b9278c2019-05-20 07:36:21 -0700822 QuicConnectionId server_connection_id;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500823 BufferedPacketList packet_list =
dschinazi7b9278c2019-05-20 07:36:21 -0700824 buffered_packets_.DeliverPacketsForNextConnection(
825 &server_connection_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500826 const std::list<BufferedPacket>& packets = packet_list.buffered_packets;
827 if (packets.empty()) {
828 return;
829 }
dschinazi7b9278c2019-05-20 07:36:21 -0700830 QuicConnectionId original_connection_id = server_connection_id;
831 server_connection_id = MaybeReplaceServerConnectionId(server_connection_id,
832 packet_list.version);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500833 QuicSession* session =
dschinazi7b9278c2019-05-20 07:36:21 -0700834 CreateQuicSession(server_connection_id, packets.front().peer_address,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500835 packet_list.alpn, packet_list.version);
dschinazi7b9278c2019-05-20 07:36:21 -0700836 if (original_connection_id != server_connection_id) {
QUICHE teamc65d1d12019-03-19 20:58:04 -0700837 session->connection()->AddIncomingConnectionId(original_connection_id);
dschinazi5c030852019-07-11 15:45:53 -0700838 session->connection()->InstallInitialCrypters(original_connection_id);
QUICHE teamc65d1d12019-03-19 20:58:04 -0700839 }
dschinazi7b9278c2019-05-20 07:36:21 -0700840 QUIC_DLOG(INFO) << "Created new session for " << server_connection_id;
dschinazi5c030852019-07-11 15:45:53 -0700841
842 DCHECK(session_map_.find(server_connection_id) == session_map_.end())
843 << "Tried to add session map existing entry " << server_connection_id;
844
dschinazi7b9278c2019-05-20 07:36:21 -0700845 session_map_.insert(
846 std::make_pair(server_connection_id, QuicWrapUnique(session)));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500847 DeliverPacketsToSession(packets, session);
848 }
849}
850
851bool QuicDispatcher::HasChlosBuffered() const {
852 return buffered_packets_.HasChlosBuffered();
853}
854
855bool QuicDispatcher::ShouldCreateOrBufferPacketForConnection(
fayang1ed1f762019-06-24 11:40:04 -0700856 const ReceivedPacketInfo& packet_info) {
dschinazi7b9278c2019-05-20 07:36:21 -0700857 QUIC_VLOG(1) << "Received packet from new connection "
fayang1ed1f762019-06-24 11:40:04 -0700858 << packet_info.destination_connection_id;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500859 return true;
860}
861
862// Return true if there is any packet buffered in the store.
dschinazi7b9278c2019-05-20 07:36:21 -0700863bool QuicDispatcher::HasBufferedPackets(QuicConnectionId server_connection_id) {
864 return buffered_packets_.HasBufferedPackets(server_connection_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500865}
866
dschinazi7b9278c2019-05-20 07:36:21 -0700867void QuicDispatcher::OnBufferPacketFailure(
868 EnqueuePacketResult result,
869 QuicConnectionId server_connection_id) {
870 QUIC_DLOG(INFO) << "Fail to buffer packet on connection "
871 << server_connection_id << " because of " << result;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500872}
873
QUICHE teama6ef0a62019-03-07 20:34:33 -0500874QuicTimeWaitListManager* QuicDispatcher::CreateQuicTimeWaitListManager() {
875 return new QuicTimeWaitListManager(writer_.get(), this, helper_->GetClock(),
876 alarm_factory_.get());
877}
878
fayang1ed1f762019-06-24 11:40:04 -0700879void QuicDispatcher::BufferEarlyPacket(const ReceivedPacketInfo& packet_info) {
880 bool is_new_connection = !buffered_packets_.HasBufferedPackets(
881 packet_info.destination_connection_id);
882 if (is_new_connection &&
883 !ShouldCreateOrBufferPacketForConnection(packet_info)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500884 return;
885 }
886
887 EnqueuePacketResult rs = buffered_packets_.EnqueuePacket(
fayang1ed1f762019-06-24 11:40:04 -0700888 packet_info.destination_connection_id,
889 packet_info.form != GOOGLE_QUIC_PACKET, packet_info.packet,
890 packet_info.self_address, packet_info.peer_address, /*is_chlo=*/false,
891 /*alpn=*/"", packet_info.version);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500892 if (rs != EnqueuePacketResult::SUCCESS) {
fayang1ed1f762019-06-24 11:40:04 -0700893 OnBufferPacketFailure(rs, packet_info.destination_connection_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500894 }
895}
896
fayang1ed1f762019-06-24 11:40:04 -0700897void QuicDispatcher::ProcessChlo(const std::string& alpn,
898 ReceivedPacketInfo* packet_info) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500899 if (!accept_new_connections_) {
900 // Don't any create new connection.
901 QUIC_CODE_COUNT(quic_reject_stop_accepting_new_connections);
902 StatelesslyTerminateConnection(
fayang1ed1f762019-06-24 11:40:04 -0700903 packet_info->destination_connection_id, packet_info->form,
dschinazi48ac9192019-07-31 00:07:26 -0700904 /*version_flag=*/true, packet_info->use_length_prefix,
905 packet_info->version, QUIC_HANDSHAKE_FAILED,
fayang1ed1f762019-06-24 11:40:04 -0700906 "Stop accepting new connections",
QUICHE teama6ef0a62019-03-07 20:34:33 -0500907 quic::QuicTimeWaitListManager::SEND_STATELESS_RESET);
908 // Time wait list will reject the packet correspondingly.
909 time_wait_list_manager()->ProcessPacket(
fayang1ed1f762019-06-24 11:40:04 -0700910 packet_info->self_address, packet_info->peer_address,
911 packet_info->destination_connection_id, packet_info->form,
912 GetPerPacketContext());
QUICHE teama6ef0a62019-03-07 20:34:33 -0500913 return;
914 }
fayang1ed1f762019-06-24 11:40:04 -0700915 if (!buffered_packets_.HasBufferedPackets(
916 packet_info->destination_connection_id) &&
917 !ShouldCreateOrBufferPacketForConnection(*packet_info)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500918 return;
919 }
danzh88e3e052019-06-13 11:47:18 -0700920 if (GetQuicFlag(FLAGS_quic_allow_chlo_buffering) &&
QUICHE teama6ef0a62019-03-07 20:34:33 -0500921 new_sessions_allowed_per_event_loop_ <= 0) {
922 // Can't create new session any more. Wait till next event loop.
fayang1ed1f762019-06-24 11:40:04 -0700923 QUIC_BUG_IF(buffered_packets_.HasChloForConnection(
924 packet_info->destination_connection_id));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500925 EnqueuePacketResult rs = buffered_packets_.EnqueuePacket(
fayang1ed1f762019-06-24 11:40:04 -0700926 packet_info->destination_connection_id,
927 packet_info->form != GOOGLE_QUIC_PACKET, packet_info->packet,
928 packet_info->self_address, packet_info->peer_address,
929 /*is_chlo=*/true, alpn, packet_info->version);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500930 if (rs != EnqueuePacketResult::SUCCESS) {
fayang1ed1f762019-06-24 11:40:04 -0700931 OnBufferPacketFailure(rs, packet_info->destination_connection_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500932 }
933 return;
934 }
QUICHE teamc65d1d12019-03-19 20:58:04 -0700935
fayang1ed1f762019-06-24 11:40:04 -0700936 QuicConnectionId original_connection_id =
937 packet_info->destination_connection_id;
938 packet_info->destination_connection_id = MaybeReplaceServerConnectionId(
939 original_connection_id, packet_info->version);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500940 // Creates a new session and process all buffered packets for this connection.
dschinazi7b9278c2019-05-20 07:36:21 -0700941 QuicSession* session =
fayang1ed1f762019-06-24 11:40:04 -0700942 CreateQuicSession(packet_info->destination_connection_id,
943 packet_info->peer_address, alpn, packet_info->version);
944 if (original_connection_id != packet_info->destination_connection_id) {
QUICHE teamc65d1d12019-03-19 20:58:04 -0700945 session->connection()->AddIncomingConnectionId(original_connection_id);
dschinazi5c030852019-07-11 15:45:53 -0700946 session->connection()->InstallInitialCrypters(original_connection_id);
QUICHE teamc65d1d12019-03-19 20:58:04 -0700947 }
dschinazi7b9278c2019-05-20 07:36:21 -0700948 QUIC_DLOG(INFO) << "Created new session for "
fayang1ed1f762019-06-24 11:40:04 -0700949 << packet_info->destination_connection_id;
dschinazi5c030852019-07-11 15:45:53 -0700950
951 DCHECK(session_map_.find(packet_info->destination_connection_id) ==
952 session_map_.end())
953 << "Tried to add session map existing entry "
954 << packet_info->destination_connection_id;
955
fayang1ed1f762019-06-24 11:40:04 -0700956 session_map_.insert(std::make_pair(packet_info->destination_connection_id,
957 QuicWrapUnique(session)));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500958 std::list<BufferedPacket> packets =
fayang1ed1f762019-06-24 11:40:04 -0700959 buffered_packets_.DeliverPackets(packet_info->destination_connection_id)
dschinazi7b9278c2019-05-20 07:36:21 -0700960 .buffered_packets;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500961 // Process CHLO at first.
fayang1ed1f762019-06-24 11:40:04 -0700962 session->ProcessUdpPacket(packet_info->self_address,
963 packet_info->peer_address, packet_info->packet);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500964 // Deliver queued-up packets in the same order as they arrived.
965 // Do this even when flag is off because there might be still some packets
966 // buffered in the store before flag is turned off.
967 DeliverPacketsToSession(packets, session);
968 --new_sessions_allowed_per_event_loop_;
969}
970
QUICHE teama6ef0a62019-03-07 20:34:33 -0500971bool QuicDispatcher::ShouldDestroySessionAsynchronously() {
972 return true;
973}
974
975void QuicDispatcher::SetLastError(QuicErrorCode error) {
976 last_error_ = error;
977}
978
fayang91475c42019-06-19 08:04:26 -0700979bool QuicDispatcher::OnFailedToDispatchPacket(
fayang1ed1f762019-06-24 11:40:04 -0700980 const ReceivedPacketInfo& /*packet_info*/) {
fayang91475c42019-06-19 08:04:26 -0700981 return false;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500982}
983
QUICHE teama6ef0a62019-03-07 20:34:33 -0500984const QuicTransportVersionVector&
985QuicDispatcher::GetSupportedTransportVersions() {
986 return version_manager_->GetSupportedTransportVersions();
987}
988
989const ParsedQuicVersionVector& QuicDispatcher::GetSupportedVersions() {
990 return version_manager_->GetSupportedVersions();
991}
992
993void QuicDispatcher::DeliverPacketsToSession(
994 const std::list<BufferedPacket>& packets,
995 QuicSession* session) {
996 for (const BufferedPacket& packet : packets) {
997 session->ProcessUdpPacket(packet.self_address, packet.peer_address,
998 *(packet.packet));
999 }
1000}
1001
fayangccbab732019-05-13 10:11:25 -07001002bool QuicDispatcher::IsSupportedVersion(const ParsedQuicVersion version) {
fayangccbab732019-05-13 10:11:25 -07001003 for (const ParsedQuicVersion& supported_version :
1004 version_manager_->GetSupportedVersions()) {
1005 if (version == supported_version) {
1006 return true;
1007 }
1008 }
1009 return false;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001010}
1011
fayangd057e662019-07-10 13:29:41 -07001012void QuicDispatcher::MaybeResetPacketsWithNoVersion(
1013 const ReceivedPacketInfo& packet_info) {
1014 DCHECK(!packet_info.version_flag);
1015 const size_t MinValidPacketLength =
1016 kPacketHeaderTypeSize + expected_server_connection_id_length_ +
1017 PACKET_1BYTE_PACKET_NUMBER + /*payload size=*/1 + /*tag size=*/12;
1018 if (packet_info.packet.length() < MinValidPacketLength) {
1019 // The packet size is too small.
1020 QUIC_CODE_COUNT(drop_too_small_packets);
1021 return;
1022 }
1023 // TODO(fayang): Consider rate limiting reset packets if reset packet size >
1024 // packet_length.
1025
1026 time_wait_list_manager()->SendPublicReset(
1027 packet_info.self_address, packet_info.peer_address,
1028 packet_info.destination_connection_id,
1029 packet_info.form != GOOGLE_QUIC_PACKET, GetPerPacketContext());
1030}
1031
QUICHE teama6ef0a62019-03-07 20:34:33 -05001032} // namespace quic