File
Blob: overlay/reuse.go
| 1 | package overlay |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | "time" |
| 7 | |
| 8 | "go.miragespace.co/specter/spec" |
| 9 | "go.miragespace.co/specter/spec/pki" |
| 10 | "go.miragespace.co/specter/spec/protocol" |
| 11 | "go.miragespace.co/specter/spec/rpc" |
| 12 | "go.miragespace.co/specter/spec/transport" |
| 13 | |
| 14 | "github.com/quic-go/quic-go" |
| 15 | "go.uber.org/zap" |
| 16 | ) |
| 17 | |
| 18 | const ( |
| 19 | reuseErrorState = "invalid state" |
| 20 | ) |
| 21 | |
| 22 | func wrapReuseError(msg string) error { |
| 23 | return fmt.Errorf("%s: %s", reuseErrorState, msg) |
| 24 | } |
| 25 | |
| 26 | func (t *QUIC) acquireNegotiation(ctx context.Context, q *quic.Conn, key string) (func(), error) { |
| 27 | for { |
| 28 | if err := ctx.Err(); err != nil { |
| 29 | return nil, err |
| 30 | } |
| 31 | if err := context.Cause(q.Context()); err != nil { |
| 32 | return nil, err |
| 33 | } |
| 34 | pending, loaded := t.negotiations.LoadOrStoreLazy(key, func() chan struct{} { return make(chan struct{}) }) |
| 35 | if !loaded { |
| 36 | return func() { |
| 37 | // Only the holder removes this entry. |
| 38 | t.negotiations.Delete(key) |
| 39 | close(pending) |
| 40 | }, nil |
| 41 | } |
| 42 | select { |
| 43 | case <-pending: |
| 44 | case <-ctx.Done(): |
| 45 | return nil, ctx.Err() |
| 46 | case <-q.Context().Done(): |
| 47 | return nil, context.Cause(q.Context()) |
| 48 | } |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | func (t *QUIC) reuseConnection(ctx context.Context, q *quic.Conn, s *quic.Stream, dir direction) (*nodeConnection, bool, error) { |
| 53 | // Setup owns the fresh connection until cancellation is disarmed under |
| 54 | // the cache lock. Once published, other callers may already be using it. |
| 55 | stopSetup := context.AfterFunc(ctx, func() { q.CloseWithError(406, "Connection setup canceled") }) |
| 56 | defer stopSetup() |
| 57 | |
| 58 | negotiation := &protocol.Connection{ |
| 59 | Identity: t.Endpoint, |
| 60 | Version: spec.BuildVersion, |
| 61 | } |
| 62 | |
| 63 | err := rpc.Send(s, negotiation) |
| 64 | if err != nil { |
| 65 | return nil, false, fmt.Errorf("error sending identity: %w", err) |
| 66 | } |
| 67 | negotiation.Reset() |
| 68 | |
| 69 | s.SetReadDeadline(time.Now().Add(quicConfig.HandshakeIdleTimeout)) |
| 70 | err = rpc.BoundedReceive(s, negotiation, 256) |
| 71 | if err != nil { |
| 72 | return nil, false, fmt.Errorf("error receiving identity: %w", err) |
| 73 | } |
| 74 | s.SetReadDeadline(time.Time{}) |
| 75 | |
| 76 | if t.UseCertificateIdentity { |
| 77 | chain := q.ConnectionState().TLS.VerifiedChains |
| 78 | if len(chain) == 0 || len(chain[0]) == 0 { |
| 79 | return nil, false, transport.ErrNoCertificate |
| 80 | } |
| 81 | cert := chain[0][0] |
| 82 | identity, err := pki.ExtractCertificateIdentity(cert) |
| 83 | if err != nil { |
| 84 | return nil, false, fmt.Errorf("extracting certificate identity: %w", err) |
| 85 | } |
| 86 | t.Logger.Debug("Using identify from certificate", zap.String("remote", q.RemoteAddr().String()), zap.Object("identity", identity)) |
| 87 | negotiation.Identity = identity.NodeIdentity() |
| 88 | } |
| 89 | |
| 90 | qKey := t.makeCachedKey(negotiation.GetIdentity()) |
| 91 | fresh := &nodeConnection{ |
| 92 | peer: negotiation.GetIdentity(), |
| 93 | quic: q, |
| 94 | direction: dir, |
| 95 | version: negotiation.GetVersion(), |
| 96 | } |
| 97 | |
| 98 | // Only one endpoint serializes negotiation, so competing connections cannot |
| 99 | // each observe FRESH and publish different winners. The first winner stays |
| 100 | // useful regardless of direction. Client identities come from certificates, |
| 101 | // so their server owns arbitration rather than comparing token addresses. |
| 102 | if t.UseCertificateIdentity || (t.VirtualTransport && t.Endpoint.GetAddress() > fresh.peer.GetAddress()) { |
| 103 | release, err := t.acquireNegotiation(ctx, q, qKey) |
| 104 | if err != nil { |
| 105 | return nil, false, err |
| 106 | } |
| 107 | defer release() |
| 108 | } |
| 109 | |
| 110 | negotiation.Reset() |
| 111 | |
| 112 | rUnlock := t.cachedMutex.RLock(qKey) |
| 113 | cache, cached := t.cachedConnections.Load(qKey) |
| 114 | selected := fresh |
| 115 | negotiation.CacheState = protocol.Connection_FRESH |
| 116 | if cached { |
| 117 | negotiation.CacheState = protocol.Connection_CACHED |
| 118 | selected = cache |
| 119 | } |
| 120 | negotiation.CacheDirection = protocol.Connection_INCOMING |
| 121 | if selected.direction == directionOutgoing { |
| 122 | negotiation.CacheDirection = protocol.Connection_OUTGOING |
| 123 | } |
| 124 | rUnlock() |
| 125 | |
| 126 | localState, localDirection := negotiation.CacheState, negotiation.CacheDirection |
| 127 | err = rpc.Send(s, negotiation) |
| 128 | if err != nil { |
| 129 | return nil, false, fmt.Errorf("error sending cache status: %w", err) |
| 130 | } |
| 131 | negotiation.Reset() |
| 132 | |
| 133 | s.SetReadDeadline(time.Now().Add(quicConfig.HandshakeIdleTimeout)) |
| 134 | err = rpc.BoundedReceive(s, negotiation, 8) |
| 135 | if err != nil { |
| 136 | return nil, false, fmt.Errorf("error receiving cache status: %w", err) |
| 137 | } |
| 138 | s.SetReadDeadline(time.Time{}) |
| 139 | |
| 140 | unlock := t.cachedMutex.Lock(qKey) |
| 141 | defer unlock() |
| 142 | |
| 143 | current, exists := t.cachedConnections.Load(qKey) |
| 144 | if exists != cached || current != cache { |
| 145 | return nil, false, wrapReuseError("cached connection changed during negotiation") |
| 146 | } |
| 147 | if cached && cache.quic.Context().Err() != nil { |
| 148 | return nil, false, wrapReuseError("cached connection closed during negotiation") |
| 149 | } |
| 150 | |
| 151 | if negotiation.CacheState != protocol.Connection_CACHED && negotiation.CacheState != protocol.Connection_FRESH { |
| 152 | return nil, false, fmt.Errorf("unknown transport cache state") |
| 153 | } |
| 154 | if negotiation.CacheDirection != protocol.Connection_INCOMING && negotiation.CacheDirection != protocol.Connection_OUTGOING { |
| 155 | return nil, false, fmt.Errorf("unknown transport cache direction") |
| 156 | } |
| 157 | // Agreement requires the same cache state and opposite ends of one connection. |
| 158 | if negotiation.CacheState != localState || negotiation.CacheDirection == localDirection { |
| 159 | return nil, false, wrapReuseError(fmt.Sprintf("peer reports %s/%s; local state is %s/%s", |
| 160 | negotiation.CacheState, negotiation.CacheDirection, localState, localDirection)) |
| 161 | } |
| 162 | if cached { |
| 163 | // Only the outgoing side closes the unused candidate. |
| 164 | if cache.direction == directionOutgoing { |
| 165 | fresh.quic.CloseWithError(508, wrapReuseError("previously cached connection was reused").Error()) |
| 166 | } |
| 167 | return cache, true, nil |
| 168 | } |
| 169 | if !stopSetup() { |
| 170 | return nil, false, ctx.Err() |
| 171 | } |
| 172 | t.cachedConnections.Store(qKey, fresh) |
| 173 | return fresh, false, nil |
| 174 | } |