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