github.com/quic-go/quic-go@v0.44.0/connection.go (about) 1 package quic 2 3 import ( 4 "bytes" 5 "context" 6 "crypto/tls" 7 "errors" 8 "fmt" 9 "io" 10 "net" 11 "reflect" 12 "sync" 13 "sync/atomic" 14 "time" 15 16 "github.com/quic-go/quic-go/internal/ackhandler" 17 "github.com/quic-go/quic-go/internal/flowcontrol" 18 "github.com/quic-go/quic-go/internal/handshake" 19 "github.com/quic-go/quic-go/internal/logutils" 20 "github.com/quic-go/quic-go/internal/protocol" 21 "github.com/quic-go/quic-go/internal/qerr" 22 "github.com/quic-go/quic-go/internal/utils" 23 "github.com/quic-go/quic-go/internal/wire" 24 "github.com/quic-go/quic-go/logging" 25 ) 26 27 type unpacker interface { 28 UnpackLongHeader(hdr *wire.Header, rcvTime time.Time, data []byte, v protocol.Version) (*unpackedPacket, error) 29 UnpackShortHeader(rcvTime time.Time, data []byte) (protocol.PacketNumber, protocol.PacketNumberLen, protocol.KeyPhaseBit, []byte, error) 30 } 31 32 type streamGetter interface { 33 GetOrOpenReceiveStream(protocol.StreamID) (receiveStreamI, error) 34 GetOrOpenSendStream(protocol.StreamID) (sendStreamI, error) 35 } 36 37 type streamManager interface { 38 GetOrOpenSendStream(protocol.StreamID) (sendStreamI, error) 39 GetOrOpenReceiveStream(protocol.StreamID) (receiveStreamI, error) 40 OpenStream() (Stream, error) 41 OpenUniStream() (SendStream, error) 42 OpenStreamSync(context.Context) (Stream, error) 43 OpenUniStreamSync(context.Context) (SendStream, error) 44 AcceptStream(context.Context) (Stream, error) 45 AcceptUniStream(context.Context) (ReceiveStream, error) 46 DeleteStream(protocol.StreamID) error 47 UpdateLimits(*wire.TransportParameters) 48 HandleMaxStreamsFrame(*wire.MaxStreamsFrame) 49 CloseWithError(error) 50 ResetFor0RTT() 51 UseResetMaps() 52 } 53 54 type cryptoStreamHandler interface { 55 StartHandshake() error 56 ChangeConnectionID(protocol.ConnectionID) 57 SetLargest1RTTAcked(protocol.PacketNumber) error 58 SetHandshakeConfirmed() 59 GetSessionTicket() ([]byte, error) 60 NextEvent() handshake.Event 61 DiscardInitialKeys() 62 io.Closer 63 ConnectionState() handshake.ConnectionState 64 } 65 66 type receivedPacket struct { 67 buffer *packetBuffer 68 69 remoteAddr net.Addr 70 rcvTime time.Time 71 data []byte 72 73 ecn protocol.ECN 74 75 info packetInfo // only valid if the contained IP address is valid 76 } 77 78 func (p *receivedPacket) Size() protocol.ByteCount { return protocol.ByteCount(len(p.data)) } 79 80 func (p *receivedPacket) Clone() *receivedPacket { 81 return &receivedPacket{ 82 remoteAddr: p.remoteAddr, 83 rcvTime: p.rcvTime, 84 data: p.data, 85 buffer: p.buffer, 86 ecn: p.ecn, 87 info: p.info, 88 } 89 } 90 91 type connRunner interface { 92 Add(protocol.ConnectionID, packetHandler) bool 93 GetStatelessResetToken(protocol.ConnectionID) protocol.StatelessResetToken 94 Retire(protocol.ConnectionID) 95 Remove(protocol.ConnectionID) 96 ReplaceWithClosed([]protocol.ConnectionID, []byte) 97 AddResetToken(protocol.StatelessResetToken, packetHandler) 98 RemoveResetToken(protocol.StatelessResetToken) 99 } 100 101 type closeError struct { 102 err error 103 remote bool 104 immediate bool 105 } 106 107 type errCloseForRecreating struct { 108 nextPacketNumber protocol.PacketNumber 109 nextVersion protocol.Version 110 } 111 112 func (e *errCloseForRecreating) Error() string { 113 return "closing connection in order to recreate it" 114 } 115 116 var connTracingID atomic.Uint64 // to be accessed atomically 117 func nextConnTracingID() ConnectionTracingID { return ConnectionTracingID(connTracingID.Add(1)) } 118 119 // A Connection is a QUIC connection 120 type connection struct { 121 // Destination connection ID used during the handshake. 122 // Used to check source connection ID on incoming packets. 123 handshakeDestConnID protocol.ConnectionID 124 // Set for the client. Destination connection ID used on the first Initial sent. 125 origDestConnID protocol.ConnectionID 126 retrySrcConnID *protocol.ConnectionID // only set for the client (and if a Retry was performed) 127 128 srcConnIDLen int 129 130 perspective protocol.Perspective 131 version protocol.Version 132 config *Config 133 134 conn sendConn 135 sendQueue sender 136 137 streamsMap streamManager 138 connIDManager *connIDManager 139 connIDGenerator *connIDGenerator 140 141 rttStats *utils.RTTStats 142 143 cryptoStreamManager *cryptoStreamManager 144 sentPacketHandler ackhandler.SentPacketHandler 145 receivedPacketHandler ackhandler.ReceivedPacketHandler 146 retransmissionQueue *retransmissionQueue 147 framer framer 148 windowUpdateQueue *windowUpdateQueue 149 connFlowController flowcontrol.ConnectionFlowController 150 tokenStoreKey string // only set for the client 151 tokenGenerator *handshake.TokenGenerator // only set for the server 152 153 unpacker unpacker 154 frameParser wire.FrameParser 155 packer packer 156 mtuDiscoverer mtuDiscoverer // initialized when the transport parameters are received 157 158 maxPayloadSizeEstimate atomic.Uint32 159 160 initialStream cryptoStream 161 handshakeStream cryptoStream 162 oneRTTStream cryptoStream // only set for the server 163 cryptoStreamHandler cryptoStreamHandler 164 165 receivedPackets chan receivedPacket 166 sendingScheduled chan struct{} 167 168 closeOnce sync.Once 169 // closeChan is used to notify the run loop that it should terminate 170 closeChan chan closeError 171 172 ctx context.Context 173 ctxCancel context.CancelCauseFunc 174 handshakeCtx context.Context 175 handshakeCtxCancel context.CancelFunc 176 177 undecryptablePackets []receivedPacket // undecryptable packets, waiting for a change in encryption level 178 undecryptablePacketsToProcess []receivedPacket 179 180 earlyConnReadyChan chan struct{} 181 sentFirstPacket bool 182 droppedInitialKeys bool 183 handshakeComplete bool 184 handshakeConfirmed bool 185 186 receivedRetry bool 187 versionNegotiated bool 188 receivedFirstPacket bool 189 190 // the minimum of the max_idle_timeout values advertised by both endpoints 191 idleTimeout time.Duration 192 creationTime time.Time 193 // The idle timeout is set based on the max of the time we received the last packet... 194 lastPacketReceivedTime time.Time 195 // ... and the time we sent a new ack-eliciting packet after receiving a packet. 196 firstAckElicitingPacketAfterIdleSentTime time.Time 197 // pacingDeadline is the time when the next packet should be sent 198 pacingDeadline time.Time 199 200 peerParams *wire.TransportParameters 201 202 timer connectionTimer 203 // keepAlivePingSent stores whether a keep alive PING is in flight. 204 // It is reset as soon as we receive a packet from the peer. 205 keepAlivePingSent bool 206 keepAliveInterval time.Duration 207 208 datagramQueue *datagramQueue 209 210 connStateMutex sync.Mutex 211 connState ConnectionState 212 213 logID string 214 tracer *logging.ConnectionTracer 215 logger utils.Logger 216 } 217 218 var ( 219 _ Connection = &connection{} 220 _ EarlyConnection = &connection{} 221 _ streamSender = &connection{} 222 ) 223 224 var newConnection = func( 225 conn sendConn, 226 runner connRunner, 227 origDestConnID protocol.ConnectionID, 228 retrySrcConnID *protocol.ConnectionID, 229 clientDestConnID protocol.ConnectionID, 230 destConnID protocol.ConnectionID, 231 srcConnID protocol.ConnectionID, 232 connIDGenerator ConnectionIDGenerator, 233 statelessResetToken protocol.StatelessResetToken, 234 conf *Config, 235 tlsConf *tls.Config, 236 tokenGenerator *handshake.TokenGenerator, 237 clientAddressValidated bool, 238 tracer *logging.ConnectionTracer, 239 tracingID ConnectionTracingID, 240 logger utils.Logger, 241 v protocol.Version, 242 ) quicConn { 243 s := &connection{ 244 conn: conn, 245 config: conf, 246 handshakeDestConnID: destConnID, 247 srcConnIDLen: srcConnID.Len(), 248 tokenGenerator: tokenGenerator, 249 oneRTTStream: newCryptoStream(), 250 perspective: protocol.PerspectiveServer, 251 tracer: tracer, 252 logger: logger, 253 version: v, 254 } 255 if origDestConnID.Len() > 0 { 256 s.logID = origDestConnID.String() 257 } else { 258 s.logID = destConnID.String() 259 } 260 s.connIDManager = newConnIDManager( 261 destConnID, 262 func(token protocol.StatelessResetToken) { runner.AddResetToken(token, s) }, 263 runner.RemoveResetToken, 264 s.queueControlFrame, 265 ) 266 s.connIDGenerator = newConnIDGenerator( 267 srcConnID, 268 &clientDestConnID, 269 func(connID protocol.ConnectionID) { runner.Add(connID, s) }, 270 runner.GetStatelessResetToken, 271 runner.Remove, 272 runner.Retire, 273 runner.ReplaceWithClosed, 274 s.queueControlFrame, 275 connIDGenerator, 276 ) 277 s.ctx, s.ctxCancel = context.WithCancelCause(context.WithValue(context.Background(), ConnectionTracingKey, tracingID)) 278 s.preSetup() 279 s.sentPacketHandler, s.receivedPacketHandler = ackhandler.NewAckHandler( 280 0, 281 protocol.ByteCount(s.config.InitialPacketSize), 282 s.rttStats, 283 clientAddressValidated, 284 s.conn.capabilities().ECN, 285 s.perspective, 286 s.tracer, 287 s.logger, 288 ) 289 s.maxPayloadSizeEstimate.Store(uint32(estimateMaxPayloadSize(protocol.ByteCount(s.config.InitialPacketSize)))) 290 params := &wire.TransportParameters{ 291 InitialMaxStreamDataBidiLocal: protocol.ByteCount(s.config.InitialStreamReceiveWindow), 292 InitialMaxStreamDataBidiRemote: protocol.ByteCount(s.config.InitialStreamReceiveWindow), 293 InitialMaxStreamDataUni: protocol.ByteCount(s.config.InitialStreamReceiveWindow), 294 InitialMaxData: protocol.ByteCount(s.config.InitialConnectionReceiveWindow), 295 MaxIdleTimeout: s.config.MaxIdleTimeout, 296 MaxBidiStreamNum: protocol.StreamNum(s.config.MaxIncomingStreams), 297 MaxUniStreamNum: protocol.StreamNum(s.config.MaxIncomingUniStreams), 298 MaxAckDelay: protocol.MaxAckDelayInclGranularity, 299 AckDelayExponent: protocol.AckDelayExponent, 300 MaxUDPPayloadSize: protocol.MaxPacketBufferSize, 301 DisableActiveMigration: true, 302 StatelessResetToken: &statelessResetToken, 303 OriginalDestinationConnectionID: origDestConnID, 304 // For interoperability with quic-go versions before May 2023, this value must be set to a value 305 // different from protocol.DefaultActiveConnectionIDLimit. 306 // If set to the default value, it will be omitted from the transport parameters, which will make 307 // old quic-go versions interpret it as 0, instead of the default value of 2. 308 // See https://github.com/quic-go/quic-go/pull/3806. 309 ActiveConnectionIDLimit: protocol.MaxActiveConnectionIDs, 310 InitialSourceConnectionID: srcConnID, 311 RetrySourceConnectionID: retrySrcConnID, 312 } 313 if s.config.EnableDatagrams { 314 params.MaxDatagramFrameSize = wire.MaxDatagramSize 315 } else { 316 params.MaxDatagramFrameSize = protocol.InvalidByteCount 317 } 318 if s.tracer != nil && s.tracer.SentTransportParameters != nil { 319 s.tracer.SentTransportParameters(params) 320 } 321 cs := handshake.NewCryptoSetupServer( 322 clientDestConnID, 323 conn.LocalAddr(), 324 conn.RemoteAddr(), 325 params, 326 tlsConf, 327 conf.Allow0RTT, 328 s.rttStats, 329 tracer, 330 logger, 331 s.version, 332 ) 333 s.cryptoStreamHandler = cs 334 s.packer = newPacketPacker(srcConnID, s.connIDManager.Get, s.initialStream, s.handshakeStream, s.sentPacketHandler, s.retransmissionQueue, cs, s.framer, s.receivedPacketHandler, s.datagramQueue, s.perspective) 335 s.unpacker = newPacketUnpacker(cs, s.srcConnIDLen) 336 s.cryptoStreamManager = newCryptoStreamManager(cs, s.initialStream, s.handshakeStream, s.oneRTTStream) 337 return s 338 } 339 340 // declare this as a variable, such that we can it mock it in the tests 341 var newClientConnection = func( 342 conn sendConn, 343 runner connRunner, 344 destConnID protocol.ConnectionID, 345 srcConnID protocol.ConnectionID, 346 connIDGenerator ConnectionIDGenerator, 347 conf *Config, 348 tlsConf *tls.Config, 349 initialPacketNumber protocol.PacketNumber, 350 enable0RTT bool, 351 hasNegotiatedVersion bool, 352 tracer *logging.ConnectionTracer, 353 tracingID ConnectionTracingID, 354 logger utils.Logger, 355 v protocol.Version, 356 ) quicConn { 357 s := &connection{ 358 conn: conn, 359 config: conf, 360 origDestConnID: destConnID, 361 handshakeDestConnID: destConnID, 362 srcConnIDLen: srcConnID.Len(), 363 perspective: protocol.PerspectiveClient, 364 logID: destConnID.String(), 365 logger: logger, 366 tracer: tracer, 367 versionNegotiated: hasNegotiatedVersion, 368 version: v, 369 } 370 s.connIDManager = newConnIDManager( 371 destConnID, 372 func(token protocol.StatelessResetToken) { runner.AddResetToken(token, s) }, 373 runner.RemoveResetToken, 374 s.queueControlFrame, 375 ) 376 s.connIDGenerator = newConnIDGenerator( 377 srcConnID, 378 nil, 379 func(connID protocol.ConnectionID) { runner.Add(connID, s) }, 380 runner.GetStatelessResetToken, 381 runner.Remove, 382 runner.Retire, 383 runner.ReplaceWithClosed, 384 s.queueControlFrame, 385 connIDGenerator, 386 ) 387 s.ctx, s.ctxCancel = context.WithCancelCause(context.WithValue(context.Background(), ConnectionTracingKey, tracingID)) 388 s.preSetup() 389 s.sentPacketHandler, s.receivedPacketHandler = ackhandler.NewAckHandler( 390 initialPacketNumber, 391 protocol.ByteCount(s.config.InitialPacketSize), 392 s.rttStats, 393 false, // has no effect 394 s.conn.capabilities().ECN, 395 s.perspective, 396 s.tracer, 397 s.logger, 398 ) 399 s.maxPayloadSizeEstimate.Store(uint32(estimateMaxPayloadSize(protocol.ByteCount(s.config.InitialPacketSize)))) 400 oneRTTStream := newCryptoStream() 401 params := &wire.TransportParameters{ 402 InitialMaxStreamDataBidiRemote: protocol.ByteCount(s.config.InitialStreamReceiveWindow), 403 InitialMaxStreamDataBidiLocal: protocol.ByteCount(s.config.InitialStreamReceiveWindow), 404 InitialMaxStreamDataUni: protocol.ByteCount(s.config.InitialStreamReceiveWindow), 405 InitialMaxData: protocol.ByteCount(s.config.InitialConnectionReceiveWindow), 406 MaxIdleTimeout: s.config.MaxIdleTimeout, 407 MaxBidiStreamNum: protocol.StreamNum(s.config.MaxIncomingStreams), 408 MaxUniStreamNum: protocol.StreamNum(s.config.MaxIncomingUniStreams), 409 MaxAckDelay: protocol.MaxAckDelayInclGranularity, 410 MaxUDPPayloadSize: protocol.MaxPacketBufferSize, 411 AckDelayExponent: protocol.AckDelayExponent, 412 DisableActiveMigration: true, 413 // For interoperability with quic-go versions before May 2023, this value must be set to a value 414 // different from protocol.DefaultActiveConnectionIDLimit. 415 // If set to the default value, it will be omitted from the transport parameters, which will make 416 // old quic-go versions interpret it as 0, instead of the default value of 2. 417 // See https://github.com/quic-go/quic-go/pull/3806. 418 ActiveConnectionIDLimit: protocol.MaxActiveConnectionIDs, 419 InitialSourceConnectionID: srcConnID, 420 } 421 if s.config.EnableDatagrams { 422 params.MaxDatagramFrameSize = wire.MaxDatagramSize 423 } else { 424 params.MaxDatagramFrameSize = protocol.InvalidByteCount 425 } 426 if s.tracer != nil && s.tracer.SentTransportParameters != nil { 427 s.tracer.SentTransportParameters(params) 428 } 429 cs := handshake.NewCryptoSetupClient( 430 destConnID, 431 params, 432 tlsConf, 433 enable0RTT, 434 s.rttStats, 435 tracer, 436 logger, 437 s.version, 438 ) 439 s.cryptoStreamHandler = cs 440 s.cryptoStreamManager = newCryptoStreamManager(cs, s.initialStream, s.handshakeStream, oneRTTStream) 441 s.unpacker = newPacketUnpacker(cs, s.srcConnIDLen) 442 s.packer = newPacketPacker(srcConnID, s.connIDManager.Get, s.initialStream, s.handshakeStream, s.sentPacketHandler, s.retransmissionQueue, cs, s.framer, s.receivedPacketHandler, s.datagramQueue, s.perspective) 443 if len(tlsConf.ServerName) > 0 { 444 s.tokenStoreKey = tlsConf.ServerName 445 } else { 446 s.tokenStoreKey = conn.RemoteAddr().String() 447 } 448 if s.config.TokenStore != nil { 449 if token := s.config.TokenStore.Pop(s.tokenStoreKey); token != nil { 450 s.packer.SetToken(token.data) 451 } 452 } 453 return s 454 } 455 456 func (s *connection) preSetup() { 457 s.initialStream = newCryptoStream() 458 s.handshakeStream = newCryptoStream() 459 s.sendQueue = newSendQueue(s.conn) 460 s.retransmissionQueue = newRetransmissionQueue() 461 s.frameParser = *wire.NewFrameParser(s.config.EnableDatagrams) 462 s.rttStats = &utils.RTTStats{} 463 s.connFlowController = flowcontrol.NewConnectionFlowController( 464 protocol.ByteCount(s.config.InitialConnectionReceiveWindow), 465 protocol.ByteCount(s.config.MaxConnectionReceiveWindow), 466 s.onHasConnectionWindowUpdate, 467 func(size protocol.ByteCount) bool { 468 if s.config.AllowConnectionWindowIncrease == nil { 469 return true 470 } 471 return s.config.AllowConnectionWindowIncrease(s, uint64(size)) 472 }, 473 s.rttStats, 474 s.logger, 475 ) 476 s.earlyConnReadyChan = make(chan struct{}) 477 s.streamsMap = newStreamsMap( 478 s.ctx, 479 s, 480 s.newFlowController, 481 uint64(s.config.MaxIncomingStreams), 482 uint64(s.config.MaxIncomingUniStreams), 483 s.perspective, 484 ) 485 s.framer = newFramer(s.streamsMap) 486 s.receivedPackets = make(chan receivedPacket, protocol.MaxConnUnprocessedPackets) 487 s.closeChan = make(chan closeError, 1) 488 s.sendingScheduled = make(chan struct{}, 1) 489 s.handshakeCtx, s.handshakeCtxCancel = context.WithCancel(context.Background()) 490 491 now := time.Now() 492 s.lastPacketReceivedTime = now 493 s.creationTime = now 494 495 s.windowUpdateQueue = newWindowUpdateQueue(s.streamsMap, s.connFlowController, s.framer.QueueControlFrame) 496 s.datagramQueue = newDatagramQueue(s.scheduleSending, s.logger) 497 s.connState.Version = s.version 498 } 499 500 // run the connection main loop 501 func (s *connection) run() error { 502 var closeErr closeError 503 defer func() { 504 s.ctxCancel(closeErr.err) 505 }() 506 507 s.timer = *newTimer() 508 509 if err := s.cryptoStreamHandler.StartHandshake(); err != nil { 510 return err 511 } 512 if err := s.handleHandshakeEvents(); err != nil { 513 return err 514 } 515 go func() { 516 if err := s.sendQueue.Run(); err != nil { 517 s.destroyImpl(err) 518 } 519 }() 520 521 if s.perspective == protocol.PerspectiveClient { 522 s.scheduleSending() // so the ClientHello actually gets sent 523 } 524 525 var sendQueueAvailable <-chan struct{} 526 527 runLoop: 528 for { 529 if s.framer.QueuedTooManyControlFrames() { 530 s.closeLocal(&qerr.TransportError{ErrorCode: InternalError}) 531 } 532 // Close immediately if requested 533 select { 534 case closeErr = <-s.closeChan: 535 break runLoop 536 default: 537 } 538 539 s.maybeResetTimer() 540 541 var processedUndecryptablePacket bool 542 if len(s.undecryptablePacketsToProcess) > 0 { 543 queue := s.undecryptablePacketsToProcess 544 s.undecryptablePacketsToProcess = nil 545 for _, p := range queue { 546 if processed := s.handlePacketImpl(p); processed { 547 processedUndecryptablePacket = true 548 } 549 // Don't set timers and send packets if the packet made us close the connection. 550 select { 551 case closeErr = <-s.closeChan: 552 break runLoop 553 default: 554 } 555 } 556 } 557 // If we processed any undecryptable packets, jump to the resetting of the timers directly. 558 if !processedUndecryptablePacket { 559 select { 560 case closeErr = <-s.closeChan: 561 break runLoop 562 case <-s.timer.Chan(): 563 s.timer.SetRead() 564 // We do all the interesting stuff after the switch statement, so 565 // nothing to see here. 566 case <-s.sendingScheduled: 567 // We do all the interesting stuff after the switch statement, so 568 // nothing to see here. 569 case <-sendQueueAvailable: 570 case firstPacket := <-s.receivedPackets: 571 wasProcessed := s.handlePacketImpl(firstPacket) 572 // Don't set timers and send packets if the packet made us close the connection. 573 select { 574 case closeErr = <-s.closeChan: 575 break runLoop 576 default: 577 } 578 if s.handshakeComplete { 579 // Now process all packets in the receivedPackets channel. 580 // Limit the number of packets to the length of the receivedPackets channel, 581 // so we eventually get a chance to send out an ACK when receiving a lot of packets. 582 numPackets := len(s.receivedPackets) 583 receiveLoop: 584 for i := 0; i < numPackets; i++ { 585 select { 586 case p := <-s.receivedPackets: 587 if processed := s.handlePacketImpl(p); processed { 588 wasProcessed = true 589 } 590 select { 591 case closeErr = <-s.closeChan: 592 break runLoop 593 default: 594 } 595 default: 596 break receiveLoop 597 } 598 } 599 } 600 // Only reset the timers if this packet was actually processed. 601 // This avoids modifying any state when handling undecryptable packets, 602 // which could be injected by an attacker. 603 if !wasProcessed { 604 continue 605 } 606 } 607 } 608 609 now := time.Now() 610 if timeout := s.sentPacketHandler.GetLossDetectionTimeout(); !timeout.IsZero() && timeout.Before(now) { 611 // This could cause packets to be retransmitted. 612 // Check it before trying to send packets. 613 if err := s.sentPacketHandler.OnLossDetectionTimeout(); err != nil { 614 s.closeLocal(err) 615 } 616 } 617 618 if keepAliveTime := s.nextKeepAliveTime(); !keepAliveTime.IsZero() && !now.Before(keepAliveTime) { 619 // send a PING frame since there is no activity in the connection 620 s.logger.Debugf("Sending a keep-alive PING to keep the connection alive.") 621 s.framer.QueueControlFrame(&wire.PingFrame{}) 622 s.keepAlivePingSent = true 623 } else if !s.handshakeComplete && now.Sub(s.creationTime) >= s.config.handshakeTimeout() { 624 s.destroyImpl(qerr.ErrHandshakeTimeout) 625 continue 626 } else { 627 idleTimeoutStartTime := s.idleTimeoutStartTime() 628 if (!s.handshakeComplete && now.Sub(idleTimeoutStartTime) >= s.config.HandshakeIdleTimeout) || 629 (s.handshakeComplete && now.After(s.nextIdleTimeoutTime())) { 630 s.destroyImpl(qerr.ErrIdleTimeout) 631 continue 632 } 633 } 634 635 if s.sendQueue.WouldBlock() { 636 // The send queue is still busy sending out packets. 637 // Wait until there's space to enqueue new packets. 638 sendQueueAvailable = s.sendQueue.Available() 639 continue 640 } 641 if err := s.triggerSending(now); err != nil { 642 s.closeLocal(err) 643 } 644 if s.sendQueue.WouldBlock() { 645 sendQueueAvailable = s.sendQueue.Available() 646 } else { 647 sendQueueAvailable = nil 648 } 649 } 650 651 s.cryptoStreamHandler.Close() 652 s.sendQueue.Close() // close the send queue before sending the CONNECTION_CLOSE 653 s.handleCloseError(&closeErr) 654 if s.tracer != nil && s.tracer.Close != nil { 655 if e := (&errCloseForRecreating{}); !errors.As(closeErr.err, &e) { 656 s.tracer.Close() 657 } 658 } 659 s.logger.Infof("Connection %s closed.", s.logID) 660 s.timer.Stop() 661 return closeErr.err 662 } 663 664 // blocks until the early connection can be used 665 func (s *connection) earlyConnReady() <-chan struct{} { 666 return s.earlyConnReadyChan 667 } 668 669 func (s *connection) HandshakeComplete() <-chan struct{} { 670 return s.handshakeCtx.Done() 671 } 672 673 func (s *connection) Context() context.Context { 674 return s.ctx 675 } 676 677 func (s *connection) supportsDatagrams() bool { 678 return s.peerParams.MaxDatagramFrameSize > 0 679 } 680 681 func (s *connection) ConnectionState() ConnectionState { 682 s.connStateMutex.Lock() 683 defer s.connStateMutex.Unlock() 684 cs := s.cryptoStreamHandler.ConnectionState() 685 s.connState.TLS = cs.ConnectionState 686 s.connState.Used0RTT = cs.Used0RTT 687 s.connState.GSO = s.conn.capabilities().GSO 688 return s.connState 689 } 690 691 // Time when the connection should time out 692 func (s *connection) nextIdleTimeoutTime() time.Time { 693 idleTimeout := max(s.idleTimeout, s.rttStats.PTO(true)*3) 694 return s.idleTimeoutStartTime().Add(idleTimeout) 695 } 696 697 // Time when the next keep-alive packet should be sent. 698 // It returns a zero time if no keep-alive should be sent. 699 func (s *connection) nextKeepAliveTime() time.Time { 700 if s.config.KeepAlivePeriod == 0 || s.keepAlivePingSent || !s.firstAckElicitingPacketAfterIdleSentTime.IsZero() { 701 return time.Time{} 702 } 703 keepAliveInterval := max(s.keepAliveInterval, s.rttStats.PTO(true)*3/2) 704 return s.lastPacketReceivedTime.Add(keepAliveInterval) 705 } 706 707 func (s *connection) maybeResetTimer() { 708 var deadline time.Time 709 if !s.handshakeComplete { 710 deadline = utils.MinTime( 711 s.creationTime.Add(s.config.handshakeTimeout()), 712 s.idleTimeoutStartTime().Add(s.config.HandshakeIdleTimeout), 713 ) 714 } else { 715 if keepAliveTime := s.nextKeepAliveTime(); !keepAliveTime.IsZero() { 716 deadline = keepAliveTime 717 } else { 718 deadline = s.nextIdleTimeoutTime() 719 } 720 } 721 722 s.timer.SetTimer( 723 deadline, 724 s.receivedPacketHandler.GetAlarmTimeout(), 725 s.sentPacketHandler.GetLossDetectionTimeout(), 726 s.pacingDeadline, 727 ) 728 } 729 730 func (s *connection) idleTimeoutStartTime() time.Time { 731 return utils.MaxTime(s.lastPacketReceivedTime, s.firstAckElicitingPacketAfterIdleSentTime) 732 } 733 734 func (s *connection) handleHandshakeComplete() error { 735 defer s.handshakeCtxCancel() 736 // Once the handshake completes, we have derived 1-RTT keys. 737 // There's no point in queueing undecryptable packets for later decryption anymore. 738 s.undecryptablePackets = nil 739 740 s.connIDManager.SetHandshakeComplete() 741 s.connIDGenerator.SetHandshakeComplete() 742 743 if s.tracer != nil && s.tracer.ChoseALPN != nil { 744 s.tracer.ChoseALPN(s.cryptoStreamHandler.ConnectionState().NegotiatedProtocol) 745 } 746 747 // The server applies transport parameters right away, but the client side has to wait for handshake completion. 748 // During a 0-RTT connection, the client is only allowed to use the new transport parameters for 1-RTT packets. 749 if s.perspective == protocol.PerspectiveClient { 750 s.applyTransportParameters() 751 return nil 752 } 753 754 // All these only apply to the server side. 755 if err := s.handleHandshakeConfirmed(); err != nil { 756 return err 757 } 758 759 ticket, err := s.cryptoStreamHandler.GetSessionTicket() 760 if err != nil { 761 return err 762 } 763 if ticket != nil { // may be nil if session tickets are disabled via tls.Config.SessionTicketsDisabled 764 s.oneRTTStream.Write(ticket) 765 for s.oneRTTStream.HasData() { 766 s.queueControlFrame(s.oneRTTStream.PopCryptoFrame(protocol.MaxPostHandshakeCryptoFrameSize)) 767 } 768 } 769 token, err := s.tokenGenerator.NewToken(s.conn.RemoteAddr()) 770 if err != nil { 771 return err 772 } 773 s.queueControlFrame(&wire.NewTokenFrame{Token: token}) 774 s.queueControlFrame(&wire.HandshakeDoneFrame{}) 775 return nil 776 } 777 778 func (s *connection) handleHandshakeConfirmed() error { 779 if err := s.dropEncryptionLevel(protocol.EncryptionHandshake); err != nil { 780 return err 781 } 782 783 s.handshakeConfirmed = true 784 s.sentPacketHandler.SetHandshakeConfirmed() 785 s.cryptoStreamHandler.SetHandshakeConfirmed() 786 787 if !s.config.DisablePathMTUDiscovery && s.conn.capabilities().DF { 788 s.mtuDiscoverer.Start() 789 } 790 return nil 791 } 792 793 func (s *connection) handlePacketImpl(rp receivedPacket) bool { 794 s.sentPacketHandler.ReceivedBytes(rp.Size()) 795 796 if wire.IsVersionNegotiationPacket(rp.data) { 797 s.handleVersionNegotiationPacket(rp) 798 return false 799 } 800 801 var counter uint8 802 var lastConnID protocol.ConnectionID 803 var processed bool 804 data := rp.data 805 p := rp 806 for len(data) > 0 { 807 var destConnID protocol.ConnectionID 808 if counter > 0 { 809 p = *(p.Clone()) 810 p.data = data 811 812 var err error 813 destConnID, err = wire.ParseConnectionID(p.data, s.srcConnIDLen) 814 if err != nil { 815 if s.tracer != nil && s.tracer.DroppedPacket != nil { 816 s.tracer.DroppedPacket(logging.PacketTypeNotDetermined, protocol.InvalidPacketNumber, protocol.ByteCount(len(data)), logging.PacketDropHeaderParseError) 817 } 818 s.logger.Debugf("error parsing packet, couldn't parse connection ID: %s", err) 819 break 820 } 821 if destConnID != lastConnID { 822 if s.tracer != nil && s.tracer.DroppedPacket != nil { 823 s.tracer.DroppedPacket(logging.PacketTypeNotDetermined, protocol.InvalidPacketNumber, protocol.ByteCount(len(data)), logging.PacketDropUnknownConnectionID) 824 } 825 s.logger.Debugf("coalesced packet has different destination connection ID: %s, expected %s", destConnID, lastConnID) 826 break 827 } 828 } 829 830 if wire.IsLongHeaderPacket(p.data[0]) { 831 hdr, packetData, rest, err := wire.ParsePacket(p.data) 832 if err != nil { 833 if s.tracer != nil && s.tracer.DroppedPacket != nil { 834 dropReason := logging.PacketDropHeaderParseError 835 if err == wire.ErrUnsupportedVersion { 836 dropReason = logging.PacketDropUnsupportedVersion 837 } 838 s.tracer.DroppedPacket(logging.PacketTypeNotDetermined, protocol.InvalidPacketNumber, protocol.ByteCount(len(data)), dropReason) 839 } 840 s.logger.Debugf("error parsing packet: %s", err) 841 break 842 } 843 lastConnID = hdr.DestConnectionID 844 845 if hdr.Version != s.version { 846 if s.tracer != nil && s.tracer.DroppedPacket != nil { 847 s.tracer.DroppedPacket(logging.PacketTypeFromHeader(hdr), protocol.InvalidPacketNumber, protocol.ByteCount(len(data)), logging.PacketDropUnexpectedVersion) 848 } 849 s.logger.Debugf("Dropping packet with version %x. Expected %x.", hdr.Version, s.version) 850 break 851 } 852 853 if counter > 0 { 854 p.buffer.Split() 855 } 856 counter++ 857 858 // only log if this actually a coalesced packet 859 if s.logger.Debug() && (counter > 1 || len(rest) > 0) { 860 s.logger.Debugf("Parsed a coalesced packet. Part %d: %d bytes. Remaining: %d bytes.", counter, len(packetData), len(rest)) 861 } 862 863 p.data = packetData 864 865 if wasProcessed := s.handleLongHeaderPacket(p, hdr); wasProcessed { 866 processed = true 867 } 868 data = rest 869 } else { 870 if counter > 0 { 871 p.buffer.Split() 872 } 873 processed = s.handleShortHeaderPacket(p, destConnID) 874 break 875 } 876 } 877 878 p.buffer.MaybeRelease() 879 return processed 880 } 881 882 func (s *connection) handleShortHeaderPacket(p receivedPacket, destConnID protocol.ConnectionID) bool { 883 var wasQueued bool 884 885 defer func() { 886 // Put back the packet buffer if the packet wasn't queued for later decryption. 887 if !wasQueued { 888 p.buffer.Decrement() 889 } 890 }() 891 892 pn, pnLen, keyPhase, data, err := s.unpacker.UnpackShortHeader(p.rcvTime, p.data) 893 if err != nil { 894 wasQueued = s.handleUnpackError(err, p, logging.PacketType1RTT) 895 return false 896 } 897 898 if s.logger.Debug() { 899 s.logger.Debugf("<- Reading packet %d (%d bytes) for connection %s, 1-RTT", pn, p.Size(), destConnID) 900 wire.LogShortHeader(s.logger, destConnID, pn, pnLen, keyPhase) 901 } 902 903 if s.receivedPacketHandler.IsPotentiallyDuplicate(pn, protocol.Encryption1RTT) { 904 s.logger.Debugf("Dropping (potentially) duplicate packet.") 905 if s.tracer != nil && s.tracer.DroppedPacket != nil { 906 s.tracer.DroppedPacket(logging.PacketType1RTT, pn, p.Size(), logging.PacketDropDuplicate) 907 } 908 return false 909 } 910 911 var log func([]logging.Frame) 912 if s.tracer != nil && s.tracer.ReceivedShortHeaderPacket != nil { 913 log = func(frames []logging.Frame) { 914 s.tracer.ReceivedShortHeaderPacket( 915 &logging.ShortHeader{ 916 DestConnectionID: destConnID, 917 PacketNumber: pn, 918 PacketNumberLen: pnLen, 919 KeyPhase: keyPhase, 920 }, 921 p.Size(), 922 p.ecn, 923 frames, 924 ) 925 } 926 } 927 if err := s.handleUnpackedShortHeaderPacket(destConnID, pn, data, p.ecn, p.rcvTime, log); err != nil { 928 s.closeLocal(err) 929 return false 930 } 931 return true 932 } 933 934 func (s *connection) handleLongHeaderPacket(p receivedPacket, hdr *wire.Header) bool /* was the packet successfully processed */ { 935 var wasQueued bool 936 937 defer func() { 938 // Put back the packet buffer if the packet wasn't queued for later decryption. 939 if !wasQueued { 940 p.buffer.Decrement() 941 } 942 }() 943 944 if hdr.Type == protocol.PacketTypeRetry { 945 return s.handleRetryPacket(hdr, p.data, p.rcvTime) 946 } 947 948 // The server can change the source connection ID with the first Handshake packet. 949 // After this, all packets with a different source connection have to be ignored. 950 if s.receivedFirstPacket && hdr.Type == protocol.PacketTypeInitial && hdr.SrcConnectionID != s.handshakeDestConnID { 951 if s.tracer != nil && s.tracer.DroppedPacket != nil { 952 s.tracer.DroppedPacket(logging.PacketTypeInitial, protocol.InvalidPacketNumber, p.Size(), logging.PacketDropUnknownConnectionID) 953 } 954 s.logger.Debugf("Dropping Initial packet (%d bytes) with unexpected source connection ID: %s (expected %s)", p.Size(), hdr.SrcConnectionID, s.handshakeDestConnID) 955 return false 956 } 957 // drop 0-RTT packets, if we are a client 958 if s.perspective == protocol.PerspectiveClient && hdr.Type == protocol.PacketType0RTT { 959 if s.tracer != nil && s.tracer.DroppedPacket != nil { 960 s.tracer.DroppedPacket(logging.PacketType0RTT, protocol.InvalidPacketNumber, p.Size(), logging.PacketDropKeyUnavailable) 961 } 962 return false 963 } 964 965 packet, err := s.unpacker.UnpackLongHeader(hdr, p.rcvTime, p.data, s.version) 966 if err != nil { 967 wasQueued = s.handleUnpackError(err, p, logging.PacketTypeFromHeader(hdr)) 968 return false 969 } 970 971 if s.logger.Debug() { 972 s.logger.Debugf("<- Reading packet %d (%d bytes) for connection %s, %s", packet.hdr.PacketNumber, p.Size(), hdr.DestConnectionID, packet.encryptionLevel) 973 packet.hdr.Log(s.logger) 974 } 975 976 if pn := packet.hdr.PacketNumber; s.receivedPacketHandler.IsPotentiallyDuplicate(pn, packet.encryptionLevel) { 977 s.logger.Debugf("Dropping (potentially) duplicate packet.") 978 if s.tracer != nil && s.tracer.DroppedPacket != nil { 979 s.tracer.DroppedPacket(logging.PacketTypeFromHeader(hdr), pn, p.Size(), logging.PacketDropDuplicate) 980 } 981 return false 982 } 983 984 if err := s.handleUnpackedLongHeaderPacket(packet, p.ecn, p.rcvTime, p.Size()); err != nil { 985 s.closeLocal(err) 986 return false 987 } 988 return true 989 } 990 991 func (s *connection) handleUnpackError(err error, p receivedPacket, pt logging.PacketType) (wasQueued bool) { 992 switch err { 993 case handshake.ErrKeysDropped: 994 if s.tracer != nil && s.tracer.DroppedPacket != nil { 995 s.tracer.DroppedPacket(pt, protocol.InvalidPacketNumber, p.Size(), logging.PacketDropKeyUnavailable) 996 } 997 s.logger.Debugf("Dropping %s packet (%d bytes) because we already dropped the keys.", pt, p.Size()) 998 case handshake.ErrKeysNotYetAvailable: 999 // Sealer for this encryption level not yet available. 1000 // Try again later. 1001 s.tryQueueingUndecryptablePacket(p, pt) 1002 return true 1003 case wire.ErrInvalidReservedBits: 1004 s.closeLocal(&qerr.TransportError{ 1005 ErrorCode: qerr.ProtocolViolation, 1006 ErrorMessage: err.Error(), 1007 }) 1008 case handshake.ErrDecryptionFailed: 1009 // This might be a packet injected by an attacker. Drop it. 1010 if s.tracer != nil && s.tracer.DroppedPacket != nil { 1011 s.tracer.DroppedPacket(pt, protocol.InvalidPacketNumber, p.Size(), logging.PacketDropPayloadDecryptError) 1012 } 1013 s.logger.Debugf("Dropping %s packet (%d bytes) that could not be unpacked. Error: %s", pt, p.Size(), err) 1014 default: 1015 var headerErr *headerParseError 1016 if errors.As(err, &headerErr) { 1017 // This might be a packet injected by an attacker. Drop it. 1018 if s.tracer != nil && s.tracer.DroppedPacket != nil { 1019 s.tracer.DroppedPacket(pt, protocol.InvalidPacketNumber, p.Size(), logging.PacketDropHeaderParseError) 1020 } 1021 s.logger.Debugf("Dropping %s packet (%d bytes) for which we couldn't unpack the header. Error: %s", pt, p.Size(), err) 1022 } else { 1023 // This is an error returned by the AEAD (other than ErrDecryptionFailed). 1024 // For example, a PROTOCOL_VIOLATION due to key updates. 1025 s.closeLocal(err) 1026 } 1027 } 1028 return false 1029 } 1030 1031 func (s *connection) handleRetryPacket(hdr *wire.Header, data []byte, rcvTime time.Time) bool /* was this a valid Retry */ { 1032 if s.perspective == protocol.PerspectiveServer { 1033 if s.tracer != nil && s.tracer.DroppedPacket != nil { 1034 s.tracer.DroppedPacket(logging.PacketTypeRetry, protocol.InvalidPacketNumber, protocol.ByteCount(len(data)), logging.PacketDropUnexpectedPacket) 1035 } 1036 s.logger.Debugf("Ignoring Retry.") 1037 return false 1038 } 1039 if s.receivedFirstPacket { 1040 if s.tracer != nil && s.tracer.DroppedPacket != nil { 1041 s.tracer.DroppedPacket(logging.PacketTypeRetry, protocol.InvalidPacketNumber, protocol.ByteCount(len(data)), logging.PacketDropUnexpectedPacket) 1042 } 1043 s.logger.Debugf("Ignoring Retry, since we already received a packet.") 1044 return false 1045 } 1046 destConnID := s.connIDManager.Get() 1047 if hdr.SrcConnectionID == destConnID { 1048 if s.tracer != nil && s.tracer.DroppedPacket != nil { 1049 s.tracer.DroppedPacket(logging.PacketTypeRetry, protocol.InvalidPacketNumber, protocol.ByteCount(len(data)), logging.PacketDropUnexpectedPacket) 1050 } 1051 s.logger.Debugf("Ignoring Retry, since the server didn't change the Source Connection ID.") 1052 return false 1053 } 1054 // If a token is already set, this means that we already received a Retry from the server. 1055 // Ignore this Retry packet. 1056 if s.receivedRetry { 1057 s.logger.Debugf("Ignoring Retry, since a Retry was already received.") 1058 return false 1059 } 1060 1061 tag := handshake.GetRetryIntegrityTag(data[:len(data)-16], destConnID, hdr.Version) 1062 if !bytes.Equal(data[len(data)-16:], tag[:]) { 1063 if s.tracer != nil && s.tracer.DroppedPacket != nil { 1064 s.tracer.DroppedPacket(logging.PacketTypeRetry, protocol.InvalidPacketNumber, protocol.ByteCount(len(data)), logging.PacketDropPayloadDecryptError) 1065 } 1066 s.logger.Debugf("Ignoring spoofed Retry. Integrity Tag doesn't match.") 1067 return false 1068 } 1069 1070 if s.logger.Debug() { 1071 s.logger.Debugf("<- Received Retry:") 1072 (&wire.ExtendedHeader{Header: *hdr}).Log(s.logger) 1073 s.logger.Debugf("Switching destination connection ID to: %s", hdr.SrcConnectionID) 1074 } 1075 if s.tracer != nil && s.tracer.ReceivedRetry != nil { 1076 s.tracer.ReceivedRetry(hdr) 1077 } 1078 newDestConnID := hdr.SrcConnectionID 1079 s.receivedRetry = true 1080 if err := s.sentPacketHandler.ResetForRetry(rcvTime); err != nil { 1081 s.closeLocal(err) 1082 return false 1083 } 1084 s.handshakeDestConnID = newDestConnID 1085 s.retrySrcConnID = &newDestConnID 1086 s.cryptoStreamHandler.ChangeConnectionID(newDestConnID) 1087 s.packer.SetToken(hdr.Token) 1088 s.connIDManager.ChangeInitialConnID(newDestConnID) 1089 s.scheduleSending() 1090 return true 1091 } 1092 1093 func (s *connection) handleVersionNegotiationPacket(p receivedPacket) { 1094 if s.perspective == protocol.PerspectiveServer || // servers never receive version negotiation packets 1095 s.receivedFirstPacket || s.versionNegotiated { // ignore delayed / duplicated version negotiation packets 1096 if s.tracer != nil && s.tracer.DroppedPacket != nil { 1097 s.tracer.DroppedPacket(logging.PacketTypeVersionNegotiation, protocol.InvalidPacketNumber, p.Size(), logging.PacketDropUnexpectedPacket) 1098 } 1099 return 1100 } 1101 1102 src, dest, supportedVersions, err := wire.ParseVersionNegotiationPacket(p.data) 1103 if err != nil { 1104 if s.tracer != nil && s.tracer.DroppedPacket != nil { 1105 s.tracer.DroppedPacket(logging.PacketTypeVersionNegotiation, protocol.InvalidPacketNumber, p.Size(), logging.PacketDropHeaderParseError) 1106 } 1107 s.logger.Debugf("Error parsing Version Negotiation packet: %s", err) 1108 return 1109 } 1110 1111 for _, v := range supportedVersions { 1112 if v == s.version { 1113 if s.tracer != nil && s.tracer.DroppedPacket != nil { 1114 s.tracer.DroppedPacket(logging.PacketTypeVersionNegotiation, protocol.InvalidPacketNumber, p.Size(), logging.PacketDropUnexpectedVersion) 1115 } 1116 // The Version Negotiation packet contains the version that we offered. 1117 // This might be a packet sent by an attacker, or it was corrupted. 1118 return 1119 } 1120 } 1121 1122 s.logger.Infof("Received a Version Negotiation packet. Supported Versions: %s", supportedVersions) 1123 if s.tracer != nil && s.tracer.ReceivedVersionNegotiationPacket != nil { 1124 s.tracer.ReceivedVersionNegotiationPacket(dest, src, supportedVersions) 1125 } 1126 newVersion, ok := protocol.ChooseSupportedVersion(s.config.Versions, supportedVersions) 1127 if !ok { 1128 s.destroyImpl(&VersionNegotiationError{ 1129 Ours: s.config.Versions, 1130 Theirs: supportedVersions, 1131 }) 1132 s.logger.Infof("No compatible QUIC version found.") 1133 return 1134 } 1135 if s.tracer != nil && s.tracer.NegotiatedVersion != nil { 1136 s.tracer.NegotiatedVersion(newVersion, s.config.Versions, supportedVersions) 1137 } 1138 1139 s.logger.Infof("Switching to QUIC version %s.", newVersion) 1140 nextPN, _ := s.sentPacketHandler.PeekPacketNumber(protocol.EncryptionInitial) 1141 s.destroyImpl(&errCloseForRecreating{ 1142 nextPacketNumber: nextPN, 1143 nextVersion: newVersion, 1144 }) 1145 } 1146 1147 func (s *connection) handleUnpackedLongHeaderPacket( 1148 packet *unpackedPacket, 1149 ecn protocol.ECN, 1150 rcvTime time.Time, 1151 packetSize protocol.ByteCount, // only for logging 1152 ) error { 1153 if !s.receivedFirstPacket { 1154 s.receivedFirstPacket = true 1155 if !s.versionNegotiated && s.tracer != nil && s.tracer.NegotiatedVersion != nil { 1156 var clientVersions, serverVersions []protocol.Version 1157 switch s.perspective { 1158 case protocol.PerspectiveClient: 1159 clientVersions = s.config.Versions 1160 case protocol.PerspectiveServer: 1161 serverVersions = s.config.Versions 1162 } 1163 s.tracer.NegotiatedVersion(s.version, clientVersions, serverVersions) 1164 } 1165 // The server can change the source connection ID with the first Handshake packet. 1166 if s.perspective == protocol.PerspectiveClient && packet.hdr.SrcConnectionID != s.handshakeDestConnID { 1167 cid := packet.hdr.SrcConnectionID 1168 s.logger.Debugf("Received first packet. Switching destination connection ID to: %s", cid) 1169 s.handshakeDestConnID = cid 1170 s.connIDManager.ChangeInitialConnID(cid) 1171 } 1172 // We create the connection as soon as we receive the first packet from the client. 1173 // We do that before authenticating the packet. 1174 // That means that if the source connection ID was corrupted, 1175 // we might have created a connection with an incorrect source connection ID. 1176 // Once we authenticate the first packet, we need to update it. 1177 if s.perspective == protocol.PerspectiveServer { 1178 if packet.hdr.SrcConnectionID != s.handshakeDestConnID { 1179 s.handshakeDestConnID = packet.hdr.SrcConnectionID 1180 s.connIDManager.ChangeInitialConnID(packet.hdr.SrcConnectionID) 1181 } 1182 if s.tracer != nil && s.tracer.StartedConnection != nil { 1183 s.tracer.StartedConnection( 1184 s.conn.LocalAddr(), 1185 s.conn.RemoteAddr(), 1186 packet.hdr.SrcConnectionID, 1187 packet.hdr.DestConnectionID, 1188 ) 1189 } 1190 } 1191 } 1192 1193 if s.perspective == protocol.PerspectiveServer && packet.encryptionLevel == protocol.EncryptionHandshake && 1194 !s.droppedInitialKeys { 1195 // On the server side, Initial keys are dropped as soon as the first Handshake packet is received. 1196 // See Section 4.9.1 of RFC 9001. 1197 if err := s.dropEncryptionLevel(protocol.EncryptionInitial); err != nil { 1198 return err 1199 } 1200 } 1201 1202 s.lastPacketReceivedTime = rcvTime 1203 s.firstAckElicitingPacketAfterIdleSentTime = time.Time{} 1204 s.keepAlivePingSent = false 1205 1206 var log func([]logging.Frame) 1207 if s.tracer != nil && s.tracer.ReceivedLongHeaderPacket != nil { 1208 log = func(frames []logging.Frame) { 1209 s.tracer.ReceivedLongHeaderPacket(packet.hdr, packetSize, ecn, frames) 1210 } 1211 } 1212 isAckEliciting, err := s.handleFrames(packet.data, packet.hdr.DestConnectionID, packet.encryptionLevel, log) 1213 if err != nil { 1214 return err 1215 } 1216 return s.receivedPacketHandler.ReceivedPacket(packet.hdr.PacketNumber, ecn, packet.encryptionLevel, rcvTime, isAckEliciting) 1217 } 1218 1219 func (s *connection) handleUnpackedShortHeaderPacket( 1220 destConnID protocol.ConnectionID, 1221 pn protocol.PacketNumber, 1222 data []byte, 1223 ecn protocol.ECN, 1224 rcvTime time.Time, 1225 log func([]logging.Frame), 1226 ) error { 1227 s.lastPacketReceivedTime = rcvTime 1228 s.firstAckElicitingPacketAfterIdleSentTime = time.Time{} 1229 s.keepAlivePingSent = false 1230 1231 isAckEliciting, err := s.handleFrames(data, destConnID, protocol.Encryption1RTT, log) 1232 if err != nil { 1233 return err 1234 } 1235 return s.receivedPacketHandler.ReceivedPacket(pn, ecn, protocol.Encryption1RTT, rcvTime, isAckEliciting) 1236 } 1237 1238 func (s *connection) handleFrames( 1239 data []byte, 1240 destConnID protocol.ConnectionID, 1241 encLevel protocol.EncryptionLevel, 1242 log func([]logging.Frame), 1243 ) (isAckEliciting bool, _ error) { 1244 // Only used for tracing. 1245 // If we're not tracing, this slice will always remain empty. 1246 var frames []logging.Frame 1247 if log != nil { 1248 frames = make([]logging.Frame, 0, 4) 1249 } 1250 handshakeWasComplete := s.handshakeComplete 1251 var handleErr error 1252 for len(data) > 0 { 1253 l, frame, err := s.frameParser.ParseNext(data, encLevel, s.version) 1254 if err != nil { 1255 return false, err 1256 } 1257 data = data[l:] 1258 if frame == nil { 1259 break 1260 } 1261 if ackhandler.IsFrameAckEliciting(frame) { 1262 isAckEliciting = true 1263 } 1264 if log != nil { 1265 frames = append(frames, logutils.ConvertFrame(frame)) 1266 } 1267 // An error occurred handling a previous frame. 1268 // Don't handle the current frame. 1269 if handleErr != nil { 1270 continue 1271 } 1272 if err := s.handleFrame(frame, encLevel, destConnID); err != nil { 1273 if log == nil { 1274 return false, err 1275 } 1276 // If we're logging, we need to keep parsing (but not handling) all frames. 1277 handleErr = err 1278 } 1279 } 1280 1281 if log != nil { 1282 log(frames) 1283 if handleErr != nil { 1284 return false, handleErr 1285 } 1286 } 1287 1288 // Handle completion of the handshake after processing all the frames. 1289 // This ensures that we correctly handle the following case on the server side: 1290 // We receive a Handshake packet that contains the CRYPTO frame that allows us to complete the handshake, 1291 // and an ACK serialized after that CRYPTO frame. In this case, we still want to process the ACK frame. 1292 if !handshakeWasComplete && s.handshakeComplete { 1293 if err := s.handleHandshakeComplete(); err != nil { 1294 return false, err 1295 } 1296 } 1297 1298 return 1299 } 1300 1301 func (s *connection) handleFrame(f wire.Frame, encLevel protocol.EncryptionLevel, destConnID protocol.ConnectionID) error { 1302 var err error 1303 wire.LogFrame(s.logger, f, false) 1304 switch frame := f.(type) { 1305 case *wire.CryptoFrame: 1306 err = s.handleCryptoFrame(frame, encLevel) 1307 case *wire.StreamFrame: 1308 err = s.handleStreamFrame(frame) 1309 case *wire.AckFrame: 1310 err = s.handleAckFrame(frame, encLevel) 1311 case *wire.ConnectionCloseFrame: 1312 s.handleConnectionCloseFrame(frame) 1313 case *wire.ResetStreamFrame: 1314 err = s.handleResetStreamFrame(frame) 1315 case *wire.MaxDataFrame: 1316 s.handleMaxDataFrame(frame) 1317 case *wire.MaxStreamDataFrame: 1318 err = s.handleMaxStreamDataFrame(frame) 1319 case *wire.MaxStreamsFrame: 1320 s.handleMaxStreamsFrame(frame) 1321 case *wire.DataBlockedFrame: 1322 case *wire.StreamDataBlockedFrame: 1323 case *wire.StreamsBlockedFrame: 1324 case *wire.StopSendingFrame: 1325 err = s.handleStopSendingFrame(frame) 1326 case *wire.PingFrame: 1327 case *wire.PathChallengeFrame: 1328 s.handlePathChallengeFrame(frame) 1329 case *wire.PathResponseFrame: 1330 // since we don't send PATH_CHALLENGEs, we don't expect PATH_RESPONSEs 1331 err = errors.New("unexpected PATH_RESPONSE frame") 1332 case *wire.NewTokenFrame: 1333 err = s.handleNewTokenFrame(frame) 1334 case *wire.NewConnectionIDFrame: 1335 err = s.handleNewConnectionIDFrame(frame) 1336 case *wire.RetireConnectionIDFrame: 1337 err = s.handleRetireConnectionIDFrame(frame, destConnID) 1338 case *wire.HandshakeDoneFrame: 1339 err = s.handleHandshakeDoneFrame() 1340 case *wire.DatagramFrame: 1341 err = s.handleDatagramFrame(frame) 1342 default: 1343 err = fmt.Errorf("unexpected frame type: %s", reflect.ValueOf(&frame).Elem().Type().Name()) 1344 } 1345 return err 1346 } 1347 1348 // handlePacket is called by the server with a new packet 1349 func (s *connection) handlePacket(p receivedPacket) { 1350 // Discard packets once the amount of queued packets is larger than 1351 // the channel size, protocol.MaxConnUnprocessedPackets 1352 select { 1353 case s.receivedPackets <- p: 1354 default: 1355 if s.tracer != nil && s.tracer.DroppedPacket != nil { 1356 s.tracer.DroppedPacket(logging.PacketTypeNotDetermined, protocol.InvalidPacketNumber, p.Size(), logging.PacketDropDOSPrevention) 1357 } 1358 } 1359 } 1360 1361 func (s *connection) handleConnectionCloseFrame(frame *wire.ConnectionCloseFrame) { 1362 if frame.IsApplicationError { 1363 s.closeRemote(&qerr.ApplicationError{ 1364 Remote: true, 1365 ErrorCode: qerr.ApplicationErrorCode(frame.ErrorCode), 1366 ErrorMessage: frame.ReasonPhrase, 1367 }) 1368 return 1369 } 1370 s.closeRemote(&qerr.TransportError{ 1371 Remote: true, 1372 ErrorCode: qerr.TransportErrorCode(frame.ErrorCode), 1373 FrameType: frame.FrameType, 1374 ErrorMessage: frame.ReasonPhrase, 1375 }) 1376 } 1377 1378 func (s *connection) handleCryptoFrame(frame *wire.CryptoFrame, encLevel protocol.EncryptionLevel) error { 1379 if err := s.cryptoStreamManager.HandleCryptoFrame(frame, encLevel); err != nil { 1380 return err 1381 } 1382 return s.handleHandshakeEvents() 1383 } 1384 1385 func (s *connection) handleHandshakeEvents() error { 1386 for { 1387 ev := s.cryptoStreamHandler.NextEvent() 1388 var err error 1389 switch ev.Kind { 1390 case handshake.EventNoEvent: 1391 return nil 1392 case handshake.EventHandshakeComplete: 1393 // Don't call handleHandshakeComplete yet. 1394 // It's advantageous to process ACK frames that might be serialized after the CRYPTO frame first. 1395 s.handshakeComplete = true 1396 case handshake.EventReceivedTransportParameters: 1397 err = s.handleTransportParameters(ev.TransportParameters) 1398 case handshake.EventRestoredTransportParameters: 1399 s.restoreTransportParameters(ev.TransportParameters) 1400 close(s.earlyConnReadyChan) 1401 case handshake.EventReceivedReadKeys: 1402 // Queue all packets for decryption that have been undecryptable so far. 1403 s.undecryptablePacketsToProcess = s.undecryptablePackets 1404 s.undecryptablePackets = nil 1405 case handshake.EventDiscard0RTTKeys: 1406 err = s.dropEncryptionLevel(protocol.Encryption0RTT) 1407 case handshake.EventWriteInitialData: 1408 _, err = s.initialStream.Write(ev.Data) 1409 case handshake.EventWriteHandshakeData: 1410 _, err = s.handshakeStream.Write(ev.Data) 1411 } 1412 if err != nil { 1413 return err 1414 } 1415 } 1416 } 1417 1418 func (s *connection) handleStreamFrame(frame *wire.StreamFrame) error { 1419 str, err := s.streamsMap.GetOrOpenReceiveStream(frame.StreamID) 1420 if err != nil { 1421 return err 1422 } 1423 if str == nil { 1424 // Stream is closed and already garbage collected 1425 // ignore this StreamFrame 1426 return nil 1427 } 1428 return str.handleStreamFrame(frame) 1429 } 1430 1431 func (s *connection) handleMaxDataFrame(frame *wire.MaxDataFrame) { 1432 s.connFlowController.UpdateSendWindow(frame.MaximumData) 1433 } 1434 1435 func (s *connection) handleMaxStreamDataFrame(frame *wire.MaxStreamDataFrame) error { 1436 str, err := s.streamsMap.GetOrOpenSendStream(frame.StreamID) 1437 if err != nil { 1438 return err 1439 } 1440 if str == nil { 1441 // stream is closed and already garbage collected 1442 return nil 1443 } 1444 str.updateSendWindow(frame.MaximumStreamData) 1445 return nil 1446 } 1447 1448 func (s *connection) handleMaxStreamsFrame(frame *wire.MaxStreamsFrame) { 1449 s.streamsMap.HandleMaxStreamsFrame(frame) 1450 } 1451 1452 func (s *connection) handleResetStreamFrame(frame *wire.ResetStreamFrame) error { 1453 str, err := s.streamsMap.GetOrOpenReceiveStream(frame.StreamID) 1454 if err != nil { 1455 return err 1456 } 1457 if str == nil { 1458 // stream is closed and already garbage collected 1459 return nil 1460 } 1461 return str.handleResetStreamFrame(frame) 1462 } 1463 1464 func (s *connection) handleStopSendingFrame(frame *wire.StopSendingFrame) error { 1465 str, err := s.streamsMap.GetOrOpenSendStream(frame.StreamID) 1466 if err != nil { 1467 return err 1468 } 1469 if str == nil { 1470 // stream is closed and already garbage collected 1471 return nil 1472 } 1473 str.handleStopSendingFrame(frame) 1474 return nil 1475 } 1476 1477 func (s *connection) handlePathChallengeFrame(frame *wire.PathChallengeFrame) { 1478 s.queueControlFrame(&wire.PathResponseFrame{Data: frame.Data}) 1479 } 1480 1481 func (s *connection) handleNewTokenFrame(frame *wire.NewTokenFrame) error { 1482 if s.perspective == protocol.PerspectiveServer { 1483 return &qerr.TransportError{ 1484 ErrorCode: qerr.ProtocolViolation, 1485 ErrorMessage: "received NEW_TOKEN frame from the client", 1486 } 1487 } 1488 if s.config.TokenStore != nil { 1489 s.config.TokenStore.Put(s.tokenStoreKey, &ClientToken{data: frame.Token}) 1490 } 1491 return nil 1492 } 1493 1494 func (s *connection) handleNewConnectionIDFrame(f *wire.NewConnectionIDFrame) error { 1495 return s.connIDManager.Add(f) 1496 } 1497 1498 func (s *connection) handleRetireConnectionIDFrame(f *wire.RetireConnectionIDFrame, destConnID protocol.ConnectionID) error { 1499 return s.connIDGenerator.Retire(f.SequenceNumber, destConnID) 1500 } 1501 1502 func (s *connection) handleHandshakeDoneFrame() error { 1503 if s.perspective == protocol.PerspectiveServer { 1504 return &qerr.TransportError{ 1505 ErrorCode: qerr.ProtocolViolation, 1506 ErrorMessage: "received a HANDSHAKE_DONE frame", 1507 } 1508 } 1509 if !s.handshakeConfirmed { 1510 return s.handleHandshakeConfirmed() 1511 } 1512 return nil 1513 } 1514 1515 func (s *connection) handleAckFrame(frame *wire.AckFrame, encLevel protocol.EncryptionLevel) error { 1516 acked1RTTPacket, err := s.sentPacketHandler.ReceivedAck(frame, encLevel, s.lastPacketReceivedTime) 1517 if err != nil { 1518 return err 1519 } 1520 if !acked1RTTPacket { 1521 return nil 1522 } 1523 // On the client side: If the packet acknowledged a 1-RTT packet, this confirms the handshake. 1524 // This is only possible if the ACK was sent in a 1-RTT packet. 1525 // This is an optimization over simply waiting for a HANDSHAKE_DONE frame, see section 4.1.2 of RFC 9001. 1526 if s.perspective == protocol.PerspectiveClient && !s.handshakeConfirmed { 1527 if err := s.handleHandshakeConfirmed(); err != nil { 1528 return err 1529 } 1530 } 1531 return s.cryptoStreamHandler.SetLargest1RTTAcked(frame.LargestAcked()) 1532 } 1533 1534 func (s *connection) handleDatagramFrame(f *wire.DatagramFrame) error { 1535 if f.Length(s.version) > wire.MaxDatagramSize { 1536 return &qerr.TransportError{ 1537 ErrorCode: qerr.ProtocolViolation, 1538 ErrorMessage: "DATAGRAM frame too large", 1539 } 1540 } 1541 s.datagramQueue.HandleDatagramFrame(f) 1542 return nil 1543 } 1544 1545 // closeLocal closes the connection and send a CONNECTION_CLOSE containing the error 1546 func (s *connection) closeLocal(e error) { 1547 s.closeOnce.Do(func() { 1548 if e == nil { 1549 s.logger.Infof("Closing connection.") 1550 } else { 1551 s.logger.Errorf("Closing connection with error: %s", e) 1552 } 1553 s.closeChan <- closeError{err: e, immediate: false, remote: false} 1554 }) 1555 } 1556 1557 // destroy closes the connection without sending the error on the wire 1558 func (s *connection) destroy(e error) { 1559 s.destroyImpl(e) 1560 <-s.ctx.Done() 1561 } 1562 1563 func (s *connection) destroyImpl(e error) { 1564 s.closeOnce.Do(func() { 1565 if nerr, ok := e.(net.Error); ok && nerr.Timeout() { 1566 s.logger.Errorf("Destroying connection: %s", e) 1567 } else { 1568 s.logger.Errorf("Destroying connection with error: %s", e) 1569 } 1570 s.closeChan <- closeError{err: e, immediate: true, remote: false} 1571 }) 1572 } 1573 1574 func (s *connection) closeRemote(e error) { 1575 s.closeOnce.Do(func() { 1576 s.logger.Errorf("Peer closed connection with error: %s", e) 1577 s.closeChan <- closeError{err: e, immediate: true, remote: true} 1578 }) 1579 } 1580 1581 func (s *connection) CloseWithError(code ApplicationErrorCode, desc string) error { 1582 s.closeLocal(&qerr.ApplicationError{ 1583 ErrorCode: code, 1584 ErrorMessage: desc, 1585 }) 1586 <-s.ctx.Done() 1587 return nil 1588 } 1589 1590 func (s *connection) closeWithTransportError(code TransportErrorCode) { 1591 s.closeLocal(&qerr.TransportError{ErrorCode: code}) 1592 <-s.ctx.Done() 1593 } 1594 1595 func (s *connection) handleCloseError(closeErr *closeError) { 1596 e := closeErr.err 1597 if e == nil { 1598 e = &qerr.ApplicationError{} 1599 } else { 1600 defer func() { 1601 closeErr.err = e 1602 }() 1603 } 1604 1605 var ( 1606 statelessResetErr *StatelessResetError 1607 versionNegotiationErr *VersionNegotiationError 1608 recreateErr *errCloseForRecreating 1609 applicationErr *ApplicationError 1610 transportErr *TransportError 1611 ) 1612 switch { 1613 case errors.Is(e, qerr.ErrIdleTimeout), 1614 errors.Is(e, qerr.ErrHandshakeTimeout), 1615 errors.As(e, &statelessResetErr), 1616 errors.As(e, &versionNegotiationErr), 1617 errors.As(e, &recreateErr), 1618 errors.As(e, &applicationErr), 1619 errors.As(e, &transportErr): 1620 default: 1621 e = &qerr.TransportError{ 1622 ErrorCode: qerr.InternalError, 1623 ErrorMessage: e.Error(), 1624 } 1625 } 1626 1627 s.streamsMap.CloseWithError(e) 1628 s.connIDManager.Close() 1629 if s.datagramQueue != nil { 1630 s.datagramQueue.CloseWithError(e) 1631 } 1632 1633 if s.tracer != nil && s.tracer.ClosedConnection != nil && !errors.As(e, &recreateErr) { 1634 s.tracer.ClosedConnection(e) 1635 } 1636 1637 // If this is a remote close we're done here 1638 if closeErr.remote { 1639 s.connIDGenerator.ReplaceWithClosed(nil) 1640 return 1641 } 1642 if closeErr.immediate { 1643 s.connIDGenerator.RemoveAll() 1644 return 1645 } 1646 // Don't send out any CONNECTION_CLOSE if this is an error that occurred 1647 // before we even sent out the first packet. 1648 if s.perspective == protocol.PerspectiveClient && !s.sentFirstPacket { 1649 s.connIDGenerator.RemoveAll() 1650 return 1651 } 1652 connClosePacket, err := s.sendConnectionClose(e) 1653 if err != nil { 1654 s.logger.Debugf("Error sending CONNECTION_CLOSE: %s", err) 1655 } 1656 s.connIDGenerator.ReplaceWithClosed(connClosePacket) 1657 } 1658 1659 func (s *connection) dropEncryptionLevel(encLevel protocol.EncryptionLevel) error { 1660 if s.tracer != nil && s.tracer.DroppedEncryptionLevel != nil { 1661 s.tracer.DroppedEncryptionLevel(encLevel) 1662 } 1663 s.sentPacketHandler.DropPackets(encLevel) 1664 s.receivedPacketHandler.DropPackets(encLevel) 1665 //nolint:exhaustive // only Initial and 0-RTT need special treatment 1666 switch encLevel { 1667 case protocol.EncryptionInitial: 1668 s.droppedInitialKeys = true 1669 s.cryptoStreamHandler.DiscardInitialKeys() 1670 case protocol.Encryption0RTT: 1671 s.streamsMap.ResetFor0RTT() 1672 if err := s.connFlowController.Reset(); err != nil { 1673 return err 1674 } 1675 return s.framer.Handle0RTTRejection() 1676 } 1677 return s.cryptoStreamManager.Drop(encLevel) 1678 } 1679 1680 // is called for the client, when restoring transport parameters saved for 0-RTT 1681 func (s *connection) restoreTransportParameters(params *wire.TransportParameters) { 1682 if s.logger.Debug() { 1683 s.logger.Debugf("Restoring Transport Parameters: %s", params) 1684 } 1685 1686 s.peerParams = params 1687 s.connIDGenerator.SetMaxActiveConnIDs(params.ActiveConnectionIDLimit) 1688 s.connFlowController.UpdateSendWindow(params.InitialMaxData) 1689 s.streamsMap.UpdateLimits(params) 1690 s.connStateMutex.Lock() 1691 s.connState.SupportsDatagrams = s.supportsDatagrams() 1692 s.connStateMutex.Unlock() 1693 } 1694 1695 func (s *connection) handleTransportParameters(params *wire.TransportParameters) error { 1696 if s.tracer != nil && s.tracer.ReceivedTransportParameters != nil { 1697 s.tracer.ReceivedTransportParameters(params) 1698 } 1699 if err := s.checkTransportParameters(params); err != nil { 1700 return &qerr.TransportError{ 1701 ErrorCode: qerr.TransportParameterError, 1702 ErrorMessage: err.Error(), 1703 } 1704 } 1705 1706 if s.perspective == protocol.PerspectiveClient && s.peerParams != nil && s.ConnectionState().Used0RTT && !params.ValidForUpdate(s.peerParams) { 1707 return &qerr.TransportError{ 1708 ErrorCode: qerr.ProtocolViolation, 1709 ErrorMessage: "server sent reduced limits after accepting 0-RTT data", 1710 } 1711 } 1712 1713 s.peerParams = params 1714 // On the client side we have to wait for handshake completion. 1715 // During a 0-RTT connection, we are only allowed to use the new transport parameters for 1-RTT packets. 1716 if s.perspective == protocol.PerspectiveServer { 1717 s.applyTransportParameters() 1718 // On the server side, the early connection is ready as soon as we processed 1719 // the client's transport parameters. 1720 close(s.earlyConnReadyChan) 1721 } 1722 1723 s.connStateMutex.Lock() 1724 s.connState.SupportsDatagrams = s.supportsDatagrams() 1725 s.connStateMutex.Unlock() 1726 return nil 1727 } 1728 1729 func (s *connection) checkTransportParameters(params *wire.TransportParameters) error { 1730 if s.logger.Debug() { 1731 s.logger.Debugf("Processed Transport Parameters: %s", params) 1732 } 1733 1734 // check the initial_source_connection_id 1735 if params.InitialSourceConnectionID != s.handshakeDestConnID { 1736 return fmt.Errorf("expected initial_source_connection_id to equal %s, is %s", s.handshakeDestConnID, params.InitialSourceConnectionID) 1737 } 1738 1739 if s.perspective == protocol.PerspectiveServer { 1740 return nil 1741 } 1742 // check the original_destination_connection_id 1743 if params.OriginalDestinationConnectionID != s.origDestConnID { 1744 return fmt.Errorf("expected original_destination_connection_id to equal %s, is %s", s.origDestConnID, params.OriginalDestinationConnectionID) 1745 } 1746 if s.retrySrcConnID != nil { // a Retry was performed 1747 if params.RetrySourceConnectionID == nil { 1748 return errors.New("missing retry_source_connection_id") 1749 } 1750 if *params.RetrySourceConnectionID != *s.retrySrcConnID { 1751 return fmt.Errorf("expected retry_source_connection_id to equal %s, is %s", s.retrySrcConnID, *params.RetrySourceConnectionID) 1752 } 1753 } else if params.RetrySourceConnectionID != nil { 1754 return errors.New("received retry_source_connection_id, although no Retry was performed") 1755 } 1756 return nil 1757 } 1758 1759 func (s *connection) applyTransportParameters() { 1760 params := s.peerParams 1761 // Our local idle timeout will always be > 0. 1762 s.idleTimeout = utils.MinNonZeroDuration(s.config.MaxIdleTimeout, params.MaxIdleTimeout) 1763 s.keepAliveInterval = min(s.config.KeepAlivePeriod, min(s.idleTimeout/2, protocol.MaxKeepAliveInterval)) 1764 s.streamsMap.UpdateLimits(params) 1765 s.frameParser.SetAckDelayExponent(params.AckDelayExponent) 1766 s.connFlowController.UpdateSendWindow(params.InitialMaxData) 1767 s.rttStats.SetMaxAckDelay(params.MaxAckDelay) 1768 s.connIDGenerator.SetMaxActiveConnIDs(params.ActiveConnectionIDLimit) 1769 if params.StatelessResetToken != nil { 1770 s.connIDManager.SetStatelessResetToken(*params.StatelessResetToken) 1771 } 1772 // We don't support connection migration yet, so we don't have any use for the preferred_address. 1773 if params.PreferredAddress != nil { 1774 // Retire the connection ID. 1775 s.connIDManager.AddFromPreferredAddress(params.PreferredAddress.ConnectionID, params.PreferredAddress.StatelessResetToken) 1776 } 1777 maxPacketSize := protocol.ByteCount(protocol.MaxPacketBufferSize) 1778 if params.MaxUDPPayloadSize > 0 && params.MaxUDPPayloadSize < maxPacketSize { 1779 maxPacketSize = params.MaxUDPPayloadSize 1780 } 1781 s.mtuDiscoverer = newMTUDiscoverer( 1782 s.rttStats, 1783 protocol.ByteCount(s.config.InitialPacketSize), 1784 maxPacketSize, 1785 s.onMTUIncreased, 1786 s.tracer, 1787 ) 1788 } 1789 1790 func (s *connection) triggerSending(now time.Time) error { 1791 s.pacingDeadline = time.Time{} 1792 1793 sendMode := s.sentPacketHandler.SendMode(now) 1794 //nolint:exhaustive // No need to handle pacing limited here. 1795 switch sendMode { 1796 case ackhandler.SendAny: 1797 return s.sendPackets(now) 1798 case ackhandler.SendNone: 1799 return nil 1800 case ackhandler.SendPacingLimited: 1801 deadline := s.sentPacketHandler.TimeUntilSend() 1802 if deadline.IsZero() { 1803 deadline = deadlineSendImmediately 1804 } 1805 s.pacingDeadline = deadline 1806 // Allow sending of an ACK if we're pacing limit. 1807 // This makes sure that a peer that is mostly receiving data (and thus has an inaccurate cwnd estimate) 1808 // sends enough ACKs to allow its peer to utilize the bandwidth. 1809 fallthrough 1810 case ackhandler.SendAck: 1811 // We can at most send a single ACK only packet. 1812 // There will only be a new ACK after receiving new packets. 1813 // SendAck is only returned when we're congestion limited, so we don't need to set the pacinggs timer. 1814 return s.maybeSendAckOnlyPacket(now) 1815 case ackhandler.SendPTOInitial: 1816 if err := s.sendProbePacket(protocol.EncryptionInitial, now); err != nil { 1817 return err 1818 } 1819 if s.sendQueue.WouldBlock() { 1820 s.scheduleSending() 1821 return nil 1822 } 1823 return s.triggerSending(now) 1824 case ackhandler.SendPTOHandshake: 1825 if err := s.sendProbePacket(protocol.EncryptionHandshake, now); err != nil { 1826 return err 1827 } 1828 if s.sendQueue.WouldBlock() { 1829 s.scheduleSending() 1830 return nil 1831 } 1832 return s.triggerSending(now) 1833 case ackhandler.SendPTOAppData: 1834 if err := s.sendProbePacket(protocol.Encryption1RTT, now); err != nil { 1835 return err 1836 } 1837 if s.sendQueue.WouldBlock() { 1838 s.scheduleSending() 1839 return nil 1840 } 1841 return s.triggerSending(now) 1842 default: 1843 return fmt.Errorf("BUG: invalid send mode %d", sendMode) 1844 } 1845 } 1846 1847 func (s *connection) sendPackets(now time.Time) error { 1848 // Path MTU Discovery 1849 // Can't use GSO, since we need to send a single packet that's larger than our current maximum size. 1850 // Performance-wise, this doesn't matter, since we only send a very small (<10) number of 1851 // MTU probe packets per connection. 1852 if s.handshakeConfirmed && s.mtuDiscoverer != nil && s.mtuDiscoverer.ShouldSendProbe(now) { 1853 ping, size := s.mtuDiscoverer.GetPing() 1854 p, buf, err := s.packer.PackMTUProbePacket(ping, size, s.version) 1855 if err != nil { 1856 return err 1857 } 1858 ecn := s.sentPacketHandler.ECNMode(true) 1859 s.logShortHeaderPacket(p.DestConnID, p.Ack, p.Frames, p.StreamFrames, p.PacketNumber, p.PacketNumberLen, p.KeyPhase, ecn, buf.Len(), false) 1860 s.registerPackedShortHeaderPacket(p, ecn, now) 1861 s.sendQueue.Send(buf, 0, ecn) 1862 // This is kind of a hack. We need to trigger sending again somehow. 1863 s.pacingDeadline = deadlineSendImmediately 1864 return nil 1865 } 1866 1867 if isBlocked, offset := s.connFlowController.IsNewlyBlocked(); isBlocked { 1868 s.framer.QueueControlFrame(&wire.DataBlockedFrame{MaximumData: offset}) 1869 } 1870 s.windowUpdateQueue.QueueAll() 1871 if cf := s.cryptoStreamManager.GetPostHandshakeData(protocol.MaxPostHandshakeCryptoFrameSize); cf != nil { 1872 s.queueControlFrame(cf) 1873 } 1874 1875 if !s.handshakeConfirmed { 1876 packet, err := s.packer.PackCoalescedPacket(false, s.maxPacketSize(), s.version) 1877 if err != nil || packet == nil { 1878 return err 1879 } 1880 s.sentFirstPacket = true 1881 if err := s.sendPackedCoalescedPacket(packet, s.sentPacketHandler.ECNMode(packet.IsOnlyShortHeaderPacket()), now); err != nil { 1882 return err 1883 } 1884 sendMode := s.sentPacketHandler.SendMode(now) 1885 if sendMode == ackhandler.SendPacingLimited { 1886 s.resetPacingDeadline() 1887 } else if sendMode == ackhandler.SendAny { 1888 s.pacingDeadline = deadlineSendImmediately 1889 } 1890 return nil 1891 } 1892 1893 if s.conn.capabilities().GSO { 1894 return s.sendPacketsWithGSO(now) 1895 } 1896 return s.sendPacketsWithoutGSO(now) 1897 } 1898 1899 func (s *connection) sendPacketsWithoutGSO(now time.Time) error { 1900 for { 1901 buf := getPacketBuffer() 1902 ecn := s.sentPacketHandler.ECNMode(true) 1903 if _, err := s.appendOneShortHeaderPacket(buf, s.maxPacketSize(), ecn, now); err != nil { 1904 if err == errNothingToPack { 1905 buf.Release() 1906 return nil 1907 } 1908 return err 1909 } 1910 1911 s.sendQueue.Send(buf, 0, ecn) 1912 1913 if s.sendQueue.WouldBlock() { 1914 return nil 1915 } 1916 sendMode := s.sentPacketHandler.SendMode(now) 1917 if sendMode == ackhandler.SendPacingLimited { 1918 s.resetPacingDeadline() 1919 return nil 1920 } 1921 if sendMode != ackhandler.SendAny { 1922 return nil 1923 } 1924 // Prioritize receiving of packets over sending out more packets. 1925 if len(s.receivedPackets) > 0 { 1926 s.pacingDeadline = deadlineSendImmediately 1927 return nil 1928 } 1929 } 1930 } 1931 1932 func (s *connection) sendPacketsWithGSO(now time.Time) error { 1933 buf := getLargePacketBuffer() 1934 maxSize := s.maxPacketSize() 1935 1936 ecn := s.sentPacketHandler.ECNMode(true) 1937 for { 1938 var dontSendMore bool 1939 size, err := s.appendOneShortHeaderPacket(buf, maxSize, ecn, now) 1940 if err != nil { 1941 if err != errNothingToPack { 1942 return err 1943 } 1944 if buf.Len() == 0 { 1945 buf.Release() 1946 return nil 1947 } 1948 dontSendMore = true 1949 } 1950 1951 if !dontSendMore { 1952 sendMode := s.sentPacketHandler.SendMode(now) 1953 if sendMode == ackhandler.SendPacingLimited { 1954 s.resetPacingDeadline() 1955 } 1956 if sendMode != ackhandler.SendAny { 1957 dontSendMore = true 1958 } 1959 } 1960 1961 // Don't send more packets in this batch if they require a different ECN marking than the previous ones. 1962 nextECN := s.sentPacketHandler.ECNMode(true) 1963 1964 // Append another packet if 1965 // 1. The congestion controller and pacer allow sending more 1966 // 2. The last packet appended was a full-size packet 1967 // 3. The next packet will have the same ECN marking 1968 // 4. We still have enough space for another full-size packet in the buffer 1969 if !dontSendMore && size == maxSize && nextECN == ecn && buf.Len()+maxSize <= buf.Cap() { 1970 continue 1971 } 1972 1973 s.sendQueue.Send(buf, uint16(maxSize), ecn) 1974 1975 if dontSendMore { 1976 return nil 1977 } 1978 if s.sendQueue.WouldBlock() { 1979 return nil 1980 } 1981 1982 // Prioritize receiving of packets over sending out more packets. 1983 if len(s.receivedPackets) > 0 { 1984 s.pacingDeadline = deadlineSendImmediately 1985 return nil 1986 } 1987 1988 buf = getLargePacketBuffer() 1989 } 1990 } 1991 1992 func (s *connection) resetPacingDeadline() { 1993 deadline := s.sentPacketHandler.TimeUntilSend() 1994 if deadline.IsZero() { 1995 deadline = deadlineSendImmediately 1996 } 1997 s.pacingDeadline = deadline 1998 } 1999 2000 func (s *connection) maybeSendAckOnlyPacket(now time.Time) error { 2001 if !s.handshakeConfirmed { 2002 ecn := s.sentPacketHandler.ECNMode(false) 2003 packet, err := s.packer.PackCoalescedPacket(true, s.maxPacketSize(), s.version) 2004 if err != nil { 2005 return err 2006 } 2007 if packet == nil { 2008 return nil 2009 } 2010 return s.sendPackedCoalescedPacket(packet, ecn, now) 2011 } 2012 2013 ecn := s.sentPacketHandler.ECNMode(true) 2014 p, buf, err := s.packer.PackAckOnlyPacket(s.maxPacketSize(), s.version) 2015 if err != nil { 2016 if err == errNothingToPack { 2017 return nil 2018 } 2019 return err 2020 } 2021 s.logShortHeaderPacket(p.DestConnID, p.Ack, p.Frames, p.StreamFrames, p.PacketNumber, p.PacketNumberLen, p.KeyPhase, ecn, buf.Len(), false) 2022 s.registerPackedShortHeaderPacket(p, ecn, now) 2023 s.sendQueue.Send(buf, 0, ecn) 2024 return nil 2025 } 2026 2027 func (s *connection) sendProbePacket(encLevel protocol.EncryptionLevel, now time.Time) error { 2028 // Queue probe packets until we actually send out a packet, 2029 // or until there are no more packets to queue. 2030 var packet *coalescedPacket 2031 for { 2032 if wasQueued := s.sentPacketHandler.QueueProbePacket(encLevel); !wasQueued { 2033 break 2034 } 2035 var err error 2036 packet, err = s.packer.MaybePackProbePacket(encLevel, s.maxPacketSize(), s.version) 2037 if err != nil { 2038 return err 2039 } 2040 if packet != nil { 2041 break 2042 } 2043 } 2044 if packet == nil { 2045 s.retransmissionQueue.AddPing(encLevel) 2046 var err error 2047 packet, err = s.packer.MaybePackProbePacket(encLevel, s.maxPacketSize(), s.version) 2048 if err != nil { 2049 return err 2050 } 2051 } 2052 if packet == nil || (len(packet.longHdrPackets) == 0 && packet.shortHdrPacket == nil) { 2053 return fmt.Errorf("connection BUG: couldn't pack %s probe packet", encLevel) 2054 } 2055 return s.sendPackedCoalescedPacket(packet, s.sentPacketHandler.ECNMode(packet.IsOnlyShortHeaderPacket()), now) 2056 } 2057 2058 // appendOneShortHeaderPacket appends a new packet to the given packetBuffer. 2059 // If there was nothing to pack, the returned size is 0. 2060 func (s *connection) appendOneShortHeaderPacket(buf *packetBuffer, maxSize protocol.ByteCount, ecn protocol.ECN, now time.Time) (protocol.ByteCount, error) { 2061 startLen := buf.Len() 2062 p, err := s.packer.AppendPacket(buf, maxSize, s.version) 2063 if err != nil { 2064 return 0, err 2065 } 2066 size := buf.Len() - startLen 2067 s.logShortHeaderPacket(p.DestConnID, p.Ack, p.Frames, p.StreamFrames, p.PacketNumber, p.PacketNumberLen, p.KeyPhase, ecn, size, false) 2068 s.registerPackedShortHeaderPacket(p, ecn, now) 2069 return size, nil 2070 } 2071 2072 func (s *connection) registerPackedShortHeaderPacket(p shortHeaderPacket, ecn protocol.ECN, now time.Time) { 2073 if s.firstAckElicitingPacketAfterIdleSentTime.IsZero() && (len(p.StreamFrames) > 0 || ackhandler.HasAckElicitingFrames(p.Frames)) { 2074 s.firstAckElicitingPacketAfterIdleSentTime = now 2075 } 2076 2077 largestAcked := protocol.InvalidPacketNumber 2078 if p.Ack != nil { 2079 largestAcked = p.Ack.LargestAcked() 2080 } 2081 s.sentPacketHandler.SentPacket(now, p.PacketNumber, largestAcked, p.StreamFrames, p.Frames, protocol.Encryption1RTT, ecn, p.Length, p.IsPathMTUProbePacket) 2082 s.connIDManager.SentPacket() 2083 } 2084 2085 func (s *connection) sendPackedCoalescedPacket(packet *coalescedPacket, ecn protocol.ECN, now time.Time) error { 2086 s.logCoalescedPacket(packet, ecn) 2087 for _, p := range packet.longHdrPackets { 2088 if s.firstAckElicitingPacketAfterIdleSentTime.IsZero() && p.IsAckEliciting() { 2089 s.firstAckElicitingPacketAfterIdleSentTime = now 2090 } 2091 largestAcked := protocol.InvalidPacketNumber 2092 if p.ack != nil { 2093 largestAcked = p.ack.LargestAcked() 2094 } 2095 s.sentPacketHandler.SentPacket(now, p.header.PacketNumber, largestAcked, p.streamFrames, p.frames, p.EncryptionLevel(), ecn, p.length, false) 2096 if s.perspective == protocol.PerspectiveClient && p.EncryptionLevel() == protocol.EncryptionHandshake && 2097 !s.droppedInitialKeys { 2098 // On the client side, Initial keys are dropped as soon as the first Handshake packet is sent. 2099 // See Section 4.9.1 of RFC 9001. 2100 if err := s.dropEncryptionLevel(protocol.EncryptionInitial); err != nil { 2101 return err 2102 } 2103 } 2104 } 2105 if p := packet.shortHdrPacket; p != nil { 2106 if s.firstAckElicitingPacketAfterIdleSentTime.IsZero() && p.IsAckEliciting() { 2107 s.firstAckElicitingPacketAfterIdleSentTime = now 2108 } 2109 largestAcked := protocol.InvalidPacketNumber 2110 if p.Ack != nil { 2111 largestAcked = p.Ack.LargestAcked() 2112 } 2113 s.sentPacketHandler.SentPacket(now, p.PacketNumber, largestAcked, p.StreamFrames, p.Frames, protocol.Encryption1RTT, ecn, p.Length, p.IsPathMTUProbePacket) 2114 } 2115 s.connIDManager.SentPacket() 2116 s.sendQueue.Send(packet.buffer, 0, ecn) 2117 return nil 2118 } 2119 2120 func (s *connection) sendConnectionClose(e error) ([]byte, error) { 2121 var packet *coalescedPacket 2122 var err error 2123 var transportErr *qerr.TransportError 2124 var applicationErr *qerr.ApplicationError 2125 if errors.As(e, &transportErr) { 2126 packet, err = s.packer.PackConnectionClose(transportErr, s.maxPacketSize(), s.version) 2127 } else if errors.As(e, &applicationErr) { 2128 packet, err = s.packer.PackApplicationClose(applicationErr, s.maxPacketSize(), s.version) 2129 } else { 2130 packet, err = s.packer.PackConnectionClose(&qerr.TransportError{ 2131 ErrorCode: qerr.InternalError, 2132 ErrorMessage: fmt.Sprintf("connection BUG: unspecified error type (msg: %s)", e.Error()), 2133 }, s.maxPacketSize(), s.version) 2134 } 2135 if err != nil { 2136 return nil, err 2137 } 2138 ecn := s.sentPacketHandler.ECNMode(packet.IsOnlyShortHeaderPacket()) 2139 s.logCoalescedPacket(packet, ecn) 2140 return packet.buffer.Data, s.conn.Write(packet.buffer.Data, 0, ecn) 2141 } 2142 2143 func (s *connection) maxPacketSize() protocol.ByteCount { 2144 if s.mtuDiscoverer == nil { 2145 // Use the configured packet size on the client side. 2146 // If the server sends a max_udp_payload_size that's smaller than this size, we can ignore this: 2147 // Apparently the server still processed the (fully padded) Initial packet anyway. 2148 if s.perspective == protocol.PerspectiveClient { 2149 return protocol.ByteCount(s.config.InitialPacketSize) 2150 } 2151 // On the server side, there's no downside to using 1200 bytes until we received the client's transport 2152 // parameters: 2153 // * If the first packet didn't contain the entire ClientHello, all we can do is ACK that packet. We don't 2154 // need a lot of bytes for that. 2155 // * If it did, we will have processed the transport parameters and initialized the MTU discoverer. 2156 return protocol.MinInitialPacketSize 2157 } 2158 return s.mtuDiscoverer.CurrentSize() 2159 } 2160 2161 func (s *connection) logLongHeaderPacket(p *longHeaderPacket, ecn protocol.ECN) { 2162 // quic-go logging 2163 if s.logger.Debug() { 2164 p.header.Log(s.logger) 2165 if p.ack != nil { 2166 wire.LogFrame(s.logger, p.ack, true) 2167 } 2168 for _, frame := range p.frames { 2169 wire.LogFrame(s.logger, frame.Frame, true) 2170 } 2171 for _, frame := range p.streamFrames { 2172 wire.LogFrame(s.logger, frame.Frame, true) 2173 } 2174 } 2175 2176 // tracing 2177 if s.tracer != nil && s.tracer.SentLongHeaderPacket != nil { 2178 frames := make([]logging.Frame, 0, len(p.frames)) 2179 for _, f := range p.frames { 2180 frames = append(frames, logutils.ConvertFrame(f.Frame)) 2181 } 2182 for _, f := range p.streamFrames { 2183 frames = append(frames, logutils.ConvertFrame(f.Frame)) 2184 } 2185 var ack *logging.AckFrame 2186 if p.ack != nil { 2187 ack = logutils.ConvertAckFrame(p.ack) 2188 } 2189 s.tracer.SentLongHeaderPacket(p.header, p.length, ecn, ack, frames) 2190 } 2191 } 2192 2193 func (s *connection) logShortHeaderPacket( 2194 destConnID protocol.ConnectionID, 2195 ackFrame *wire.AckFrame, 2196 frames []ackhandler.Frame, 2197 streamFrames []ackhandler.StreamFrame, 2198 pn protocol.PacketNumber, 2199 pnLen protocol.PacketNumberLen, 2200 kp protocol.KeyPhaseBit, 2201 ecn protocol.ECN, 2202 size protocol.ByteCount, 2203 isCoalesced bool, 2204 ) { 2205 if s.logger.Debug() && !isCoalesced { 2206 s.logger.Debugf("-> Sending packet %d (%d bytes) for connection %s, 1-RTT (ECN: %s)", pn, size, s.logID, ecn) 2207 } 2208 // quic-go logging 2209 if s.logger.Debug() { 2210 wire.LogShortHeader(s.logger, destConnID, pn, pnLen, kp) 2211 if ackFrame != nil { 2212 wire.LogFrame(s.logger, ackFrame, true) 2213 } 2214 for _, f := range frames { 2215 wire.LogFrame(s.logger, f.Frame, true) 2216 } 2217 for _, f := range streamFrames { 2218 wire.LogFrame(s.logger, f.Frame, true) 2219 } 2220 } 2221 2222 // tracing 2223 if s.tracer != nil && s.tracer.SentShortHeaderPacket != nil { 2224 fs := make([]logging.Frame, 0, len(frames)+len(streamFrames)) 2225 for _, f := range frames { 2226 fs = append(fs, logutils.ConvertFrame(f.Frame)) 2227 } 2228 for _, f := range streamFrames { 2229 fs = append(fs, logutils.ConvertFrame(f.Frame)) 2230 } 2231 var ack *logging.AckFrame 2232 if ackFrame != nil { 2233 ack = logutils.ConvertAckFrame(ackFrame) 2234 } 2235 s.tracer.SentShortHeaderPacket( 2236 &logging.ShortHeader{ 2237 DestConnectionID: destConnID, 2238 PacketNumber: pn, 2239 PacketNumberLen: pnLen, 2240 KeyPhase: kp, 2241 }, 2242 size, 2243 ecn, 2244 ack, 2245 fs, 2246 ) 2247 } 2248 } 2249 2250 func (s *connection) logCoalescedPacket(packet *coalescedPacket, ecn protocol.ECN) { 2251 if s.logger.Debug() { 2252 // There's a short period between dropping both Initial and Handshake keys and completion of the handshake, 2253 // during which we might call PackCoalescedPacket but just pack a short header packet. 2254 if len(packet.longHdrPackets) == 0 && packet.shortHdrPacket != nil { 2255 s.logShortHeaderPacket( 2256 packet.shortHdrPacket.DestConnID, 2257 packet.shortHdrPacket.Ack, 2258 packet.shortHdrPacket.Frames, 2259 packet.shortHdrPacket.StreamFrames, 2260 packet.shortHdrPacket.PacketNumber, 2261 packet.shortHdrPacket.PacketNumberLen, 2262 packet.shortHdrPacket.KeyPhase, 2263 ecn, 2264 packet.shortHdrPacket.Length, 2265 false, 2266 ) 2267 return 2268 } 2269 if len(packet.longHdrPackets) > 1 { 2270 s.logger.Debugf("-> Sending coalesced packet (%d parts, %d bytes) for connection %s", len(packet.longHdrPackets), packet.buffer.Len(), s.logID) 2271 } else { 2272 s.logger.Debugf("-> Sending packet %d (%d bytes) for connection %s, %s", packet.longHdrPackets[0].header.PacketNumber, packet.buffer.Len(), s.logID, packet.longHdrPackets[0].EncryptionLevel()) 2273 } 2274 } 2275 for _, p := range packet.longHdrPackets { 2276 s.logLongHeaderPacket(p, ecn) 2277 } 2278 if p := packet.shortHdrPacket; p != nil { 2279 s.logShortHeaderPacket(p.DestConnID, p.Ack, p.Frames, p.StreamFrames, p.PacketNumber, p.PacketNumberLen, p.KeyPhase, ecn, p.Length, true) 2280 } 2281 } 2282 2283 // AcceptStream returns the next stream openend by the peer 2284 func (s *connection) AcceptStream(ctx context.Context) (Stream, error) { 2285 return s.streamsMap.AcceptStream(ctx) 2286 } 2287 2288 func (s *connection) AcceptUniStream(ctx context.Context) (ReceiveStream, error) { 2289 return s.streamsMap.AcceptUniStream(ctx) 2290 } 2291 2292 // OpenStream opens a stream 2293 func (s *connection) OpenStream() (Stream, error) { 2294 return s.streamsMap.OpenStream() 2295 } 2296 2297 func (s *connection) OpenStreamSync(ctx context.Context) (Stream, error) { 2298 return s.streamsMap.OpenStreamSync(ctx) 2299 } 2300 2301 func (s *connection) OpenUniStream() (SendStream, error) { 2302 return s.streamsMap.OpenUniStream() 2303 } 2304 2305 func (s *connection) OpenUniStreamSync(ctx context.Context) (SendStream, error) { 2306 return s.streamsMap.OpenUniStreamSync(ctx) 2307 } 2308 2309 func (s *connection) newFlowController(id protocol.StreamID) flowcontrol.StreamFlowController { 2310 initialSendWindow := s.peerParams.InitialMaxStreamDataUni 2311 if id.Type() == protocol.StreamTypeBidi { 2312 if id.InitiatedBy() == s.perspective { 2313 initialSendWindow = s.peerParams.InitialMaxStreamDataBidiRemote 2314 } else { 2315 initialSendWindow = s.peerParams.InitialMaxStreamDataBidiLocal 2316 } 2317 } 2318 return flowcontrol.NewStreamFlowController( 2319 id, 2320 s.connFlowController, 2321 protocol.ByteCount(s.config.InitialStreamReceiveWindow), 2322 protocol.ByteCount(s.config.MaxStreamReceiveWindow), 2323 initialSendWindow, 2324 s.onHasStreamWindowUpdate, 2325 s.rttStats, 2326 s.logger, 2327 ) 2328 } 2329 2330 // scheduleSending signals that we have data for sending 2331 func (s *connection) scheduleSending() { 2332 select { 2333 case s.sendingScheduled <- struct{}{}: 2334 default: 2335 } 2336 } 2337 2338 // tryQueueingUndecryptablePacket queues a packet for which we're missing the decryption keys. 2339 // The logging.PacketType is only used for logging purposes. 2340 func (s *connection) tryQueueingUndecryptablePacket(p receivedPacket, pt logging.PacketType) { 2341 if s.handshakeComplete { 2342 panic("shouldn't queue undecryptable packets after handshake completion") 2343 } 2344 if len(s.undecryptablePackets)+1 > protocol.MaxUndecryptablePackets { 2345 if s.tracer != nil && s.tracer.DroppedPacket != nil { 2346 s.tracer.DroppedPacket(pt, protocol.InvalidPacketNumber, p.Size(), logging.PacketDropDOSPrevention) 2347 } 2348 s.logger.Infof("Dropping undecryptable packet (%d bytes). Undecryptable packet queue full.", p.Size()) 2349 return 2350 } 2351 s.logger.Infof("Queueing packet (%d bytes) for later decryption", p.Size()) 2352 if s.tracer != nil && s.tracer.BufferedPacket != nil { 2353 s.tracer.BufferedPacket(pt, p.Size()) 2354 } 2355 s.undecryptablePackets = append(s.undecryptablePackets, p) 2356 } 2357 2358 func (s *connection) queueControlFrame(f wire.Frame) { 2359 s.framer.QueueControlFrame(f) 2360 s.scheduleSending() 2361 } 2362 2363 func (s *connection) onHasStreamWindowUpdate(id protocol.StreamID) { 2364 s.windowUpdateQueue.AddStream(id) 2365 s.scheduleSending() 2366 } 2367 2368 func (s *connection) onHasConnectionWindowUpdate() { 2369 s.windowUpdateQueue.AddConnection() 2370 s.scheduleSending() 2371 } 2372 2373 func (s *connection) onHasStreamData(id protocol.StreamID) { 2374 s.framer.AddActiveStream(id) 2375 s.scheduleSending() 2376 } 2377 2378 func (s *connection) onStreamCompleted(id protocol.StreamID) { 2379 if err := s.streamsMap.DeleteStream(id); err != nil { 2380 s.closeLocal(err) 2381 } 2382 } 2383 2384 func (s *connection) onMTUIncreased(mtu protocol.ByteCount) { 2385 s.maxPayloadSizeEstimate.Store(uint32(estimateMaxPayloadSize(mtu))) 2386 s.sentPacketHandler.SetMaxDatagramSize(mtu) 2387 } 2388 2389 func (s *connection) SendDatagram(p []byte) error { 2390 if !s.supportsDatagrams() { 2391 return errors.New("datagram support disabled") 2392 } 2393 2394 f := &wire.DatagramFrame{DataLenPresent: true} 2395 // The payload size estimate is conservative. 2396 // Under many circumstances we could send a few more bytes. 2397 maxDataLen := min( 2398 f.MaxDataLen(s.peerParams.MaxDatagramFrameSize, s.version), 2399 protocol.ByteCount(s.maxPayloadSizeEstimate.Load()), 2400 ) 2401 if protocol.ByteCount(len(p)) > maxDataLen { 2402 return &DatagramTooLargeError{MaxDatagramPayloadSize: int64(maxDataLen)} 2403 } 2404 f.Data = make([]byte, len(p)) 2405 copy(f.Data, p) 2406 return s.datagramQueue.Add(f) 2407 } 2408 2409 func (s *connection) ReceiveDatagram(ctx context.Context) ([]byte, error) { 2410 if !s.config.EnableDatagrams { 2411 return nil, errors.New("datagram support disabled") 2412 } 2413 return s.datagramQueue.Receive(ctx) 2414 } 2415 2416 func (s *connection) LocalAddr() net.Addr { 2417 return s.conn.LocalAddr() 2418 } 2419 2420 func (s *connection) RemoteAddr() net.Addr { 2421 return s.conn.RemoteAddr() 2422 } 2423 2424 func (s *connection) GetVersion() protocol.Version { 2425 return s.version 2426 } 2427 2428 func (s *connection) NextConnection() Connection { 2429 <-s.HandshakeComplete() 2430 s.streamsMap.UseResetMaps() 2431 return s 2432 } 2433 2434 // estimateMaxPayloadSize estimates the maximum payload size for short header packets. 2435 // It is not very sophisticated: it just subtracts the size of header (assuming the maximum 2436 // connection ID length), and the size of the encryption tag. 2437 func estimateMaxPayloadSize(mtu protocol.ByteCount) protocol.ByteCount { 2438 return mtu - 1 /* type byte */ - 20 /* maximum connection ID length */ - 16 /* tag size */ 2439 }