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