server.go 14 KB

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