Browse Source

toc: move the OSCAR client code into server/oscarclient

Moves TOC's in-memory OSCAR client (login, connections, request
tracking) into server/oscarclient and the feedbag mirror into state.
ServeConn runs each connection on a goroutine owned by the server.
Mike 1 week ago
parent
commit
65e15e323f

+ 13 - 12
AGENTS.md

@@ -38,18 +38,19 @@ logic.
 
 ## Key packages
 
-| Package           | Role                                                                                                                                                                                                           |
-|-------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-| `cmd/server`      | Entry point; wires dependencies and starts all servers.                                                                                                                                                        |
-| `config`          | Configuration via env vars (`envconfig`). Config files are generated from the `Config` struct—do **not** edit them by hand; run `make config` instead.                                                         |
-| `foodgroup`       | Core business logic for OSCAR "food groups": Auth, Buddy, Feedbag, ICBM, Chat, BART, Locate, OService, ICQ, Admin, PermitDeny, ODir, Stats, UserLookup, ChatNav. Shared by the OSCAR, TOC, and WebAPI servers. |
-| `wire`            | Wire formats: OSCAR SNAC/FLAP encoding, TLV, food group codes, rate limits, frames, plus AMF3 encoding for the Web AIM client.                                                                                 |
-| `state`           | Persistence and in-memory state: `SQLiteUserStore`, `InMemorySessionManager`, `InMemoryChatSessionManager`, DB migrations.                                                                                     |
-| `server/oscar`    | OSCAR protocol server; SNAC routing and handler wiring.                                                                                                                                                        |
-| `server/toc`      | TOC protocol server (text-based). Each TOC user is an OSCAR client of the OSCAR server, connected over in-memory OSCAR connections (`OSCARServer.ServeConn`).                                                  |
-| `server/kerberos` | Kerberos auth server.                                                                                                                                                                                          |
-| `server/http`     | Management HTTP API (users, sessions, chat rooms). Spec: `api.yml`.                                                                                                                                            |
-| `server/webapi`   | Web AIM-style API (AMF3). Spec: `docs/open_api/webapi.yml`.                                                                                                                                                    |
+| Package              | Role                                                                                                                                                                                                           |
+|----------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
+| `cmd/server`         | Entry point; wires dependencies and starts all servers.                                                                                                                                                        |
+| `config`             | Configuration via env vars (`envconfig`). Config files are generated from the `Config` struct—do **not** edit them by hand; run `make config` instead.                                                         |
+| `foodgroup`          | Core business logic for OSCAR "food groups": Auth, Buddy, Feedbag, ICBM, Chat, BART, Locate, OService, ICQ, Admin, PermitDeny, ODir, Stats, UserLookup, ChatNav. Shared by the OSCAR, TOC, and WebAPI servers. |
+| `wire`               | Wire formats: OSCAR SNAC/FLAP encoding, TLV, food group codes, rate limits, frames, plus AMF3 encoding for the Web AIM client.                                                                                 |
+| `state`              | Persistence and in-memory state: `SQLiteUserStore`, `InMemorySessionManager`, `InMemoryChatSessionManager`, DB migrations.                                                                                     |
+| `server/oscar`       | OSCAR protocol server; SNAC routing and handler wiring.                                                                                                                                                        |
+| `server/toc`         | TOC protocol server (text-based). Each TOC user is an OSCAR client of the OSCAR server (see `server/oscarclient`).                                                                                             |
+| `server/oscarclient` | Client side of the in-memory OSCAR connections that TOC opens to the OSCAR server (`Server.ServeConn`): login, service connections, SNAC decoding and request tracking.                                        |
+| `server/kerberos`    | Kerberos auth server.                                                                                                                                                                                          |
+| `server/http`        | Management HTTP API (users, sessions, chat rooms). Spec: `api.yml`.                                                                                                                                            |
+| `server/webapi`      | Web AIM-style API (AMF3). Spec: `docs/open_api/webapi.yml`.                                                                                                                                                    |
 
 ## Database
 

+ 6 - 3
cmd/server/factory.go

@@ -22,6 +22,7 @@ import (
 	"github.com/mk6i/open-oscar-server/server/kerberos"
 	"github.com/mk6i/open-oscar-server/server/oscar"
 	oscarmiddleware "github.com/mk6i/open-oscar-server/server/oscar/middleware"
+	"github.com/mk6i/open-oscar-server/server/oscarclient"
 	"github.com/mk6i/open-oscar-server/server/toc"
 	"github.com/mk6i/open-oscar-server/server/webapi"
 	"github.com/mk6i/open-oscar-server/state"
@@ -451,9 +452,11 @@ func TOC(deps Container, oscarServer *oscar.Server) *toc.Server {
 				deps.inMemorySessionManager,
 				deps.sqLiteUserStore,
 			),
-			Logger:           logger,
-			OSCARServer:      oscarServer,
-			OSCAREndpoint:    deps.Listeners[0].PlainEndpoint(),
+			Logger: logger,
+			OSCARClient: oscarclient.Client{
+				Server: oscarServer,
+				Logger: logger,
+			},
 			SessionRetriever: deps.inMemorySessionManager,
 			TOCConfigStore:   deps.sqLiteUserStore,
 			RandIntn:         rand.Intn,

+ 13 - 5
server/oscar/server.go

@@ -159,16 +159,24 @@ func (s *Server) acceptLoop(ln net.Listener, endpointCfg config.Endpoint) {
 	}
 }
 
+// ErrServerClosed is returned by ServeConn once the server has begun shutting
+// down.
+var ErrServerClosed = errors.New("OSCAR server closed")
+
 // ServeConn serves a connection that didn't come from one of the server's
 // listeners, such as an in-memory connection opened by the TOC server, as if
