• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 // Responsible for creating packets on behalf of a QuicConnection.
6 // Packets are serialized just-in-time. Stream data and control frames will be
7 // requested from the Connection just-in-time. Frames are accumulated into
8 // "current" packet until no more frames can fit, then current packet gets
9 // serialized and passed to connection via OnSerializedPacket().
10 //
11 // Whether a packet should be serialized is determined by whether delegate is
12 // writable. If the Delegate is not writable, then no operations will cause
13 // a packet to be serialized.
14 
15 #ifndef QUICHE_QUIC_CORE_QUIC_PACKET_CREATOR_H_
16 #define QUICHE_QUIC_CORE_QUIC_PACKET_CREATOR_H_
17 
18 #include <cstddef>
19 #include <memory>
20 #include <utility>
21 #include <vector>
22 
23 #include "absl/base/attributes.h"
24 #include "absl/strings/string_view.h"
25 #include "absl/types/optional.h"
26 #include "quiche/quic/core/frames/quic_stream_frame.h"
27 #include "quiche/quic/core/quic_coalesced_packet.h"
28 #include "quiche/quic/core/quic_connection_id.h"
29 #include "quiche/quic/core/quic_framer.h"
30 #include "quiche/quic/core/quic_packets.h"
31 #include "quiche/quic/core/quic_types.h"
32 #include "quiche/quic/platform/api/quic_export.h"
33 #include "quiche/quic/platform/api/quic_flags.h"
34 #include "quiche/common/platform/api/quiche_mem_slice.h"
35 #include "quiche/common/quiche_circular_deque.h"
36 
37 namespace quic {
38 namespace test {
39 class QuicPacketCreatorPeer;
40 }
41 
42 class QUIC_EXPORT_PRIVATE QuicPacketCreator {
43  public:
44   // A delegate interface for further processing serialized packet.
45   class QUIC_EXPORT_PRIVATE DelegateInterface {
46    public:
~DelegateInterface()47     virtual ~DelegateInterface() {}
48     // Get a buffer of kMaxOutgoingPacketSize bytes to serialize the next
49     // packet. If the return value's buffer is nullptr, QuicPacketCreator will
50     // serialize on a stack buffer.
51     virtual QuicPacketBuffer GetPacketBuffer() = 0;
52     // Called when a packet is serialized. Delegate take the ownership of
53     // |serialized_packet|.
54     virtual void OnSerializedPacket(SerializedPacket serialized_packet) = 0;
55 
56     // Called when an unrecoverable error is encountered.
57     virtual void OnUnrecoverableError(QuicErrorCode error,
58                                       const std::string& error_details) = 0;
59 
60     // Consults delegate whether a packet should be generated.
61     virtual bool ShouldGeneratePacket(HasRetransmittableData retransmittable,
62                                       IsHandshake handshake) = 0;
63     // Called when there is data to be sent. Retrieves updated ACK frame from
64     // the delegate.
65     virtual const QuicFrames MaybeBundleAckOpportunistically() = 0;
66 
67     // Returns the packet fate for serialized packets which will be handed over
68     // to delegate via OnSerializedPacket(). Called when a packet is about to be
69     // serialized.
70     virtual SerializedPacketFate GetSerializedPacketFate(
71         bool is_mtu_discovery, EncryptionLevel encryption_level) = 0;
72   };
73 
74   // Interface which gets callbacks from the QuicPacketCreator at interesting
75   // points.  Implementations must not mutate the state of the creator
76   // as a result of these callbacks.
77   class QUIC_EXPORT_PRIVATE DebugDelegate {
78    public:
~DebugDelegate()79     virtual ~DebugDelegate() {}
80 
81     // Called when a frame has been added to the current packet.
OnFrameAddedToPacket(const QuicFrame &)82     virtual void OnFrameAddedToPacket(const QuicFrame& /*frame*/) {}
83 
84     // Called when a stream frame is coalesced with an existing stream frame.
85     // |frame| is the new stream frame.
OnStreamFrameCoalesced(const QuicStreamFrame &)86     virtual void OnStreamFrameCoalesced(const QuicStreamFrame& /*frame*/) {}
87   };
88 
89   // Set the peer address and connection IDs with which the serialized packet
90   // will be sent to during the scope of this object. Upon exiting the scope,
91   // the original peer address and connection IDs are restored.
92   class QUIC_EXPORT_PRIVATE ScopedPeerAddressContext {
93    public:
94     ScopedPeerAddressContext(QuicPacketCreator* creator,
95                              QuicSocketAddress address,
96                              bool update_connection_id);
97 
98     ScopedPeerAddressContext(QuicPacketCreator* creator,
99                              QuicSocketAddress address,
100                              const QuicConnectionId& client_connection_id,
101                              const QuicConnectionId& server_connection_id,
102                              bool update_connection_id);
103     ~ScopedPeerAddressContext();
104 
105    private:
106     QuicPacketCreator* creator_;
107     QuicSocketAddress old_peer_address_;
108     QuicConnectionId old_client_connection_id_;
109     QuicConnectionId old_server_connection_id_;
110     bool update_connection_id_;
111   };
112 
113   QuicPacketCreator(QuicConnectionId server_connection_id, QuicFramer* framer,
114                     DelegateInterface* delegate);
115   QuicPacketCreator(QuicConnectionId server_connection_id, QuicFramer* framer,
116                     QuicRandom* random, DelegateInterface* delegate);
117   QuicPacketCreator(const QuicPacketCreator&) = delete;
118   QuicPacketCreator& operator=(const QuicPacketCreator&) = delete;
119 
120   ~QuicPacketCreator();
121 
122   // Makes the framer not serialize the protocol version in sent packets.
123   void StopSendingVersion();
124 
125   // SetDiversificationNonce sets the nonce that will be sent in each public
126   // header of packets encrypted at the initial encryption level. Should only
127   // be called by servers.
128   void SetDiversificationNonce(const DiversificationNonce& nonce);
129 
130   // Update the packet number length to use in future packets as soon as it
131   // can be safely changed.
132   // TODO(fayang): Directly set packet number length instead of compute it in
133   // creator.
134   void UpdatePacketNumberLength(QuicPacketNumber least_packet_awaited_by_peer,
135                                 QuicPacketCount max_packets_in_flight);
136 
137   // Skip |count| packet numbers.
138   void SkipNPacketNumbers(QuicPacketCount count,
139                           QuicPacketNumber least_packet_awaited_by_peer,
140                           QuicPacketCount max_packets_in_flight);
141 
142   // The overhead the framing will add for a packet with one frame.
143   static size_t StreamFramePacketOverhead(
144       QuicTransportVersion version, uint8_t destination_connection_id_length,
145       uint8_t source_connection_id_length, bool include_version,
146       bool include_diversification_nonce,
147       QuicPacketNumberLength packet_number_length,
148       quiche::QuicheVariableLengthIntegerLength retry_token_length_length,
149       quiche::QuicheVariableLengthIntegerLength length_length,
150       QuicStreamOffset offset);
151 
152   // Returns false and flushes all pending frames if current open packet is
153   // full.
154   // If current packet is not full, creates a stream frame that fits into the
155   // open packet and adds it to the packet.
156   bool ConsumeDataToFillCurrentPacket(QuicStreamId id, size_t data_size,
157                                       QuicStreamOffset offset, bool fin,
158                                       bool needs_full_padding,
159                                       TransmissionType transmission_type,
160                                       QuicFrame* frame);
161 
162   // Creates a CRYPTO frame that fits into the current packet (which must be
163   // empty) and adds it to the packet.
164   bool ConsumeCryptoDataToFillCurrentPacket(EncryptionLevel level,
165                                             size_t write_length,
166                                             QuicStreamOffset offset,
167                                             bool needs_full_padding,
168                                             TransmissionType transmission_type,
169                                             QuicFrame* frame);
170 
171   // Returns true if current open packet can accommodate more stream frames of
172   // stream |id| at |offset| and data length |data_size|, false otherwise.
173   // TODO(fayang): mark this const by moving RemoveSoftMaxPacketLength out.
174   bool HasRoomForStreamFrame(QuicStreamId id, QuicStreamOffset offset,
175                              size_t data_size);
176 
177   // Returns true if current open packet can accommodate a message frame of
178   // |length|.
179   // TODO(fayang): mark this const by moving RemoveSoftMaxPacketLength out.
180   bool HasRoomForMessageFrame(QuicByteCount length);
181 
182   // Serializes all added frames into a single packet and invokes the delegate_
183   // to further process the SerializedPacket.
184   void FlushCurrentPacket();
185 
186   // Optimized method to create a QuicStreamFrame and serialize it. Adds the
187   // QuicStreamFrame to the returned SerializedPacket.  Sets
188   // |num_bytes_consumed| to the number of bytes consumed to create the
189   // QuicStreamFrame.
190   void CreateAndSerializeStreamFrame(QuicStreamId id, size_t write_length,
191                                      QuicStreamOffset iov_offset,
192                                      QuicStreamOffset stream_offset, bool fin,
193                                      TransmissionType transmission_type,
194                                      size_t* num_bytes_consumed);
195 
196   // Returns true if there are frames pending to be serialized.
197   bool HasPendingFrames() const;
198 
199   // TODO(haoyuewang) Remove this debug utility.
200   // Returns the information of pending frames as a string.
201   std::string GetPendingFramesInfo() const;
202 
203   // Returns true if there are retransmittable frames pending to be serialized.
204   bool HasPendingRetransmittableFrames() const;
205 
206   // Returns true if there are stream frames for |id| pending to be serialized.
207   bool HasPendingStreamFramesOfStream(QuicStreamId id) const;
208 
209   // Returns the number of bytes which are available to be used by additional
210   // frames in the packet.  Since stream frames are slightly smaller when they
211   // are the last frame in a packet, this method will return a different
212   // value than max_packet_size - PacketSize(), in this case.
213   size_t BytesFree() const;
214 
215   // Since PADDING frames are always prepended, a separate function computes
216   // available space without considering STREAM frame expansion.
217   size_t BytesFreeForPadding() const;
218 
219   // Returns the number of bytes that the packet will expand by if a new frame
220   // is added to the packet. If the last frame was a stream frame, it will
221   // expand slightly when a new frame is added, and this method returns the
222   // amount of expected expansion.
223   size_t ExpansionOnNewFrame() const;
224 
225   // Returns the number of bytes that the packet will expand by when a new frame
226   // is going to be added. |last_frame| is the last frame of the packet.
227   static size_t ExpansionOnNewFrameWithLastFrame(const QuicFrame& last_frame,
228                                                  QuicTransportVersion version);
229 
230   // Returns the number of bytes in the current packet, including the header,
231   // if serialized with the current frames.  Adding a frame to the packet
232   // may change the serialized length of existing frames, as per the comment
233   // in BytesFree.
234   size_t PacketSize() const;
235 
236   // Tries to add |frame| to the packet creator's list of frames to be
237   // serialized. If the frame does not fit into the current packet, flushes the
238   // packet and returns false.
239   bool AddFrame(const QuicFrame& frame, TransmissionType transmission_type);
240 
241   // Identical to AddSavedFrame, but allows the frame to be padded.
242   bool AddPaddedSavedFrame(const QuicFrame& frame,
243                            TransmissionType transmission_type);
244 
245   // Creates a connectivity probing packet for versions prior to version 99.
246   std::unique_ptr<SerializedPacket> SerializeConnectivityProbingPacket();
247 
248   // Create connectivity probing request and response packets using PATH
249   // CHALLENGE and PATH RESPONSE frames, respectively, for version 99/IETF QUIC.
250   // SerializePathChallengeConnectivityProbingPacket will pad the packet to be
251   // MTU bytes long.
252   std::unique_ptr<SerializedPacket>
253   SerializePathChallengeConnectivityProbingPacket(
254       const QuicPathFrameBuffer& payload);
255 
256   // If |is_padded| is true then SerializePathResponseConnectivityProbingPacket
257   // will pad the packet to be MTU bytes long, else it will not pad the packet.
258   // |payloads| is cleared.
259   std::unique_ptr<SerializedPacket>
260   SerializePathResponseConnectivityProbingPacket(
261       const quiche::QuicheCircularDeque<QuicPathFrameBuffer>& payloads,
262       const bool is_padded);
263 
264   // Add PATH_RESPONSE to current packet, flush before or afterwards if needed.
265   bool AddPathResponseFrame(const QuicPathFrameBuffer& data_buffer);
266 
267   // Add PATH_CHALLENGE to current packet, flush before or afterwards if needed.
268   // This is a best effort adding. It may fail becasue of delegate state, but
269   // it's okay because of path validation retry mechanism.
270   void AddPathChallengeFrame(const QuicPathFrameBuffer& payload);
271 
272   // Returns a dummy packet that is valid but contains no useful information.
273   static SerializedPacket NoPacket();
274 
275   // Returns the server connection ID to send over the wire.
GetServerConnectionId()276   const QuicConnectionId& GetServerConnectionId() const {
277     return server_connection_id_;
278   }
279 
280   // Returns the client connection ID to send over the wire.
GetClientConnectionId()281   const QuicConnectionId& GetClientConnectionId() const {
282     return client_connection_id_;
283   }
284 
285   // Returns the destination connection ID to send over the wire.
286   QuicConnectionId GetDestinationConnectionId() const;
287 
288   // Returns the source connection ID to send over the wire.
289   QuicConnectionId GetSourceConnectionId() const;
290 
291   // Returns length of destination connection ID to send over the wire.
292   uint8_t GetDestinationConnectionIdLength() const;
293 
294   // Returns length of source connection ID to send over the wire.
295   uint8_t GetSourceConnectionIdLength() const;
296 
297   // Sets whether the server connection ID should be sent over the wire.
298   void SetServerConnectionIdIncluded(
299       QuicConnectionIdIncluded server_connection_id_included);
300 
301   // Update the server connection ID used in outgoing packets.
302   void SetServerConnectionId(QuicConnectionId server_connection_id);
303 
304   // Update the client connection ID used in outgoing packets.
305   void SetClientConnectionId(QuicConnectionId client_connection_id);
306 
307   // Sets the encryption level that will be applied to new packets.
308   void set_encryption_level(EncryptionLevel level);
encryption_level()309   EncryptionLevel encryption_level() { return packet_.encryption_level; }
310 
311   // packet number of the last created packet, or 0 if no packets have been
312   // created.
packet_number()313   QuicPacketNumber packet_number() const { return packet_.packet_number; }
314 
max_packet_length()315   QuicByteCount max_packet_length() const { return max_packet_length_; }
316 
has_ack()317   bool has_ack() const { return packet_.has_ack; }
318 
has_stop_waiting()319   bool has_stop_waiting() const { return packet_.has_stop_waiting; }
320 
321   // Sets the encrypter to use for the encryption level and updates the max
322   // plaintext size.
323   void SetEncrypter(EncryptionLevel level,
324                     std::unique_ptr<QuicEncrypter> encrypter);
325 
326   // Indicates whether the packet creator is in a state where it can change
327   // current maximum packet length.
328   bool CanSetMaxPacketLength() const;
329 
330   // Sets the maximum packet length.
331   void SetMaxPacketLength(QuicByteCount length);
332 
333   // Sets the maximum DATAGRAM/MESSAGE frame size we can send.
334   void SetMaxDatagramFrameSize(QuicByteCount max_datagram_frame_size);
335 
336   // Set a soft maximum packet length in the creator. If a packet cannot be
337   // successfully created, creator will remove the soft limit and use the actual
338   // max packet length.
339   void SetSoftMaxPacketLength(QuicByteCount length);
340 
341   // Increases pending_padding_bytes by |size|. Pending padding will be sent by
342   // MaybeAddPadding().
343   void AddPendingPadding(QuicByteCount size);
344 
345   // Sets the retry token to be sent over the wire in IETF Initial packets.
346   void SetRetryToken(absl::string_view retry_token);
347 
348   // Consumes retransmittable control |frame|. Returns true if the frame is
349   // successfully consumed. Returns false otherwise.
350   bool ConsumeRetransmittableControlFrame(const QuicFrame& frame);
351 
352   // Given some data, may consume part or all of it and pass it to the
353   // packet creator to be serialized into packets. If not in batch
354   // mode, these packets will also be sent during this call.
355   // When |state| is FIN_AND_PADDING, random padding of size [1, 256] will be
356   // added after stream frames. If current constructed packet cannot
357   // accommodate, the padding will overflow to the next packet(s).
358   QuicConsumedData ConsumeData(QuicStreamId id, size_t write_length,
359                                QuicStreamOffset offset,
360                                StreamSendingState state);
361 
362   // Sends as many data only packets as allowed by the send algorithm and the
363   // available iov.
364   // This path does not support padding, or bundling pending frames.
365   // In case we access this method from ConsumeData, total_bytes_consumed
366   // keeps track of how many bytes have already been consumed.
367   QuicConsumedData ConsumeDataFastPath(QuicStreamId id, size_t write_length,
368                                        QuicStreamOffset offset, bool fin,
369                                        size_t total_bytes_consumed);
370 
371   // Consumes data for CRYPTO frames sent at |level| starting at |offset| for a
372   // total of |write_length| bytes, and returns the number of bytes consumed.
373   // The data is passed into the packet creator and serialized into one or more
374   // packets.
375   size_t ConsumeCryptoData(EncryptionLevel level, size_t write_length,
376                            QuicStreamOffset offset);
377 
378   // Generates an MTU discovery packet of specified size.
379   void GenerateMtuDiscoveryPacket(QuicByteCount target_mtu);
380 
381   // Called when there is data to be sent, Retrieves updated ACK frame from
382   // delegate_ and flushes it.
383   void MaybeBundleAckOpportunistically();
384 
385   // Called to flush ACK and STOP_WAITING frames, returns false if the flush
386   // fails.
387   bool FlushAckFrame(const QuicFrames& frames);
388 
389   // Adds a random amount of padding (between 1 to 256 bytes).
390   void AddRandomPadding();
391 
392   // Attaches packet flusher.
393   void AttachPacketFlusher();
394 
395   // Flushes everything, including current open packet and pending padding.
396   void Flush();
397 
398   // Sends remaining pending padding.
399   // Pending paddings should only be sent when there is nothing else to send.
400   void SendRemainingPendingPadding();
401 
402   // Set the minimum number of bytes for the server connection id length;
403   void SetServerConnectionIdLength(uint32_t length);
404 
405   // Set transmission type of next constructed packets.
406   void SetTransmissionType(TransmissionType type);
407 
408   // Tries to add a message frame containing |message| and returns the status.
409   MessageStatus AddMessageFrame(QuicMessageId message_id,
410                                 absl::Span<quiche::QuicheMemSlice> message);
411 
412   // Returns the largest payload that will fit into a single MESSAGE frame.
413   QuicPacketLength GetCurrentLargestMessagePayload() const;
414   // Returns the largest payload that will fit into a single MESSAGE frame at
415   // any point during the connection.  This assumes the version and
416   // connection ID lengths do not change.
417   QuicPacketLength GetGuaranteedLargestMessagePayload() const;
418 
419   // Packet number of next created packet.
420   QuicPacketNumber NextSendingPacketNumber() const;
421 
set_debug_delegate(DebugDelegate * debug_delegate)422   void set_debug_delegate(DebugDelegate* debug_delegate) {
423     debug_delegate_ = debug_delegate;
424   }
425 
pending_padding_bytes()426   QuicByteCount pending_padding_bytes() const { return pending_padding_bytes_; }
427 
version()428   ParsedQuicVersion version() const { return framer_->version(); }
429 
transport_version()430   QuicTransportVersion transport_version() const {
431     return framer_->transport_version();
432   }
433 
434   // Returns the minimum size that the plaintext of a packet must be.
435   static size_t MinPlaintextPacketSize(
436       const ParsedQuicVersion& version,
437       QuicPacketNumberLength packet_number_length);
438 
439   // Indicates whether packet flusher is currently attached.
440   bool PacketFlusherAttached() const;
441 
set_fully_pad_crypto_handshake_packets(bool new_value)442   void set_fully_pad_crypto_handshake_packets(bool new_value) {
443     fully_pad_crypto_handshake_packets_ = new_value;
444   }
445 
fully_pad_crypto_handshake_packets()446   bool fully_pad_crypto_handshake_packets() const {
447     return fully_pad_crypto_handshake_packets_;
448   }
449 
450   // Serialize a probing packet that uses IETF QUIC's PATH CHALLENGE frame. Also
451   // fills the packet with padding.
452   size_t BuildPaddedPathChallengePacket(const QuicPacketHeader& header,
453                                         char* buffer, size_t packet_length,
454                                         const QuicPathFrameBuffer& payload,
455                                         EncryptionLevel level);
456 
457   // Serialize a probing response packet that uses IETF QUIC's PATH RESPONSE
458   // frame. Also fills the packet with padding if |is_padded| is
459   // true. |payloads| is always emptied, even if the packet can not be
460   // successfully built.
461   size_t BuildPathResponsePacket(
462       const QuicPacketHeader& header, char* buffer, size_t packet_length,
463       const quiche::QuicheCircularDeque<QuicPathFrameBuffer>& payloads,
464       const bool is_padded, EncryptionLevel level);
465 
466   // Serializes a probing packet, which is a padded PING packet. Returns the
467   // length of the packet. Returns 0 if it fails to serialize.
468   size_t BuildConnectivityProbingPacket(const QuicPacketHeader& header,
469                                         char* buffer, size_t packet_length,
470                                         EncryptionLevel level);
471 
472   // Serializes |coalesced| to provided |buffer|, returns coalesced packet
473   // length if serialization succeeds. Otherwise, returns 0.
474   size_t SerializeCoalescedPacket(const QuicCoalescedPacket& coalesced,
475                                   char* buffer, size_t buffer_len);
476 
477   // Returns true if max_packet_length_ is currently a soft value.
478   bool HasSoftMaxPacketLength() const;
479 
480   // Use this address to sent to the peer from now on. If this address is
481   // different from the current one, flush all the queue frames first.
482   void SetDefaultPeerAddress(QuicSocketAddress address);
483 
484   // Return true if retry_token_ is not empty.
485   bool HasRetryToken() const;
486 
peer_address()487   const QuicSocketAddress& peer_address() const { return packet_.peer_address; }
488 
489  private:
490   friend class test::QuicPacketCreatorPeer;
491 
492   // Used to 1) clear queued_frames_, 2) report unrecoverable error (if
493   // serialization fails) upon exiting the scope.
494   class QUIC_EXPORT_PRIVATE ScopedSerializationFailureHandler {
495    public:
496     explicit ScopedSerializationFailureHandler(QuicPacketCreator* creator);
497     ~ScopedSerializationFailureHandler();
498 
499    private:
500     QuicPacketCreator* creator_;  // Unowned.
501   };
502 
503   // Attempts to build a data packet with chaos protection. If this packet isn't
504   // supposed to be protected or if serialization fails then absl::nullopt is
505   // returned. Otherwise returns the serialized length.
506   absl::optional<size_t> MaybeBuildDataPacketWithChaosProtection(
507       const QuicPacketHeader& header, char* buffer);
508 
509   // Creates a stream frame which fits into the current open packet. If
510   // |data_size| is 0 and fin is true, the expected behavior is to consume
511   // the fin.
512   void CreateStreamFrame(QuicStreamId id, size_t data_size,
513                          QuicStreamOffset offset, bool fin, QuicFrame* frame);
514 
515   // Creates a CRYPTO frame which fits into the current open packet. Returns
516   // false if there isn't enough room in the current open packet for a CRYPTO
517   // frame, and true if there is.
518   bool CreateCryptoFrame(EncryptionLevel level, size_t write_length,
519                          QuicStreamOffset offset, QuicFrame* frame);
520 
521   void FillPacketHeader(QuicPacketHeader* header);
522 
523   // Adds a padding frame to the current packet (if there is space) when (1)
524   // current packet needs full padding or (2) there are pending paddings.
525   void MaybeAddPadding();
526 
527   // Serializes all frames which have been added and adds any which should be
528   // retransmitted to packet_.retransmittable_frames. All frames must fit into
529   // a single packet. Returns true on success, otherwise, returns false.
530   // Fails if |encrypted_buffer| is not large enough for the encrypted packet.
531   //
532   // Padding may be added if |allow_padding|. Currently, the only case where it
533   // is disallowed is reserializing a coalesced initial packet.
534   ABSL_MUST_USE_RESULT bool SerializePacket(
535       QuicOwnedPacketBuffer encrypted_buffer, size_t encrypted_buffer_len,
536       bool allow_padding);
537 
538   // Called after a new SerialiedPacket is created to call the delegate's
539   // OnSerializedPacket and reset state.
540   void OnSerializedPacket();
541 
542   // Clears all fields of packet_ that should be cleared between serializations.
543   void ClearPacket();
544 
545   // Re-serialzes frames of ENCRYPTION_INITIAL packet in coalesced packet with
546   // the original packet's packet number and packet number length.
547   // |padding_size| indicates the size of necessary padding. Returns 0 if
548   // serialization fails.
549   size_t ReserializeInitialPacketInCoalescedPacket(
550       const SerializedPacket& packet, size_t padding_size, char* buffer,
551       size_t buffer_len);
552 
553   // Tries to coalesce |frame| with the back of |queued_frames_|.
554   // Returns true on success.
555   bool MaybeCoalesceStreamFrame(const QuicStreamFrame& frame);
556 
557   // Called to remove the soft max_packet_length and restores
558   // latched_hard_max_packet_length_ if the packet cannot accommodate a single
559   // frame. Returns true if the soft limit is successfully removed. Returns
560   // false if either there is no current soft limit or there are queued frames
561   // (such that the packet length cannot be changed).
562   bool RemoveSoftMaxPacketLength();
563 
564   // Returns true if a diversification nonce should be included in the current
565   // packet's header.
566   bool IncludeNonceInPublicHeader() const;
567 
568   // Returns true if version should be included in current packet's header.
569   bool IncludeVersionInHeader() const;
570 
571   // Returns length of packet number to send over the wire.
572   // packet_.packet_number_length should never be read directly, use this
573   // function instead.
574   QuicPacketNumberLength GetPacketNumberLength() const;
575 
576   // Returns the size in bytes of the packet header.
577   size_t PacketHeaderSize() const;
578 
579   // Returns whether the destination connection ID is sent over the wire.
580   QuicConnectionIdIncluded GetDestinationConnectionIdIncluded() const;
581 
582   // Returns whether the source connection ID is sent over the wire.
583   QuicConnectionIdIncluded GetSourceConnectionIdIncluded() const;
584 
585   // Returns length of the retry token variable length integer to send over the
586   // wire. Is non-zero for v99 IETF Initial packets.
587   quiche::QuicheVariableLengthIntegerLength GetRetryTokenLengthLength() const;
588 
589   // Returns the retry token to send over the wire, only sent in
590   // v99 IETF Initial packets.
591   absl::string_view GetRetryToken() const;
592 
593   // Returns length of the length variable length integer to send over the
594   // wire. Is non-zero for v99 IETF Initial, 0-RTT or Handshake packets.
595   quiche::QuicheVariableLengthIntegerLength GetLengthLength() const;
596 
597   // Returns true if |frame| is a ClientHello.
598   bool StreamFrameIsClientHello(const QuicStreamFrame& frame) const;
599 
600   // Returns true if packet under construction has IETF long header.
601   bool HasIetfLongHeader() const;
602 
603   // Get serialized frame length. Returns 0 if the frame does not fit into
604   // current packet.
605   size_t GetSerializedFrameLength(const QuicFrame& frame);
606 
607   // Add extra padding to pending_padding_bytes_ to meet minimum plaintext
608   // packet size required for header protection.
609   void MaybeAddExtraPaddingForHeaderProtection();
610 
611   // Returns true and close connection if it attempts to send unencrypted data.
612   bool AttemptingToSendUnencryptedStreamData();
613 
614   // Add the given frame to the current packet with full padding. If the current
615   // packet doesn't have enough space, flush once and try again. Return false if
616   // fail to add.
617   bool AddPaddedFrameWithRetry(const QuicFrame& frame);
618 
619   // Does not own these delegates or the framer.
620   DelegateInterface* delegate_;
621   DebugDelegate* debug_delegate_;
622   QuicFramer* framer_;
623   QuicRandom* random_;
624 
625   // Controls whether version should be included while serializing the packet.
626   // send_version_in_packet_ should never be read directly, use
627   // IncludeVersionInHeader() instead.
628   bool send_version_in_packet_;
629   // If true, then |diversification_nonce_| will be included in the header of
630   // all packets created at the initial encryption level.
631   bool have_diversification_nonce_;
632   DiversificationNonce diversification_nonce_;
633   // Maximum length including headers and encryption (UDP payload length.)
634   QuicByteCount max_packet_length_;
635   size_t max_plaintext_size_;
636   // Whether the server_connection_id is sent over the wire.
637   QuicConnectionIdIncluded server_connection_id_included_;
638 
639   // Frames to be added to the next SerializedPacket
640   QuicFrames queued_frames_;
641 
642   // Serialization size of header + frames. If there is no queued frames,
643   // packet_size_ is 0.
644   // TODO(ianswett): Move packet_size_ into SerializedPacket once
645   // QuicEncryptedPacket has been flattened into SerializedPacket.
646   size_t packet_size_;
647   QuicConnectionId server_connection_id_;
648   QuicConnectionId client_connection_id_;
649 
650   // Packet used to invoke OnSerializedPacket.
651   SerializedPacket packet_;
652 
653   // Retry token to send over the wire in v99 IETF Initial packets.
654   std::string retry_token_;
655 
656   // Pending padding bytes to send. Pending padding bytes will be sent in next
657   // packet(s) (after all other frames) if current constructed packet does not
658   // have room to send all of them.
659   QuicByteCount pending_padding_bytes_;
660 
661   // Indicates whether current constructed packet needs full padding to max
662   // packet size. Please note, full padding does not consume pending padding
663   // bytes.
664   bool needs_full_padding_;
665 
666   // Transmission type of the next serialized packet.
667   TransmissionType next_transmission_type_;
668 
669   // True if packet flusher is currently attached.
670   bool flusher_attached_;
671 
672   // Whether crypto handshake packets should be fully padded.
673   bool fully_pad_crypto_handshake_packets_;
674 
675   // Packet number of the first packet of a write operation. This gets set
676   // when the out-most flusher attaches and gets cleared when the out-most
677   // flusher detaches.
678   QuicPacketNumber write_start_packet_number_;
679 
680   // If not 0, this latches the actual max_packet_length when
681   // SetSoftMaxPacketLength is called and max_packet_length_ gets
682   // set to a soft value.
683   QuicByteCount latched_hard_max_packet_length_;
684 
685   // The maximum length of a MESSAGE/DATAGRAM frame that our peer is willing to
686   // accept. There is no limit for QUIC_CRYPTO connections, but QUIC+TLS
687   // negotiates this during the handshake.
688   QuicByteCount max_datagram_frame_size_;
689 };
690 
691 }  // namespace quic
692 
693 #endif  // QUICHE_QUIC_CORE_QUIC_PACKET_CREATOR_H_
694