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