server.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. package toc
  2. import (
  3. "bufio"
  4. "bytes"
  5. "context"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "log/slog"
  10. "net"
  11. "net/http"
  12. "net/netip"
  13. "sync"
  14. "syscall"
  15. "time"
  16. "github.com/patrickmn/go-cache"
  17. "golang.org/x/sync/errgroup"
  18. "golang.org/x/time/rate"
  19. "github.com/mk6i/retro-aim-server/state"
  20. "github.com/mk6i/retro-aim-server/wire"
  21. )
  22. var (
  23. // errClientReq indicates that an error occurred while reading a client request
  24. errClientReq = errors.New("failed to read client request")
  25. // errServerWrite indicates that an error occurred while writing a server response
  26. errServerWrite = errors.New("failed to send server response")
  27. // errTOCProcessing indicates that an error occurred in the TOC handler
  28. errTOCProcessing = errors.New("failed to process TOC request")
  29. )
  30. // bufferedConn is a wrapper around net.Conn that allows peeking into the
  31. // incoming connection without consuming data. It is useful for multiplexing
  32. // TOC/HTTP and TOC/FLAP connections.
  33. //
  34. // It embeds net.Conn, so all standard connection methods remain available.
  35. type bufferedConn struct {
  36. r *bufio.Reader
  37. net.Conn
  38. }
  39. // newBufferedConn wraps a net.Conn with buffered reading capabilities.
  40. func newBufferedConn(c net.Conn) bufferedConn {
  41. return bufferedConn{bufio.NewReader(c), c}
  42. }
  43. // Peek returns the next n bytes from the buffer without advancing the reader.
  44. // If fewer than n bytes are available, it returns an error.
  45. func (b bufferedConn) Peek(n int) ([]byte, error) {
  46. return b.r.Peek(n)
  47. }
  48. // Read reads data into p from the buffered connection.
  49. // It prioritizes buffered data before reading from the underlying connection.
  50. func (b bufferedConn) Read(p []byte) (int, error) {
  51. return b.r.Read(p)
  52. }
  53. // channelListener is an implementation of net.Listener that accepts connections
  54. // from a channel instead of a network socket. It is useful for attaching an
  55. // HTTP service to a connection on the fly.
  56. type channelListener struct {
  57. ch chan net.Conn // Channel used to receive connections.
  58. ctx context.Context
  59. }
  60. // Accept waits for and returns the next connection from the channel.
  61. // If the channel is closed, it returns io.EOF to indicate no more connections.
  62. func (l *channelListener) Accept() (net.Conn, error) {
  63. select {
  64. case <-l.ctx.Done():
  65. return nil, io.EOF
  66. case ch := <-l.ch:
  67. return ch, io.EOF
  68. }
  69. }
  70. // Close closes the listener. Since channelListener does not manage an actual
  71. // network connection, this is a no-op and always returns nil.
  72. func (l *channelListener) Close() error {
  73. return nil
  74. }
  75. // Addr returns the network address of the listener.
  76. // Since channelListener is not bound to a real network address, it returns nil.
  77. func (l *channelListener) Addr() net.Addr {
  78. return nil
  79. }
  80. // IPRateLimiter provides per-IP rate limiting using a token bucket algorithm.
  81. // It caches individual rate limiters per IP address with automatic TTL expiration.
  82. type IPRateLimiter struct {
  83. cache *cache.Cache // In-memory cache of rate limiters keyed by IP
  84. rate rate.Limit // Allowed request rate (events per second)
  85. burst int // Maximum burst size
  86. }
  87. // NewIPRateLimiter returns a new IPRateLimiter that limits each IP to the specified
  88. // rate and burst, with limiter state expiring after the given TTL.
  89. // Entries are retained for up to 2×TTL to reduce churn under frequent lookups.
  90. func NewIPRateLimiter(rate rate.Limit, burst int, ttl time.Duration) *IPRateLimiter {
  91. return &IPRateLimiter{
  92. cache: cache.New(ttl, 2*ttl),
  93. rate: rate,
  94. burst: burst,
  95. }
  96. }
  97. // Allow returns true if the request from the given IP is allowed under its rate limit.
  98. // If no limiter exists for the IP, one is created and tracked in the cache.
  99. func (l *IPRateLimiter) Allow(ip string) (allowed bool) {
  100. limiter, found := l.cache.Get(ip)
  101. if !found {
  102. limiter = rate.NewLimiter(l.rate, l.burst)
  103. l.cache.Set(ip, limiter, cache.DefaultExpiration)
  104. }
  105. return limiter.(*rate.Limiter).Allow()
  106. }
  107. func NewServer(
  108. listenerCfg []string,
  109. logger *slog.Logger,
  110. BOSProxy OSCARProxy,
  111. ipRateLimiter *IPRateLimiter,
  112. recalcWarning func(ctx context.Context, sess *state.Session) error,
  113. lowerWarnLevel func(ctx context.Context, sess *state.Session),
  114. ) *Server {
  115. ctx, cancel := context.WithCancel(context.Background())
  116. s := &Server{
  117. bosProxy: BOSProxy,
  118. conns: make(map[net.Conn]struct{}),
  119. listenerCfg: listenerCfg,
  120. logger: logger,
  121. loginIPRateLimiter: ipRateLimiter,
  122. recalcWarning: recalcWarning,
  123. lowerWarnLevel: lowerWarnLevel,
  124. servers: make([]*http.Server, 0, len(listenerCfg)),
  125. shutdownCancel: cancel,
  126. shutdownCtx: ctx,
  127. }
  128. for range listenerCfg {
  129. s.servers = append(s.servers, &http.Server{
  130. Handler: BOSProxy.NewServeMux(),
  131. BaseContext: func(net.Listener) context.Context {
  132. return s.shutdownCtx
  133. },
  134. })
  135. }
  136. return s
  137. }
  138. // Server implements a TOC protocol server that multiplexes TOC/HTTP and
  139. // TOC/FLAP requests. It acts as a gateway, forwarding all TOC requests
  140. // to the OSCAR server for processing.
  141. type Server struct {
  142. bosProxy OSCARProxy
  143. logger *slog.Logger
  144. loginIPRateLimiter *IPRateLimiter
  145. recalcWarning func(ctx context.Context, sess *state.Session) error
  146. lowerWarnLevel func(ctx context.Context, sess *state.Session)
  147. listenerCfg []string
  148. listeners []net.Listener
  149. servers []*http.Server
  150. connMu sync.Mutex
  151. conns map[net.Conn]struct{}
  152. connWg sync.WaitGroup
  153. listenWg sync.WaitGroup
  154. shutdownCtx context.Context
  155. shutdownCancel context.CancelFunc
  156. }
  157. func (s *Server) ListenAndServe() error {
  158. g, ctx := errgroup.WithContext(s.shutdownCtx)
  159. for i, cfg := range s.listenerCfg {
  160. ln, err := net.Listen("tcp", cfg)
  161. if err != nil {
  162. s.cleanupListeners()
  163. s.shutdownCancel()
  164. return fmt.Errorf("unable to start TOC server: %w", err)
  165. }
  166. s.logger.InfoContext(ctx, "starting server", "listen_host", cfg)
  167. s.listeners = append(s.listeners, ln)
  168. s.listenWg.Add(1)
  169. httpCh := make(chan net.Conn)
  170. g.Go(func() error {
  171. cl := &channelListener{
  172. ch: httpCh,
  173. ctx: s.shutdownCtx,
  174. }
  175. if err := s.servers[i].Serve(cl); !errors.Is(err, http.ErrServerClosed) && !errors.Is(err, io.EOF) {
  176. s.shutdownCancel()
  177. return err
  178. }
  179. return nil
  180. })
  181. g.Go(func() error {
  182. s.acceptLoop(ctx, ln, httpCh)
  183. return nil
  184. })
  185. }
  186. return g.Wait()
  187. }
  188. func (s *Server) Shutdown(ctx context.Context) error {
  189. s.logger.Debug("Initiating graceful shutdown...")
  190. s.shutdownCancel()
  191. s.cleanupListeners()
  192. // Wait for handlers to complete
  193. done := make(chan struct{})
  194. go func() {
  195. s.connWg.Wait()
  196. s.listenWg.Wait()
  197. close(done)
  198. }()
  199. for _, srv := range s.servers {
  200. _ = srv.Shutdown(ctx)
  201. }
  202. select {
  203. case <-done:
  204. s.logger.Info("shutdown complete")
  205. case <-ctx.Done():
  206. s.logger.Info("shutdown complete, but connections didn't close cleanly")
  207. }
  208. return nil
  209. }
  210. func (s *Server) cleanupListeners() {
  211. for _, ln := range s.listeners {
  212. _ = ln.Close()
  213. }
  214. s.listeners = nil
  215. }
  216. func (s *Server) acceptLoop(ctx context.Context, ln net.Listener, httpCh chan net.Conn) {
  217. defer s.listenWg.Done()
  218. for {
  219. conn, err := ln.Accept()
  220. if err != nil {
  221. if errors.Is(err, net.ErrClosed) {
  222. return
  223. }
  224. s.logger.Error("accept error", "err", err.Error())
  225. continue
  226. }
  227. go func() {
  228. if err := s.handleConnection(conn, ctx, httpCh); err != nil {
  229. s.logger.InfoContext(ctx, "user session failed", "err", err.Error())
  230. }
  231. }()
  232. }
  233. }
  234. // handleConnection inspects and routes an incoming connection. If the connection
  235. // starts with "FLAP", handle as TOC/FLAP; otherwise, dispatch for HTTP
  236. // processing.
  237. func (s *Server) handleConnection(conn net.Conn, ctx context.Context, httpCh chan net.Conn) error {
  238. bufCon := newBufferedConn(conn)
  239. doFlap := "FLAP"
  240. buf, err := bufCon.Peek(len(doFlap))
  241. if err != nil {
  242. return fmt.Errorf("bufCon.Peek: %w", err)
  243. }
  244. // handle TOC/FLAP
  245. if string(buf) == doFlap {
  246. defer func() {
  247. // untrack connections
  248. s.connMu.Lock()
  249. delete(s.conns, conn)
  250. s.connMu.Unlock()
  251. _ = conn.Close()
  252. s.connWg.Done()
  253. }()
  254. // track connection
  255. s.connMu.Lock()
  256. s.conns[conn] = struct{}{}
  257. s.connMu.Unlock()
  258. s.connWg.Add(1)
  259. if err = s.dispatchFLAP(ctx, bufCon); err != nil {
  260. switch {
  261. case errors.Is(err, io.EOF):
  262. case errors.Is(err, net.ErrClosed):
  263. case errors.Is(err, syscall.ECONNRESET):
  264. return nil
  265. default:
  266. return fmt.Errorf("s.dispatchFLAP: %w", err)
  267. }
  268. }
  269. return nil
  270. }
  271. // handle TOC/HTTP
  272. select {
  273. case httpCh <- bufCon:
  274. return nil
  275. case <-ctx.Done():
  276. return nil
  277. }
  278. }
  279. func (s *Server) dispatchFLAP(ctx context.Context, conn net.Conn) error {
  280. var once sync.Once
  281. closeConn := func() {
  282. once.Do(func() {
  283. _ = conn.Close()
  284. })
  285. }
  286. defer closeConn()
  287. ctx = context.WithValue(ctx, "ip", conn.RemoteAddr().String())
  288. clientFlap, err := s.initFLAP(conn)
  289. if err != nil {
  290. return err
  291. }
  292. ip, _, err := net.SplitHostPort(conn.RemoteAddr().String())
  293. if err != nil {
  294. s.logger.Error("failed to parse remote address", "err", err.Error())
  295. return err
  296. }
  297. if ok := s.loginIPRateLimiter.Allow(ip); !ok {
  298. if err := clientFlap.SendDataFrame([]byte("ERROR:983")); err != nil {
  299. return fmt.Errorf("clientFlap.SendDataFrame: %w", err)
  300. }
  301. return nil
  302. }
  303. sessBOS, err := s.login(ctx, clientFlap)
  304. if err != nil {
  305. return fmt.Errorf("s.login: %w", err)
  306. }
  307. if sessBOS == nil {
  308. return nil // user not found
  309. }
  310. ctx = context.WithValue(ctx, "screenName", sessBOS.IdentScreenName())
  311. remoteAddr, ok := ctx.Value("ip").(string)
  312. if ok {
  313. ip, err := netip.ParseAddrPort(remoteAddr)
  314. if err != nil {
  315. return errors.New("unable to parse ip addr")
  316. }
  317. sessBOS.SetRemoteAddr(&ip)
  318. }
  319. chatRegistry := NewChatRegistry()
  320. return s.handleTOCRequest(ctx, closeConn, sessBOS, chatRegistry, clientFlap)
  321. }
  322. // handleTOCRequest processes incoming TOC requests and coordinates their handling.
  323. // It reads client requests, processes TOC commands, and sends responses back to the client.
  324. //
  325. // Returns:
  326. // - errClientReq if an error occurs while reading the TOC request. wraps
  327. // io.EOF if the client disconnected.
  328. // - errTOCProcessing if an error occurs while processing the TOC command.
  329. // - errServerWrite if an error occurs while sending the TOC response.
  330. func (s *Server) handleTOCRequest(
  331. ctx context.Context,
  332. closeConn func(),
  333. sessBOS *state.Session,
  334. chatRegistry *ChatRegistry,
  335. clientFlap *wire.FlapClient,
  336. ) error {
  337. if err := s.recalcWarning(ctx, sessBOS); err != nil {
  338. return fmt.Errorf("failed to recalculate warning level: %w", err)
  339. }
  340. // TOC response queue
  341. msgCh := make(chan []byte, 1)
  342. g, ctx := errgroup.WithContext(ctx)
  343. // process TOC client requests and enqueue TOC server responses
  344. g.Go(func() error {
  345. err := s.runClientCommands(ctx, g.Go, sessBOS, chatRegistry, clientFlap, msgCh)
  346. return errors.Join(err, errClientReq)
  347. })
  348. // translate OSCAR server responses to TOC responses and enqueue them
  349. g.Go(func() error {
  350. err := s.bosProxy.RecvBOS(ctx, sessBOS, chatRegistry, msgCh)
  351. closeConn() // unblock runClientCommands
  352. return errors.Join(err, errTOCProcessing)
  353. })
  354. // send TOC server responses to the client
  355. g.Go(func() error {
  356. err := s.sendToClient(ctx, msgCh, clientFlap)
  357. closeConn() // unblock runClientCommands
  358. return errors.Join(err, errServerWrite)
  359. })
  360. // process warning limits
  361. g.Go(func() error {
  362. s.lowerWarnLevel(ctx, sessBOS)
  363. return nil
  364. })
  365. return g.Wait()
  366. }
  367. func (s *Server) runClientCommands(ctx context.Context, doAsync func(f func() error), sessBOS *state.Session, chatRegistry *ChatRegistry, clientFlap *wire.FlapClient, toCh chan<- []byte) error {
  368. for {
  369. clientFrame, err := clientFlap.ReceiveFLAP()
  370. if err != nil {
  371. return err
  372. }
  373. switch clientFrame.FrameType {
  374. case wire.FLAPFrameSignoff:
  375. return io.EOF // client disconnected
  376. case wire.FLAPFrameKeepAlive:
  377. // keep alive heartbeat, do nothing for now.
  378. // todo set connection deadline to future time
  379. case wire.FLAPFrameData:
  380. clientFrame.Payload = bytes.TrimRight(clientFrame.Payload, "\x00") // trim null terminator
  381. if len(clientFrame.Payload) == 0 {
  382. return errors.New("TOC command is empty")
  383. }
  384. if len(clientFrame.Payload) > 2048 {
  385. return errors.New("TOC command exceeds maximum length (2048)")
  386. }
  387. msg := s.bosProxy.RecvClientCmd(ctx, sessBOS, chatRegistry, clientFrame.Payload, toCh, doAsync)
  388. if len(msg) > 0 {
  389. select {
  390. case toCh <- []byte(msg):
  391. case <-ctx.Done():
  392. return nil
  393. }
  394. }
  395. default:
  396. return fmt.Errorf("unexpected clientFlap clientFrame type %d", clientFrame.FrameType)
  397. }
  398. }
  399. }
  400. func (s *Server) sendToClient(ctx context.Context, toClient <-chan []byte, clientFlap *wire.FlapClient) error {
  401. for {
  402. select {
  403. case <-ctx.Done():
  404. return nil
  405. case msg := <-toClient:
  406. if err := clientFlap.SendDataFrame(msg); err != nil {
  407. return fmt.Errorf("clientFlap.SendDataFrame: %w", err)
  408. }
  409. if s.logger.Enabled(ctx, slog.LevelDebug) {
  410. s.logger.DebugContext(ctx, "server response", "command", msg)
  411. } else {
  412. // just log the command, omit params
  413. idx := len(msg)
  414. if col := bytes.IndexByte(msg, ':'); col > -1 {
  415. idx = col
  416. }
  417. s.logger.InfoContext(ctx, "server response", "command", msg[0:idx])
  418. }
  419. }
  420. }
  421. }
  422. func (s *Server) login(ctx context.Context, clientFlap *wire.FlapClient) (*state.Session, error) {
  423. clientFrame, err := clientFlap.ReceiveFLAP()
  424. if err != nil {
  425. if errors.Is(err, io.EOF) {
  426. return nil, nil
  427. }
  428. return nil, fmt.Errorf("clientFlap.ReceiveFLAP: %w", err)
  429. }
  430. cmd := clientFrame.Payload
  431. var args []byte
  432. if idx := bytes.IndexByte(clientFrame.Payload, ' '); idx > -1 {
  433. cmd, args = clientFrame.Payload[:idx], clientFrame.Payload[idx:]
  434. }
  435. if string(cmd) != "toc_signon" {
  436. return nil, errors.New("expected toc_signon")
  437. }
  438. sessBOS, reply := s.bosProxy.Signon(ctx, args)
  439. for _, m := range reply {
  440. if err := clientFlap.SendDataFrame([]byte(m)); err != nil {
  441. return nil, fmt.Errorf("clientFlap.SendDataFrame: %w", err)
  442. }
  443. }
  444. return sessBOS, nil
  445. }
  446. // initFLAP sets up a new FLAP connection. It returns a flap client if the
  447. // connection successfully initialized.
  448. func (s *Server) initFLAP(rw io.ReadWriter) (*wire.FlapClient, error) {
  449. expected := "FLAPON\r\n\r\n"
  450. buf := make([]byte, len(expected))
  451. _, err := io.ReadFull(rw, buf)
  452. if err != nil {
  453. return nil, fmt.Errorf("io.ReadFull: %w", err)
  454. }
  455. if expected != string(buf) {
  456. return nil, fmt.Errorf("expected FLAPON, got %s", buf)
  457. }
  458. clientFlap := wire.NewFlapClient(0, rw, rw)
  459. if err := clientFlap.SendSignonFrame(nil); err != nil {
  460. return nil, fmt.Errorf("clientFlap.SendSignonFrame: %w", err)
  461. }
  462. if _, err := clientFlap.ReceiveSignonFrame(); err != nil {
  463. return nil, fmt.Errorf("clientFlap.ReceiveSignonFrame: %w", err)
  464. }
  465. return clientFlap, nil
  466. }