server.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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. lowerWarnLevel func(ctx context.Context, sess *state.Session),
  113. ) *Server {
  114. ctx, cancel := context.WithCancel(context.Background())
  115. s := &Server{
  116. bosProxy: BOSProxy,
  117. conns: make(map[net.Conn]struct{}),
  118. listenerCfg: listenerCfg,
  119. logger: logger,
  120. loginIPRateLimiter: ipRateLimiter,
  121. lowerWarnLevel: lowerWarnLevel,
  122. servers: make([]*http.Server, 0, len(listenerCfg)),
  123. shutdownCancel: cancel,
  124. shutdownCtx: ctx,
  125. }
  126. for range listenerCfg {
  127. s.servers = append(s.servers, &http.Server{
  128. Handler: BOSProxy.NewServeMux(),
  129. BaseContext: func(net.Listener) context.Context {
  130. return s.shutdownCtx
  131. },
  132. })
  133. }
  134. return s
  135. }
  136. // Server implements a TOC protocol server that multiplexes TOC/HTTP and
  137. // TOC/FLAP requests. It acts as a gateway, forwarding all TOC requests
  138. // to the OSCAR server for processing.
  139. type Server struct {
  140. bosProxy OSCARProxy
  141. logger *slog.Logger
  142. loginIPRateLimiter *IPRateLimiter
  143. lowerWarnLevel func(ctx context.Context, sess *state.Session)
  144. listenerCfg []string
  145. listeners []net.Listener
  146. servers []*http.Server
  147. connMu sync.Mutex
  148. conns map[net.Conn]struct{}
  149. connWg sync.WaitGroup
  150. listenWg sync.WaitGroup
  151. shutdownCtx context.Context
  152. shutdownCancel context.CancelFunc
  153. }
  154. func (s *Server) ListenAndServe() error {
  155. g, ctx := errgroup.WithContext(s.shutdownCtx)
  156. for i, cfg := range s.listenerCfg {
  157. ln, err := net.Listen("tcp", cfg)
  158. if err != nil {
  159. s.cleanupListeners()
  160. s.shutdownCancel()
  161. return fmt.Errorf("unable to start TOC server: %w", err)
  162. }
  163. s.logger.InfoContext(ctx, "starting server", "listen_host", cfg)
  164. s.listeners = append(s.listeners, ln)
  165. s.listenWg.Add(1)
  166. httpCh := make(chan net.Conn)
  167. g.Go(func() error {
  168. cl := &channelListener{
  169. ch: httpCh,
  170. ctx: s.shutdownCtx,
  171. }
  172. if err := s.servers[i].Serve(cl); !errors.Is(err, http.ErrServerClosed) && !errors.Is(err, io.EOF) {
  173. fmt.Println("HAHA")
  174. s.shutdownCancel()
  175. return err
  176. }
  177. return nil
  178. })
  179. g.Go(func() error {
  180. s.acceptLoop(ctx, ln, httpCh)
  181. return nil
  182. })
  183. }
  184. return g.Wait()
  185. }
  186. func (s *Server) Shutdown(ctx context.Context) error {
  187. s.logger.Debug("Initiating graceful shutdown...")
  188. s.shutdownCancel()
  189. s.cleanupListeners()
  190. // Wait for handlers to complete
  191. done := make(chan struct{})
  192. go func() {
  193. s.connWg.Wait()
  194. s.listenWg.Wait()
  195. close(done)
  196. }()
  197. for _, srv := range s.servers {
  198. _ = srv.Shutdown(ctx)
  199. }
  200. select {
  201. case <-done:
  202. s.logger.Info("shutdown complete")
  203. case <-ctx.Done():
  204. s.logger.Info("shutdown complete, but connections didn't close cleanly")
  205. }
  206. return nil
  207. }
  208. func (s *Server) cleanupListeners() {
  209. for _, ln := range s.listeners {
  210. _ = ln.Close()
  211. }
  212. s.listeners = nil
  213. }
  214. func (s *Server) acceptLoop(ctx context.Context, ln net.Listener, httpCh chan net.Conn) {
  215. defer s.listenWg.Done()
  216. for {
  217. conn, err := ln.Accept()
  218. if err != nil {
  219. if errors.Is(err, net.ErrClosed) {
  220. return
  221. }
  222. s.logger.Error("accept error", "err", err.Error())
  223. continue
  224. }
  225. go func() {
  226. if err := s.handleConnection(conn, ctx, httpCh); err != nil {
  227. s.logger.InfoContext(ctx, "user session failed", "err", err.Error())
  228. }
  229. }()
  230. }
  231. }
  232. // handleConnection inspects and routes an incoming connection. If the connection
  233. // starts with "FLAP", handle as TOC/FLAP; otherwise, dispatch for HTTP
  234. // processing.
  235. func (s *Server) handleConnection(conn net.Conn, ctx context.Context, httpCh chan net.Conn) error {
  236. bufCon := newBufferedConn(conn)
  237. doFlap := "FLAP"
  238. buf, err := bufCon.Peek(len(doFlap))
  239. if err != nil {
  240. return fmt.Errorf("bufCon.Peek: %w", err)
  241. }
  242. // handle TOC/FLAP
  243. if string(buf) == doFlap {
  244. defer func() {
  245. // untrack connections
  246. s.connMu.Lock()
  247. delete(s.conns, conn)
  248. s.connMu.Unlock()
  249. _ = conn.Close()
  250. s.connWg.Done()
  251. }()
  252. // track connection
  253. s.connMu.Lock()
  254. s.conns[conn] = struct{}{}
  255. s.connMu.Unlock()
  256. s.connWg.Add(1)
  257. if err = s.dispatchFLAP(ctx, bufCon); err != nil {
  258. switch {
  259. case errors.Is(err, io.EOF):
  260. case errors.Is(err, net.ErrClosed):
  261. case errors.Is(err, syscall.ECONNRESET):
  262. return nil
  263. default:
  264. return fmt.Errorf("s.dispatchFLAP: %w", err)
  265. }
  266. }
  267. return nil
  268. }
  269. // handle TOC/HTTP
  270. select {
  271. case httpCh <- bufCon:
  272. return nil
  273. case <-ctx.Done():
  274. return nil
  275. }
  276. }
  277. func (s *Server) dispatchFLAP(ctx context.Context, conn net.Conn) error {
  278. var once sync.Once
  279. closeConn := func() {
  280. once.Do(func() {
  281. _ = conn.Close()
  282. })
  283. }
  284. defer closeConn()
  285. ctx = context.WithValue(ctx, "ip", conn.RemoteAddr().String())
  286. clientFlap, err := s.initFLAP(conn)
  287. if err != nil {
  288. return err
  289. }
  290. ip, _, err := net.SplitHostPort(conn.RemoteAddr().String())
  291. if err != nil {
  292. s.logger.Error("failed to parse remote address", "err", err.Error())
  293. return err
  294. }
  295. if ok := s.loginIPRateLimiter.Allow(ip); !ok {
  296. if err := clientFlap.SendDataFrame([]byte("ERROR:983")); err != nil {
  297. return fmt.Errorf("clientFlap.SendDataFrame: %w", err)
  298. }
  299. return nil
  300. }
  301. sessBOS, err := s.login(ctx, clientFlap)
  302. if err != nil {
  303. return fmt.Errorf("s.login: %w", err)
  304. }
  305. if sessBOS == nil {
  306. return nil // user not found
  307. }
  308. ctx = context.WithValue(ctx, "screenName", sessBOS.IdentScreenName())
  309. remoteAddr, ok := ctx.Value("ip").(string)
  310. if ok {
  311. ip, err := netip.ParseAddrPort(remoteAddr)
  312. if err != nil {
  313. return errors.New("unable to parse ip addr")
  314. }
  315. sessBOS.SetRemoteAddr(&ip)
  316. }
  317. chatRegistry := NewChatRegistry()
  318. return s.handleTOCRequest(ctx, closeConn, sessBOS, chatRegistry, clientFlap)
  319. }
  320. // handleTOCRequest processes incoming TOC requests and coordinates their handling.
  321. // It reads client requests, processes TOC commands, and sends responses back to the client.
  322. //
  323. // Returns:
  324. // - errClientReq if an error occurs while reading the TOC request. wraps
  325. // io.EOF if the client disconnected.
  326. // - errTOCProcessing if an error occurs while processing the TOC command.
  327. // - errServerWrite if an error occurs while sending the TOC response.
  328. func (s *Server) handleTOCRequest(
  329. ctx context.Context,
  330. closeConn func(),
  331. sessBOS *state.Session,
  332. chatRegistry *ChatRegistry,
  333. clientFlap *wire.FlapClient,
  334. ) error {
  335. // TOC response queue
  336. msgCh := make(chan []byte, 1)
  337. g, ctx := errgroup.WithContext(ctx)
  338. // process TOC client requests and enqueue TOC server responses
  339. g.Go(func() error {
  340. err := s.runClientCommands(ctx, g.Go, sessBOS, chatRegistry, clientFlap, msgCh)
  341. return errors.Join(err, errClientReq)
  342. })
  343. // translate OSCAR server responses to TOC responses and enqueue them
  344. g.Go(func() error {
  345. err := s.bosProxy.RecvBOS(ctx, sessBOS, chatRegistry, msgCh)
  346. closeConn() // unblock runClientCommands
  347. return errors.Join(err, errTOCProcessing)
  348. })
  349. // send TOC server responses to the client
  350. g.Go(func() error {
  351. err := s.sendToClient(ctx, msgCh, clientFlap)
  352. closeConn() // unblock runClientCommands
  353. return errors.Join(err, errServerWrite)
  354. })
  355. // process warning limits
  356. g.Go(func() error {
  357. s.lowerWarnLevel(ctx, sessBOS)
  358. return nil
  359. })
  360. return g.Wait()
  361. }
  362. func (s *Server) runClientCommands(ctx context.Context, doAsync func(f func() error), sessBOS *state.Session, chatRegistry *ChatRegistry, clientFlap *wire.FlapClient, toCh chan<- []byte) error {
  363. for {
  364. clientFrame, err := clientFlap.ReceiveFLAP()
  365. if err != nil {
  366. return err
  367. }
  368. switch clientFrame.FrameType {
  369. case wire.FLAPFrameSignoff:
  370. return io.EOF // client disconnected
  371. case wire.FLAPFrameKeepAlive:
  372. // keep alive heartbeat, do nothing for now.
  373. // todo set connection deadline to future time
  374. case wire.FLAPFrameData:
  375. clientFrame.Payload = bytes.TrimRight(clientFrame.Payload, "\x00") // trim null terminator
  376. if len(clientFrame.Payload) == 0 {
  377. return errors.New("TOC command is empty")
  378. }
  379. if len(clientFrame.Payload) > 2048 {
  380. return errors.New("TOC command exceeds maximum length (2048)")
  381. }
  382. msg := s.bosProxy.RecvClientCmd(ctx, sessBOS, chatRegistry, clientFrame.Payload, toCh, doAsync)
  383. if len(msg) > 0 {
  384. select {
  385. case toCh <- []byte(msg):
  386. case <-ctx.Done():
  387. return nil
  388. }
  389. }
  390. default:
  391. return fmt.Errorf("unexpected clientFlap clientFrame type %d", clientFrame.FrameType)
  392. }
  393. }
  394. }
  395. func (s *Server) sendToClient(ctx context.Context, toClient <-chan []byte, clientFlap *wire.FlapClient) error {
  396. for {
  397. select {
  398. case <-ctx.Done():
  399. return nil
  400. case msg := <-toClient:
  401. if err := clientFlap.SendDataFrame(msg); err != nil {
  402. return fmt.Errorf("clientFlap.SendDataFrame: %w", err)
  403. }
  404. if s.logger.Enabled(ctx, slog.LevelDebug) {
  405. s.logger.DebugContext(ctx, "server response", "command", msg)
  406. } else {
  407. // just log the command, omit params
  408. idx := len(msg)
  409. if col := bytes.IndexByte(msg, ':'); col > -1 {
  410. idx = col
  411. }
  412. s.logger.InfoContext(ctx, "server response", "command", msg[0:idx])
  413. }
  414. }
  415. }
  416. }
  417. func (s *Server) login(ctx context.Context, clientFlap *wire.FlapClient) (*state.Session, error) {
  418. clientFrame, err := clientFlap.ReceiveFLAP()
  419. if err != nil {
  420. if errors.Is(err, io.EOF) {
  421. return nil, nil
  422. }
  423. return nil, fmt.Errorf("clientFlap.ReceiveFLAP: %w", err)
  424. }
  425. cmd := clientFrame.Payload
  426. var args []byte
  427. if idx := bytes.IndexByte(clientFrame.Payload, ' '); idx > -1 {
  428. cmd, args = clientFrame.Payload[:idx], clientFrame.Payload[idx:]
  429. }
  430. if string(cmd) != "toc_signon" {
  431. return nil, errors.New("expected toc_signon")
  432. }
  433. sessBOS, reply := s.bosProxy.Signon(ctx, args)
  434. for _, m := range reply {
  435. if err := clientFlap.SendDataFrame([]byte(m)); err != nil {
  436. return nil, fmt.Errorf("clientFlap.SendDataFrame: %w", err)
  437. }
  438. }
  439. return sessBOS, nil
  440. }
  441. // initFLAP sets up a new FLAP connection. It returns a flap client if the
  442. // connection successfully initialized.
  443. func (s *Server) initFLAP(rw io.ReadWriter) (*wire.FlapClient, error) {
  444. expected := "FLAPON\r\n\r\n"
  445. buf := make([]byte, len(expected))
  446. _, err := io.ReadFull(rw, buf)
  447. if err != nil {
  448. return nil, fmt.Errorf("io.ReadFull: %w", err)
  449. }
  450. if expected != string(buf) {
  451. return nil, fmt.Errorf("expected FLAPON, got %s", buf)
  452. }
  453. clientFlap := wire.NewFlapClient(0, rw, rw)
  454. if err := clientFlap.SendSignonFrame(nil); err != nil {
  455. return nil, fmt.Errorf("clientFlap.SendSignonFrame: %w", err)
  456. }
  457. if _, err := clientFlap.ReceiveSignonFrame(); err != nil {
  458. return nil, fmt.Errorf("clientFlap.ReceiveSignonFrame: %w", err)
  459. }
  460. return clientFlap, nil
  461. }