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