blob: 259b577c9800eb838b48c29b1e69e4f363d7c8f4 [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// Accumulates frames for the next packet until more frames no longer fit or
6// it's time to create a packet from them.
7
8#ifndef QUICHE_QUIC_CORE_QUIC_PACKET_CREATOR_H_
9#define QUICHE_QUIC_CORE_QUIC_PACKET_CREATOR_H_
10
11#include <cstddef>
12#include <memory>
13#include <utility>
14#include <vector>
15
QUICHE teama6ef0a62019-03-07 20:34:33 -050016#include "net/third_party/quiche/src/quic/core/quic_framer.h"
17#include "net/third_party/quiche/src/quic/core/quic_packets.h"
18#include "net/third_party/quiche/src/quic/core/quic_pending_retransmission.h"
19#include "net/third_party/quiche/src/quic/core/quic_types.h"
20#include "net/third_party/quiche/src/quic/platform/api/quic_export.h"
21
22namespace quic {
23namespace test {
24class QuicPacketCreatorPeer;
25}
26
27class QUIC_EXPORT_PRIVATE QuicPacketCreator {
28 public:
29 // A delegate interface for further processing serialized packet.
ianswettb023c7b2019-05-06 12:38:10 -070030 class QUIC_EXPORT_PRIVATE DelegateInterface {
QUICHE teama6ef0a62019-03-07 20:34:33 -050031 public:
ianswettb023c7b2019-05-06 12:38:10 -070032 virtual ~DelegateInterface() {}
dschinazi66dea072019-04-09 11:41:06 -070033 // Get a buffer of kMaxOutgoingPacketSize bytes to serialize the next
34 // packet. If return nullptr, QuicPacketCreator will serialize on a stack
35 // buffer.
QUICHE teama6ef0a62019-03-07 20:34:33 -050036 virtual char* GetPacketBuffer() = 0;
37 // Called when a packet is serialized. Delegate does not take the ownership
38 // of |serialized_packet|, but takes ownership of any frames it removes
39 // from |packet.retransmittable_frames|.
40 virtual void OnSerializedPacket(SerializedPacket* serialized_packet) = 0;
ianswettb023c7b2019-05-06 12:38:10 -070041
42 // Called when an unrecoverable error is encountered.
43 virtual void OnUnrecoverableError(QuicErrorCode error,
44 const std::string& error_details,
45 ConnectionCloseSource source) = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -050046 };
47
48 // Interface which gets callbacks from the QuicPacketCreator at interesting
49 // points. Implementations must not mutate the state of the creator
50 // as a result of these callbacks.
51 class QUIC_EXPORT_PRIVATE DebugDelegate {
52 public:
53 virtual ~DebugDelegate() {}
54
55 // Called when a frame has been added to the current packet.
56 virtual void OnFrameAddedToPacket(const QuicFrame& frame) {}
57 };
58
dschinazi7b9278c2019-05-20 07:36:21 -070059 QuicPacketCreator(QuicConnectionId server_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -050060 QuicFramer* framer,
61 DelegateInterface* delegate);
dschinazi7b9278c2019-05-20 07:36:21 -070062 QuicPacketCreator(QuicConnectionId server_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -050063 QuicFramer* framer,
64 QuicRandom* random,
65 DelegateInterface* delegate);
66 QuicPacketCreator(const QuicPacketCreator&) = delete;
67 QuicPacketCreator& operator=(const QuicPacketCreator&) = delete;
68
69 ~QuicPacketCreator();
70
71 // Makes the framer not serialize the protocol version in sent packets.
72 void StopSendingVersion();
73
74 // SetDiversificationNonce sets the nonce that will be sent in each public
75 // header of packets encrypted at the initial encryption level. Should only
76 // be called by servers.
77 void SetDiversificationNonce(const DiversificationNonce& nonce);
78
79 // Update the packet number length to use in future packets as soon as it
80 // can be safely changed.
81 // TODO(fayang): Directly set packet number length instead of compute it in
82 // creator.
83 void UpdatePacketNumberLength(QuicPacketNumber least_packet_awaited_by_peer,
84 QuicPacketCount max_packets_in_flight);
85
86 // The overhead the framing will add for a packet with one frame.
87 static size_t StreamFramePacketOverhead(
88 QuicTransportVersion version,
89 QuicConnectionIdLength destination_connection_id_length,
90 QuicConnectionIdLength source_connection_id_length,
91 bool include_version,
92 bool include_diversification_nonce,
93 QuicPacketNumberLength packet_number_length,
94 QuicVariableLengthIntegerLength retry_token_length_length,
95 QuicVariableLengthIntegerLength length_length,
96 QuicStreamOffset offset);
97
98 // Returns false and flushes all pending frames if current open packet is
99 // full.
100 // If current packet is not full, creates a stream frame that fits into the
101 // open packet and adds it to the packet.
102 bool ConsumeData(QuicStreamId id,
ianswette28f0222019-04-04 13:31:22 -0700103 size_t data_length,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500104 QuicStreamOffset offset,
105 bool fin,
106 bool needs_full_padding,
107 TransmissionType transmission_type,
108 QuicFrame* frame);
109
110 // Creates a CRYPTO frame that fits into the current packet (which must be
111 // empty) and adds it to the packet.
112 bool ConsumeCryptoData(EncryptionLevel level,
113 size_t write_length,
114 QuicStreamOffset offset,
nharper51961cf2019-05-13 13:23:24 -0700115 bool needs_full_padding,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500116 TransmissionType transmission_type,
117 QuicFrame* frame);
118
119 // Returns true if current open packet can accommodate more stream frames of
120 // stream |id| at |offset| and data length |data_size|, false otherwise.
121 bool HasRoomForStreamFrame(QuicStreamId id,
122 QuicStreamOffset offset,
123 size_t data_size);
124
125 // Returns true if current open packet can accommodate a message frame of
126 // |length|.
127 bool HasRoomForMessageFrame(QuicByteCount length);
128
129 // Re-serializes frames with the original packet's packet number length.
130 // Used for retransmitting packets to ensure they aren't too long.
131 void ReserializeAllFrames(const QuicPendingRetransmission& retransmission,
132 char* buffer,
133 size_t buffer_len);
134
135 // Serializes all added frames into a single packet and invokes the delegate_
136 // to further process the SerializedPacket.
137 void Flush();
138
139 // Optimized method to create a QuicStreamFrame and serialize it. Adds the
140 // QuicStreamFrame to the returned SerializedPacket. Sets
141 // |num_bytes_consumed| to the number of bytes consumed to create the
142 // QuicStreamFrame.
143 void CreateAndSerializeStreamFrame(QuicStreamId id,
144 size_t write_length,
145 QuicStreamOffset iov_offset,
146 QuicStreamOffset stream_offset,
147 bool fin,
148 TransmissionType transmission_type,
149 size_t* num_bytes_consumed);
150
151 // Returns true if there are frames pending to be serialized.
152 bool HasPendingFrames() const;
153
154 // Returns true if there are retransmittable frames pending to be serialized.
155 bool HasPendingRetransmittableFrames() const;
156
157 // Returns true if there are stream frames for |id| pending to be serialized.
158 bool HasPendingStreamFramesOfStream(QuicStreamId id) const;
159
160 // Returns the number of bytes which are available to be used by additional
161 // frames in the packet. Since stream frames are slightly smaller when they
162 // are the last frame in a packet, this method will return a different
163 // value than max_packet_size - PacketSize(), in this case.
164 size_t BytesFree();
165
166 // Returns the number of bytes that the packet will expand by if a new frame
167 // is added to the packet. If the last frame was a stream frame, it will
168 // expand slightly when a new frame is added, and this method returns the
169 // amount of expected expansion.
170 size_t ExpansionOnNewFrame() const;
171
172 // Returns the number of bytes in the current packet, including the header,
173 // if serialized with the current frames. Adding a frame to the packet
174 // may change the serialized length of existing frames, as per the comment
175 // in BytesFree.
176 size_t PacketSize();
177
178 // Tries to add |frame| to the packet creator's list of frames to be
179 // serialized. If the frame does not fit into the current packet, flushes the
180 // packet and returns false.
181 bool AddSavedFrame(const QuicFrame& frame,
182 TransmissionType transmission_type);
183
184 // Identical to AddSavedFrame, but allows the frame to be padded.
185 bool AddPaddedSavedFrame(const QuicFrame& frame,
186 TransmissionType transmission_type);
187
188 // Creates a version negotiation packet which supports |supported_versions|.
189 std::unique_ptr<QuicEncryptedPacket> SerializeVersionNegotiationPacket(
190 bool ietf_quic,
191 const ParsedQuicVersionVector& supported_versions);
192
193 // Creates a connectivity probing packet for versions prior to version 99.
194 OwningSerializedPacketPointer SerializeConnectivityProbingPacket();
195
196 // Create connectivity probing request and response packets using PATH
197 // CHALLENGE and PATH RESPONSE frames, respectively, for version 99/IETF QUIC.
198 // SerializePathChallengeConnectivityProbingPacket will pad the packet to be
199 // MTU bytes long.
200 OwningSerializedPacketPointer SerializePathChallengeConnectivityProbingPacket(
201 QuicPathFrameBuffer* payload);
202
203 // If |is_padded| is true then SerializePathResponseConnectivityProbingPacket
204 // will pad the packet to be MTU bytes long, else it will not pad the packet.
205 // |payloads| is cleared.
206 OwningSerializedPacketPointer SerializePathResponseConnectivityProbingPacket(
207 const QuicDeque<QuicPathFrameBuffer>& payloads,
208 const bool is_padded);
209
210 // Returns a dummy packet that is valid but contains no useful information.
211 static SerializedPacket NoPacket();
212
QUICHE team2252b702019-05-14 23:55:14 -0400213 // Returns the destination connection ID to send over the wire.
214 QuicConnectionId GetDestinationConnectionId() const;
215
216 // Returns the source connection ID to send over the wire.
217 QuicConnectionId GetSourceConnectionId() const;
218
QUICHE teama6ef0a62019-03-07 20:34:33 -0500219 // Returns length of destination connection ID to send over the wire.
220 QuicConnectionIdLength GetDestinationConnectionIdLength() const;
221
222 // Returns length of source connection ID to send over the wire.
223 QuicConnectionIdLength GetSourceConnectionIdLength() const;
224
dschinazi7b9278c2019-05-20 07:36:21 -0700225 // Sets whether the server connection ID should be sent over the wire.
226 void SetServerConnectionIdIncluded(
227 QuicConnectionIdIncluded server_connection_id_included);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500228
QUICHE teamc65d1d12019-03-19 20:58:04 -0700229 // Update the connection ID used in outgoing packets.
dschinazi7b9278c2019-05-20 07:36:21 -0700230 void SetServerConnectionId(QuicConnectionId server_connection_id);
QUICHE teamc65d1d12019-03-19 20:58:04 -0700231
QUICHE teama6ef0a62019-03-07 20:34:33 -0500232 // Sets the encryption level that will be applied to new packets.
233 void set_encryption_level(EncryptionLevel level) {
234 packet_.encryption_level = level;
235 }
236
237 // packet number of the last created packet, or 0 if no packets have been
238 // created.
239 QuicPacketNumber packet_number() const { return packet_.packet_number; }
240
241 QuicByteCount max_packet_length() const { return max_packet_length_; }
242
243 bool has_ack() const { return packet_.has_ack; }
244
245 bool has_stop_waiting() const { return packet_.has_stop_waiting; }
246
247 // Sets the encrypter to use for the encryption level and updates the max
248 // plaintext size.
249 void SetEncrypter(EncryptionLevel level,
250 std::unique_ptr<QuicEncrypter> encrypter);
251
252 // Indicates whether the packet creator is in a state where it can change
253 // current maximum packet length.
254 bool CanSetMaxPacketLength() const;
255
256 // Sets the maximum packet length.
257 void SetMaxPacketLength(QuicByteCount length);
258
259 // Increases pending_padding_bytes by |size|. Pending padding will be sent by
260 // MaybeAddPadding().
261 void AddPendingPadding(QuicByteCount size);
262
263 // Sets transmission type of next constructed packets.
264 void SetTransmissionType(TransmissionType type);
265
dschinazi244f6dc2019-05-06 15:45:16 -0700266 // Sets the retry token to be sent over the wire in IETF Initial packets.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500267 void SetRetryToken(QuicStringPiece retry_token);
268
269 // Returns the largest payload that will fit into a single MESSAGE frame.
ianswettb239f862019-04-05 09:15:06 -0700270 QuicPacketLength GetCurrentLargestMessagePayload() const;
271 // Returns the largest payload that will fit into a single MESSAGE frame at
272 // any point during the connection. This assumes the version and
273 // connection ID lengths do not change.
274 QuicPacketLength GetGuaranteedLargestMessagePayload() const;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500275
276 void set_debug_delegate(DebugDelegate* debug_delegate) {
277 debug_delegate_ = debug_delegate;
278 }
279
280 void set_can_set_transmission_type(bool can_set_transmission_type) {
281 can_set_transmission_type_ = can_set_transmission_type;
282 }
283
wub98669f52019-04-18 10:49:18 -0700284 bool can_set_transmission_type() const { return can_set_transmission_type_; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500285
286 QuicByteCount pending_padding_bytes() const { return pending_padding_bytes_; }
287
288 QuicTransportVersion transport_version() const {
289 return framer_->transport_version();
290 }
291
nharper55fa6132019-05-07 19:37:21 -0700292 // Returns the minimum size that the plaintext of a packet must be.
QUICHE team2252b702019-05-14 23:55:14 -0400293 static size_t MinPlaintextPacketSize(const ParsedQuicVersion& version);
nharper55fa6132019-05-07 19:37:21 -0700294
QUICHE teama6ef0a62019-03-07 20:34:33 -0500295 private:
296 friend class test::QuicPacketCreatorPeer;
297
298 // Creates a stream frame which fits into the current open packet. If
QUICHE teamf08778a2019-03-14 08:10:26 -0700299 // |data_size| is 0 and fin is true, the expected behavior is to consume
300 // the fin.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500301 void CreateStreamFrame(QuicStreamId id,
QUICHE teamf08778a2019-03-14 08:10:26 -0700302 size_t data_size,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500303 QuicStreamOffset offset,
304 bool fin,
305 QuicFrame* frame);
306
307 // Creates a CRYPTO frame which fits into the current open packet. Returns
308 // false if there isn't enough room in the current open packet for a CRYPTO
309 // frame, and true if there is.
310 bool CreateCryptoFrame(EncryptionLevel level,
311 size_t write_length,
312 QuicStreamOffset offset,
313 QuicFrame* frame);
314
315 void FillPacketHeader(QuicPacketHeader* header);
316
317 // Adds a |frame| if there is space and returns false and flushes all pending
318 // frames if there isn't room. If |save_retransmittable_frames| is true,
319 // saves the |frame| in the next SerializedPacket.
320 bool AddFrame(const QuicFrame& frame,
321 bool save_retransmittable_frames,
322 TransmissionType transmission_type);
323
324 // Adds a padding frame to the current packet (if there is space) when (1)
325 // current packet needs full padding or (2) there are pending paddings.
326 void MaybeAddPadding();
327
328 // Serializes all frames which have been added and adds any which should be
329 // retransmitted to packet_.retransmittable_frames. All frames must fit into
330 // a single packet.
331 // Fails if |buffer_len| isn't long enough for the encrypted packet.
332 void SerializePacket(char* encrypted_buffer, size_t buffer_len);
333
334 // Called after a new SerialiedPacket is created to call the delegate's
335 // OnSerializedPacket and reset state.
336 void OnSerializedPacket();
337
338 // Clears all fields of packet_ that should be cleared between serializations.
339 void ClearPacket();
340
341 // Returns true if a diversification nonce should be included in the current
342 // packet's header.
343 bool IncludeNonceInPublicHeader() const;
344
345 // Returns true if version should be included in current packet's header.
346 bool IncludeVersionInHeader() const;
347
348 // Returns length of packet number to send over the wire.
349 // packet_.packet_number_length should never be read directly, use this
350 // function instead.
351 QuicPacketNumberLength GetPacketNumberLength() const;
352
nharper55fa6132019-05-07 19:37:21 -0700353 // Returns the size in bytes of the packet header.
354 size_t PacketHeaderSize() const;
355
QUICHE teama6ef0a62019-03-07 20:34:33 -0500356 // Returns whether the destination connection ID is sent over the wire.
357 QuicConnectionIdIncluded GetDestinationConnectionIdIncluded() const;
358
359 // Returns whether the source connection ID is sent over the wire.
360 QuicConnectionIdIncluded GetSourceConnectionIdIncluded() const;
361
362 // Returns length of the retry token variable length integer to send over the
363 // wire. Is non-zero for v99 IETF Initial packets.
364 QuicVariableLengthIntegerLength GetRetryTokenLengthLength() const;
365
366 // Returns the retry token to send over the wire, only sent in
367 // v99 IETF Initial packets.
368 QuicStringPiece GetRetryToken() const;
369
370 // Returns length of the length variable length integer to send over the
371 // wire. Is non-zero for v99 IETF Initial, 0-RTT or Handshake packets.
372 QuicVariableLengthIntegerLength GetLengthLength() const;
373
ianswette28f0222019-04-04 13:31:22 -0700374 // Returns true if |frame| is a ClientHello.
375 bool StreamFrameIsClientHello(const QuicStreamFrame& frame) const;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500376
377 // Returns true if packet under construction has IETF long header.
378 bool HasIetfLongHeader() const;
379
380 // Does not own these delegates or the framer.
381 DelegateInterface* delegate_;
382 DebugDelegate* debug_delegate_;
383 QuicFramer* framer_;
384 QuicRandom* random_;
385
386 // Controls whether version should be included while serializing the packet.
387 // send_version_in_packet_ should never be read directly, use
388 // IncludeVersionInHeader() instead.
389 bool send_version_in_packet_;
390 // If true, then |diversification_nonce_| will be included in the header of
391 // all packets created at the initial encryption level.
392 bool have_diversification_nonce_;
393 DiversificationNonce diversification_nonce_;
394 // Maximum length including headers and encryption (UDP payload length.)
395 QuicByteCount max_packet_length_;
396 size_t max_plaintext_size_;
dschinazi7b9278c2019-05-20 07:36:21 -0700397 // Whether the server_connection_id is sent over the wire.
398 QuicConnectionIdIncluded server_connection_id_included_;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500399
400 // Frames to be added to the next SerializedPacket
401 QuicFrames queued_frames_;
402
403 // packet_size should never be read directly, use PacketSize() instead.
404 // TODO(ianswett): Move packet_size_ into SerializedPacket once
405 // QuicEncryptedPacket has been flattened into SerializedPacket.
406 size_t packet_size_;
dschinazi7b9278c2019-05-20 07:36:21 -0700407 QuicConnectionId server_connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500408
409 // Packet used to invoke OnSerializedPacket.
410 SerializedPacket packet_;
411
412 // Retry token to send over the wire in v99 IETF Initial packets.
vasilvvc48c8712019-03-11 13:38:16 -0700413 std::string retry_token_;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500414
415 // Pending padding bytes to send. Pending padding bytes will be sent in next
416 // packet(s) (after all other frames) if current constructed packet does not
417 // have room to send all of them.
418 QuicByteCount pending_padding_bytes_;
419
420 // Indicates whether current constructed packet needs full padding to max
421 // packet size. Please note, full padding does not consume pending padding
422 // bytes.
423 bool needs_full_padding_;
424
425 // If true, packet_'s transmission type is only set by
426 // SetPacketTransmissionType and does not get cleared in ClearPacket.
427 bool can_set_transmission_type_;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500428};
429
430} // namespace quic
431
432#endif // QUICHE_QUIC_CORE_QUIC_PACKET_CREATOR_H_