-// it had arrived on the listener at endpointCfg. It returns when the
-// connection ends.
-func (s *Server) ServeConn(conn net.Conn, endpointCfg config.Endpoint) {
+// it had arrived on the plain listener of the server's first listener group.
+// The server serves it on a goroutine of its own that Shutdown waits for, and
+// ServeConn returns without waiting for the connection to end. Once the
+// server has begun shutting down, ServeConn closes conn and returns
+// ErrServerClosed.
+func (s *Server) ServeConn(conn net.Conn) error {
 	if !s.trackConn(conn) {
 		_ = conn.Close()
-		return
+		return ErrServerClosed
 	}
-	s.handleConnection(s.shutdownCtx, conn, endpointCfg)
+	go s.handleConnection(s.shutdownCtx, conn, s.listenerGroups[0].PlainEndpoint())
+	return nil
 }
 
 // trackConn registers conn so that Shutdown waits for it. It returns false

+ 42 - 14
server/oscar/server_test.go

@@ -1245,7 +1245,9 @@ func Test_oscarServer_receiveSessMessages_Chat_integration(t *testing.T) {
 	signoutWG.Wait()
 }
 
-func newServeConnTestServer() *Server {
+// newServeConnTestServer returns a server whose only listener group is
+// group.
+func newServeConnTestServer(group config.ListenerGroup) *Server {
 	return NewServer(
 		nil,
 		nil,
@@ -1257,40 +1259,66 @@ func newServeConnTestServer() *Server {
 		nil,
 		wire.DefaultSNACRateLimits(),
 		nil,
-		nil,
+		[]config.ListenerGroup{group},
 		func(ctx context.Context, instance *state.SessionInstance) error { return nil },
 		func(ctx context.Context, instance *state.SessionInstance) {},
 	)
 }
 
 func TestServer_ServeConn(t *testing.T) {
-	server := newServeConnTestServer()
+	group := config.ListenerGroup{Name: "LOCAL", BOSListenAddress: ":5190", BOSAdvertisedHostPlain: "127.0.0.1:5190"}
+	server := newServeConnTestServer(group)
 
-	var gotEndpoint config.Endpoint
-	var gotRemote net.Addr
+	type served struct {
+		endpoint config.Endpoint
+		remote   net.Addr
+	}
+	servedCh := make(chan served, 1)
+	release := make(chan struct{})
 	server.handler = func(ctx context.Context, conn net.Conn, endpointCfg config.Endpoint) error {
-		gotEndpoint = endpointCfg
-		gotRemote = conn.RemoteAddr()
+		servedCh <- served{endpoint: endpointCfg, remote: conn.RemoteAddr()}
+		<-release
 		return nil
 	}
 
 	serverEnd, clientEnd := net.Pipe()
 	clientAddr := &net.TCPAddr{IP: net.IPv4(10, 0, 0, 5), Port: 4321}
-	endpoint := config.Endpoint{ListenAddress: ":5190", Group: config.ListenerGroup{Name: "LOCAL"}}
 
-	server.ServeConn(fakeConn{Conn: serverEnd, remote: clientAddr}, endpoint)
+	// ServeConn returns while the connection is still being served, as if it
+	// had arrived on the first group's plain listener
+	assert.NoError(t, server.ServeConn(fakeConn{Conn: serverEnd, remote: clientAddr}))
+	got := <-servedCh
+	assert.Equal(t, group.PlainEndpoint(), got.endpoint)
+	assert.Equal(t, clientAddr, got.remote)
 
-	assert.Equal(t, endpoint, gotEndpoint)
-	assert.Equal(t, clientAddr, gotRemote)
+	// Shutdown waits for the connection's goroutine
+	shutdownDone := make(chan struct{})
+	go func() {
+		assert.NoError(t, server.Shutdown(context.Background()))
+		close(shutdownDone)
+	}()
+	select {
+	case <-shutdownDone:
+		t.Fatal("Shutdown returned while a connection was still being served")
+	case <-time.After(50 * time.Millisecond):
+	}
+	close(release)
+	select {
+	case <-shutdownDone:
+	case <-time.After(5 * time.Second):
+		t.Fatal("Shutdown didn't return after the connection ended")
+	}
 
-	// the connection is closed once served
+	// the connection is closed and untracked once served
 	_, err := clientEnd.Read(make([]byte, 1))
 	assert.Error(t, err)
+	server.connMu.Lock()
 	assert.Empty(t, server.conns)
+	server.connMu.Unlock()
 }
 
 func TestServer_ServeConn_afterShutdown(t *testing.T) {
-	server := newServeConnTestServer()
+	server := newServeConnTestServer(config.ListenerGroup{Name: "LOCAL"})
 
 	called := false
 	server.handler = func(ctx context.Context, conn net.Conn, endpointCfg config.Endpoint) error {
@@ -1300,7 +1328,7 @@ func TestServer_ServeConn_afterShutdown(t *testing.T) {
 	assert.NoError(t, server.Shutdown(context.Background()))
 
 	serverEnd, clientEnd := net.Pipe()
-	server.ServeConn(serverEnd, config.Endpoint{})
+	assert.ErrorIs(t, server.ServeConn(serverEnd), ErrServerClosed)
 
 	assert.False(t, called)
 	_, err := clientEnd.Read(make([]byte, 1))

+ 148 - 0
server/oscarclient/client.go

@@ -0,0 +1,148 @@
+package oscarclient
+
+import (
+	"bytes"
+	"context"
+	"fmt"
+	"log/slog"
+	"net"
+	"time"
+
+	"github.com/mk6i/open-oscar-server/wire"
+)
+
+// OSCARServer serves OSCAR connections that in-process clients open.
+type OSCARServer interface {
+	// ServeConn starts serving conn as if it had been accepted on one of
+	// the server's listeners. The server owns the goroutine that serves it.
+	// It returns an error if the server won't serve the connection.
+	ServeConn(conn net.Conn) error
+}
+
+// Client signs users on to the OSCAR server over in-memory connections, as
+// an ordinary OSCAR client would.
+type Client struct {
+	// Server serves the connections.
+	Server OSCARServer
+	// Logger records problems on the connections, such as SNACs that don't
+	// decode or a consumer that falls too far behind.
+	Logger *slog.Logger
+}
+
+// clientAddrConn is the server end of an in-memory OSCAR connection. It
+// reports the client's address as its remote address, so that the OSCAR
+// server sees where the user really connects from.
+type clientAddrConn struct {
+	net.Conn
+	clientAddr net.Addr
+}
+
+func (c clientAddrConn) RemoteAddr() net.Addr {
+	return c.clientAddr
+}
+
+// dial opens an in-memory connection to the OSCAR server on behalf of the
+// client at clientAddr.
+func (c Client) dial(clientAddr net.Addr) (net.Conn, error) {
+	clientEnd, serverEnd := net.Pipe()
+	if err := c.Server.ServeConn(clientAddrConn{Conn: serverEnd, clientAddr: clientAddr}); err != nil {
+		_ = clientEnd.Close()
+		return nil, fmt.Errorf("ServeConn: %w", err)
+	}
+	return clientEnd, nil
+}
+
+// Login signs on to the OSCAR auth service with the given signon TLVs
+// and returns the server's reply TLVs, which hold either a login cookie or an
+// error code.
+func (c Client) Login(clientAddr net.Addr, signonTLVs []wire.TLV) (wire.TLVRestBlock, error) {
+	conn, err := c.dial(clientAddr)
+	if err != nil {
+		return wire.TLVRestBlock{}, err
+	}
+	defer func() { _ = conn.Close() }()
+
+	flapc := wire.NewFlapClient(0, conn, conn)
+	if _, err := flapc.ReceiveSignonFrame(); err != nil {
+		return wire.TLVRestBlock{}, fmt.Errorf("ReceiveSignonFrame: %w", err)
+	}
+	if err := flapc.SendSignonFrame(signonTLVs); err != nil {
+		return wire.TLVRestBlock{}, fmt.Errorf("SendSignonFrame: %w", err)
+	}
+
+	frame, err := flapc.ReceiveFLAP()
+	if err != nil {
+		return wire.TLVRestBlock{}, fmt.Errorf("ReceiveFLAP: %w", err)
+	}
+
+	switch frame.FrameType {
+	case wire.FLAPFrameSignoff:
+		block := wire.TLVRestBlock{}
+		if err := wire.UnmarshalBE(&block, bytes.NewReader(frame.Payload)); err != nil {
+			return wire.TLVRestBlock{}, fmt.Errorf("UnmarshalBE: %w", err)
+		}
+		return block, nil
+	case wire.FLAPFrameData:
+		// the server answers with a BUCP login response when it rate limits
+		// an address that recently signed on with BUCP
+		msg, err := decodeSNAC(frame.Payload)
+		if err != nil {
+			return wire.TLVRestBlock{}, fmt.Errorf("decodeSNAC: %w", err)
+		}
+		reply, ok := msg.Body.(wire.SNAC_0x17_0x03_BUCPLoginResponse)
+		if !ok {
+			return wire.TLVRestBlock{}, fmt.Errorf("unexpected login reply %s",
+				wire.SubGroupName(msg.Frame.FoodGroup, msg.Frame.SubGroup))
+		}
+		return reply.TLVRestBlock, nil
+	default:
+		return wire.TLVRestBlock{}, fmt.Errorf("unexpected login reply frame type %d", frame.FrameType)
+	}
+}
+
+// ConnectService connects to the OSCAR service that loginCookie grants access
+// to, either BOS or a chat room, and waits for the server to report the
+// service online. The deadline of ctx, if it has one, bounds the wait. The
+// caller must start the returned connection's Run right away.
+func (c Client) ConnectService(ctx context.Context, clientAddr net.Addr, loginCookie []byte) (*FLAPConn, error) {
+	conn, err := c.dial(clientAddr)
+	if err != nil {
+		return nil, err
+	}
+	if deadline, ok := ctx.Deadline(); ok {
+		_ = conn.SetDeadline(deadline)
+	}
+
+	flapc := wire.NewFlapClient(0, conn, conn)
+	if err := func() error {
+		if _, err := flapc.ReceiveSignonFrame(); err != nil {
+			return fmt.Errorf("ReceiveSignonFrame: %w", err)
+		}
+		if err := flapc.SendSignonFrame([]wire.TLV{wire.NewTLVBE(wire.OServiceTLVTagsLoginCookie, loginCookie)}); err != nil {
+			return fmt.Errorf("SendSignonFrame: %w", err)
+		}
+
+		frame, err := flapc.ReceiveFLAP()
+		if err != nil {
+			return fmt.Errorf("ReceiveFLAP: %w", err)
+		}
+		if frame.FrameType == wire.FLAPFrameSignoff {
+			return ErrSignedOff
+		}
+		msg, err := decodeSNAC(frame.Payload)
+		if err != nil {
+			return fmt.Errorf("decodeSNAC: %w", err)
+		}
+		if _, ok := msg.Body.(wire.SNAC_0x01_0x03_OServiceHostOnline); !ok {
+			return fmt.Errorf("expected host online, got %s",
+				wire.SubGroupName(msg.Frame.FoodGroup, msg.Frame.SubGroup))
+		}
+		return nil
+	}(); err != nil {
+		_ = conn.Close()
+		return nil, err
+	}
+
+	_ = conn.SetDeadline(time.Time{})
+	return newFLAPConn(conn, flapc, c.Logger), nil
+}

+ 213 - 0
server/oscarclient/client_test.go

@@ -0,0 +1,213 @@
+package oscarclient
+
+import (
+	"context"
+	"errors"
+	"log/slog"
+	"net"
+	"os"
+	"testing"
+	"time"
+
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
+
+	"github.com/mk6i/open-oscar-server/wire"
+)
+
+// stubServer serves each connection with serve on a goroutine of its own, or
+// refuses it with refuse if set.
+type stubServer struct {
+	serve  func(conn net.Conn)
+	refuse error
+}
+
+func (s stubServer) ServeConn(conn net.Conn) error {
+	if s.refuse != nil {
+		_ = conn.Close()
+		return s.refuse
+	}
+	go func() {
+		defer func() { _ = conn.Close() }()
+		s.serve(conn)
+	}()
+	return nil
+}
+
+func TestClient_serverRefusesConnection(t *testing.T) {
+	refused := errors.New("shutting down")
+	c := Client{Server: stubServer{refuse: refused}, Logger: slog.Default()}
+	clientAddr := &net.TCPAddr{IP: net.IPv4(10, 0, 0, 5), Port: 4321}
+
+	_, err := c.Login(clientAddr, nil)
+	assert.ErrorIs(t, err, refused)
+
+	_, err = c.ConnectService(context.Background(), clientAddr, []byte("cookie"))
+	assert.ErrorIs(t, err, refused)
+}
+
+func TestClient_ConnectService(t *testing.T) {
+	later := make(chan struct{})
+	server := stubServer{
+		serve: func(conn net.Conn) {
+			flapc := wire.NewFlapClient(100, conn, conn)
+			assert.NoError(t, flapc.SendSignonFrame(nil))
+			_, err := flapc.ReceiveSignonFrame()
+			assert.NoError(t, err)
+			assert.NoError(t, flapc.SendSNAC(
+				wire.SNACFrame{FoodGroup: wire.OService, SubGroup: wire.OServiceHostOnline},
+				wire.SNAC_0x01_0x03_OServiceHostOnline{}))
+
+			<-later
+			assert.NoError(t, flapc.SendSNAC(
+				wire.SNACFrame{FoodGroup: wire.OService, SubGroup: wire.OServiceEvilNotification},
+				wire.SNAC_0x01_0x10_OServiceEvilNotification{NewEvil: 1}))
+		},
+	}
+	c := Client{Server: server, Logger: slog.Default()}
+
+	ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
+	defer cancel()
+	conn, err := c.ConnectService(ctx, &net.TCPAddr{IP: net.IPv4(10, 0, 0, 5), Port: 4321}, []byte("cookie"))
+	require.NoError(t, err)
+	defer conn.Close()
+	go conn.Run(context.Background())
+
+	// The handshake's deadline doesn't outlive it.
+	<-ctx.Done()
+	time.Sleep(20 * time.Millisecond)
+	close(later)
+	select {
+	case msg := <-conn.Messages():
+		assert.Equal(t, wire.SNAC_0x01_0x10_OServiceEvilNotification{NewEvil: 1}, msg.Body)
+	case <-conn.Closed():
+		t.Fatal("the connection closed after the handshake's deadline")
+	case <-time.After(time.Second):
+		t.Fatal("no SNAC arrived")
+	}
+}
+
+func TestClient_ConnectService_handshakeDeadline(t *testing.T) {
+	server := stubServer{
+		serve: func(conn net.Conn) {
+			// never starts the handshake; returns once the client hangs up
+			_, _ = conn.Read(make([]byte, 1))
+		},
+	}
+	c := Client{Server: server, Logger: slog.Default()}
+
+	ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
+	defer cancel()
+
+	errCh := make(chan error, 1)
+	go func() {
+		_, err := c.ConnectService(ctx, &net.TCPAddr{IP: net.IPv4(10, 0, 0, 5), Port: 4321}, []byte("cookie"))
+		errCh <- err
+	}()
+
+	select {
+	case err := <-errCh:
+		assert.ErrorIs(t, err, os.ErrDeadlineExceeded)
+	case <-time.After(time.Second):
+		t.Fatal("ConnectService outlived its deadline")
+	}
+}
+
+func TestClient_Login(t *testing.T) {
+	clientAddr := &net.TCPAddr{IP: net.IPv4(10, 0, 0, 5), Port: 4321}
+	signonTLVs := []wire.TLV{
+		wire.NewTLVBE(wire.LoginTLVTagsScreenName, "me"),
+		wire.NewTLVBE(wire.LoginTLVTagsRoastedTOCPassword, []byte("roasted")),
+	}
+
+	tests := []struct {
+		name string
+		// reply answers the signon; nil hangs up without answering
+		reply   func(t *testing.T, flapc *wire.FlapClient)
+		want    wire.TLVRestBlock
+		wantErr string
+	}{
+		{
+			name: "signoff with a login cookie",
+			reply: func(t *testing.T, flapc *wire.FlapClient) {
+				assert.NoError(t, flapc.NewSignoff(wire.TLVRestBlock{TLVList: wire.TLVList{
+					wire.NewTLVBE(wire.LoginTLVTagsAuthorizationCookie, []byte("cookie")),
+				}}))
+			},
+			want: wire.TLVRestBlock{TLVList: wire.TLVList{
+				wire.NewTLVBE(wire.LoginTLVTagsAuthorizationCookie, []byte("cookie")),
+			}},
+		},
+		{
+			name: "signoff with an error code",
+			reply: func(t *testing.T, flapc *wire.FlapClient) {
+				assert.NoError(t, flapc.NewSignoff(wire.TLVRestBlock{TLVList: wire.TLVList{
+					wire.NewTLVBE(wire.LoginTLVTagsErrorSubcode, wire.LoginErrInvalidPassword),
+				}}))
+			},
+			want: wire.TLVRestBlock{TLVList: wire.TLVList{
+				wire.NewTLVBE(wire.LoginTLVTagsErrorSubcode, wire.LoginErrInvalidPassword),
+			}},
+		},
+		{
+			name: "BUCP login response",
+			reply: func(t *testing.T, flapc *wire.FlapClient) {
+				assert.NoError(t, flapc.SendSNAC(
+					wire.SNACFrame{FoodGroup: wire.BUCP, SubGroup: wire.BUCPLoginResponse},
+					wire.SNAC_0x17_0x03_BUCPLoginResponse{TLVRestBlock: wire.TLVRestBlock{TLVList: wire.TLVList{
+						wire.NewTLVBE(wire.LoginTLVTagsErrorSubcode, wire.LoginErrRateLimitExceeded),
+					}}}))
+			},
+			want: wire.TLVRestBlock{TLVList: wire.TLVList{
+				wire.NewTLVBE(wire.LoginTLVTagsErrorSubcode, wire.LoginErrRateLimitExceeded),
+			}},
+		},
+		{
+			name: "SNAC other than a BUCP login response",
+			reply: func(t *testing.T, flapc *wire.FlapClient) {
+				assert.NoError(t, flapc.SendSNAC(
+					wire.SNACFrame{FoodGroup: wire.OService, SubGroup: wire.OServiceHostOnline},
+					wire.SNAC_0x01_0x03_OServiceHostOnline{}))
+			},
+			wantErr: "unexpected login reply",
+		},
+		{
+			name: "frame other than signoff or data",
+			reply: func(t *testing.T, flapc *wire.FlapClient) {
+				assert.NoError(t, flapc.SendKeepAliveFrame())
+			},
+			wantErr: "unexpected login reply frame type",
+		},
+		{
+			name:    "server hangs up without replying",
+			wantErr: "ReceiveFLAP",
+		},
+	}
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			server := stubServer{
+				serve: func(conn net.Conn) {
+					assert.Equal(t, clientAddr, conn.RemoteAddr())
+					flapc := wire.NewFlapClient(100, conn, conn)
+					assert.NoError(t, flapc.SendSignonFrame(nil))
+					signon, err := flapc.ReceiveSignonFrame()
+					assert.NoError(t, err)
+					assert.Equal(t, wire.TLVList(signonTLVs), signon.TLVList)
+					if tt.reply != nil {
+						tt.reply(t, flapc)
+					}
+				},
+			}
+			c := Client{Server: server, Logger: slog.Default()}
+
+			got, err := c.Login(clientAddr, signonTLVs)
+			if tt.wantErr != "" {
+				assert.ErrorContains(t, err, tt.wantErr)
+				return
+			}
+			assert.NoError(t, err)
+			assert.Equal(t, tt.want, got)
+		})
+	}
+}

+ 105 - 0
server/oscarclient/conn.go

@@ -0,0 +1,105 @@
+// Package oscarclient connects in-process protocol servers, such as TOC, to
+// the OSCAR server as ordinary OSCAR clients.
+package oscarclient
+
+import (
+	"context"
+	"errors"
+	"log/slog"
+	"net"
+	"sync"
+
+	"github.com/mk6i/open-oscar-server/wire"
+)
+
+// ErrSignedOff indicates that the OSCAR server refused or ended a connection
+// with a signoff frame.
+var ErrSignedOff = errors.New("signed off by OSCAR server")
+
+// queueLimit is how many received SNACs a connection holds for its consumer,
+// the same as an OSCAR session's message queue.
+const queueLimit = 1000
+
+// FLAPConn is a client's FLAP connection to an OSCAR service, either BOS or
+// a chat room.
+type FLAPConn struct {
+	conn   net.Conn
+	flapc  *wire.FlapClient
+	logger *slog.Logger
+	// msgs holds SNACs received from the server until the consumer takes
+	// them. Run never waits on it, so it keeps reading from the server even
+	// while the consumer is busy; otherwise the server's writes would block,
+	// and with them its reads of the SNACs the client sends.
+	msgs      chan wire.SNACMessage
+	closed    chan struct{}
+	closeOnce sync.Once
+}
+
+// newFLAPConn wraps a FLAP connection that has finished signing on to an
+// OSCAR service.
+func newFLAPConn(conn net.Conn, flapc *wire.FlapClient, logger *slog.Logger) *FLAPConn {
+	return &FLAPConn{
+		conn:   conn,
+		flapc:  flapc,
+		logger: logger,
+		msgs:   make(chan wire.SNACMessage, queueLimit),
+		closed: make(chan struct{}),
+	}
+}
+
+// Run reads SNACs from the server into Messages until the connection closes
+// from either end or ctx is done, then closes the connection. The consumer
+// runs it on a goroutine of its own, from the moment the connection is
+// returned: until Run is reading, the server's writes to the connection
+// block, and with them its reads of the SNACs the client sends.
+func (c *FLAPConn) Run(ctx context.Context) {
+	stop := context.AfterFunc(ctx, c.Close)
+	defer stop()
+	defer c.Close()
+	for {
+		frame, err := c.flapc.ReceiveFLAP()
+		if err != nil {
+			return
+		}
+		switch frame.FrameType {
+		case wire.FLAPFrameData:
+			msg, err := decodeSNAC(frame.Payload)
+			if err != nil {
+				c.logger.Debug("unable to decode SNAC from OSCAR server", "err", err.Error())
+				continue
+			}
+			select {
+			case c.msgs <- msg:
+			default:
+				// like the OSCAR server, disconnect a client that falls too far behind
+				c.logger.Warn("client isn't keeping up with the OSCAR server, disconnecting")
+				return
+			}
+		case wire.FLAPFrameSignoff:
+			return
+		}
+	}
+}
+
+// SendSNAC sends a SNAC to the OSCAR server.
+func (c *FLAPConn) SendSNAC(frame wire.SNACFrame, body any) error {
+	return c.flapc.SendSNAC(frame, body)
+}
+
+// Messages returns the SNACs received from the server in arrival order.
+func (c *FLAPConn) Messages() <-chan wire.SNACMessage {
+	return c.msgs
+}
+
+// Closed returns a channel that is closed when the connection closes.
+func (c *FLAPConn) Closed() <-chan struct{} {
+	return c.closed
+}
+
+// Close closes the connection. It is safe to call more than once.
+func (c *FLAPConn) Close() {
+	c.closeOnce.Do(func() {
+		close(c.closed)
+		_ = c.conn.Close()
+	})
+}

+ 60 - 9
server/toc/oscar_conn_test.go → server/oscarclient/conn_test.go

@@ -1,7 +1,8 @@
-package toc
+package oscarclient
 
 import (
 	"bytes"
+	"context"
 	"log/slog"
 	"net"
 	"testing"
@@ -16,6 +17,7 @@ func TestFLAPConn_readsWhileConsumerIsBusy(t *testing.T) {
 	clientEnd, serverEnd := net.Pipe()
 	server := wire.NewFlapClient(0, serverEnd, serverEnd)
 	conn := newFLAPConn(clientEnd, wire.NewFlapClient(0, clientEnd, clientEnd), slog.Default())
+	go conn.Run(context.Background())
 	defer conn.Close()
 
 	// nobody reads conn.Messages() yet, so each send returns only because the
@@ -43,7 +45,7 @@ func marshalSNAC(t *testing.T, frame wire.SNACFrame, body any) []byte {
 	return buf.Bytes()
 }
 
-func TestDecodeSNAC(t *testing.T) {
+func Test_decodeSNAC(t *testing.T) {
 	cases := []struct {
 		name    string
 		payload func(t *testing.T) []byte
@@ -51,13 +53,15 @@ func TestDecodeSNAC(t *testing.T) {
 		wantErr bool
 	}{
 		{
-			name: "SNAC TOC handles",
+			name: "SNAC a client handles",
 			payload: func(t *testing.T) []byte {
 				return marshalSNAC(t, wire.SNACFrame{FoodGroup: wire.Buddy, SubGroup: wire.BuddyArrived, RequestID: 7},
 					wire.SNAC_0x03_0x0B_BuddyArrived{TLVUserInfo: wire.TLVUserInfo{ScreenName: "them", WarningLevel: 10}})
 			},
-			want: newSNAC(wire.Buddy, wire.BuddyArrived, 7,
-				wire.SNAC_0x03_0x0B_BuddyArrived{TLVUserInfo: wire.TLVUserInfo{ScreenName: "them", WarningLevel: 10}}),
+			want: wire.SNACMessage{
+				Frame: wire.SNACFrame{FoodGroup: wire.Buddy, SubGroup: wire.BuddyArrived, RequestID: 7},
+				Body:  wire.SNAC_0x03_0x0B_BuddyArrived{TLVUserInfo: wire.TLVUserInfo{ScreenName: "them", WarningLevel: 10}},
+			},
 		},
 		{
 			name: "relayed feedbag insert",
@@ -65,8 +69,10 @@ func TestDecodeSNAC(t *testing.T) {
 				return marshalSNAC(t, wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagInsertItem},
 					wire.SNAC_0x13_0x09_FeedbagUpdateItem{Items: []wire.FeedbagItem{{Name: "them"}}})
 			},
-			want: newSNAC(wire.Feedbag, wire.FeedbagInsertItem, 0,
-				wire.SNAC_0x13_0x08_FeedbagInsertItem{Items: []wire.FeedbagItem{{Name: "them"}}}),
+			want: wire.SNACMessage{
+				Frame: wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagInsertItem},
+				Body:  wire.SNAC_0x13_0x08_FeedbagInsertItem{Items: []wire.FeedbagItem{{Name: "them"}}},
+			},
 		},
 		{
 			name: "error in any food group",
@@ -74,10 +80,13 @@ func TestDecodeSNAC(t *testing.T) {
 				return marshalSNAC(t, wire.SNACFrame{FoodGroup: wire.ICBM, SubGroup: wire.ICBMErr, RequestID: 3},
 					wire.SNACError{Code: wire.ErrorCodeNotLoggedOn})
 			},
-			want: newSNAC(wire.ICBM, wire.ICBMErr, 3, wire.SNACError{Code: wire.ErrorCodeNotLoggedOn}),
+			want: wire.SNACMessage{
+				Frame: wire.SNACFrame{FoodGroup: wire.ICBM, SubGroup: wire.ICBMErr, RequestID: 3},
+				Body:  wire.SNACError{Code: wire.ErrorCodeNotLoggedOn},
+			},
 		},
 		{
-			name: "SNAC TOC doesn't handle has no body",
+			name: "SNAC no client handles has no body",
 			payload: func(t *testing.T) []byte {
 				return marshalSNAC(t, wire.SNACFrame{FoodGroup: wire.Stats, SubGroup: wire.StatsSetMinReportInterval},
 					wire.SNAC_0x0B_0x02_StatsSetMinReportInterval{MinReportInterval: 1})
@@ -117,6 +126,7 @@ func TestFLAPConn(t *testing.T) {
 	clientEnd, serverEnd := net.Pipe()
 	server := wire.NewFlapClient(0, serverEnd, serverEnd)
 	conn := newFLAPConn(clientEnd, wire.NewFlapClient(0, clientEnd, clientEnd), slog.Default())
+	go conn.Run(context.Background())
 
 	// SNACs sent to the server arrive intact
 	go func() {
@@ -152,6 +162,7 @@ func TestFLAPConn_closesWhenConsumerFallsBehind(t *testing.T) {
 	clientEnd, serverEnd := net.Pipe()
 	server := wire.NewFlapClient(0, serverEnd, serverEnd)
 	conn := newFLAPConn(clientEnd, wire.NewFlapClient(0, clientEnd, clientEnd), slog.Default())
+	go conn.Run(context.Background())
 
 	// nobody reads conn.Messages(), so its buffer fills up
 	go func() {
@@ -182,3 +193,43 @@ func TestFLAPConn_Close(t *testing.T) {
 	assert.Error(t, err)
 	<-conn.Closed()
 }
+
+func TestFLAPConn_Run_endsWithContext(t *testing.T) {
+	clientEnd, serverEnd := net.Pipe()
+	defer func() { _ = serverEnd.Close() }()
+	conn := newFLAPConn(clientEnd, wire.NewFlapClient(0, clientEnd, clientEnd), slog.Default())
+
+	ctx, cancel := context.WithCancel(context.Background())
+	done := make(chan struct{})
+	go func() {
+		conn.Run(ctx)
+		close(done)
+	}()
+
+	cancel()
+	select {
+	case <-done:
+	case <-time.After(time.Second):
+		t.Fatal("Run didn't return after its context was done")
+	}
+	<-conn.Closed()
+}
+
+func TestFLAPConn_Run_endsWhenClosed(t *testing.T) {
+	clientEnd, serverEnd := net.Pipe()
+	defer func() { _ = serverEnd.Close() }()
+	conn := newFLAPConn(clientEnd, wire.NewFlapClient(0, clientEnd, clientEnd), slog.Default())
+
+	done := make(chan struct{})
+	go func() {
+		conn.Run(context.Background())
+		close(done)
+	}()
+
+	conn.Close()
+	select {
+	case <-done:
+	case <-time.After(time.Second):
+		t.Fatal("Run didn't return after the connection closed")
+	}
+}

+ 71 - 0
server/oscarclient/decode.go

@@ -0,0 +1,71 @@
+package oscarclient
+
+import (
+	"bytes"
+	"fmt"
+	"io"
+
+	"github.com/mk6i/open-oscar-server/wire"
+)
+
+// snacDecoders unmarshal the bodies of the SNACs that in-process clients
+// handle, keyed by food group and subgroup.
+var snacDecoders = map[[2]uint16]func(r io.Reader) (any, error){
+	{wire.OService, wire.OServiceHostOnline}:       decodeBody[wire.SNAC_0x01_0x03_OServiceHostOnline],
+	{wire.OService, wire.OServiceServiceResponse}:  decodeBody[wire.SNAC_0x01_0x05_OServiceServiceResponse],
+	{wire.OService, wire.OServiceRateParamChange}:  decodeBody[wire.SNAC_0x01_0x0A_OServiceRateParamsChange],
+	{wire.OService, wire.OServiceUserInfoUpdate}:   decodeBody[wire.SNAC_0x01_0x0F_OServiceUserInfoUpdate],
+	{wire.OService, wire.OServiceEvilNotification}: decodeBody[wire.SNAC_0x01_0x10_OServiceEvilNotification],
+	{wire.Locate, wire.LocateUserInfoReply}:        decodeBody[wire.SNAC_0x02_0x06_LocateUserInfoReply],
+	{wire.Buddy, wire.BuddyArrived}:                decodeBody[wire.SNAC_0x03_0x0B_BuddyArrived],
+	{wire.Buddy, wire.BuddyDeparted}:               decodeBody[wire.SNAC_0x03_0x0C_BuddyDeparted],
+	{wire.ICBM, wire.ICBMChannelMsgToClient}:       decodeBody[wire.SNAC_0x04_0x07_ICBMChannelMsgToClient],
+	{wire.ICBM, wire.ICBMEvilReply}:                decodeBody[wire.SNAC_0x04_0x09_ICBMEvilReply],
+	{wire.ICBM, wire.ICBMClientEvent}:              decodeBody[wire.SNAC_0x04_0x14_ICBMClientEvent],
+	{wire.Admin, wire.AdminInfoChangeReply}:        decodeBody[wire.SNAC_0x07_0x05_AdminChangeReply],
+	{wire.ChatNav, wire.ChatNavNavInfo}:            decodeBody[wire.SNAC_0x0D_0x09_ChatNavNavInfo],
+	{wire.Chat, wire.ChatUsersJoined}:              decodeBody[wire.SNAC_0x0E_0x03_ChatUsersJoined],
+	{wire.Chat, wire.ChatUsersLeft}:                decodeBody[wire.SNAC_0x0E_0x04_ChatUsersLeft],
+	{wire.Chat, wire.ChatChannelMsgToClient}:       decodeBody[wire.SNAC_0x0E_0x06_ChatChannelMsgToClient],
+	{wire.Feedbag, wire.FeedbagReply}:              decodeBody[wire.SNAC_0x13_0x06_FeedbagReply],
+	{wire.Feedbag, wire.FeedbagInsertItem}:         decodeBody[wire.SNAC_0x13_0x08_FeedbagInsertItem],
+	{wire.Feedbag, wire.FeedbagUpdateItem}:         decodeBody[wire.SNAC_0x13_0x09_FeedbagUpdateItem],
+	{wire.Feedbag, wire.FeedbagDeleteItem}:         decodeBody[wire.SNAC_0x13_0x0A_FeedbagDeleteItem],
+	{wire.Feedbag, wire.FeedbagStatus}:             decodeBody[wire.SNAC_0x13_0x0E_FeedbagStatus],
+	{wire.BUCP, wire.BUCPLoginResponse}:            decodeBody[wire.SNAC_0x17_0x03_BUCPLoginResponse],
+}
+
+// snacErrorSubGroup is the subgroup of the error SNAC in every food group.
+const snacErrorSubGroup = 0x0001
+
+// decodeSNAC unmarshals a SNAC received from the OSCAR server. A SNAC that no
+// in-process client handles is returned with a nil body.
+func decodeSNAC(payload []byte) (wire.SNACMessage, error) {
+	r := bytes.NewReader(payload)
+	msg := wire.SNACMessage{}
+	if err := wire.UnmarshalBE(&msg.Frame, r); err != nil {
+		return msg, fmt.Errorf("unmarshal SNAC frame: %w", err)
+	}
+
+	decode := snacDecoders[[2]uint16{msg.Frame.FoodGroup, msg.Frame.SubGroup}]
+	if msg.Frame.SubGroup == snacErrorSubGroup {
+		decode = decodeBody[wire.SNACError]
+	}
+	if decode == nil {
+		return msg, nil
+	}
+
+	body, err := decode(r)
+	if err != nil {
+		return msg, fmt.Errorf("unmarshal %s: %w",
+			wire.SubGroupName(msg.Frame.FoodGroup, msg.Frame.SubGroup), err)
+	}
+	msg.Body = body
+	return msg, nil
+}
+
+func decodeBody[T any](r io.Reader) (any, error) {
+	var body T
+	err := wire.UnmarshalBE(&body, r)
+	return body, err
+}

+ 89 - 0
server/oscarclient/request_tracker.go

@@ -0,0 +1,89 @@
+package oscarclient
+
+import (
+	"sync"
+	"time"
+
+	"github.com/mk6i/open-oscar-server/wire"
+)
+
+// requestTTL is how long a sent SNAC waits for a reply before it is no
+// longer tracked. Requests the server drops, such as rate-limited ones, never
+// get a reply.
+const requestTTL = 60 * time.Second
+
+// RequestTracker tracks the SNACs a client sends to the OSCAR server by
+// request ID, so that a reply can be matched to the request that produced it.
+type RequestTracker struct {
+	mu      sync.Mutex
+	lastID  uint32
+	entries map[uint32]pendingRequest
+	timeNow func() time.Time
+}
+
+// pendingRequest is a SNAC request awaiting a reply.
+type pendingRequest struct {
+	// frame is the request's SNAC frame.
+	frame wire.SNACFrame
+	// data holds whatever the reply handler needs to know about the request.
+	data   any
+	sentAt time.Time
+}
+
+// NewRequestTracker creates a RequestTracker with no pending requests.
+func NewRequestTracker() *RequestTracker {
+	return &RequestTracker{
+		entries: make(map[uint32]pendingRequest),
+		timeNow: time.Now,
+	}
+}
+
+// Track records the request frame along with data under the next request ID,
+// and returns frame with that request ID set. Entries older than requestTTL
+// are swept out.
+func (c *RequestTracker) Track(frame wire.SNACFrame, data any) wire.SNACFrame {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+
+	now := c.timeNow()
+	for id, entry := range c.entries {
+		if now.Sub(entry.sentAt) > requestTTL {
+			delete(c.entries, id)
+		}
+	}
+
+	c.lastID++
+	if c.lastID >= wire.ReqIDFromServer {
+		c.lastID = 1
+	}
+	frame.RequestID = c.lastID
+	c.entries[frame.RequestID] = pendingRequest{
+		frame:  frame,
+		data:   data,
+		sentAt: now,
+	}
+	return frame
+}
+
+// Take removes the request that reply answers and returns the frame and data
+// it was tracked with. The request ID alone identifies the request: the OSCAR
+// server sends a client only its own request IDs, 0, or wire.ReqIDFromServer,
+// and Track hands out neither of the latter two.
+func (c *RequestTracker) Take(reply wire.SNACFrame) (frame wire.SNACFrame, data any, ok bool) {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+
+	entry, ok := c.entries[reply.RequestID]
+	if !ok {
+		return wire.SNACFrame{}, nil, false
+	}
+	delete(c.entries, reply.RequestID)
+	return entry.frame, entry.data, true
+}
+
+// Remove drops the request with the given ID.
+func (c *RequestTracker) Remove(requestID uint32) {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+	delete(c.entries, requestID)
+}

+ 93 - 0
server/oscarclient/request_tracker_test.go

@@ -0,0 +1,93 @@
+package oscarclient
+
+import (
+	"testing"
+	"time"
+
+	"github.com/stretchr/testify/assert"
+
+	"github.com/mk6i/open-oscar-server/wire"
+)
+
+func TestRequestTracker_trackAndTake(t *testing.T) {
+	c := NewRequestTracker()
+
+	first := c.Track(wire.SNACFrame{FoodGroup: wire.Locate, SubGroup: wire.LocateUserInfoQuery}, "status of them")
+	second := c.Track(wire.SNACFrame{FoodGroup: wire.ICBM, SubGroup: wire.ICBMEvilRequest}, "warning")
+
+	assert.Equal(t, uint32(1), first.RequestID)
+	assert.Equal(t, uint32(2), second.RequestID)
+
+	frame, data, ok := c.Take(wire.SNACFrame{FoodGroup: wire.Locate, SubGroup: wire.LocateUserInfoReply, RequestID: 1})
+	assert.True(t, ok)
+	assert.Equal(t, first, frame)
+	assert.Equal(t, "status of them", data)
+
+	// an entry is removed once taken
+	_, _, ok = c.Take(wire.SNACFrame{FoodGroup: wire.Locate, RequestID: 1})
+	assert.False(t, ok)
+
+	frame, data, ok = c.Take(wire.SNACFrame{FoodGroup: wire.ICBM, SubGroup: wire.ICBMErr, RequestID: 2})
+	assert.True(t, ok)
+	assert.Equal(t, second, frame)
+	assert.Equal(t, "warning", data)
+}
+
+func TestRequestTracker_remove(t *testing.T) {
+	c := NewRequestTracker()
+
+	frame := c.Track(wire.SNACFrame{FoodGroup: wire.Locate, SubGroup: wire.LocateUserInfoQuery}, nil)
+	c.Remove(frame.RequestID)
+
+	_, _, ok := c.Take(wire.SNACFrame{FoodGroup: wire.Locate, RequestID: frame.RequestID})
+	assert.False(t, ok)
+}
+
+func TestRequestTracker_sweepsExpiredEntries(t *testing.T) {
+	now := time.Now()
+	c := NewRequestTracker()
+	c.timeNow = func() time.Time { return now }
+
+	old := c.Track(wire.SNACFrame{FoodGroup: wire.ICBM, SubGroup: wire.ICBMChannelMsgToHost}, nil)
+
+	now = now.Add(requestTTL + time.Second)
+	fresh := c.Track(wire.SNACFrame{FoodGroup: wire.ICBM, SubGroup: wire.ICBMChannelMsgToHost}, nil)
+
+	_, _, ok := c.Take(wire.SNACFrame{FoodGroup: wire.ICBM, RequestID: old.RequestID})
+	assert.False(t, ok)
+	_, _, ok = c.Take(wire.SNACFrame{FoodGroup: wire.ICBM, RequestID: fresh.RequestID})
+	assert.True(t, ok)
+}
+
+func TestRequestTracker_requestIDWrapsBeforeServerRange(t *testing.T) {
+	c := NewRequestTracker()
+	c.lastID = wire.ReqIDFromServer - 1
+
+	frame := c.Track(wire.SNACFrame{FoodGroup: wire.ICBM}, nil)
+
+	assert.Equal(t, uint32(1), frame.RequestID)
+}
+
+func TestRequestTracker_takeIgnoresServerRequestIDs(t *testing.T) {
+	cases := []struct {
+		name      string
+		requestID uint32
+	}{
+		{name: "request ID left unset", requestID: 0},
+		{name: "server request ID", requestID: wire.ReqIDFromServer},
+	}
+
+	for _, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			c := NewRequestTracker()
+			frame := c.Track(wire.SNACFrame{FoodGroup: wire.ICBM, SubGroup: wire.ICBMChannelMsgToHost}, nil)
+
+			_, _, ok := c.Take(wire.SNACFrame{FoodGroup: wire.ICBM, SubGroup: wire.ICBMChannelMsgToClient, RequestID: tc.requestID})
+			assert.False(t, ok)
+
+			// the tracked request is still pending
+			_, _, ok = c.Take(frame)
+			assert.True(t, ok)
+		})
+	}
+}

+ 48 - 43
server/toc/cmd_client.go

@@ -18,7 +18,7 @@ import (
 
 	"github.com/google/uuid"
 
-	"github.com/mk6i/open-oscar-server/config"
+	"github.com/mk6i/open-oscar-server/server/oscarclient"
 	"github.com/mk6i/open-oscar-server/state"
 	"github.com/mk6i/open-oscar-server/wire"
 )
@@ -38,11 +38,8 @@ type OSCARProxy struct {
 	HTTPIPRateLimiter *IPRateLimiter
 	LocateService     LocateService
 	Logger            *slog.Logger
-	// OSCARServer serves the OSCAR connections TOC opens for its users.
-	OSCARServer OSCARServer
-	// OSCAREndpoint is the OSCAR listener that TOC's connections appear to
-	// arrive on.
-	OSCAREndpoint    config.Endpoint
+	// OSCARClient signs TOC's users on to the OSCAR server.
+	OSCARClient      oscarclient.Client
 	SessionRetriever SessionRetriever
 	TOCConfigStore   TOCConfigStore
 	// RandIntn is the source for feedbag item ID generation.
@@ -53,11 +50,11 @@ type OSCARProxy struct {
 // signonTimeout bounds how long await waits for a reply during signon.
 const signonTimeout = 10 * time.Second
 
-// Request contexts are cached with each SNAC that TOC sends to the OSCAR
-// server, under the SNAC's request ID (see snacCache). When the reply or error
-// comes back, cmd_server.go uses the context's type to tell which TOC command
-// the reply answers, and the context's fields for what the reply doesn't
-// carry.
+// Request contexts are tracked with each SNAC that TOC sends to the OSCAR
+// server, under the SNAC's request ID (see oscarclient.RequestTracker). When
+// the reply or error comes back, cmd_server.go uses the context's type to tell
+// which TOC command the reply answers, and the context's fields for what the
+// reply doesn't carry.
 type (
 	// getStatusReqCtx is the request context of a toc_get_status user info
 	// query.
@@ -213,22 +210,22 @@ func (s OSCARProxy) RecvClientCmd(ctx context.Context, me *tocConn, payload []by
 }
 
 // send sends a SNAC request to the OSCAR server over conn. The request is
-// cached by request ID along with data so that cmd_server.go can handle the
+// tracked by request ID along with data so that cmd_server.go can handle the
 // reply. It returns a TOC error if the SNAC could not be sent.
 func (s OSCARProxy) send(ctx context.Context, me *tocConn, conn oscarConn, foodGroup uint16, subGroup uint16, body any, data any) []string {
 	frame := wire.SNACFrame{
 		FoodGroup: foodGroup,
 		SubGroup:  subGroup,
 	}
-	me.cache.add(&frame, data)
+	frame = me.requests.Track(frame, data)
 	return s.sendFrame(ctx, me, conn, frame, body)
 }
 
-// sendFrame sends a SNAC request whose frame is already cached. It returns a
+// sendFrame sends a SNAC request whose frame is already tracked. It returns a
 // TOC error if the SNAC could not be sent.
 func (s OSCARProxy) sendFrame(ctx context.Context, me *tocConn, conn oscarConn, frame wire.SNACFrame, body any) []string {
 	if err := conn.SendSNAC(frame, body); err != nil {
-		me.cache.remove(frame.RequestID)
+		me.requests.Remove(frame.RequestID)
 		return s.runtimeErr(ctx, fmt.Errorf("SendSNAC(%s, %s): %w",
 			wire.FoodGroupName(frame.FoodGroup), wire.SubGroupName(frame.FoodGroup, frame.SubGroup), err))
 	}
@@ -517,10 +514,14 @@ func (s OSCARProxy) requestChatService(ctx context.Context, me *tocConn, chatID
 // connectChat opens a connection to the chat room identified by loginCookie
 // and signs the user into the room.
 func (s OSCARProxy) connectChat(ctx context.Context, me *tocConn, loginCookie []byte) (oscarConn, error) {
-	conn, err := s.connectService(me.clientAddr, loginCookie)
+	conn, err := s.OSCARClient.ConnectService(ctx, me.clientAddr, loginCookie)
 	if err != nil {
-		return nil, fmt.Errorf("connectService: %w", err)
+		return nil, fmt.Errorf("ConnectService: %w", err)
 	}
+	me.goAsync(func(ctx context.Context) error {
+		conn.Run(ctx)
+		return nil
+	})
 
 	subscribe := wire.SNAC_0x01_0x08_OServiceRateParamsSubAdd{
 		ClassIDs: []uint16{1, 2, 3, 4, 5},
@@ -1072,18 +1073,18 @@ func (s OSCARProxy) deleteFeedbag(ctx context.Context, me *tocConn, items []wire
 // sendFeedbagChange sends a feedbag change and records it in the feedbag
 // mirror as pending until the server confirms it.
 func (s OSCARProxy) sendFeedbagChange(ctx context.Context, me *tocConn, subGroup uint16, body any, del bool, items []wire.FeedbagItem) []string {
-	me.feedbag.sendMu.Lock()
-	defer me.feedbag.sendMu.Unlock()
+	me.feedbagSendMu.Lock()
+	defer me.feedbagSendMu.Unlock()
 
 	frame := wire.SNACFrame{
 		FoodGroup: wire.Feedbag,
 		SubGroup:  subGroup,
 	}
-	me.cache.add(&frame, feedbagChangeReqCtx{})
-	me.feedbag.sent(frame.RequestID, del, items)
+	frame = me.requests.Track(frame, feedbagChangeReqCtx{})
+	me.feedbag.Sent(frame.RequestID, del, items)
 
 	if msg := s.sendFrame(ctx, me, me.bos, frame, body); msg != nil {
-		me.feedbag.discard(frame.RequestID)
+		me.feedbag.Discard(frame.RequestID)
 		return msg
 	}
 	return nil
@@ -1092,11 +1093,11 @@ func (s OSCARProxy) sendFeedbagChange(ctx context.Context, me *tocConn, subGroup
 // reloadFeedbag queries the server's feedbag to replace the feedbag mirror.
 // FeedbagReply finishes the reload.
 func (s OSCARProxy) reloadFeedbag(ctx context.Context, me *tocConn) []string {
-	me.feedbag.sendMu.Lock()
-	defer me.feedbag.sendMu.Unlock()
+	me.feedbagSendMu.Lock()
+	defer me.feedbagSendMu.Unlock()
 
 	return s.send(ctx, me, me.bos, wire.Feedbag, wire.FeedbagQuery, struct{}{}, feedbagReloadReqCtx{
-		marker: me.feedbag.mark(),
+		marker: me.feedbag.Mark(),
 	})
 }
 
@@ -1124,7 +1125,7 @@ func (s OSCARProxy) SetPDMode(ctx context.Context, me *tocConn, args []byte) []s
 		return s.runtimeErr(ctx, errors.New("invalid pd mode specified"))
 	}
 
-	fl := state.NewFeedbagList(me.feedbag.snapshot(), s.RandIntn)
+	fl := state.NewFeedbagList(me.feedbag.Snapshot(), s.RandIntn)
 	fl.SetMode(uint8(mode))
 
 	if pending := fl.PendingUpdates(); len(pending) > 0 {
@@ -1155,7 +1156,7 @@ func (s OSCARProxy) NewGroup(ctx context.Context, me *tocConn, args []byte) []st
 		return s.runtimeErr(ctx, fmt.Errorf("empty group name"))
 	}
 
-	fl := state.NewFeedbagList(me.feedbag.snapshot(), s.RandIntn)
+	fl := state.NewFeedbagList(me.feedbag.Snapshot(), s.RandIntn)
 	fl.AddGroup(groupName)
 
 	if pending := fl.PendingUpdates(); len(pending) > 0 {
@@ -1185,7 +1186,7 @@ func (s OSCARProxy) DelGroup(ctx context.Context, me *tocConn, args []byte) []st
 		return s.runtimeErr(ctx, fmt.Errorf("empty group name"))
 	}
 
-	fl := state.NewFeedbagList(me.feedbag.snapshot(), s.RandIntn)
+	fl := state.NewFeedbagList(me.feedbag.Snapshot(), s.RandIntn)
 	fl.DeleteGroup(groupName)
 
 	pending := fl.PendingDeletes()
@@ -1234,7 +1235,7 @@ func (s OSCARProxy) NewBuddies(ctx context.Context, me *tocConn, args []byte) []
 		return s.runtimeErr(ctx, fmt.Errorf("parseTOC2Config: %w", err))
 	}
 
-	fl := state.NewFeedbagList(me.feedbag.snapshot(), s.RandIntn)
+	fl := state.NewFeedbagList(me.feedbag.Snapshot(), s.RandIntn)
 
 	var replies []string
 
@@ -1331,7 +1332,7 @@ func (s OSCARProxy) RemoveBuddy2(ctx context.Context, me *tocConn, args []byte)
 		return s.runtimeErr(ctx, fmt.Errorf("missing params: need at least one screenname and group"))
 	}
 
-	fl := state.NewFeedbagList(me.feedbag.snapshot(), s.RandIntn)
+	fl := state.NewFeedbagList(me.feedbag.Snapshot(), s.RandIntn)
 
 	groupName := params[len(params)-1]
 	screenNames := params[:len(params)-1]
@@ -1376,7 +1377,7 @@ func (s OSCARProxy) AddPermit2(ctx context.Context, me *tocConn, args []byte) []
 		return s.runtimeErr(ctx, fmt.Errorf("no screennames provided"))
 	}
 
-	fl := state.NewFeedbagList(me.feedbag.snapshot(), s.RandIntn)
+	fl := state.NewFeedbagList(me.feedbag.Snapshot(), s.RandIntn)
 
 	for _, sn := range screenNames {
 		fl.PermitUser(sn)
@@ -1409,7 +1410,7 @@ func (s OSCARProxy) RemovePermit2(ctx context.Context, me *tocConn, args []byte)
 		return s.runtimeErr(ctx, fmt.Errorf("no screennames provided"))
 	}
 
-	fl := state.NewFeedbagList(me.feedbag.snapshot(), s.RandIntn)
+	fl := state.NewFeedbagList(me.feedbag.Snapshot(), s.RandIntn)
 
 	for _, sn := range screenNames {
 		fl.DeletePermit(sn)
@@ -1442,7 +1443,7 @@ func (s OSCARProxy) AddDeny2(ctx context.Context, me *tocConn, args []byte) []st
 		return s.runtimeErr(ctx, fmt.Errorf("no screennames provided"))
 	}
 
-	fl := state.NewFeedbagList(me.feedbag.snapshot(), s.RandIntn)
+	fl := state.NewFeedbagList(me.feedbag.Snapshot(), s.RandIntn)
 
 	for _, sn := range screenNames {
 		fl.DenyUser(sn)
@@ -1475,7 +1476,7 @@ func (s OSCARProxy) RemoveDeny2(ctx context.Context, me *tocConn, args []byte) [
 		return s.runtimeErr(ctx, fmt.Errorf("no screennames provided"))
 	}
 
-	fl := state.NewFeedbagList(me.feedbag.snapshot(), s.RandIntn)
+	fl := state.NewFeedbagList(me.feedbag.Snapshot(), s.RandIntn)
 
 	for _, sn := range screenNames {
 		fl.DeleteDeny(sn)
@@ -1883,7 +1884,7 @@ func (s OSCARProxy) SetInfo(ctx context.Context, me *tocConn, args []byte) []str
 // Command syntax: toc_signon <authorizer host> <authorizer port> <User Name> <Password> <language> <version>
 // Command syntax: toc2_signon <authorizer host> <authorizer port> <User Name> <Password> <language> <version>
 // Command syntax: toc2_login <authorizer host> <authorizer port> <User Name> <Password> <language> <version> [additional params...]
-func (s OSCARProxy) Signon(ctx context.Context, args []byte, clientAddr net.Addr) (*tocConn, []string) {
+func (s OSCARProxy) Signon(ctx context.Context, args []byte, clientAddr net.Addr, goAsync func(f func(ctx context.Context) error)) (*tocConn, []string) {
 	var cmd, userName, password string
 
 	if _, err := parseArgs(args, &cmd, nil, nil, &userName, &password); err != nil {
@@ -1913,9 +1914,9 @@ func (s OSCARProxy) Signon(ctx context.Context, args []byte, clientAddr net.Addr
 		signonTLVs = append(signonTLVs, wire.NewTLVBE(wire.LoginTLVTagsMultiConnFlags, wire.MultiConnFlagsRecentClient))
 	}
 
-	block, err := s.authenticate(clientAddr, signonTLVs)
+	block, err := s.OSCARClient.Login(clientAddr, signonTLVs)
 	if err != nil {
-		return nil, s.runtimeErr(ctx, fmt.Errorf("authenticate: %w", err))
+		return nil, s.runtimeErr(ctx, fmt.Errorf("OSCARClient.Login: %w", err))
 	}
 
 	if code, failed := block.Uint16BE(wire.LoginTLVTagsErrorSubcode); failed {
@@ -1931,10 +1932,14 @@ func (s OSCARProxy) Signon(ctx context.Context, args []byte, clientAddr net.Addr
 		return nil, s.runtimeErr(ctx, fmt.Errorf("unable to get session id from payload"))
 	}
 
-	bos, err := s.connectService(clientAddr, authCookie)
+	bos, err := s.OSCARClient.ConnectService(ctx, clientAddr, authCookie)
 	if err != nil {
-		return nil, s.runtimeErr(ctx, fmt.Errorf("connectService: %w", err))
+		return nil, s.runtimeErr(ctx, fmt.Errorf("ConnectService: %w", err))
 	}
+	goAsync(func(ctx context.Context) error {
+		bos.Run(ctx)
+		return nil
+	})
 
 	me := newTOCConn(bos, state.NewIdentScreenName(userName), clientAddr)
 	me.isTOC2 = cmd != "toc_signon"
@@ -2006,7 +2011,7 @@ func (s OSCARProxy) signonConfig(ctx context.Context, me *tocConn, cmd string) (
 		return nil, fmt.Errorf("unexpected feedbag reply %v", reply.Frame)
 	}
 
-	me.feedbag.reset(feedbag.Items)
+	me.feedbag.Reset(feedbag.Items)
 
 	cfg, err := buildToc2Config(feedbag.Items)
 	if err != nil {
@@ -2023,8 +2028,8 @@ func (s OSCARProxy) await(ctx context.Context, me *tocConn, foodGroup uint16, su
 		FoodGroup: foodGroup,
 		SubGroup:  subGroup,
 	}
-	me.cache.add(&frame, nil)
-	defer me.cache.remove(frame.RequestID)
+	frame = me.requests.Track(frame, nil)
+	defer me.requests.Remove(frame.RequestID)
 
 	if err := me.bos.SendSNAC(frame, body); err != nil {
 		return wire.SNACMessage{}, fmt.Errorf("SendSNAC: %w", err)
@@ -2045,7 +2050,7 @@ func (s OSCARProxy) await(ctx context.Context, me *tocConn, foodGroup uint16, su
 			}
 			return msg, nil
 		case <-me.bos.Closed():
-			return wire.SNACMessage{}, errSignedOff
+			return wire.SNACMessage{}, oscarclient.ErrSignedOff
 		case <-timeout.C:
 			return wire.SNACMessage{}, errors.New("timed out waiting for reply")
 		case <-ctx.Done():

+ 54 - 50
server/toc/cmd_client_test.go

@@ -13,6 +13,7 @@ import (
 	"github.com/google/uuid"
 	"github.com/stretchr/testify/assert"
 
+	"github.com/mk6i/open-oscar-server/server/oscarclient"
 	"github.com/mk6i/open-oscar-server/state"
 	"github.com/mk6i/open-oscar-server/wire"
 )
@@ -27,8 +28,8 @@ type cmdTestCase struct {
 	sendErrs []error
 	// wantSNACs are the SNACs the command sends to the BOS server
 	wantSNACs []wire.SNACMessage
-	// wantCacheData is the request context cached with the first SNAC
-	wantCacheData any
+	// wantRequestData is the request context tracked with the first SNAC
+	wantRequestData any
 	// wantMsg is the expected TOC response
 	wantMsg []string
 }
@@ -49,30 +50,30 @@ func runCmdTests(t *testing.T, cases []cmdTestCase) {
 
 			assert.Equal(t, tc.wantMsg, msg)
 			assert.Equal(t, tc.wantSNACs, bos.sentSNACs())
-			if tc.wantCacheData != nil {
-				req, ok := me.cache.take(wire.SNACFrame{FoodGroup: tc.wantSNACs[0].Frame.FoodGroup, RequestID: 1})
+			if tc.wantRequestData != nil {
+				_, data, ok := me.requests.Take(wire.SNACFrame{FoodGroup: tc.wantSNACs[0].Frame.FoodGroup, RequestID: 1})
 				assert.True(t, ok)
-				assert.Equal(t, tc.wantCacheData, req.data)
+				assert.Equal(t, tc.wantRequestData, data)
 			}
 		})
 	}
 }
 
 func TestOSCARProxy_send(t *testing.T) {
-	t.Run("caches the request until its reply arrives", func(t *testing.T) {
+	t.Run("tracks the request until its reply arrives", func(t *testing.T) {
 		me, bos := newTestTOCConn(newTestSession("me"))
 		svc := OSCARProxy{Logger: slog.Default()}
 
 		msg := svc.send(context.Background(), me, bos, wire.Locate, wire.LocateUserInfoQuery, struct{}{}, getStatusReqCtx{screenName: "them"})
 		assert.Nil(t, msg)
 
-		req, ok := me.cache.take(wire.SNACFrame{FoodGroup: wire.Locate, RequestID: 1})
+		frame, data, ok := me.requests.Take(wire.SNACFrame{FoodGroup: wire.Locate, RequestID: 1})
 		assert.True(t, ok)
-		assert.Equal(t, wire.LocateUserInfoQuery, req.frame.SubGroup)
-		assert.Equal(t, getStatusReqCtx{screenName: "them"}, req.data)
+		assert.Equal(t, wire.LocateUserInfoQuery, frame.SubGroup)
+		assert.Equal(t, getStatusReqCtx{screenName: "them"}, data)
 	})
 
-	t.Run("drops the cached request when the send fails", func(t *testing.T) {
+	t.Run("drops the tracked request when the send fails", func(t *testing.T) {
 		me, bos := newTestTOCConn(newTestSession("me"))
 		bos.sendErrs = []error{io.EOF}
 		svc := OSCARProxy{Logger: slog.Default()}
@@ -80,7 +81,7 @@ func TestOSCARProxy_send(t *testing.T) {
 		msg := svc.send(context.Background(), me, bos, wire.Locate, wire.LocateUserInfoQuery, struct{}{}, nil)
 		assert.Equal(t, []string{cmdInternalSvcErr}, msg)
 
-		_, ok := me.cache.take(wire.SNACFrame{FoodGroup: wire.Locate, RequestID: 1})
+		_, _, ok := me.requests.Take(wire.SNACFrame{FoodGroup: wire.Locate, RequestID: 1})
 		assert.False(t, ok)
 	})
 }
@@ -255,8 +256,8 @@ func TestOSCARProxy_RecvClientCmd_ChangePassword(t *testing.T) {
 					},
 				}),
 			},
-			wantCacheData: changePasswdReqCtx{},
-			wantMsg:       []string{},
+			wantRequestData: changePasswdReqCtx{},
+			wantMsg:         []string{},
 		},
 		{
 			name:     "request password change, send fails",
@@ -296,8 +297,8 @@ func TestOSCARProxy_RecvClientCmd_FormatNickname(t *testing.T) {
 					},
 				}),
 			},
-			wantCacheData: formatNickReqCtx{},
-			wantMsg:       []string{},
+			wantRequestData: formatNickReqCtx{},
+			wantMsg:         []string{},
 		},
 		{
 			name:     "bad command",
@@ -318,8 +319,8 @@ func TestOSCARProxy_RecvClientCmd_Evil(t *testing.T) {
 					ScreenName: "them",
 				}),
 			},
-			wantCacheData: evilReqCtx{},
-			wantMsg:       []string{},
+			wantRequestData: evilReqCtx{},
+			wantMsg:         []string{},
 		},
 		{
 			name:     "successfully warn anonymously",
@@ -330,8 +331,8 @@ func TestOSCARProxy_RecvClientCmd_Evil(t *testing.T) {
 					ScreenName: "them",
 				}),
 			},
-			wantCacheData: evilReqCtx{},
-			wantMsg:       []string{},
+			wantRequestData: evilReqCtx{},
+			wantMsg:         []string{},
 		},
 		{
 			name:     "warn with incorrect type",
@@ -356,8 +357,8 @@ func TestOSCARProxy_RecvClientCmd_GetStatus(t *testing.T) {
 					ScreenName: "them",
 				}),
 			},
-			wantCacheData: getStatusReqCtx{screenName: "them"},
-			wantMsg:       []string{},
+			wantRequestData: getStatusReqCtx{screenName: "them"},
+			wantMsg:         []string{},
 		},
 		{
 			name:     "request status, send fails",
@@ -394,8 +395,8 @@ func TestOSCARProxy_RecvClientCmd_ChatJoin(t *testing.T) {
 					},
 				}),
 			},
-			wantCacheData: chatJoinReqCtx{},
-			wantMsg:       []string{},
+			wantRequestData: chatJoinReqCtx{},
+			wantMsg:         []string{},
 		},
 		{
 			name:     "request room creation, send fails",
@@ -435,11 +436,11 @@ func TestOSCARProxy_RecvClientCmd_ChatAccept(t *testing.T) {
 	}
 
 	cases := []struct {
-		name          string
-		givenCmd      string
-		wantSNACs     []wire.SNACMessage
-		wantCacheData any
-		wantMsg       []string
+		name            string
+		givenCmd        string
+		wantSNACs       []wire.SNACMessage
+		wantRequestData any
+		wantMsg         []string
 	}{
 		{
 			name:     "successfully request room info",
@@ -451,8 +452,8 @@ func TestOSCARProxy_RecvClientCmd_ChatAccept(t *testing.T) {
 					InstanceNumber: 0,
 				}),
 			},
-			wantCacheData: chatAcceptReqCtx{chatID: 0},
-			wantMsg:       []string{},
+			wantRequestData: chatAcceptReqCtx{chatID: 0},
+			wantMsg:         []string{},
 		},
 		{
 			name:     "accept invitation to unknown room",
@@ -483,10 +484,10 @@ func TestOSCARProxy_RecvClientCmd_ChatAccept(t *testing.T) {
 
 			assert.Equal(t, tc.wantMsg, msg)
 			assert.Equal(t, tc.wantSNACs, bos.sentSNACs())
-			if tc.wantCacheData != nil {
-				req, ok := me.cache.take(wire.SNACFrame{FoodGroup: wire.ChatNav, RequestID: 1})
+			if tc.wantRequestData != nil {
+				_, data, ok := me.requests.Take(wire.SNACFrame{FoodGroup: wire.ChatNav, RequestID: 1})
 				assert.True(t, ok)
-				assert.Equal(t, tc.wantCacheData, req.data)
+				assert.Equal(t, tc.wantRequestData, data)
 			}
 		})
 	}
@@ -1799,7 +1800,7 @@ func TestOSCARProxy_RecvClientCmd_NewBuddies(t *testing.T) {
 			me, bos := newTestTOCConn(tc.me)
 			me.isTOC2 = true
 			for _, params := range tc.mockParams.feedbagParams {
-				me.feedbag.reset(params.results)
+				me.feedbag.Reset(params.results)
 			}
 			wantSNACs, sendErrs := feedbagSNACs(tc.mockParams.feedBagParams)
 			bos.sendErrs = sendErrs
@@ -1972,7 +1973,7 @@ func TestOSCARProxy_RecvClientCmd_NewGroup(t *testing.T) {
 			me, bos := newTestTOCConn(tc.me)
 			me.isTOC2 = true
 			for _, params := range tc.mockParams.feedbagParams {
-				me.feedbag.reset(params.results)
+				me.feedbag.Reset(params.results)
 			}
 			wantSNACs, sendErrs := feedbagSNACs(tc.mockParams.feedBagParams)
 			bos.sendErrs = sendErrs
@@ -2146,7 +2147,7 @@ func TestOSCARProxy_RecvClientCmd_DelGroup(t *testing.T) {
 			me, bos := newTestTOCConn(tc.me)
 			me.isTOC2 = true
 			for _, params := range tc.mockParams.feedbagParams {
-				me.feedbag.reset(params.results)
+				me.feedbag.Reset(params.results)
 			}
 			wantSNACs, sendErrs := feedbagSNACs(tc.mockParams.feedBagParams)
 			bos.sendErrs = sendErrs
@@ -2331,7 +2332,7 @@ func TestOSCARProxy_RecvClientCmd_SetPDMode(t *testing.T) {
 			me, bos := newTestTOCConn(tc.me)
 			me.isTOC2 = true
 			for _, params := range tc.mockParams.feedbagParams {
-				me.feedbag.reset(params.results)
+				me.feedbag.Reset(params.results)
 			}
 			wantSNACs, sendErrs := feedbagSNACs(tc.mockParams.feedBagParams)
 			bos.sendErrs = sendErrs
@@ -2469,7 +2470,7 @@ func TestOSCARProxy_RecvClientCmd_AddPermit2(t *testing.T) {
 			me, bos := newTestTOCConn(tc.me)
 			me.isTOC2 = true
 			for _, params := range tc.mockParams.feedbagParams {
-				me.feedbag.reset(params.results)
+				me.feedbag.Reset(params.results)
 			}
 			wantSNACs, sendErrs := feedbagSNACs(tc.mockParams.feedBagParams)
 			bos.sendErrs = sendErrs
@@ -2606,7 +2607,7 @@ func TestOSCARProxy_RecvClientCmd_AddDeny2(t *testing.T) {
 			me, bos := newTestTOCConn(tc.me)
 			me.isTOC2 = true
 			for _, params := range tc.mockParams.feedbagParams {
-				me.feedbag.reset(params.results)
+				me.feedbag.Reset(params.results)
 			}
 			wantSNACs, sendErrs := feedbagSNACs(tc.mockParams.feedBagParams)
 			bos.sendErrs = sendErrs
@@ -2745,7 +2746,7 @@ func TestOSCARProxy_RecvClientCmd_RemoveBuddy2(t *testing.T) {
 			me, bos := newTestTOCConn(tc.me)
 			me.isTOC2 = true
 			for _, params := range tc.mockParams.feedbagParams {
-				me.feedbag.reset(params.results)
+				me.feedbag.Reset(params.results)
 			}
 			wantSNACs, sendErrs := feedbagSNACs(tc.mockParams.feedBagParams)
 			bos.sendErrs = sendErrs
@@ -2892,7 +2893,7 @@ func TestOSCARProxy_RecvClientCmd_RemovePermit2(t *testing.T) {
 			me, bos := newTestTOCConn(tc.me)
 			me.isTOC2 = true
 			for _, params := range tc.mockParams.feedbagParams {
-				me.feedbag.reset(params.results)
+				me.feedbag.Reset(params.results)
 			}
 			wantSNACs, sendErrs := feedbagSNACs(tc.mockParams.feedBagParams)
 			bos.sendErrs = sendErrs
@@ -3039,7 +3040,7 @@ func TestOSCARProxy_RecvClientCmd_RemoveDeny2(t *testing.T) {
 			me, bos := newTestTOCConn(tc.me)
 			me.isTOC2 = true
 			for _, params := range tc.mockParams.feedbagParams {
-				me.feedbag.reset(params.results)
+				me.feedbag.Reset(params.results)
 			}
 			wantSNACs, sendErrs := feedbagSNACs(tc.mockParams.feedBagParams)
 			bos.sendErrs = sendErrs
@@ -3968,10 +3969,13 @@ func TestOSCARProxy_Signon(t *testing.T) {
 
 			svc := OSCARProxy{
 				Logger:         slog.Default(),
-				OSCARServer:    oscarServer,
+				OSCARClient:    oscarclient.Client{Server: oscarServer, Logger: slog.Default()},
 				TOCConfigStore: tocConfigStore,
 			}
-			me, msg := svc.Signon(ctx, []byte(tc.givenCmd), clientAddr)
+			goAsync := func(f func(ctx context.Context) error) {
+				go func() { _ = f(ctx) }()
+			}
+			me, msg := svc.Signon(ctx, []byte(tc.givenCmd), clientAddr, goAsync)
 			assert.Equal(t, tc.wantMsg, msg)
 
 			if tc.authReply != nil {
@@ -4005,7 +4009,7 @@ func TestOSCARProxy_Signon(t *testing.T) {
 			assert.Equal(t, tc.wantTOC2, me.IsTOC2())
 			assert.Equal(t, tc.wantMsgEnc, me.SupportsTOC2MsgEnc())
 			assert.Len(t, me.backlog, tc.wantBacklog)
-			assert.Equal(t, tc.wantFeedbag, me.feedbag.snapshot())
+			assert.Equal(t, tc.wantFeedbag, me.feedbag.Snapshot())
 			me.bos.Close()
 		})
 	}
@@ -4038,7 +4042,7 @@ func TestOSCARProxy_RecvClientCmd_LocalRateLimit(t *testing.T) {
 func TestOSCARProxy_RecvClientCmd_FeedbagMirrorFollowsChanges(t *testing.T) {
 	me, bos := newTestTOCConn(newTestSession("me"))
 	me.isTOC2 = true
-	me.feedbag.reset([]wire.FeedbagItem{
+	me.feedbag.Reset([]wire.FeedbagItem{
 		{
 			ClassID:   wire.FeedbagClassIdGroup,
 			TLVLBlock: wire.TLVLBlock{TLVList: wire.TLVList{wire.NewTLVBE(wire.FeedbagAttributesOrder, []uint16{})}},
@@ -4073,19 +4077,19 @@ func TestOSCARProxy_RecvClientCmd_FeedbagMirrorFollowsChanges(t *testing.T) {
 	}, sent[1].Body.(wire.SNAC_0x13_0x09_FeedbagUpdateItem).Items)
 	assert.Equal(t, wire.FeedbagInsertItem, sent[2].Frame.SubGroup)
 
-	names := me.feedbag.groupNames()
+	names := me.feedbag.GroupNames()
 	assert.Equal(t, "Family", names[1])
 
 	// deleting the group removes it from the mirror
 	assert.Equal(t, []string{}, svc.RecvClientCmd(context.Background(), me, []byte("toc2_del_group Family")))
-	_, hasFamily := me.feedbag.groupNames()[1]
+	_, hasFamily := me.feedbag.GroupNames()[1]
 	assert.False(t, hasFamily)
 
 	// a change that fails to send is forgotten
-	before := me.feedbag.snapshot()
+	before := me.feedbag.Snapshot()
 	bos.sendErrs = append(make([]error, len(bos.sentSNACs())), io.EOF)
 	assert.Equal(t, []string{cmdInternalSvcErr}, svc.RecvClientCmd(context.Background(), me, []byte("toc2_new_group Work")))
-	assert.Equal(t, before, me.feedbag.snapshot())
+	assert.Equal(t, before, me.feedbag.Snapshot())
 }
 
 func TestOSCARProxy_RecvClientCmd_TOC2CmdFromTOC1(t *testing.T) {

+ 28 - 28
server/toc/cmd_server.go

@@ -66,7 +66,7 @@ func (s OSCARProxy) recvBOSSNAC(ctx context.Context, me *tocConn, snac wire.SNAC
 		msg = s.Eviled(v)
 	case wire.SNAC_0x01_0x0A_OServiceRateParamsChange:
 		msg = s.RateParamsChange(v)
-		if v.Code == rateParamsChangeClear && me.feedbag.hasPending() {
+		if v.Code == rateParamsChangeClear && me.feedbag.HasPending() {
 			// the server may have dropped feedbag changes without replying
 			// while limited
 			msg = s.reloadFeedbag(ctx, me)
@@ -77,18 +77,18 @@ func (s OSCARProxy) recvBOSSNAC(ctx context.Context, me *tocConn, snac wire.SNAC
 		}
 	case wire.SNAC_0x13_0x08_FeedbagInsertItem:
 		if me.IsTOC2() {
-			me.feedbag.applyRemote(false, v.Items)
+			me.feedbag.ApplyRemote(false, v.Items)
 			msg = s.Inserted2(me, v.Items)
 		}
 	case wire.SNAC_0x13_0x09_FeedbagUpdateItem:
 		if me.IsTOC2() {
-			me.feedbag.applyRemote(false, v.Items)
+			me.feedbag.ApplyRemote(false, v.Items)
 			msg = s.Inserted2(me, v.Items)
 		}
 	case wire.SNAC_0x13_0x0A_FeedbagDeleteItem:
 		if me.IsTOC2() {
 			msg = s.Deleted2(me, v)
-			me.feedbag.applyRemote(true, v.Items)
+			me.feedbag.ApplyRemote(true, v.Items)
 		}
 	case wire.SNACError:
 		msg = s.SNACError(ctx, me, snac.Frame, v)
@@ -106,7 +106,7 @@ func (s OSCARProxy) recvBOSSNAC(ctx context.Context, me *tocConn, snac wire.SNAC
 		s.FeedbagReply(me, snac.Frame, v)
 	case wire.SNAC_0x04_0x09_ICBMEvilReply:
 		// the warning succeeded and there's nothing to tell the client
-		me.cache.take(snac.Frame)
+		me.requests.Take(snac.Frame)
 	default:
 		s.Logger.DebugContext(ctx, fmt.Sprintf("unsupported snac. foodgroup: %s subgroup: %s",
 			wire.FoodGroupName(snac.Frame.FoodGroup),
@@ -136,7 +136,7 @@ func (s OSCARProxy) RecvChat(ctx context.Context, me *tocConn, conn oscarConn, c
 				sendOrCancel(ctx, me.toCh, s.ChatUpdateBuddyArrived(v, chatID))
 			case wire.SNAC_0x0E_0x06_ChatChannelMsgToClient:
 				// a reflected message answers the user's own toc_chat_send
-				me.cache.take(snac.Frame)
+				me.requests.Take(snac.Frame)
 				sendOrCancel(ctx, me.toCh, s.ChatIn(ctx, me, v, chatID))
 			case wire.SNAC_0x01_0x0A_OServiceRateParamsChange:
 				if msg := s.RateParamsChange(v); len(msg) > 0 {
@@ -168,14 +168,14 @@ func (s OSCARProxy) RateParamsChange(snac wire.SNAC_0x01_0x0A_OServiceRateParams
 // SNACError handles an error reply from the OSCAR server according to the
 // request that caused it.
 func (s OSCARProxy) SNACError(ctx context.Context, me *tocConn, frame wire.SNACFrame, snac wire.SNACError) []string {
-	req, ok := me.cache.take(frame)
+	reqFrame, reqData, ok := me.requests.Take(frame)
 	if !ok {
 		s.Logger.DebugContext(ctx, "received SNAC error for unknown request",
 			"foodgroup", wire.FoodGroupName(frame.FoodGroup), "code", snac.Code)
 		return nil
 	}
 
-	switch data := req.data.(type) {
+	switch data := reqData.(type) {
 	case getStatusReqCtx:
 		if snac.Code == wire.ErrorCodeNotLoggedOn {
 			return []string{fmt.Sprintf("ERROR:%s:%s", wire.TOCErrorGeneralUserNotAvailable, data.screenName)}
@@ -186,14 +186,14 @@ func (s OSCARProxy) SNACError(ctx context.Context, me *tocConn, frame wire.SNACF
 		return []string{"ERROR:" + wire.TOCErrorGeneralWarningUserNotAvailable}
 	case feedbagChangeReqCtx:
 		s.Logger.DebugContext(ctx, "feedbag change failed", "code", snac.Code)
-		me.feedbag.discard(frame.RequestID)
+		me.feedbag.Discard(frame.RequestID)
 		return nil
 	case chatJoinReqCtx, chatAcceptReqCtx, chatServiceReqCtx:
 		return s.runtimeErr(ctx, fmt.Errorf("unable to join chat room, %s error code: %d",
-			wire.SubGroupName(req.frame.FoodGroup, req.frame.SubGroup), snac.Code))
+			wire.SubGroupName(reqFrame.FoodGroup, reqFrame.SubGroup), snac.Code))
 	default:
 		s.Logger.DebugContext(ctx, "received SNAC error",
-			"request", wire.SubGroupName(req.frame.FoodGroup, req.frame.SubGroup), "code", snac.Code)
+			"request", wire.SubGroupName(reqFrame.FoodGroup, reqFrame.SubGroup), "code", snac.Code)
 		return nil
 	}
 }
@@ -201,25 +201,25 @@ func (s OSCARProxy) SNACError(ctx context.Context, me *tocConn, frame wire.SNACF
 // FeedbagStatus confirms the items of a feedbag change that the server
 // accepted.
 func (s OSCARProxy) FeedbagStatus(me *tocConn, frame wire.SNACFrame, snac wire.SNAC_0x13_0x0E_FeedbagStatus) {
-	me.cache.take(frame)
-	me.feedbag.confirm(frame.RequestID, snac.Results)
+	me.requests.Take(frame)
+	me.feedbag.Confirm(frame.RequestID, snac.Results)
 }
 
 // FeedbagReply finishes reloading the feedbag mirror.
 func (s OSCARProxy) FeedbagReply(me *tocConn, frame wire.SNACFrame, snac wire.SNAC_0x13_0x06_FeedbagReply) {
-	req, ok := me.cache.take(frame)
+	_, reqData, ok := me.requests.Take(frame)
 	if !ok {
 		return
 	}
-	if data, ok := req.data.(feedbagReloadReqCtx); ok {
-		me.feedbag.reload(data.marker, snac.Items)
+	if data, ok := reqData.(feedbagReloadReqCtx); ok {
+		me.feedbag.Reload(data.marker, snac.Items)
 	}
 }
 
 // UserInfoReply handles the user info reply to toc_get_status, which is sent
 // to the client as UPDATE_BUDDY.
 func (s OSCARProxy) UserInfoReply(me *tocConn, frame wire.SNACFrame, snac wire.SNAC_0x02_0x06_LocateUserInfoReply) []string {
-	me.cache.take(frame)
+	me.requests.Take(frame)
 	return []string{userInfoToUpdateBuddy(snac.TLVUserInfo, me)}
 }
 
@@ -227,7 +227,7 @@ func (s OSCARProxy) UserInfoReply(me *tocConn, frame wire.SNACFrame, snac wire.S
 // ADMIN_PASSWD_STATUS, or to toc_format_nickname, sent as ADMIN_NICK_STATUS
 // and NICK.
 func (s OSCARProxy) AdminChangeReply(ctx context.Context, me *tocConn, frame wire.SNACFrame, snac wire.SNAC_0x07_0x05_AdminChangeReply) []string {
-	req, ok := me.cache.take(frame)
+	reqFrame, reqData, ok := me.requests.Take(frame)
 	if !ok {
 		s.Logger.DebugContext(ctx, "received admin change reply for unknown request")
 		return nil
@@ -235,7 +235,7 @@ func (s OSCARProxy) AdminChangeReply(ctx context.Context, me *tocConn, frame wir
 
 	code, hasErr := snac.Uint16BE(wire.AdminTLVErrorCode)
 
-	switch req.data.(type) {
+	switch reqData.(type) {
 	case changePasswdReqCtx:
 		if hasErr {
 			switch code {
@@ -263,14 +263,14 @@ func (s OSCARProxy) AdminChangeReply(ctx context.Context, me *tocConn, frame wir
 		}
 		return []string{"ADMIN_NICK_STATUS:0", "NICK:" + val}
 	default:
-		return s.runtimeErr(ctx, fmt.Errorf("AdminChangeReply: unexpected request %v", req.frame))
+		return s.runtimeErr(ctx, fmt.Errorf("AdminChangeReply: unexpected request %v", reqFrame))
 	}
 }
 
 // ChatNavInfo continues toc_chat_join and toc_chat_accept once the chat room
 // info arrives, by requesting a connection to the room.
 func (s OSCARProxy) ChatNavInfo(ctx context.Context, me *tocConn, frame wire.SNACFrame, snac wire.SNAC_0x0D_0x09_ChatNavNavInfo) []string {
-	req, ok := me.cache.take(frame)
+	reqFrame, reqData, ok := me.requests.Take(frame)
 	if !ok {
 		s.Logger.DebugContext(ctx, "received chat nav info for unknown request")
 		return nil
@@ -290,7 +290,7 @@ func (s OSCARProxy) ChatNavInfo(ctx context.Context, me *tocConn, frame wire.SNA
 		return s.runtimeErr(ctx, errors.New("roomInfo.String: missing wire.ChatRoomTLVRoomName"))
 	}
 
-	switch data := req.data.(type) {
+	switch data := reqData.(type) {
 	case chatJoinReqCtx:
 		chatID := me.chats.Add(wire.ICBMRoomInfo{
 			Exchange: roomInfo.Exchange,
@@ -301,7 +301,7 @@ func (s OSCARProxy) ChatNavInfo(ctx context.Context, me *tocConn, frame wire.SNA
 	case chatAcceptReqCtx:
 		return s.requestChatService(ctx, me, data.chatID, roomName, roomInfo.Cookie)
 	default:
-		return s.runtimeErr(ctx, fmt.Errorf("ChatNavNavInfo: unexpected request %v", req.frame))
+		return s.runtimeErr(ctx, fmt.Errorf("ChatNavNavInfo: unexpected request %v", reqFrame))
 	}
 }
 
@@ -310,14 +310,14 @@ func (s OSCARProxy) ChatNavInfo(ctx context.Context, me *tocConn, frame wire.SNA
 // from the room, so that the client knows the room before its first
 // CHAT_UPDATE_BUDDY.
 func (s OSCARProxy) ChatServiceResponse(ctx context.Context, me *tocConn, frame wire.SNACFrame, snac wire.SNAC_0x01_0x05_OServiceServiceResponse) []string {
-	req, ok := me.cache.take(frame)
+	reqFrame, reqData, ok := me.requests.Take(frame)
 	if !ok {
 		s.Logger.DebugContext(ctx, "received service response for unknown request")
 		return nil
 	}
-	data, ok := req.data.(chatServiceReqCtx)
+	data, ok := reqData.(chatServiceReqCtx)
 	if !ok {
-		return s.runtimeErr(ctx, fmt.Errorf("OServiceServiceResponse: unexpected request %v", req.frame))
+		return s.runtimeErr(ctx, fmt.Errorf("OServiceServiceResponse: unexpected request %v", reqFrame))
 	}
 
 	loginCookie, hasCookie := snac.Bytes(wire.OServiceTLVTagsLoginCookie)
@@ -660,7 +660,7 @@ func (s OSCARProxy) UpdateBuddyDeparted(snac wire.SNAC_0x03_0x0C_BuddyDeparted,
 // from the feedbag mirror; buddy alias comes from TLV.
 func (s OSCARProxy) Inserted2(me *tocConn, items []wire.FeedbagItem) []string {
 	var out []string
-	groupNameByID := me.feedbag.groupNames()
+	groupNameByID := me.feedbag.GroupNames()
 	for _, item := range items {
 		switch item.ClassID {
 		case wire.FeedbagClassIdGroup:
@@ -708,7 +708,7 @@ func (s OSCARProxy) Inserted2(me *tocConn, items []wire.FeedbagItem) []string {
 // that deleted buddies' group names can still be found there.
 func (s OSCARProxy) Deleted2(me *tocConn, snac wire.SNAC_0x13_0x0A_FeedbagDeleteItem) []string {
 	var out []string
-	groupNameByID := me.feedbag.groupNames()
+	groupNameByID := me.feedbag.GroupNames()
 	for _, item := range snac.Items {
 		switch item.ClassID {
 		case wire.FeedbagClassIdGroup:

+ 43 - 32
server/toc/cmd_server_test.go

@@ -9,6 +9,7 @@ import (
 
 	"github.com/stretchr/testify/assert"
 
+	"github.com/mk6i/open-oscar-server/server/oscarclient"
 	"github.com/mk6i/open-oscar-server/wire"
 )
 
@@ -1078,7 +1079,7 @@ func TestOSCARProxy_RecvBOS_Inserted2(t *testing.T) {
 
 			me := testConn(withTOC2(true))
 			for _, params := range tc.mockParams.feedbagParams {
-				me.feedbag.reset(params.results)
+				me.feedbag.Reset(params.results)
 			}
 
 			ch := make(chan []string)
@@ -1232,7 +1233,7 @@ func TestOSCARProxy_RecvBOS_Deleted2(t *testing.T) {
 
 			me := testConn(withTOC2(true))
 			for _, params := range tc.mockParams.feedbagParams {
-				me.feedbag.reset(params.results)
+				me.feedbag.Reset(params.results)
 			}
 
 			ch := make(chan []string)
@@ -1296,6 +1297,12 @@ func assertResponse(t *testing.T, me *tocConn, ch <-chan []string, want []string
 }
 
 func TestOSCARProxy_RecvBOS_Replies(t *testing.T) {
+	// pendingRequest is a request still tracked after the reply is handled.
+	type pendingRequest struct {
+		frame wire.SNACFrame
+		data  any
+	}
+
 	roomInfo := func(cookie string, name string) wire.SNAC_0x0D_0x09_ChatNavNavInfo {
 		return wire.SNAC_0x0D_0x09_ChatNavNavInfo{
 			TLVRestBlock: wire.TLVRestBlock{
@@ -1335,9 +1342,9 @@ func TestOSCARProxy_RecvBOS_Replies(t *testing.T) {
 	cases := []struct {
 		// name is the unit test name
 		name string
-		// reqFrame is the cached request the reply answers, as request ID 1
+		// reqFrame is the tracked request the reply answers, as request ID 1
 		reqFrame *wire.SNACFrame
-		// reqData is the cached request context
+		// reqData is the tracked request context
 		reqData any
 		// givenRoom is a chat room the user was invited to, as chat ID 0
 		givenRoom *wire.ICBMRoomInfo
@@ -1347,8 +1354,9 @@ func TestOSCARProxy_RecvBOS_Replies(t *testing.T) {
 		wantCmd []string
 		// wantSNACs are the follow-up SNACs sent to the BOS server
 		wantSNACs []wire.SNACMessage
-		// wantCached are the requests still cached afterward, by request ID
-		wantCached map[uint32]any
+		// wantPending are the requests still pending afterward; every other
+		// request, including the one at reqFrame, must be gone
+		wantPending []pendingRequest
 	}{
 		{
 			name:     "toc_get_status reply",
@@ -1403,13 +1411,6 @@ func TestOSCARProxy_RecvBOS_Replies(t *testing.T) {
 			name:     "error for unknown request is ignored",
 			givenMsg: newSNAC(wire.ICBM, wire.ICBMErr, 1, wire.SNACError{Code: wire.ErrorCodeNotLoggedOn}),
 		},
-		{
-			name:       "error from another food group does not match request",
-			reqFrame:   &wire.SNACFrame{FoodGroup: wire.Locate, SubGroup: wire.LocateUserInfoQuery},
-			reqData:    getStatusReqCtx{screenName: "them"},
-			givenMsg:   newSNAC(wire.ICBM, wire.ICBMErr, 1, wire.SNACError{Code: wire.ErrorCodeNotLoggedOn}),
-			wantCached: map[uint32]any{1: getStatusReqCtx{screenName: "them"}},
-		},
 		{
 			name:     "toc_chat_join room creation error",
 			reqFrame: &wire.SNACFrame{FoodGroup: wire.ChatNav, SubGroup: wire.ChatNavCreateRoom},
@@ -1497,7 +1498,10 @@ func TestOSCARProxy_RecvBOS_Replies(t *testing.T) {
 			wantSNACs: []wire.SNACMessage{
 				newSNAC(wire.OService, wire.OServiceServiceRequest, 2, serviceRequest("4-0-my room")),
 			},
-			wantCached: map[uint32]any{2: chatServiceReqCtx{chatID: 0, roomName: "my room"}},
+			wantPending: []pendingRequest{{
+				frame: wire.SNACFrame{FoodGroup: wire.OService, SubGroup: wire.OServiceServiceRequest, RequestID: 2},
+				data:  chatServiceReqCtx{chatID: 0, roomName: "my room"},
+			}},
 		},
 		{
 			name:      "toc_chat_accept room info requests a chat connection",
@@ -1508,7 +1512,10 @@ func TestOSCARProxy_RecvBOS_Replies(t *testing.T) {
 			wantSNACs: []wire.SNACMessage{
 				newSNAC(wire.OService, wire.OServiceServiceRequest, 2, serviceRequest("4-0-their room")),
 			},
-			wantCached: map[uint32]any{2: chatServiceReqCtx{chatID: 0, roomName: "their room"}},
+			wantPending: []pendingRequest{{
+				frame: wire.SNACFrame{FoodGroup: wire.OService, SubGroup: wire.OServiceServiceRequest, RequestID: 2},
+				data:  chatServiceReqCtx{chatID: 0, roomName: "their room"},
+			}},
 		},
 		{
 			name:     "chat room info missing room TLV",
@@ -1548,8 +1555,9 @@ func TestOSCARProxy_RecvBOS_Replies(t *testing.T) {
 			ctx, cancel := context.WithCancel(context.Background())
 
 			me := testConn()
+			var reqFrame wire.SNACFrame
 			if tc.reqFrame != nil {
-				me.cache.add(tc.reqFrame, tc.reqData)
+				reqFrame = me.requests.Track(*tc.reqFrame, tc.reqData)
 			}
 			if tc.givenRoom != nil {
 				me.chats.Add(*tc.givenRoom)
@@ -1570,14 +1578,17 @@ func TestOSCARProxy_RecvBOS_Replies(t *testing.T) {
 
 			assert.Equal(t, tc.wantSNACs, bos.sentSNACs())
 
-			cached := make(map[uint32]any)
-			for id, entry := range me.cache.entries {
-				cached[id] = entry.data
+			for _, want := range tc.wantPending {
+				frame, data, ok := me.requests.Take(want.frame)
+				if assert.True(t, ok, "request %d isn't pending", want.frame.RequestID) {
+					assert.Equal(t, want.frame, frame)
+					assert.Equal(t, want.data, data)
+				}
 			}
-			if tc.wantCached == nil {
-				tc.wantCached = map[uint32]any{}
+			if tc.reqFrame != nil {
+				_, _, ok := me.requests.Take(reqFrame)
+				assert.False(t, ok, "request %d is still pending", reqFrame.RequestID)
 			}
-			assert.Equal(t, tc.wantCached, cached)
 
 			cancel()
 			wg.Wait()
@@ -1603,7 +1614,7 @@ func TestOSCARProxy_RecvBOS_ChatServiceResponse(t *testing.T) {
 	oscarServer := &fakeOSCARServer{handlers: []func(net.Conn){chat.handle}}
 	svc := OSCARProxy{
 		Logger:      slog.Default(),
-		OSCARServer: oscarServer,
+		OSCARClient: oscarclient.Client{Server: oscarServer, Logger: slog.Default()},
 	}
 
 	wg := &sync.WaitGroup{}
@@ -1616,7 +1627,7 @@ func TestOSCARProxy_RecvBOS_ChatServiceResponse(t *testing.T) {
 			assert.NoError(t, f(ctx))
 		}()
 	}
-	me.cache.add(&wire.SNACFrame{FoodGroup: wire.OService, SubGroup: wire.OServiceServiceRequest},
+	me.requests.Track(wire.SNACFrame{FoodGroup: wire.OService, SubGroup: wire.OServiceServiceRequest},
 		chatServiceReqCtx{chatID: 0, roomName: "My Room"})
 	ch := make(chan []string)
 	me.toCh = ch
@@ -1761,7 +1772,7 @@ func TestOSCARProxy_RecvBOS_FeedbagMirror(t *testing.T) {
 	ctx, cancel := context.WithCancel(context.Background())
 
 	me := testConn(withTOC2(true))
-	me.feedbag.reset([]wire.FeedbagItem{work, alice})
+	me.feedbag.Reset([]wire.FeedbagItem{work, alice})
 	svc := testOSCARProxy(t)
 
 	ch := make(chan []string)
@@ -1778,8 +1789,8 @@ func TestOSCARProxy_RecvBOS_FeedbagMirror(t *testing.T) {
 	assert.Nil(t, svc.upsertFeedbag(ctx, me, wire.FeedbagInsertItem, []wire.FeedbagItem{bob, carol}))
 	bos.msgs <- newSNAC(wire.Feedbag, wire.FeedbagStatus, 1, wire.SNAC_0x13_0x0E_FeedbagStatus{Results: []uint16{0, 0x0E}})
 	assertResponse(t, me, ch, nil)
-	assert.False(t, me.feedbag.hasPending())
-	assert.Equal(t, []wire.FeedbagItem{work, alice, bob}, me.feedbag.snapshot())
+	assert.False(t, me.feedbag.HasPending())
+	assert.Equal(t, []wire.FeedbagItem{work, alice, bob}, me.feedbag.Snapshot())
 
 	// changes from other locations update the mirror
 	bos.msgs <- newSNAC(wire.Feedbag, wire.FeedbagInsertItem, wire.ReqIDFromServer,
@@ -1789,7 +1800,7 @@ func TestOSCARProxy_RecvBOS_FeedbagMirror(t *testing.T) {
 	bos.msgs <- newSNAC(wire.Feedbag, wire.FeedbagDeleteItem, wire.ReqIDFromServer,
 		wire.SNAC_0x13_0x0A_FeedbagDeleteItem{Items: []wire.FeedbagItem{alice}})
 	assert.Equal(t, []string{"DELETED2:b:alice:Work"}, <-ch)
-	assert.Equal(t, []wire.FeedbagItem{work, bob, carol}, me.feedbag.snapshot())
+	assert.Equal(t, []wire.FeedbagItem{work, bob, carol}, me.feedbag.Snapshot())
 
 	// a change may be dropped while the server is limiting requests, so the
 	// mirror is reloaded once the limit clears
@@ -1807,8 +1818,8 @@ func TestOSCARProxy_RecvBOS_FeedbagMirror(t *testing.T) {
 	bos.msgs <- newSNAC(wire.Feedbag, wire.FeedbagReply, 3,
 		wire.SNAC_0x13_0x06_FeedbagReply{Items: []wire.FeedbagItem{work, bob, carol}})
 	assertResponse(t, me, ch, nil)
-	assert.False(t, me.feedbag.hasPending())
-	assert.Equal(t, []wire.FeedbagItem{work, bob, carol}, me.feedbag.snapshot())
+	assert.False(t, me.feedbag.HasPending())
+	assert.Equal(t, []wire.FeedbagItem{work, bob, carol}, me.feedbag.Snapshot())
 
 	// with nothing pending, a cleared limit doesn't reload the mirror
 	bos.msgs <- newSNAC(wire.OService, wire.OServiceRateParamChange, wire.ReqIDFromServer,
@@ -1820,8 +1831,8 @@ func TestOSCARProxy_RecvBOS_FeedbagMirror(t *testing.T) {
 	assert.Nil(t, svc.upsertFeedbag(ctx, me, wire.FeedbagInsertItem, []wire.FeedbagItem{dave}))
 	bos.msgs <- newSNAC(wire.Feedbag, wire.FeedbagErr, 4, wire.SNACError{Code: wire.ErrorCodeInsufficientRights})
 	assertResponse(t, me, ch, nil)
-	assert.False(t, me.feedbag.hasPending())
-	assert.Equal(t, []wire.FeedbagItem{work, bob, carol}, me.feedbag.snapshot())
+	assert.False(t, me.feedbag.HasPending())
+	assert.Equal(t, []wire.FeedbagItem{work, bob, carol}, me.feedbag.Snapshot())
 
 	cancel()
 	wg.Wait()

+ 10 - 8
server/toc/helpers_test.go

@@ -13,7 +13,6 @@ import (
 	"github.com/stretchr/testify/assert"
 	"github.com/stretchr/testify/mock"
 
-	"github.com/mk6i/open-oscar-server/config"
 	"github.com/mk6i/open-oscar-server/state"
 	"github.com/mk6i/open-oscar-server/wire"
 )
@@ -327,28 +326,31 @@ func newReceivedSNAC(t *testing.T, foodGroup uint16, subGroup uint16, reqID uint
 	}
 }
 
-// fakeOSCARServer is an OSCARServer that serves each connection TOC opens
-// with the next of its handlers, in order.
+// fakeOSCARServer is an oscarclient.OSCARServer that serves each connection TOC opens
+// with the next of its handlers, in order, each on a goroutine of its own.
 type fakeOSCARServer struct {
 	mu          sync.Mutex
 	handlers    []func(conn net.Conn)
 	clientAddrs []net.Addr
 }
 
-func (s *fakeOSCARServer) ServeConn(conn net.Conn, _ config.Endpoint) {
-	defer func() { _ = conn.Close() }()
-
+func (s *fakeOSCARServer) ServeConn(conn net.Conn) error {
 	s.mu.Lock()
 	s.clientAddrs = append(s.clientAddrs, conn.RemoteAddr())
 	if len(s.handlers) == 0 {
 		s.mu.Unlock()
-		return
+		_ = conn.Close()
+		return nil
 	}
 	handler := s.handlers[0]
 	s.handlers = s.handlers[1:]
 	s.mu.Unlock()
 
-	handler(conn)
+	go func() {
+		defer func() { _ = conn.Close() }()
+		handler(conn)
+	}()
+	return nil
 }
 
 // fakeAuth returns an auth service handler that records the client's signon

+ 0 - 275
server/toc/oscar_conn.go

@@ -1,275 +0,0 @@
-package toc
-
-import (
-	"bytes"
-	"errors"
-	"fmt"
-	"io"
-	"log/slog"
-	"net"
-	"sync"
-
-	"github.com/mk6i/open-oscar-server/wire"
-)
-
-// errSignedOff indicates that the OSCAR server refused or ended a connection
-// with a signoff frame.
-var errSignedOff = errors.New("signed off by OSCAR server")
-
-// oscarConn is a TOC user's connection to an OSCAR service, either BOS or a
-// chat room.
-type oscarConn interface {
-	// SendSNAC sends a SNAC to the OSCAR server.
-	SendSNAC(frame wire.SNACFrame, body any) error
-	// Messages returns the SNACs received from the server, replies and
-	// server-initiated messages alike, in arrival order.
-	Messages() <-chan wire.SNACMessage
-	// Closed returns a channel that is closed when the connection closes.
-	Closed() <-chan struct{}
-	// Close closes the connection.
-	Close()
-}
-
-// snacQueueLimit is how many received SNACs a connection holds for the TOC
-// consumer, the same as an OSCAR session's message queue.
-const snacQueueLimit = 1000
-
-// flapConn is an oscarConn over a FLAP connection to the OSCAR server.
-type flapConn struct {
-	conn   net.Conn
-	flapc  *wire.FlapClient
-	logger *slog.Logger
-	// msgs holds SNACs received from the server until the TOC consumer takes
-	// them. read never waits on it, so it keeps reading from the server even
-	// while the consumer is busy; otherwise the server's writes would block,
-	// and with them its reads of the SNACs TOC sends.
-	msgs      chan wire.SNACMessage
-	closed    chan struct{}
-	closeOnce sync.Once
-}
-
-// newFLAPConn wraps a FLAP connection that has finished signing on to an
-// OSCAR service and starts reading SNACs from it.
-func newFLAPConn(conn net.Conn, flapc *wire.FlapClient, logger *slog.Logger) *flapConn {
-	c := &flapConn{
-		conn:   conn,
-		flapc:  flapc,
-		logger: logger,
-		msgs:   make(chan wire.SNACMessage, snacQueueLimit),
-		closed: make(chan struct{}),
-	}
-	go c.read()
-	return c
-}
-
-func (c *flapConn) read() {
-	defer c.Close()
-	for {
-		frame, err := c.flapc.ReceiveFLAP()
-		if err != nil {
-			return
-		}
-		switch frame.FrameType {
-		case wire.FLAPFrameData:
-			msg, err := decodeSNAC(frame.Payload)
-			if err != nil {
-				c.logger.Debug("unable to decode SNAC from OSCAR server", "err", err.Error())
-				continue
-			}
-			select {
-			case c.msgs <- msg:
-			default:
-				// like the OSCAR server, disconnect a client that falls too far behind
-				c.logger.Warn("TOC client isn't keeping up with the OSCAR server, disconnecting")
-				return
-			}
-		case wire.FLAPFrameSignoff:
-			return
-		}
-	}
-}
-
-func (c *flapConn) SendSNAC(frame wire.SNACFrame, body any) error {
-	return c.flapc.SendSNAC(frame, body)
-}
-
-func (c *flapConn) Messages() <-chan wire.SNACMessage {
-	return c.msgs
-}
-
-func (c *flapConn) Closed() <-chan struct{} {
-	return c.closed
-}
-
-func (c *flapConn) Close() {
-	c.closeOnce.Do(func() {
-		close(c.closed)
-		_ = c.conn.Close()
-	})
-}
-
-// clientAddrConn is the server end of an in-memory OSCAR connection. It
-// reports the TOC client's address as its remote address, so that the OSCAR
-// server sees where the user really connects from.
-type clientAddrConn struct {
-	net.Conn
-	clientAddr net.Addr
-}
-
-func (c clientAddrConn) RemoteAddr() net.Addr {
-	return c.clientAddr
-}
-
-// dialOSCAR opens an in-memory connection to the OSCAR server on behalf of
-// the TOC client at clientAddr.
-func (s OSCARProxy) dialOSCAR(clientAddr net.Addr) net.Conn {
-	clientEnd, serverEnd := net.Pipe()
-	go s.OSCARServer.ServeConn(clientAddrConn{Conn: serverEnd, clientAddr: clientAddr}, s.OSCAREndpoint)
-	return clientEnd
-}
-
-// authenticate signs on to the OSCAR auth service with the given signon TLVs
-// and returns the server's reply TLVs, which hold either a login cookie or an
-// error code.
-func (s OSCARProxy) authenticate(clientAddr net.Addr, signonTLVs []wire.TLV) (wire.TLVRestBlock, error) {
-	conn := s.dialOSCAR(clientAddr)
-	defer func() { _ = conn.Close() }()
-
-	flapc := wire.NewFlapClient(0, conn, conn)
-	if _, err := flapc.ReceiveSignonFrame(); err != nil {
-		return wire.TLVRestBlock{}, fmt.Errorf("ReceiveSignonFrame: %w", err)
-	}
-	if err := flapc.SendSignonFrame(signonTLVs); err != nil {
-		return wire.TLVRestBlock{}, fmt.Errorf("SendSignonFrame: %w", err)
-	}
-
-	frame, err := flapc.ReceiveFLAP()
-	if err != nil {
-		return wire.TLVRestBlock{}, fmt.Errorf("ReceiveFLAP: %w", err)
-	}
-
-	switch frame.FrameType {
-	case wire.FLAPFrameSignoff:
-		block := wire.TLVRestBlock{}
-		if err := wire.UnmarshalBE(&block, bytes.NewReader(frame.Payload)); err != nil {
-			return wire.TLVRestBlock{}, fmt.Errorf("UnmarshalBE: %w", err)
-		}
-		return block, nil
-	case wire.FLAPFrameData:
-		// the server answers with a BUCP login response when it rate limits
-		// an address that recently signed on with BUCP
-		msg, err := decodeSNAC(frame.Payload)
-		if err != nil {
-			return wire.TLVRestBlock{}, fmt.Errorf("decodeSNAC: %w", err)
-		}
-		reply, ok := msg.Body.(wire.SNAC_0x17_0x03_BUCPLoginResponse)
-		if !ok {
-			return wire.TLVRestBlock{}, fmt.Errorf("unexpected login reply %s",
-				wire.SubGroupName(msg.Frame.FoodGroup, msg.Frame.SubGroup))
-		}
-		return reply.TLVRestBlock, nil
-	default:
-		return wire.TLVRestBlock{}, fmt.Errorf("unexpected login reply frame type %d", frame.FrameType)
-	}
-}
-
-// connectService connects to the OSCAR service that loginCookie grants access
-// to, either BOS or a chat room, and waits for the server to report the
-// service online.
-func (s OSCARProxy) connectService(clientAddr net.Addr, loginCookie []byte) (*flapConn, error) {
-	conn := s.dialOSCAR(clientAddr)
-
-	flapc := wire.NewFlapClient(0, conn, conn)
-	if err := func() error {
-		if _, err := flapc.ReceiveSignonFrame(); err != nil {
-			return fmt.Errorf("ReceiveSignonFrame: %w", err)
-		}
-		if err := flapc.SendSignonFrame([]wire.TLV{wire.NewTLVBE(wire.OServiceTLVTagsLoginCookie, loginCookie)}); err != nil {
-			return fmt.Errorf("SendSignonFrame: %w", err)
-		}
-
-		frame, err := flapc.ReceiveFLAP()
-		if err != nil {
-			return fmt.Errorf("ReceiveFLAP: %w", err)
-		}
-		if frame.FrameType == wire.FLAPFrameSignoff {
-			return errSignedOff
-		}
-		msg, err := decodeSNAC(frame.Payload)
-		if err != nil {
-			return fmt.Errorf("decodeSNAC: %w", err)
-		}
-		if _, ok := msg.Body.(wire.SNAC_0x01_0x03_OServiceHostOnline); !ok {
-			return fmt.Errorf("expected host online, got %s",
-				wire.SubGroupName(msg.Frame.FoodGroup, msg.Frame.SubGroup))
-		}
-		return nil
-	}(); err != nil {
-		_ = conn.Close()
-		return nil, err
-	}
-
-	return newFLAPConn(conn, flapc, s.Logger), nil
-}
-
-// snacDecoders unmarshal the bodies of the SNACs a TOC connection handles,
-// keyed by food group and subgroup.
-var snacDecoders = map[[2]uint16]func(r io.Reader) (any, error){
-	{wire.OService, wire.OServiceHostOnline}:       decodeBody[wire.SNAC_0x01_0x03_OServiceHostOnline],
-	{wire.OService, wire.OServiceServiceResponse}:  decodeBody[wire.SNAC_0x01_0x05_OServiceServiceResponse],
-	{wire.OService, wire.OServiceRateParamChange}:  decodeBody[wire.SNAC_0x01_0x0A_OServiceRateParamsChange],
-	{wire.OService, wire.OServiceUserInfoUpdate}:   decodeBody[wire.SNAC_0x01_0x0F_OServiceUserInfoUpdate],
-	{wire.OService, wire.OServiceEvilNotification}: decodeBody[wire.SNAC_0x01_0x10_OServiceEvilNotification],
-	{wire.Locate, wire.LocateUserInfoReply}:        decodeBody[wire.SNAC_0x02_0x06_LocateUserInfoReply],
-	{wire.Buddy, wire.BuddyArrived}:                decodeBody[wire.SNAC_0x03_0x0B_BuddyArrived],
-	{wire.Buddy, wire.BuddyDeparted}:               decodeBody[wire.SNAC_0x03_0x0C_BuddyDeparted],
-	{wire.ICBM, wire.ICBMChannelMsgToClient}:       decodeBody[wire.SNAC_0x04_0x07_ICBMChannelMsgToClient],
-	{wire.ICBM, wire.ICBMEvilReply}:                decodeBody[wire.SNAC_0x04_0x09_ICBMEvilReply],
-	{wire.ICBM, wire.ICBMClientEvent}:              decodeBody[wire.SNAC_0x04_0x14_ICBMClientEvent],
-	{wire.Admin, wire.AdminInfoChangeReply}:        decodeBody[wire.SNAC_0x07_0x05_AdminChangeReply],
-	{wire.ChatNav, wire.ChatNavNavInfo}:            decodeBody[wire.SNAC_0x0D_0x09_ChatNavNavInfo],
-	{wire.Chat, wire.ChatUsersJoined}:              decodeBody[wire.SNAC_0x0E_0x03_ChatUsersJoined],
-	{wire.Chat, wire.ChatUsersLeft}:                decodeBody[wire.SNAC_0x0E_0x04_ChatUsersLeft],
-	{wire.Chat, wire.ChatChannelMsgToClient}:       decodeBody[wire.SNAC_0x0E_0x06_ChatChannelMsgToClient],
-	{wire.Feedbag, wire.FeedbagReply}:              decodeBody[wire.SNAC_0x13_0x06_FeedbagReply],
-	{wire.Feedbag, wire.FeedbagInsertItem}:         decodeBody[wire.SNAC_0x13_0x08_FeedbagInsertItem],
-	{wire.Feedbag, wire.FeedbagUpdateItem}:         decodeBody[wire.SNAC_0x13_0x09_FeedbagUpdateItem],
-	{wire.Feedbag, wire.FeedbagDeleteItem}:         decodeBody[wire.SNAC_0x13_0x0A_FeedbagDeleteItem],
-	{wire.Feedbag, wire.FeedbagStatus}:             decodeBody[wire.SNAC_0x13_0x0E_FeedbagStatus],
-	{wire.BUCP, wire.BUCPLoginResponse}:            decodeBody[wire.SNAC_0x17_0x03_BUCPLoginResponse],
-}
-
-// snacErrorSubGroup is the subgroup of the error SNAC in every food group.
-const snacErrorSubGroup = 0x0001
-
-// decodeSNAC unmarshals a SNAC received from the OSCAR server. A SNAC that
-// TOC doesn't handle is returned with a nil body.
-func decodeSNAC(payload []byte) (wire.SNACMessage, error) {
-	r := bytes.NewReader(payload)
-	msg := wire.SNACMessage{}
-	if err := wire.UnmarshalBE(&msg.Frame, r); err != nil {
-		return msg, fmt.Errorf("unmarshal SNAC frame: %w", err)
-	}
-
-	decode := snacDecoders[[2]uint16{msg.Frame.FoodGroup, msg.Frame.SubGroup}]
-	if msg.Frame.SubGroup == snacErrorSubGroup {
-		decode = decodeBody[wire.SNACError]
-	}
-	if decode == nil {
-		return msg, nil
-	}
-
-	body, err := decode(r)
-	if err != nil {
-		return msg, fmt.Errorf("unmarshal %s: %w",
-			wire.SubGroupName(msg.Frame.FoodGroup, msg.Frame.SubGroup), err)
-	}
-	msg.Body = body
-	return msg, nil
-}
-
-func decodeBody[T any](r io.Reader) (any, error) {
-	var body T
-	err := wire.UnmarshalBE(&body, r)
-	return body, err
-}

+ 17 - 9
server/toc/server.go

@@ -339,17 +339,26 @@ func (s *Server) dispatchFLAP(ctx context.Context, conn net.Conn) error {
 		return err
 	}
 
-	me, err := s.login(ctx, clientFlap, conn.RemoteAddr())
-	if err != nil {
-		return fmt.Errorf("s.login: %w", err)
+	// the group runs every goroutine of the TOC session, starting with the
+	// BOS connection's reader during signon
+	g, ctx := errgroup.WithContext(ctx)
+	goAsync := func(f func(ctx context.Context) error) {
+		g.Go(func() error { return f(ctx) })
 	}
-	if me == nil {
+
+	me, err := s.login(ctx, clientFlap, conn.RemoteAddr(), goAsync)
+	if err != nil || me == nil {
+		// a failed signon closes the BOS connection, which ends its reader
+		_ = g.Wait()
+		if err != nil {
+			return fmt.Errorf("s.login: %w", err)
+		}
 		return nil // signon failed
 	}
 
 	ctx = context.WithValue(ctx, screenNameContextKey, me.IdentScreenName())
 
-	return s.handleTOCRequest(ctx, closeConn, me, clientFlap)
+	return s.handleTOCRequest(ctx, g, closeConn, me, clientFlap)
 }
 
 // handleTOCRequest processes incoming TOC requests and coordinates their handling.
@@ -362,6 +371,7 @@ func (s *Server) dispatchFLAP(ctx context.Context, conn net.Conn) error {
 //   - errServerWrite if an error occurs while sending the TOC response.
 func (s *Server) handleTOCRequest(
 	ctx context.Context,
+	g *errgroup.Group,
 	closeConn func(),
 	me *tocConn,
 	clientFlap *wire.FlapClient,
@@ -369,8 +379,6 @@ func (s *Server) handleTOCRequest(
 	// TOC response queue
 	msgCh := make(chan []string, 1)
 
-	g, ctx := errgroup.WithContext(ctx)
-
 	me.toCh = msgCh
 	me.goAsync = func(f func(ctx context.Context) error) {
 		g.Go(func() error { return f(ctx) })
@@ -460,7 +468,7 @@ func (s *Server) sendToClient(ctx context.Context, toClient <-chan []string, cli
 	}
 }
 
-func (s *Server) login(ctx context.Context, clientFlap *wire.FlapClient, clientAddr net.Addr) (*tocConn, error) {
+func (s *Server) login(ctx context.Context, clientFlap *wire.FlapClient, clientAddr net.Addr, goAsync func(f func(ctx context.Context) error)) (*tocConn, error) {
 	clientFrame, err := clientFlap.ReceiveFLAP()
 	if err != nil {
 		if errors.Is(err, io.EOF) {
@@ -469,7 +477,7 @@ func (s *Server) login(ctx context.Context, clientFlap *wire.FlapClient, clientA
 		return nil, fmt.Errorf("clientFlap.ReceiveFLAP: %w", err)
 	}
 
-	me, reply := s.bosProxy.Signon(ctx, clientFrame.Payload, clientAddr)
+	me, reply := s.bosProxy.Signon(ctx, clientFrame.Payload, clientAddr, goAsync)
 
 	for _, m := range reply {
 		if err := clientFlap.SendDataFrame([]byte(m)); err != nil {

+ 11 - 5
server/toc/server_test.go

@@ -11,6 +11,7 @@ import (
 	"github.com/mk6i/open-oscar-server/wire"
 
 	"github.com/stretchr/testify/assert"
+	"golang.org/x/sync/errgroup"
 )
 
 // ensure correct behavior during global context cancellation (server shutdown)
@@ -34,7 +35,8 @@ func TestServer_handleTOCRequest_serverShutdown(t *testing.T) {
 			_ = serverReader.Close()
 		}
 		me, _ := newTestTOCConn(newTestSession("me"))
-		err := sv.handleTOCRequest(ctx, closeConn, me, fc)
+		g, gctx := errgroup.WithContext(ctx)
+		err := sv.handleTOCRequest(gctx, g, closeConn, me, fc)
 		assert.True(t, errors.Is(err, errTOCProcessing) || errors.Is(err, errServerWrite))
 	}()
 
@@ -64,7 +66,8 @@ func TestServer_handleTOCRequest_clientReadDisconnect(t *testing.T) {
 			bosProxy: testOSCARProxy(t),
 			logger:   slog.Default(),
 		}
-		err := sv.handleTOCRequest(context.Background(), closeConn, me, fc)
+		g, gctx := errgroup.WithContext(context.Background())
+		err := sv.handleTOCRequest(gctx, g, closeConn, me, fc)
 		assert.ErrorIs(t, err, errClientReq)
 		assert.ErrorIs(t, err, io.ErrClosedPipe)
 	}()
@@ -97,7 +100,8 @@ func TestServer_handleTOCRequest_sessClose(t *testing.T) {
 			bosProxy: testOSCARProxy(t),
 			logger:   slog.Default(),
 		}
-		err := sv.handleTOCRequest(context.Background(), closeConn, me, fc)
+		g, gctx := errgroup.WithContext(context.Background())
+		err := sv.handleTOCRequest(gctx, g, closeConn, me, fc)
 		assert.ErrorIs(t, err, errTOCProcessing)
 		assert.ErrorIs(t, err, errDisconnect)
 	}()
@@ -130,7 +134,8 @@ func TestServer_handleTOCRequest_replyFailure(t *testing.T) {
 			bosProxy: testOSCARProxy(t),
 			logger:   slog.Default(),
 		}
-		err := sv.handleTOCRequest(context.Background(), closeConn, me, fc)
+		g, gctx := errgroup.WithContext(context.Background())
+		err := sv.handleTOCRequest(gctx, g, closeConn, me, fc)
 		assert.ErrorIs(t, err, errServerWrite)
 		assert.ErrorIs(t, err, io.ErrClosedPipe)
 	}()
@@ -168,7 +173,8 @@ func TestServer_handleTOCRequest_happyPath(t *testing.T) {
 			logger:   slog.Default(),
 		}
 		me, _ := newTestTOCConn(newTestSession("me"))
-		err := sv.handleTOCRequest(context.Background(), closeConn, me, fc)
+		g, gctx := errgroup.WithContext(context.Background())
+		err := sv.handleTOCRequest(gctx, g, closeConn, me, fc)
 		assert.ErrorIs(t, err, errClientReq)
 		assert.ErrorIs(t, err, io.ErrClosedPipe)
 	}()

+ 0 - 85
server/toc/snac_cache.go

@@ -1,85 +0,0 @@
-package toc
-
-import (
-	"sync"
-	"time"
-
-	"github.com/mk6i/open-oscar-server/wire"
-)
-
-// snacCacheTTL is how long a sent SNAC waits for a reply before it is dropped
-// from the cache. Requests the server drops, such as rate-limited ones, never
-// get a reply.
-const snacCacheTTL = 60 * time.Second
-
-// snacCache tracks the SNACs a TOC connection sends to the OSCAR server by
-// request ID, so that a reply can be matched to the request that produced it.
-type snacCache struct {
-	mu      sync.Mutex
-	lastID  uint32
-	entries map[uint32]sentSNAC
-	timeNow func() time.Time
-}
-
-// sentSNAC is a SNAC request awaiting a reply.
-type sentSNAC struct {
-	// frame is the request's SNAC frame.
-	frame wire.SNACFrame
-	// data holds whatever the reply handler needs to know about the request.
-	data   any
-	sentAt time.Time
-}
-
-func newSNACCache() *snacCache {
-	return &snacCache{
-		entries: make(map[uint32]sentSNAC),
-		timeNow: time.Now,
-	}
-}
-
-// add assigns the next request ID to frame and records the request along with
-// data. Entries older than snacCacheTTL are swept out.
-func (c *snacCache) add(frame *wire.SNACFrame, data any) {
-	c.mu.Lock()
-	defer c.mu.Unlock()
-
-	now := c.timeNow()
-	for id, entry := range c.entries {
-		if now.Sub(entry.sentAt) > snacCacheTTL {
-			delete(c.entries, id)
-		}
-	}
-
-	c.lastID++
-	if c.lastID >= wire.ReqIDFromServer {
-		c.lastID = 1
-	}
-	frame.RequestID = c.lastID
-	c.entries[frame.RequestID] = sentSNAC{
-		frame:  *frame,
-		data:   data,
-		sentAt: now,
-	}
-}
-
-// take removes and returns the request that reply answers. A reply only
-// matches a request in the same food group, so that a relayed SNAC carrying
-// another user's request ID is not mistaken for a reply.
-func (c *snacCache) take(reply wire.SNACFrame) (sentSNAC, bool) {
-	c.mu.Lock()
-	defer c.mu.Unlock()
-
-	entry, ok := c.entries[reply.RequestID]
-	if !ok || entry.frame.FoodGroup != reply.FoodGroup {
-		return sentSNAC{}, false
-	}
-	delete(c.entries, reply.RequestID)
-	return entry, true
-}
-
-// remove drops the request with the given ID.
-func (c *snacCache) remove(requestID uint32) {
-	c.mu.Lock()
-	defer c.mu.Unlock()
-	delete(c.entries, requestID)
-}

+ 0 - 89
server/toc/snac_cache_test.go

@@ -1,89 +0,0 @@
-package toc
-
-import (
-	"testing"
-	"time"
-
-	"github.com/stretchr/testify/assert"
-
-	"github.com/mk6i/open-oscar-server/wire"
-)
-
-func TestSNACCache_addAndTake(t *testing.T) {
-	c := newSNACCache()
-
-	first := wire.SNACFrame{FoodGroup: wire.Locate, SubGroup: wire.LocateUserInfoQuery}
-	c.add(&first, getStatusReqCtx{screenName: "them"})
-	second := wire.SNACFrame{FoodGroup: wire.ICBM, SubGroup: wire.ICBMEvilRequest}
-	c.add(&second, evilReqCtx{})
-
-	assert.Equal(t, uint32(1), first.RequestID)
-	assert.Equal(t, uint32(2), second.RequestID)
-
-	req, ok := c.take(wire.SNACFrame{FoodGroup: wire.Locate, SubGroup: wire.LocateUserInfoReply, RequestID: 1})
-	assert.True(t, ok)
-	assert.Equal(t, first, req.frame)
-	assert.Equal(t, getStatusReqCtx{screenName: "them"}, req.data)
-
-	// an entry is removed once taken
-	_, ok = c.take(wire.SNACFrame{FoodGroup: wire.Locate, RequestID: 1})
-	assert.False(t, ok)
-
-	req, ok = c.take(wire.SNACFrame{FoodGroup: wire.ICBM, SubGroup: wire.ICBMErr, RequestID: 2})
-	assert.True(t, ok)
-	assert.Equal(t, evilReqCtx{}, req.data)
-}
-
-func TestSNACCache_takeRequiresMatchingFoodGroup(t *testing.T) {
-	c := newSNACCache()
-
-	frame := wire.SNACFrame{FoodGroup: wire.Locate, SubGroup: wire.LocateUserInfoQuery}
-	c.add(&frame, getStatusReqCtx{screenName: "them"})
-
-	// a relayed SNAC that happens to carry the same request ID is not a reply
-	_, ok := c.take(wire.SNACFrame{FoodGroup: wire.ICBM, SubGroup: wire.ICBMClientEvent, RequestID: 1})
-	assert.False(t, ok)
-
-	// the real reply still finds the request
-	_, ok = c.take(wire.SNACFrame{FoodGroup: wire.Locate, SubGroup: wire.LocateUserInfoReply, RequestID: 1})
-	assert.True(t, ok)
-}
-
-func TestSNACCache_remove(t *testing.T) {
-	c := newSNACCache()
-
-	frame := wire.SNACFrame{FoodGroup: wire.Locate, SubGroup: wire.LocateUserInfoQuery}
-	c.add(&frame, nil)
-	c.remove(frame.RequestID)
-
-	_, ok := c.take(wire.SNACFrame{FoodGroup: wire.Locate, RequestID: frame.RequestID})
-	assert.False(t, ok)
-}
-
-func TestSNACCache_sweepsExpiredEntries(t *testing.T) {
-	now := time.Now()
-	c := newSNACCache()
-	c.timeNow = func() time.Time { return now }
-
-	old := wire.SNACFrame{FoodGroup: wire.ICBM, SubGroup: wire.ICBMChannelMsgToHost}
-	c.add(&old, nil)
-
-	now = now.Add(snacCacheTTL + time.Second)
-	fresh := wire.SNACFrame{FoodGroup: wire.ICBM, SubGroup: wire.ICBMChannelMsgToHost}
-	c.add(&fresh, nil)
-
-	_, ok := c.take(wire.SNACFrame{FoodGroup: wire.ICBM, RequestID: old.RequestID})
-	assert.False(t, ok)
-	_, ok = c.take(wire.SNACFrame{FoodGroup: wire.ICBM, RequestID: fresh.RequestID})
-	assert.True(t, ok)
-}
-
-func TestSNACCache_requestIDWrapsBeforeServerRange(t *testing.T) {
-	c := newSNACCache()
-	c.lastID = wire.ReqIDFromServer - 1
-
-	frame := wire.SNACFrame{FoodGroup: wire.ICBM}
-	c.add(&frame, nil)
-
-	assert.Equal(t, uint32(1), frame.RequestID)
-}

+ 9 - 182
server/toc/toc_conn.go

@@ -3,12 +3,12 @@ package toc
 import (
 	"context"
 	"net"
-	"slices"
 	"sync"
 	"time"
 
 	"golang.org/x/time/rate"
 
+	"github.com/mk6i/open-oscar-server/server/oscarclient"
 	"github.com/mk6i/open-oscar-server/state"
 	"github.com/mk6i/open-oscar-server/wire"
 )
@@ -21,8 +21,8 @@ type tocConn struct {
 	bos oscarConn
 	// chats tracks the chat rooms the user has been invited to or joined.
 	chats *ChatRegistry
-	// cache matches SNAC replies to the requests that produced them.
-	cache *snacCache
+	// requests matches SNAC replies to the requests that produced them.
+	requests *oscarclient.RequestTracker
 	// ident is the user's screen name.
 	ident state.IdentScreenName
 	// isTOC2 is true for TOC2 clients.
@@ -47,7 +47,10 @@ type tocConn struct {
 	// started.
 	backlog []wire.SNACMessage
 	// feedbag is the TOC2 user's buddy list.
-	feedbag *feedbagMirror
+	feedbag *state.FeedbagMirror
+	// feedbagSendMu keeps feedbag changes and reloads in the order they're
+	// sent.
+	feedbagSendMu sync.Mutex
 }
 
 // newTOCConn creates a TOC connection for the signed-on user ident whose BOS
@@ -56,11 +59,11 @@ func newTOCConn(bos oscarConn, ident state.IdentScreenName, clientAddr net.Addr)
 	return &tocConn{
 		bos:        bos,
 		chats:      NewChatRegistry(),
-		cache:      newSNACCache(),
+		requests:   oscarclient.NewRequestTracker(),
 		ident:      ident,
 		clientAddr: clientAddr,
 		limiter:    rate.NewLimiter(rate.Every(1500*time.Millisecond), 5),
-		feedbag:    &feedbagMirror{},
+		feedbag:    &state.FeedbagMirror{},
 	}
 }
 
@@ -151,179 +154,3 @@ func (c *ChatRegistry) RemoveConn(chatID int) {
 	defer c.m.Unlock()
 	delete(c.conns, chatID)
 }
-
-// feedbagMirror is TOC's copy of the user's feedbag (server-side buddy list).
-// It holds the feedbag as the server last confirmed it plus the changes TOC
-// sent that the server hasn't confirmed yet. Commands work from the
-// feedbag as it will be once those changes land, and only confirmed changes
-// become part of the confirmed feedbag.
-type feedbagMirror struct {
-	// sendMu keeps changes and reloads in the order they're sent.
-	sendMu sync.Mutex
-
-	mu        sync.Mutex
-	confirmed []wire.FeedbagItem
-	pending   []feedbagChange
-	lastSeq   uint64
-}
-
-// feedbagChange is a feedbag change sent to the server and not yet
-// confirmed.
-type feedbagChange struct {
-	seq       uint64
-	requestID uint32
-	del       bool
-	items     []wire.FeedbagItem
-}
-
-// snapshot returns the feedbag with all pending changes applied.
-func (m *feedbagMirror) snapshot() []wire.FeedbagItem {
-	m.mu.Lock()
-	defer m.mu.Unlock()
-	items := append([]wire.FeedbagItem(nil), m.confirmed...)
-	for _, change := range m.pending {
-		items = applyFeedbagChange(items, change.del, change.items)
-	}
-	return cloneFeedbagItems(items)
-}
-
-// reset replaces the confirmed feedbag with items and forgets pending
-// changes.
-func (m *feedbagMirror) reset(items []wire.FeedbagItem) {
-	m.mu.Lock()
-	defer m.mu.Unlock()
-	m.confirmed = cloneFeedbagItems(items)
-	m.pending = nil
-}
-
-// sent records a change TOC is sending as request requestID. del is true
-// when the change deletes items.
-func (m *feedbagMirror) sent(requestID uint32, del bool, items []wire.FeedbagItem) {
-	m.mu.Lock()
-	defer m.mu.Unlock()
-	m.lastSeq++
-	m.pending = append(m.pending, feedbagChange{
-		seq:       m.lastSeq,
-		requestID: requestID,
-		del:       del,
-		items:     cloneFeedbagItems(items),
-	})
-}
-
-// confirm applies the items of change requestID that the server accepted,
-// according to results, and forgets the change.
-func (m *feedbagMirror) confirm(requestID uint32, results []uint16) {
-	m.mu.Lock()
-	defer m.mu.Unlock()
-	i := m.indexOf(requestID)
-	if i < 0 {
-		return
-	}
-	change := m.pending[i]
-	var accepted []wire.FeedbagItem
-	for j, item := range change.items {
-		if j < len(results) && results[j] == 0 {
-			accepted = append(accepted, item)
-		}
-	}
-	m.confirmed = applyFeedbagChange(m.confirmed, change.del, accepted)
-	m.pending = append(m.pending[:i], m.pending[i+1:]...)
-}
-
-// discard forgets change requestID, which the server rejected.
-func (m *feedbagMirror) discard(requestID uint32) {
-	m.mu.Lock()
-	defer m.mu.Unlock()
-	if i := m.indexOf(requestID); i >= 0 {
-		m.pending = append(m.pending[:i], m.pending[i+1:]...)
-	}
-}
-
-// hasPending returns true if any change is awaiting confirmation.
-func (m *feedbagMirror) hasPending() bool {
-	m.mu.Lock()
-	defer m.mu.Unlock()
-	return len(m.pending) > 0
-}
-
-// mark returns a marker for the changes sent so far, for reload.
-func (m *feedbagMirror) mark() uint64 {
-	m.mu.Lock()
-	defer m.mu.Unlock()
-	return m.lastSeq
-}
-
-// reload replaces the confirmed feedbag with items, the server's feedbag as of
-// a query sent after the changes up to marker. Those changes are forgotten,
-// since the server either applied them or dropped them. Changes sent after the
-// query stay pending.
-func (m *feedbagMirror) reload(marker uint64, items []wire.FeedbagItem) {
-	m.mu.Lock()
-	defer m.mu.Unlock()
-	m.confirmed = cloneFeedbagItems(items)
-	var pending []feedbagChange
-	for _, change := range m.pending {
-		if change.seq > marker {
-			pending = append(pending, change)
-		}
-	}
-	m.pending = pending
-}
-
-// applyRemote applies a change made at another of the user's locations. del
-// is true when the change deletes items.
-func (m *feedbagMirror) applyRemote(del bool, items []wire.FeedbagItem) {
-	m.mu.Lock()
-	defer m.mu.Unlock()
-	m.confirmed = applyFeedbagChange(m.confirmed, del, cloneFeedbagItems(items))
-}
-
-// groupNames returns the name of each group by group ID, with all pending
-// changes applied.
-func (m *feedbagMirror) groupNames() map[uint16]string {
-	names := make(map[uint16]string)
-	for _, item := range m.snapshot() {
-		if item.ClassID == wire.FeedbagClassIdGroup {
-			names[item.GroupID] = item.Name
-		}
-	}
-	return names
-}
-
-func (m *feedbagMirror) indexOf(requestID uint32) int {
-	for i, change := range m.pending {
-		if change.requestID == requestID {
-			return i
-		}
-	}
-	return -1
-}
-
-// cloneFeedbagItems returns a copy of items that shares no TLV lists with
-// them, since state.FeedbagList edits TLV lists in place.
-func cloneFeedbagItems(items []wire.FeedbagItem) []wire.FeedbagItem {
-	items = slices.Clone(items)
-	for i := range items {
-		items[i].TLVList = slices.Clone(items[i].TLVList)
-	}
-	return items
-}
-
-// applyFeedbagChange returns items with changed upserted, or deleted when del
-// is true. Items match by group and item ID.
-func applyFeedbagChange(items []wire.FeedbagItem, del bool, changed []wire.FeedbagItem) []wire.FeedbagItem {
-	for _, item := range changed {
-		i := slices.IndexFunc(items, func(existing wire.FeedbagItem) bool {
-			return existing.GroupID == item.GroupID && existing.ItemID == item.ItemID
-		})
-		switch {
-		case del && i >= 0:
-			items = slices.Delete(items, i, i+1)
-		case !del && i >= 0:
-			items[i] = item
-		case !del:
-			items = append(items, item)
-		}
-	}
-	return items
-}

+ 12 - 8
server/toc/types.go

@@ -2,20 +2,24 @@ package toc
 
 import (
 	"context"
-	"net"
 	"time"
 
-	"github.com/mk6i/open-oscar-server/config"
 	"github.com/mk6i/open-oscar-server/state"
 	"github.com/mk6i/open-oscar-server/wire"
 )
 
-// OSCARServer serves OSCAR connections that the TOC server opens on behalf of
-// its users.
-type OSCARServer interface {
-	// ServeConn serves conn as if it had been accepted on the listener at
-	// endpointCfg, and returns when the connection ends.
-	ServeConn(conn net.Conn, endpointCfg config.Endpoint)
+// oscarConn is a TOC user's connection to an OSCAR service, either BOS or a
+// chat room.
+type oscarConn interface {
+	// SendSNAC sends a SNAC to the OSCAR server.
+	SendSNAC(frame wire.SNACFrame, body any) error
+	// Messages returns the SNACs received from the server, replies and
+	// server-initiated messages alike, in arrival order.
+	Messages() <-chan wire.SNACMessage
+	// Closed returns a channel that is closed when the connection closes.
+	Closed() <-chan struct{}
+	// Close closes the connection.
+	Close()
 }
 
 // LocateService looks up user profiles and directory info for the TOC HTTP

+ 181 - 0
state/feedbag_mirror.go

@@ -0,0 +1,181 @@
+package state
+
+import (
+	"slices"
+	"sync"
+
+	"github.com/mk6i/open-oscar-server/wire"
+)
+
+// FeedbagMirror is a client's copy of a user's feedbag (server-side buddy
+// list). It holds the feedbag as the server last confirmed it plus the changes
+// the client sent that the server hasn't confirmed yet. Clients work from the
+// feedbag as it will be once those changes land, and only confirmed changes
+// become part of the confirmed feedbag.
+type FeedbagMirror struct {
+	mu        sync.Mutex
+	confirmed []wire.FeedbagItem
+	pending   []feedbagChange
+	lastSeq   uint64
+}
+
+// feedbagChange is a feedbag change sent to the server and not yet
+// confirmed.
+type feedbagChange struct {
+	seq       uint64
+	requestID uint32
+	del       bool
+	items     []wire.FeedbagItem
+}
+
+// Snapshot returns the feedbag with all pending changes applied.
+func (m *FeedbagMirror) Snapshot() []wire.FeedbagItem {
+	m.mu.Lock()
+	defer m.mu.Unlock()
+	items := append([]wire.FeedbagItem(nil), m.confirmed...)
+	for _, change := range m.pending {
+		items = applyFeedbagChange(items, change.del, change.items)
+	}
+	return cloneFeedbagItems(items)
+}
+
+// Reset replaces the confirmed feedbag with items and forgets pending
+// changes.
+func (m *FeedbagMirror) Reset(items []wire.FeedbagItem) {
+	m.mu.Lock()
+	defer m.mu.Unlock()
+	m.confirmed = cloneFeedbagItems(items)
+	m.pending = nil
+}
+
+// Sent records a change the client is sending as request requestID. del is
+// true when the change deletes items.
+func (m *FeedbagMirror) Sent(requestID uint32, del bool, items []wire.FeedbagItem) {
+	m.mu.Lock()
+	defer m.mu.Unlock()
+	m.lastSeq++
+	m.pending = append(m.pending, feedbagChange{
+		seq:       m.lastSeq,
+		requestID: requestID,
+		del:       del,
+		items:     cloneFeedbagItems(items),
+	})
+}
+
+// Confirm applies the items of change requestID that the server accepted,
+// according to results, and forgets the change.
+func (m *FeedbagMirror) Confirm(requestID uint32, results []uint16) {
+	m.mu.Lock()
+	defer m.mu.Unlock()
+	i := m.indexOf(requestID)
+	if i < 0 {
+		return
+	}
+	change := m.pending[i]
+	var accepted []wire.FeedbagItem
+	for j, item := range change.items {
+		if j < len(results) && results[j] == 0 {
+			accepted = append(accepted, item)
+		}
+	}
+	m.confirmed = applyFeedbagChange(m.confirmed, change.del, accepted)
+	m.pending = append(m.pending[:i], m.pending[i+1:]...)
+}
+
+// Discard forgets change requestID, which the server rejected.
+func (m *FeedbagMirror) Discard(requestID uint32) {
+	m.mu.Lock()
+	defer m.mu.Unlock()
+	if i := m.indexOf(requestID); i >= 0 {
+		m.pending = append(m.pending[:i], m.pending[i+1:]...)
+	}
+}
+
+// HasPending returns true if any change is awaiting confirmation.
+func (m *FeedbagMirror) HasPending() bool {
+	m.mu.Lock()
+	defer m.mu.Unlock()
+	return len(m.pending) > 0
+}
+
+// Mark returns a marker for the changes sent so far, for Reload.
+func (m *FeedbagMirror) Mark() uint64 {
+	m.mu.Lock()
+	defer m.mu.Unlock()
+	return m.lastSeq
+}
+
+// Reload replaces the confirmed feedbag with items, the server's feedbag as of
+// a query sent after the changes up to marker. Those changes are forgotten,
+// since the server either applied them or dropped them. Changes sent after the
+// query stay pending.
+func (m *FeedbagMirror) Reload(marker uint64, items []wire.FeedbagItem) {
+	m.mu.Lock()
+	defer m.mu.Unlock()
+	m.confirmed = cloneFeedbagItems(items)
+	var pending []feedbagChange
+	for _, change := range m.pending {
+		if change.seq > marker {
+			pending = append(pending, change)
+		}
+	}
+	m.pending = pending
+}
+
+// ApplyRemote applies a change made at another of the user's locations. del
+// is true when the change deletes items.
+func (m *FeedbagMirror) ApplyRemote(del bool, items []wire.FeedbagItem) {
+	m.mu.Lock()
+	defer m.mu.Unlock()
+	m.confirmed = applyFeedbagChange(m.confirmed, del, cloneFeedbagItems(items))
+}
+
+// GroupNames returns the name of each group by group ID, with all pending
+// changes applied.
+func (m *FeedbagMirror) GroupNames() map[uint16]string {
+	names := make(map[uint16]string)
+	for _, item := range m.Snapshot() {
+		if item.ClassID == wire.FeedbagClassIdGroup {
+			names[item.GroupID] = item.Name
+		}
+	}
+	return names
+}
+
+func (m *FeedbagMirror) indexOf(requestID uint32) int {
+	for i, change := range m.pending {
+		if change.requestID == requestID {
+			return i
+		}
+	}
+	return -1
+}
+
+// cloneFeedbagItems returns a copy of items that shares no TLV lists with
+// them, since FeedbagList edits TLV lists in place.
+func cloneFeedbagItems(items []wire.FeedbagItem) []wire.FeedbagItem {
+	items = slices.Clone(items)
+	for i := range items {
+		items[i].TLVList = slices.Clone(items[i].TLVList)
+	}
+	return items
+}
+
+// applyFeedbagChange returns items with changed upserted, or deleted when del
+// is true. Items match by group and item ID.
+func applyFeedbagChange(items []wire.FeedbagItem, del bool, changed []wire.FeedbagItem) []wire.FeedbagItem {
+	for _, item := range changed {
+		i := slices.IndexFunc(items, func(existing wire.FeedbagItem) bool {
+			return existing.GroupID == item.GroupID && existing.ItemID == item.ItemID
+		})
+		switch {
+		case del && i >= 0:
+			items = slices.Delete(items, i, i+1)
+		case !del && i >= 0:
+			items[i] = item
+		case !del:
+			items = append(items, item)
+		}
+	}
+	return items
+}

+ 50 - 50
server/toc/toc_conn_test.go → state/feedbag_mirror_test.go

@@ -1,4 +1,4 @@
-package toc
+package state
 
 import (
 	"testing"
@@ -17,66 +17,66 @@ func TestFeedbagMirror(t *testing.T) {
 	carol := wire.FeedbagItem{ClassID: wire.FeedbagClassIdBuddy, GroupID: 1, ItemID: 4, Name: "carol"}
 
 	t.Run("pending changes show in the snapshot until confirmed", func(t *testing.T) {
-		m := &feedbagMirror{}
-		m.reset([]wire.FeedbagItem{root, friends, alice})
+		m := &FeedbagMirror{}
+		m.Reset([]wire.FeedbagItem{root, friends, alice})
 
-		m.sent(1, false, []wire.FeedbagItem{aliceRenamed, bob})
-		m.sent(2, true, []wire.FeedbagItem{aliceRenamed})
-		assert.True(t, m.hasPending())
-		assert.Equal(t, []wire.FeedbagItem{root, friends, bob}, m.snapshot())
+		m.Sent(1, false, []wire.FeedbagItem{aliceRenamed, bob})
+		m.Sent(2, true, []wire.FeedbagItem{aliceRenamed})
+		assert.True(t, m.HasPending())
+		assert.Equal(t, []wire.FeedbagItem{root, friends, bob}, m.Snapshot())
 
 		// only the accepted items are confirmed
-		m.confirm(1, []uint16{0, 0x0E})
-		m.confirm(2, []uint16{0})
-		assert.False(t, m.hasPending())
-		assert.Equal(t, []wire.FeedbagItem{root, friends}, m.snapshot())
+		m.Confirm(1, []uint16{0, 0x0E})
+		m.Confirm(2, []uint16{0})
+		assert.False(t, m.HasPending())
+		assert.Equal(t, []wire.FeedbagItem{root, friends}, m.Snapshot())
 	})
 
 	t.Run("a rejected change is discarded", func(t *testing.T) {
-		m := &feedbagMirror{}
-		m.reset([]wire.FeedbagItem{root, friends})
+		m := &FeedbagMirror{}
+		m.Reset([]wire.FeedbagItem{root, friends})
 
-		m.sent(1, false, []wire.FeedbagItem{bob})
-		m.discard(1)
-		assert.False(t, m.hasPending())
-		assert.Equal(t, []wire.FeedbagItem{root, friends}, m.snapshot())
+		m.Sent(1, false, []wire.FeedbagItem{bob})
+		m.Discard(1)
+		assert.False(t, m.HasPending())
+		assert.Equal(t, []wire.FeedbagItem{root, friends}, m.Snapshot())
 	})
 
 	t.Run("a reload keeps changes sent after its query", func(t *testing.T) {
-		m := &feedbagMirror{}
-		m.reset([]wire.FeedbagItem{root, friends})
+		m := &FeedbagMirror{}
+		m.Reset([]wire.FeedbagItem{root, friends})
 
-		m.sent(1, false, []wire.FeedbagItem{bob}) // dropped by the server
-		marker := m.mark()
-		m.sent(2, false, []wire.FeedbagItem{carol})
+		m.Sent(1, false, []wire.FeedbagItem{bob}) // dropped by the server
+		marker := m.Mark()
+		m.Sent(2, false, []wire.FeedbagItem{carol})
 
-		m.reload(marker, []wire.FeedbagItem{root, friends, alice})
-		assert.Equal(t, []wire.FeedbagItem{root, friends, alice, carol}, m.snapshot())
+		m.Reload(marker, []wire.FeedbagItem{root, friends, alice})
+		assert.Equal(t, []wire.FeedbagItem{root, friends, alice, carol}, m.Snapshot())
 
 		// the confirmation of the dropped change never comes; a late one for
 		// a change the reload covered changes nothing
-		m.confirm(1, []uint16{0})
-		m.confirm(2, []uint16{0})
-		assert.False(t, m.hasPending())
-		assert.Equal(t, []wire.FeedbagItem{root, friends, alice, carol}, m.snapshot())
+		m.Confirm(1, []uint16{0})
+		m.Confirm(2, []uint16{0})
+		assert.False(t, m.HasPending())
+		assert.Equal(t, []wire.FeedbagItem{root, friends, alice, carol}, m.Snapshot())
 	})
 
 	t.Run("changes from other locations apply right away", func(t *testing.T) {
-		m := &feedbagMirror{}
-		m.reset([]wire.FeedbagItem{root, friends, alice})
-
-		m.applyRemote(false, []wire.FeedbagItem{bob})
-		m.applyRemote(true, []wire.FeedbagItem{alice})
-		assert.False(t, m.hasPending())
-		assert.Equal(t, []wire.FeedbagItem{root, friends, bob}, m.snapshot())
-		assert.Equal(t, map[uint16]string{0: "", 1: "Friends"}, m.groupNames())
+		m := &FeedbagMirror{}
+		m.Reset([]wire.FeedbagItem{root, friends, alice})
+
+		m.ApplyRemote(false, []wire.FeedbagItem{bob})
+		m.ApplyRemote(true, []wire.FeedbagItem{alice})
+		assert.False(t, m.HasPending())
+		assert.Equal(t, []wire.FeedbagItem{root, friends, bob}, m.Snapshot())
+		assert.Equal(t, map[uint16]string{0: "", 1: "Friends"}, m.GroupNames())
 	})
 
 	t.Run("a snapshot doesn't change with the mirror", func(t *testing.T) {
-		m := &feedbagMirror{}
-		m.reset([]wire.FeedbagItem{root, friends, alice})
-		snapshot := m.snapshot()
-		m.applyRemote(true, []wire.FeedbagItem{alice})
+		m := &FeedbagMirror{}
+		m.Reset([]wire.FeedbagItem{root, friends, alice})
+		snapshot := m.Snapshot()
+		m.ApplyRemote(true, []wire.FeedbagItem{alice})
 		assert.Equal(t, []wire.FeedbagItem{root, friends, alice}, snapshot)
 	})
 
@@ -91,26 +91,26 @@ func TestFeedbagMirror(t *testing.T) {
 			items[0].Set(wire.NewTLVBE(wire.FeedbagAttributesOrder, []uint16{9}))
 		}
 
-		m := &feedbagMirror{}
+		m := &FeedbagMirror{}
 		items := []wire.FeedbagItem{order(1)}
-		m.reset(items)
+		m.Reset(items)
 		edit(items)
-		edit(m.snapshot())
-		assert.Equal(t, []wire.FeedbagItem{order(1)}, m.snapshot())
+		edit(m.Snapshot())
+		assert.Equal(t, []wire.FeedbagItem{order(1)}, m.Snapshot())
 
 		items = []wire.FeedbagItem{order(1, 2)}
-		m.sent(1, false, items)
+		m.Sent(1, false, items)
 		edit(items)
-		assert.Equal(t, []wire.FeedbagItem{order(1, 2)}, m.snapshot())
+		assert.Equal(t, []wire.FeedbagItem{order(1, 2)}, m.Snapshot())
 
 		items = []wire.FeedbagItem{order(1, 2, 3)}
-		m.reload(m.mark(), items)
+		m.Reload(m.Mark(), items)
 		edit(items)
-		assert.Equal(t, []wire.FeedbagItem{order(1, 2, 3)}, m.snapshot())
+		assert.Equal(t, []wire.FeedbagItem{order(1, 2, 3)}, m.Snapshot())
 
 		items = []wire.FeedbagItem{order(1, 2, 3, 4)}
-		m.applyRemote(false, items)
+		m.ApplyRemote(false, items)
 		edit(items)
-		assert.Equal(t, []wire.FeedbagItem{order(1, 2, 3, 4)}, m.snapshot())
+		assert.Equal(t, []wire.FeedbagItem{order(1, 2, 3, 4)}, m.Snapshot())
 	})
 }