From c591236dea779e51570cc2d5e87ddd66401c22cd Mon Sep 17 00:00:00 2001 From: Maximilian Rink Date: Fri, 30 Oct 2026 15:17:34 +0100 Subject: [PATCH] server: close the losing incoming connection when its OPEN arrives Since b841cb71, when the peer's OPEN arrives on our outgoing connection while the incoming connection is in OpenSent and has no OPEN yet, and we have the higher BGP Identifier, opensent() sends Cease/Connection Collision Resolution on the incoming connection at once and closes it. RFC 4271 Section 6.8 detects a collision when an OPEN arrives: Upon receipt of an OPEN message, the local system MUST examine all of its connections that are in the OpenConfirm state. The peer has not sent its OPEN on that connection yet, so it does not see the close as the losing side of a collision. FRR connects again. With graceful restart negotiated, the new connection arrives while the session on our connection is Established and is handled as a restart of the peer (RFC 4724 Section 4.2), so the session goes down a second time. In a lab with FRR 10.x, every carrier fault caused two session drops instead of one (confirmed with packet captures). Keep the losing incoming connection open until the peer's first message arrives on it. trackCollisionLoser takes over its recv goroutine, so a message that is partly read is not cut, and answers that message as OpenSent does (RFC 4271 Section 8.2.2): the message error, the OPEN Message Error, the FSM Error, no answer to a version error, but a valid OPEN gets Cease/Connection Collision Resolution. The BGP Identifiers were compared at the OPEN on our connection; both OPENs of a real peer carry the same one. What it sends is not counted for the session, which runs on the other connection; the message it receives is still counted in the session's received message counters, as recvMessageWithError() counts every message it reads. The connection is also closed when the peer closes it, when its OpenSent hold timer expires and when the handler stops. The hold timer is the one opensent() started for the connection; it is not restarted at the collision. twoByteAsTrans and isTreatAsWithdraw become atomic: the recv goroutine of the losing connection outlives OpenSent and reads them in recvMessageWithError, while stateChange() writes them under fsm.lock on the way to Established. TestFSMHandlerOpensent_OutgoingOpenFirst now expects the Cease on the incoming connection after the peer's OPEN on it. Fixes #3863 Signed-off-by: Maximilian Rink Assisted-by: Claude Opus 5.5 --- pkg/server/collision_test.go | 291 +++++++++++++++++++++++++++++++++++ pkg/server/fsm.go | 98 ++++++++---- pkg/server/fsm_test.go | 12 +- 3 files changed, 371 insertions(+), 30 deletions(-) create mode 100644 pkg/server/collision_test.go diff --git a/pkg/server/collision_test.go b/pkg/server/collision_test.go new file mode 100644 index 000000000..d1b99b99f --- /dev/null +++ b/pkg/server/collision_test.go @@ -0,0 +1,291 @@ +package server + +import ( + "context" + "encoding/binary" + "io" + "net" + "net/netip" + "strconv" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/require" + "go.uber.org/goleak" + + "github.com/osrg/gobgp/v4/api" + "github.com/osrg/gobgp/v4/pkg/packet/bgp" +) + +// scriptedPeer is the remote side of a connection collision: it plays the +// BGP messages of a peer by hand on two TCP connections. +type scriptedPeer struct { + t *testing.T + asn uint32 + id netip.Addr +} + +func (p *scriptedPeer) write(c net.Conn, m *bgp.BGPMessage) { + p.t.Helper() + b, err := m.Serialize() + require.NoError(p.t, err) + _, err = c.Write(b) + require.NoError(p.t, err) +} + +func (p *scriptedPeer) open() *bgp.BGPMessage { + p.t.Helper() + m, err := bgp.NewBGPOpenMessage(uint16(p.asn), 90, p.id, []bgp.OptionParameterInterface{ + bgp.NewOptionParameterCapability([]bgp.ParameterCapabilityInterface{ + bgp.NewCapMultiProtocol(bgp.RF_IPv4_UC), + bgp.NewCapFourOctetASNumber(p.asn), + }), + }) + require.NoError(p.t, err) + return m +} + +// read returns the next BGP message on c. +func (p *scriptedPeer) read(c net.Conn) *bgp.BGPMessage { + p.t.Helper() + require.NoError(p.t, c.SetReadDeadline(time.Now().Add(10*time.Second))) + hdr := make([]byte, bgp.BGP_HEADER_LENGTH) + _, err := io.ReadFull(c, hdr) + require.NoError(p.t, err) + body := make([]byte, int(binary.BigEndian.Uint16(hdr[16:18]))-bgp.BGP_HEADER_LENGTH) + _, err = io.ReadFull(c, body) + require.NoError(p.t, err) + m, err := bgp.ParseBGPMessage(append(hdr, body...)) + require.NoError(p.t, err) + return m +} + +func (p *scriptedPeer) expect(c net.Conn, typ uint8) *bgp.BGPMessage { + p.t.Helper() + m := p.read(c) + require.Equal(p.t, typ, m.Header.Type, "message %v", m.Body) + return m +} + +// RFC 4271 Section 6.8 detects a collision when an OPEN arrives, so GoBGP +// must not close the peer's connection before the peer's OPEN arrived on it. +// Here GoBGP (dominant) gets the peer's OPEN on its own connection (A) first +// and is Established there, while the peer's connection (B) has no OPEN yet. +// FRR answers an early close of B by connecting again, and with graceful +// restart that new connection ends the session (BOOTy CI: two drops per +// fault). GoBGP keeps B open, answers the OPEN on B with Cease/Connection +// Collision Resolution, and the session on A stays: exactly one. +func TestCollisionLoserClosedOnlyAfterItsOpen(t *testing.T) { + ctx := t.Context() + lc := &net.ListenConfig{} + peerL, err := lc.Listen(ctx, "tcp4", "127.0.0.1:0") + require.NoError(t, err) + t.Cleanup(func() { peerL.Close() }) + l, err := lc.Listen(ctx, "tcp4", "127.0.0.1:0") + require.NoError(t, err) + gobgpPort := l.Addr().(*net.TCPAddr).Port + require.NoError(t, l.Close()) + + s := NewBgpServer() + go s.Serve() + require.NoError(t, s.StartBgp(ctx, &api.StartBgpRequest{Global: &api.Global{ + Asn: 65001, RouterId: "192.0.2.17", ListenPort: int32(gobgpPort), ListenAddresses: []string{"127.0.0.1"}, + }})) + t.Cleanup(func() { _ = s.StopBgp(context.Background(), &api.StopBgpRequest{}) }) + p := &scriptedPeer{t: t, asn: 65002, id: netip.MustParseAddr("10.0.0.1")} + require.NoError(t, s.AddPeer(ctx, &api.AddPeerRequest{Peer: &api.Peer{ + Conf: &api.PeerConf{NeighborAddress: "127.0.0.1", PeerAsn: 65002}, + Transport: &api.Transport{RemotePort: uint32(peerL.Addr().(*net.TCPAddr).Port)}, + Timers: &api.Timers{Config: &api.TimersConfig{IdleHoldTimeAfterReset: 1}}, + }})) + + a, err := peerL.Accept() + require.NoError(t, err) + t.Cleanup(func() { a.Close() }) + p.expect(a, bgp.BGP_MSG_OPEN) + b, err := (&net.Dialer{}).DialContext(ctx, "tcp4", net.JoinHostPort("127.0.0.1", strconv.Itoa(gobgpPort))) + require.NoError(t, err) + t.Cleanup(func() { b.Close() }) + p.expect(b, bgp.BGP_MSG_OPEN) // GoBGP is in OpenSent on B + + w := newPeerStateWaiter(s, api.PeerState_SESSION_STATE_ESTABLISHED) + oa, err := p.open().Serialize() + require.NoError(t, err) + ka, err := bgp.NewBGPKeepAliveMessage().Serialize() + require.NoError(t, err) + _, err = a.Write(append(oa, ka...)) + require.NoError(t, err) + p.expect(a, bgp.BGP_MSG_KEEPALIVE) + w.Wait(t, 5*time.Second) + + // B is still open: no message and no close before the peer's OPEN. + require.NoError(t, b.SetReadDeadline(time.Now().Add(300*time.Millisecond))) + _, err = b.Read(make([]byte, 1)) + var ne net.Error + require.ErrorAs(t, err, &ne, "GoBGP closed the peer's connection before its OPEN: %v", err) + require.True(t, ne.Timeout()) + + // The peer's OPEN on B: GoBGP closes B as the collision loser. + p.write(b, p.open()) + m := p.expect(b, bgp.BGP_MSG_NOTIFICATION) + n := m.Body.(*bgp.BGPNotification) + require.Equal(t, uint8(bgp.BGP_ERROR_CEASE), n.ErrorCode) + require.Equal(t, uint8(bgp.BGP_ERROR_SUB_CONNECTION_COLLISION_RESOLUTION), n.ErrorSubcode) + + // Exactly one session, which stays up. + var peer *api.Peer + require.Never(t, func() bool { + _ = s.ListPeer(ctx, &api.ListPeerRequest{}, func(p *api.Peer) { peer = p }) + return peer.GetState().GetSessionState() != api.PeerState_SESSION_STATE_ESTABLISHED + }, 500*time.Millisecond, 20*time.Millisecond) + var established uint32 + require.NoError(t, s.mgmtOperation(func() error { + established = s.neighborMap[netip.MustParseAddr("127.0.0.1")].fsm.pConf.ReadOnly().State.EstablishedCount + return nil + }, false)) + require.Equal(t, uint32(1), established, "sessions established") +} + +// loserOpensent runs opensent() on the incoming connection with GoBGP +// dominant (RFC 4271 Section 6.8). before is written on the incoming +// connection, then the peer's OPEN arrives on the outgoing connection, and +// the incoming connection loses the collision before the peer's OPEN +// arrived on it, delay after opensent() started. It returns the incoming +// connection, a function that stops the handler, and a goleak option that +// ignores the goroutines that existed before opensent(). +func loserOpensent(t *testing.T, before []byte, holdTime float64, delay time.Duration) (*peer, *MockConnection, context.CancelFunc, goleak.Option) { + t.Helper() + incoming := NewMockConnection() + outgoing := NewMockConnection() + p, h := makePeerAndHandler(incoming) + t.Cleanup(func() { + cleanPeerAndHandler(p, h) + incoming.Close() + outgoing.Close() + }) + p.fsm.opensentHoldTime = holdTime + p.fsm.gConf.Config.RouterId = netip.MustParseAddr("10.0.0.9") + conf := p.fsm.pConf.ReadCopy() + conf.Config.PeerAs = 65002 + p.fsm.pConf.Update(&conf) + p.fsm.outgoingConnMgr = &outgoingConnManager{fsm: p.fsm} + p.fsm.outgoingConnMgr.state.Store(bgp.BGP_FSM_OPENSENT) + open, err := bgp.NewBGPOpenMessage(65002, 90, netip.MustParseAddr("10.0.0.1"), nil) + require.NoError(t, err) + + baseline := goleak.IgnoreCurrent() + ctx, cancel := context.WithCancel(t.Context()) + done := make(chan bgp.FSMState, 1) + go func() { + state, _ := h.opensent(ctx) + done <- state + }() + if len(before) > 0 { + // net.Pipe: Write returns when the recv goroutine has read it. + _, err = incoming.remote.Write(before) + require.NoError(t, err) + } + time.Sleep(delay) + p.fsm.outgoingConnCh <- outgoingConn{conn: outgoing, open: open} + select { + case state := <-done: + require.Equal(t, bgp.BGP_FSM_OPENCONFIRM, state) + case <-time.After(5 * time.Second): + t.Fatal("the OpenSent handler did not return") + } + require.Same(t, outgoing, p.fsm.conn) + require.Empty(t, incoming.GetSentMessages(), "the losing connection got an answer before the peer sent anything") + return p, incoming, cancel, baseline +} + +// The losing connection answers the first message on it as OpenSent does +// (RFC 4271 Section 8.2.2), a valid OPEN with Cease/Connection Collision +// Resolution, without touching the counters of the session on the other +// connection. +func TestCollisionLoserAnswers(t *testing.T) { + open := func(as uint16) []byte { + m, err := bgp.NewBGPOpenMessage(as, 90, netip.MustParseAddr("10.0.0.1"), nil) + require.NoError(t, err) + return mustSerialize(t, m) + } + ob := open(65002) + for _, tt := range []struct { + name string + before []byte // on the losing connection before the collision + after []byte // and after it + // the NOTIFICATION that GoBGP sends, none for nil + want []uint8 + }{ + {"open", nil, ob, []uint8{bgp.BGP_ERROR_CEASE, bgp.BGP_ERROR_SUB_CONNECTION_COLLISION_RESOLUTION}}, + // The OPEN header arrives before the collision and the body after + // it: the message is not cut, it is an OPEN. + {"split open", ob[:bgp.BGP_HEADER_LENGTH], ob[bgp.BGP_HEADER_LENGTH:], []uint8{bgp.BGP_ERROR_CEASE, bgp.BGP_ERROR_SUB_CONNECTION_COLLISION_RESOLUTION}}, + // An invalid OPEN gets its OPEN Message Error, not the Cease. + {"bad peer as", nil, open(65003), []uint8{bgp.BGP_ERROR_OPEN_MESSAGE_ERROR, bgp.BGP_ERROR_SUB_BAD_PEER_AS}}, + {"keepalive", nil, mustSerialize(t, bgp.NewBGPKeepAliveMessage()), []uint8{bgp.BGP_ERROR_FSM_ERROR, 1}}, + // RFC 4271 Section 8.2.2, OpenSent, Event 24: no answer. + {"version error", nil, mustSerialize(t, bgp.NewBGPNotificationMessage(bgp.BGP_ERROR_OPEN_MESSAGE_ERROR, bgp.BGP_ERROR_SUB_UNSUPPORTED_VERSION_NUMBER, nil)), nil}, + {"cease", nil, mustSerialize(t, bgp.NewBGPNotificationMessage(bgp.BGP_ERROR_CEASE, bgp.BGP_ERROR_SUB_CONNECTION_COLLISION_RESOLUTION, nil)), []uint8{bgp.BGP_ERROR_FSM_ERROR, 1}}, + // RFC 4271 Section 6.1: a header without the all-ones marker. + {"bad marker", nil, append(make([]byte, 16), 0, 19, bgp.BGP_MSG_KEEPALIVE), []uint8{bgp.BGP_ERROR_MESSAGE_HEADER_ERROR, bgp.BGP_ERROR_SUB_CONNECTION_NOT_SYNCHRONIZED}}, + } { + t.Run(tt.name, func(t *testing.T) { + p, in, _, baseline := loserOpensent(t, tt.before, 10, 0) + sent := atomic.LoadUint64(&p.fsm.counterStats.Sent.Notification) + _, err := in.remote.Write(tt.after) + require.NoError(t, err) + // The goroutine that keeps the connection ends after the + // answer. + goleak.VerifyNone(t, baseline) + msgs := in.GetSentMessages() + if tt.want == nil { + require.Empty(t, msgs, "GoBGP answered") + } else { + require.Len(t, msgs, 1) + m, err := bgp.ParseBGPMessage(msgs[0]) + require.NoError(t, err) + require.Equal(t, uint8(bgp.BGP_MSG_NOTIFICATION), m.Header.Type) + n := m.Body.(*bgp.BGPNotification) + require.Equal(t, tt.want, []uint8{n.ErrorCode, n.ErrorSubcode}) + } + require.Equal(t, sent, atomic.LoadUint64(&p.fsm.counterStats.Sent.Notification), "the session's NOTIFICATION counter changed") + }) + } +} + +// The losing connection is closed without an answer, and the goroutine +// that keeps it ends, when the peer closes it, when the handler stops and +// when the OpenSent hold time expires. +func TestCollisionLoserEnds(t *testing.T) { + t.Run("peer closes", func(t *testing.T) { + _, in, _, baseline := loserOpensent(t, nil, 10, 0) + require.NoError(t, in.remote.Close()) + goleak.VerifyNone(t, baseline) + }) + t.Run("handler stops", func(t *testing.T) { + _, in, cancel, baseline := loserOpensent(t, nil, 10, 0) + cancel() + goleak.VerifyNone(t, baseline) + require.Empty(t, in.GetSentMessages()) + _, err := in.remote.Write([]byte{0}) + require.ErrorIs(t, err, io.ErrClosedPipe) + }) + t.Run("hold time", func(t *testing.T) { + // The OpenSent hold timer of the incoming connection keeps + // running: it expires 2s after opensent() started, not 2s after + // the collision. + _, in, _, baseline := loserOpensent(t, nil, 2, 1500*time.Millisecond) + require.Eventually(t, func() bool { return goleak.Find(baseline) == nil }, 1200*time.Millisecond, 50*time.Millisecond) + require.Empty(t, in.GetSentMessages()) + _, err := in.remote.Write([]byte{0}) + require.ErrorIs(t, err, io.ErrClosedPipe) + }) +} + +func mustSerialize(t *testing.T, m *bgp.BGPMessage) []byte { + t.Helper() + b, err := m.Serialize() + require.NoError(t, err) + return b +} diff --git a/pkg/server/fsm.go b/pkg/server/fsm.go index a984671c1..a38f528ab 100644 --- a/pkg/server/fsm.go +++ b/pkg/server/fsm.go @@ -592,11 +592,11 @@ type fsm struct { outgoingConnMgr *outgoingConnManager idleHoldTime float64 // for the current or next Idle state idleHoldBackoff float64 - opensentHoldTime float64 // imutable - twoByteAsTrans bool + opensentHoldTime float64 // imutable + twoByteAsTrans atomic.Bool // read by recv goroutines that can outlive a state isEBGP bool isConfed bool - isTreatAsWithdraw bool + isTreatAsWithdraw atomic.Bool // multiple fsm goroutines access. no lock required due to how they are used. conn net.Conn @@ -656,6 +656,49 @@ func (fsm *fsm) resolveCollision(open *bgp.BGPOpen, incoming, outgoing net.Conn) return false } +// trackCollisionLoser keeps conn, the incoming connection that lost a +// collision before the peer's OPEN arrived on it, open until the peer's +// first message arrives on it. RFC 4271 Section 6.8 detects a collision +// "upon receipt of an OPEN message", and a peer whose connection is closed +// before that does not see a collision and connects again. The goroutine +// takes over the recv goroutine of conn (wg, recvChan, reasonCh), so a +// message that is partly read is not cut. It answers that message as +// OpenSent does (RFC 4271 Section 8.2.2), but a valid OPEN with +// Cease/Connection Collision Resolution, and does not count what it sends +// for the session on the other connection. The BGP Identifiers were +// compared at the OPEN on our connection; both OPENs of a real peer carry +// the same one. conn is closed after the answer, when the peer closes it, +// when hold, the OpenSent hold timer of conn, expires and when ctx ends. +func (h *fsmHandler) trackCollisionLoser(ctx context.Context, conn net.Conn, wg *sync.WaitGroup, recvChan <-chan *fsmMsg, reasonCh <-chan fsmStateReason, hold *time.Timer) { + fsm := h.fsm + go func() { + defer hold.Stop() + select { + case e := <-recvChan: + nextState, _, notif := fsm.handleOpen(e) + if nextState == bgp.BGP_FSM_OPENCONFIRM { + notif = bgp.NewBGPNotificationMessage(bgp.BGP_ERROR_CEASE, bgp.BGP_ERROR_SUB_CONNECTION_COLLISION_RESOLUTION, nil) + } + if notif != nil { + body := notif.Body.(*bgp.BGPNotification) + fsm.logger.Info("sent notification on the losing connection of a collision", + slog.Int("Code", int(body.ErrorCode)), + slog.Int("Subcode", int(body.ErrorSubcode))) + b, _ := notif.Serialize() + conn.SetWriteDeadline(time.Now().Add(time.Second)) + _, _ = conn.Write(b) + } + case <-reasonCh: + case <-hold.C: + case <-ctx.Done(): + } + // stop the recv goroutine + conn.SetReadDeadline(time.Now()) + conn.Close() + wg.Wait() + }() +} + func (fsm *fsm) bgpMessageResetStats() { atomic.StoreUint64(&fsm.counterStats.Received.Total, 0) atomic.StoreUint64(&fsm.counterStats.Received.Update, 0) @@ -928,11 +971,11 @@ func (fsm *fsm) stateChange(nextState bgp.FSMState, reason *fsmStateReason) { fsm.isEBGP = conf.IsEBGPPeer(fsm.gConf) fsm.isConfed = fsm.gConf.IsConfederationMember(conf.State.PeerAs) - fsm.isTreatAsWithdraw = conf.ErrorHandling.Config.TreatAsWithdraw + fsm.isTreatAsWithdraw.Store(conf.ErrorHandling.Config.TreatAsWithdraw) // reset the state set by the previous session - fsm.twoByteAsTrans = false + fsm.twoByteAsTrans.Store(false) if _, y := fsm.capMap[bgp.BGP_CAP_FOUR_OCTET_AS_NUMBER]; !y { - fsm.twoByteAsTrans = true + fsm.twoByteAsTrans.Store(true) break } y := func() bool { @@ -945,7 +988,7 @@ func (fsm *fsm) stateChange(nextState bgp.FSMState, reason *fsmStateReason) { return false }() if !y { - fsm.twoByteAsTrans = true + fsm.twoByteAsTrans.Store(true) } } } @@ -1657,11 +1700,11 @@ func (h *fsmHandler) recvMessageWithError(conn net.Conn, stateReasonCh chan<- fs now := time.Now() handling := bgp.ERROR_HANDLING_NONE - useRevisedError := h.fsm.isTreatAsWithdraw + useRevisedError := h.fsm.isTreatAsWithdraw.Load() m, err := bgp.ParseBGPBody(hd, bodyBuf, &bgp.MarshallingOption{ AddPath: h.fsm.familyMap.Load().(map[bgp.Family]bgp.BGPAddPathMode), - Use2ByteAS: h.fsm.twoByteAsTrans, // true if peer does NOT support 4-byte AS + Use2ByteAS: h.fsm.twoByteAsTrans.Load(), // true if peer does NOT support 4-byte AS ExtendedMessage: h.fsm.extendedMessage.Load(), }) if err != nil { @@ -1809,8 +1852,13 @@ func (h *fsmHandler) opensent(ctx context.Context) (bgp.FSMState, *fsmStateReaso reasonCh := make(chan fsmStateReason, 1) recvChan := make(chan *fsmMsg, 1) go h.recvMessage(ctx, fsm.conn, recvChan, reasonCh, wg) + // set when trackCollisionLoser took over the recv goroutine + handedOver := false defer func() { + if handedOver { + return + } // for to stop the recv goroutine fsm.conn.SetReadDeadline(time.Now()) wg.Wait() @@ -1886,22 +1934,20 @@ func (h *fsmHandler) opensent(ctx context.Context) (bgp.FSMState, *fsmStateReaso // means outside of the protocol. We still use it, like FRR // does: both connections are with the same peer, so its BGP // Identifier is known. Resolve the collision now. - if !fsm.resolveCollision(result.open.Body.(*bgp.BGPOpen), fsm.conn, result.conn) { - // The incoming connection is kept. Stay in OpenSent - // and wait for the peer's OPEN on it. + open := result.open.Body.(*bgp.BGPOpen) + if !fsm.isDominant(open) { + // The incoming connection is kept: resolveCollision + // closes the outgoing one. Stay in OpenSent and wait + // for the peer's OPEN on the incoming connection. + fsm.resolveCollision(open, fsm.conn, result.conn) continue } - // resolveCollision closed the incoming connection. Its recv - // goroutine ends with a read error; drop what it reported. - wg.Wait() - select { - case <-recvChan: - default: - } - select { - case <-reasonCh: - default: - } + // Our connection is kept. The incoming one is closed only + // when the peer's OPEN arrives on it, as RFC 4271 Section + // 6.8 describes: trackCollisionLoser waits for it. + debuglog.Log(fsm.logger, "collision detected: dominant on active side, close the incoming connection when its OPEN arrives") + handedOver = true + h.trackCollisionLoser(ctx, fsm.conn, wg, recvChan, reasonCh, holdTimer) fsm.lock.Lock() fsm.conn = result.conn @@ -2120,7 +2166,7 @@ func (h *fsmHandler) sendMessageloop(ctx context.Context, conn net.Conn, stateRe fsm := h.fsm ticker := keepaliveTicker(fsm) send := func(m *bgp.BGPMessage) error { - if fsm.twoByteAsTrans && m.Header.Type == bgp.BGP_MSG_UPDATE { + if fsm.twoByteAsTrans.Load() && m.Header.Type == bgp.BGP_MSG_UPDATE { debuglog.Log(fsm.logger, "update for 2byte AS peer", slog.Any("State", debuglog.Lazy(fsm.state.Load())), slog.Any("Data", m)) @@ -2272,7 +2318,7 @@ func (h *fsmHandler) recvMessageloop(ctx context.Context, conn net.Conn, holdtim rfMap := h.fsm.familyMap.Load().(map[bgp.Family]bgp.BGPAddPathMode) handling := fmsg.handling - useRevisedError := h.fsm.isTreatAsWithdraw + useRevisedError := h.fsm.isTreatAsWithdraw.Load() var validationErr error // A discarded attribute leaves the rest of the message in @@ -2312,7 +2358,7 @@ func (h *fsmHandler) recvMessageloop(ctx context.Context, conn net.Conn, holdtim } } - if !h.fsm.twoByteAsTrans { + if !h.fsm.twoByteAsTrans.Load() { table.DiscardAs4Attrs(body) } table.UpdatePathAggregator4ByteAs(body) diff --git a/pkg/server/fsm_test.go b/pkg/server/fsm_test.go index dfc3bdb19..688e97fc0 100644 --- a/pkg/server/fsm_test.go +++ b/pkg/server/fsm_test.go @@ -1489,7 +1489,7 @@ func TestRecvMessageWithError_MalformedNextHop(t *testing.T) { // handled inside recvMessageWithError. The panic only occurs when // treat-as-withdraw is enabled and the malformed attribute survives // into ValidateUpdateMsg. - h.fsm.isTreatAsWithdraw = true + h.fsm.isTreatAsWithdraw.Store(true) go m.remote.Write(raw) @@ -1513,7 +1513,7 @@ func TestRecvMessageWithError_MalformedNextHop(t *testing.T) { }) // Without RFC 7606, the error should cause a session reset. - h.fsm.isTreatAsWithdraw = false + h.fsm.isTreatAsWithdraw.Store(false) go m.remote.Write(raw) @@ -2078,7 +2078,7 @@ func recvUpdate(t *testing.T, raw []byte) (*fsmMsg, *bgp.BGPMessage) { p, h := makePeerAndHandler(m) t.Cleanup(func() { cleanPeerAndHandler(p, h) }) - h.fsm.isTreatAsWithdraw = true + h.fsm.isTreatAsWithdraw.Store(true) h.fsm.familyMap.Store(map[bgp.Family]bgp.BGPAddPathMode{bgp.RF_IPv4_UC: bgp.BGP_ADD_PATH_NONE}) received := make(chan *fsmMsg, 1) @@ -2437,9 +2437,13 @@ func TestFSMHandlerOpensent_OutgoingOpenFirst(t *testing.T) { }() if tt.wantOutgoing { - requireCollisionCease(t, sentMessage(t, incoming, 0)) msg := sentMessage(t, outgoing, 0) require.Equal(t, uint8(bgp.BGP_MSG_KEEPALIVE), msg.Header.Type) + // The incoming connection is closed only when the + // peer's OPEN arrives on it (RFC 4271 Section 6.8). + require.Empty(t, incoming.GetSentMessages()) + go incoming.PushBgpMessage(open) + requireCollisionCease(t, sentMessage(t, incoming, 0)) } else { requireCollisionCease(t, sentMessage(t, outgoing, 0)) // Still in OpenSent: the OPEN on the incoming