server.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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. }
  59. // Accept waits for and returns the next connection from the channel.
  60. // If the channel is closed, it returns io.EOF to indicate no more connections.
  61. func (l *channelListener) Accept() (net.Conn, error) {
  62. ch, ok := <-l.ch
  63. if !ok {
  64. return nil, io.EOF
  65. }
  66. return ch, nil
  67. }
  68. // Close closes the listener. Since channelListener does not manage an actual
  69. // network connection, this is a no-op and always returns nil.
  70. func (l *channelListener) Close() error {
  71. return nil
  72. }
  73. // Addr returns the network address of the listener.
  74. // Since channelListener is not bound to a real network address, it returns nil.
  75. func (l *channelListener) Addr() net.Addr {
  76. return nil
  77. }
  78. // IPRateLimiter provides per-IP rate limiting using a token bucket algorithm.
  79. // It caches individual rate limiters per IP address with automatic TTL expiration.
  80. type IPRateLimiter struct {
  81. cache *cache.Cache // In-memory cache of rate limiters keyed by IP
  82. rate rate.Limit // Allowed request rate (events per second)
  83. burst int // Maximum burst size
  84. }
  85. // NewIPRateLimiter returns a new IPRateLimiter that limits each IP to the specified
  86. // rate and burst, with limiter state expiring after the given TTL.
  87. // Entries are retained for up to 2×TTL to reduce churn under frequent lookups.
  88. func NewIPRateLimiter(rate rate.Limit, burst int, ttl time.Duration) *IPRateLimiter {
  89. return &IPRateLimiter{
  90. cache: cache.New(ttl, 2*ttl),
  91. rate: rate,
  92. burst: burst,
  93. }
  94. }
  95. // Allow returns true if the request from the given IP is allowed under its rate limit.
  96. // If no limiter exists for the IP, one is created and tracked in the cache.
  97. func (l *IPRateLimiter) Allow(ip string) (allowed bool) {
  98. limiter, found := l.cache.Get(ip)
  99. if !found {
  100. limiter = rate.NewLimiter(l.rate, l.burst)
  101. l.cache.Set(ip, limiter, cache.DefaultExpiration)
  102. }
  103. return limiter.(*rate.Limiter).Allow()
  104. }
  105. // Server implements a TOC protocol server that multiplexes TOC/HTTP and
  106. // TOC/FLAP requests. It acts as a gateway, forwarding all TOC requests
  107. // to the OSCAR server for processing.
  108. type Server struct {
  109. BOSProxy OSCARProxy
  110. ListenAddr string
  111. Logger *slog.Logger
  112. LoginIPRateLimiter *IPRateLimiter
  113. }
  114. func (rt Server) Start(ctx context.Context) error {
  115. listener, err := net.Listen("tcp", rt.ListenAddr)
  116. if err != nil {
  117. return fmt.Errorf("unable to start TOC server: %w", err)
  118. }
  119. rt.Logger.InfoContext(ctx, "starting server", "listen_host", rt.ListenAddr)
  120. go func() {
  121. <-ctx.Done()
  122. _ = listener.Close()
  123. }()
  124. httpServer := &http.Server{
  125. Handler: rt.BOSProxy.NewServeMux(),
  126. BaseContext: func(net.Listener) context.Context {
  127. return ctx
  128. },
  129. }
  130. httpCh := make(chan net.Conn)
  131. defer close(httpCh)
  132. go func() {
  133. _ = httpServer.Serve(&channelListener{ch: httpCh})
  134. }()
  135. wg := sync.WaitGroup{}
  136. for {
  137. conn, err := listener.Accept()
  138. if err != nil {
  139. if errors.Is(err, net.ErrClosed) {
  140. break
  141. }
  142. rt.Logger.ErrorContext(ctx, "accept failed", "err", err.Error())
  143. continue
  144. }
  145. wg.Add(1)
  146. go func() {
  147. defer wg.Done()
  148. if err := rt.dispatchConn(conn, ctx, httpCh); err != nil {
  149. rt.Logger.ErrorContext(ctx, "client disconnected with error", "err", err.Error())
  150. }
  151. }()
  152. }
  153. if !waitForShutdown(&wg) {
  154. rt.Logger.ErrorContext(ctx, "shutdown complete, but connections didn't close cleanly")
  155. } else {
  156. rt.Logger.InfoContext(ctx, "shutdown complete")
  157. }
  158. return nil
  159. }
  160. // dispatchConn inspects and routes an incoming connection. If the connection
  161. // starts with "FLAP", handle as TOC/FLAP; otherwise, dispatch for HTTP
  162. // processing.
  163. func (rt Server) dispatchConn(conn net.Conn, ctx context.Context, httpCh chan net.Conn) error {
  164. bufCon := newBufferedConn(conn)
  165. doFlap := "FLAP"
  166. buf, err := bufCon.Peek(len(doFlap))
  167. if err != nil {
  168. return fmt.Errorf("bufCon.Peek: %w", err)
  169. }
  170. // handle TOC/FLAP
  171. if string(buf) == doFlap {
  172. if err = rt.dispatchFLAP(ctx, bufCon); err != nil {
  173. switch {
  174. case errors.Is(err, io.EOF):
  175. case errors.Is(err, net.ErrClosed):
  176. case errors.Is(err, syscall.ECONNRESET):
  177. return nil
  178. default:
  179. return fmt.Errorf("rt.dispatchFLAP: %w", err)
  180. }
  181. }
  182. return nil
  183. }
  184. // handle TOC/HTTP
  185. select {
  186. case httpCh <- bufCon:
  187. return nil
  188. case <-ctx.Done():
  189. return nil
  190. }
  191. }
  192. func (rt Server) dispatchFLAP(ctx context.Context, conn net.Conn) error {
  193. var once sync.Once
  194. closeConn := func() {
  195. once.Do(func() {
  196. _ = conn.Close()
  197. })
  198. }
  199. defer closeConn()
  200. ctx = context.WithValue(ctx, "ip", conn.RemoteAddr().String())
  201. clientFlap, err := rt.initFLAP(conn)
  202. if err != nil {
  203. return err
  204. }
  205. ip, _, err := net.SplitHostPort(conn.RemoteAddr().String())
  206. if err != nil {
  207. rt.Logger.Error("failed to parse remote address", "err", err.Error())
  208. return err
  209. }
  210. if ok := rt.LoginIPRateLimiter.Allow(ip); !ok {
  211. if err := clientFlap.SendDataFrame([]byte("ERROR:983")); err != nil {
  212. return fmt.Errorf("clientFlap.SendDataFrame: %w", err)
  213. }
  214. return nil
  215. }
  216. sessBOS, err := rt.login(ctx, clientFlap)
  217. if err != nil {
  218. return fmt.Errorf("rt.login: %w", err)
  219. }
  220. if sessBOS == nil {
  221. return nil // user not found
  222. }
  223. ctx = context.WithValue(ctx, "screenName", sessBOS.IdentScreenName())
  224. remoteAddr, ok := ctx.Value("ip").(string)
  225. if ok {
  226. ip, err := netip.ParseAddrPort(remoteAddr)
  227. if err != nil {
  228. return errors.New("unable to parse ip addr")
  229. }
  230. sessBOS.SetRemoteAddr(&ip)
  231. }
  232. chatRegistry := NewChatRegistry()
  233. defer rt.BOSProxy.Signout(ctx, sessBOS, chatRegistry)
  234. return rt.handleTOCRequest(ctx, closeConn, sessBOS, chatRegistry, clientFlap)
  235. }
  236. // handleTOCRequest processes incoming TOC requests and coordinates their handling.
  237. // It reads client requests, processes TOC commands, and sends responses back to the client.
  238. //
  239. // Returns:
  240. // - errClientReq if an error occurs while reading the TOC request. wraps
  241. // io.EOF if the client disconnected.
  242. // - errTOCProcessing if an error occurs while processing the TOC command.
  243. // - errServerWrite if an error occurs while sending the TOC response.
  244. func (rt Server) handleTOCRequest(
  245. ctx context.Context,
  246. closeConn func(),
  247. sessBOS *state.Session,
  248. chatRegistry *ChatRegistry,
  249. clientFlap *wire.FlapClient,
  250. ) error {
  251. // TOC response queue
  252. msgCh := make(chan []byte, 1)
  253. g, ctx := errgroup.WithContext(ctx)
  254. // process TOC client requests and enqueue TOC server responses
  255. g.Go(func() error {
  256. err := rt.runClientCommands(ctx, g.Go, sessBOS, chatRegistry, clientFlap, msgCh)
  257. return errors.Join(err, errClientReq)
  258. })
  259. // translate OSCAR server responses to TOC responses and enqueue them
  260. g.Go(func() error {
  261. err := rt.BOSProxy.RecvBOS(ctx, sessBOS, chatRegistry, msgCh)
  262. closeConn() // unblock runClientCommands
  263. return errors.Join(err, errTOCProcessing)
  264. })
  265. // send TOC server responses to the client
  266. g.Go(func() error {
  267. err := rt.sendToClient(ctx, msgCh, clientFlap)
  268. closeConn() // unblock runClientCommands
  269. return errors.Join(err, errServerWrite)
  270. })
  271. return g.Wait()
  272. }
  273. func (rt Server) runClientCommands(ctx context.Context, doAsync func(f func() error), sessBOS *state.Session, chatRegistry *ChatRegistry, clientFlap *wire.FlapClient, toCh chan<- []byte) error {
  274. for {
  275. clientFrame, err := clientFlap.ReceiveFLAP()
  276. if err != nil {
  277. return err
  278. }
  279. switch clientFrame.FrameType {
  280. case wire.FLAPFrameSignoff:
  281. return io.EOF // client disconnected
  282. case wire.FLAPFrameKeepAlive:
  283. // keep alive heartbeat, do nothing for now.
  284. // todo set connection deadline to future time
  285. case wire.FLAPFrameData:
  286. clientFrame.Payload = bytes.TrimRight(clientFrame.Payload, "\x00") // trim null terminator
  287. if len(clientFrame.Payload) == 0 {
  288. return errors.New("TOC command is empty")
  289. }
  290. if len(clientFrame.Payload) > 2048 {
  291. return errors.New("TOC command exceeds maximum length (2048)")
  292. }
  293. msg := rt.BOSProxy.RecvClientCmd(ctx, sessBOS, chatRegistry, clientFrame.Payload, toCh, doAsync)
  294. if len(msg) > 0 {
  295. select {
  296. case toCh <- []byte(msg):
  297. case <-ctx.Done():
  298. return nil
  299. }
  300. }
  301. default:
  302. return fmt.Errorf("unexpected clientFlap clientFrame type %d", clientFrame.FrameType)
  303. }
  304. }
  305. }
  306. func (rt Server) sendToClient(ctx context.Context, toClient <-chan []byte, clientFlap *wire.FlapClient) error {
  307. for {
  308. select {
  309. case <-ctx.Done():
  310. return nil
  311. case msg := <-toClient:
  312. if err := clientFlap.SendDataFrame(msg); err != nil {
  313. return fmt.Errorf("clientFlap.SendDataFrame: %w", err)
  314. }
  315. if rt.Logger.Enabled(ctx, slog.LevelDebug) {
  316. rt.Logger.DebugContext(ctx, "server response", "command", msg)
  317. } else {
  318. // just log the command, omit params
  319. idx := len(msg)
  320. if col := bytes.IndexByte(msg, ':'); col > -1 {
  321. idx = col
  322. }
  323. rt.Logger.InfoContext(ctx, "server response", "command", msg[0:idx])
  324. }
  325. }
  326. }
  327. }
  328. func (rt Server) login(ctx context.Context, clientFlap *wire.FlapClient) (*state.Session, error) {
  329. clientFrame, err := clientFlap.ReceiveFLAP()
  330. if err != nil {
  331. if errors.Is(err, io.EOF) {
  332. return nil, nil
  333. }
  334. return nil, fmt.Errorf("clientFlap.ReceiveFLAP: %w", err)
  335. }
  336. cmd := clientFrame.Payload
  337. var args []byte
  338. if idx := bytes.IndexByte(clientFrame.Payload, ' '); idx > -1 {
  339. cmd, args = clientFrame.Payload[:idx], clientFrame.Payload[idx:]
  340. }
  341. if string(cmd) != "toc_signon" {
  342. return nil, errors.New("expected toc_signon")
  343. }
  344. sessBOS, reply := rt.BOSProxy.Signon(ctx, args)
  345. for _, m := range reply {
  346. if err := clientFlap.SendDataFrame([]byte(m)); err != nil {
  347. return nil, fmt.Errorf("clientFlap.SendDataFrame: %w", err)
  348. }
  349. }
  350. return sessBOS, nil
  351. }
  352. // initFLAP sets up a new FLAP connection. It returns a flap client if the
  353. // connection successfully initialized.
  354. func (rt Server) initFLAP(rw io.ReadWriter) (*wire.FlapClient, error) {
  355. expected := "FLAPON\r\n\r\n"
  356. buf := make([]byte, len(expected))
  357. _, err := io.ReadFull(rw, buf)
  358. if err != nil {
  359. return nil, fmt.Errorf("io.ReadFull: %w", err)
  360. }
  361. if expected != string(buf) {
  362. return nil, fmt.Errorf("expected FLAPON, got %s", buf)
  363. }
  364. clientFlap := wire.NewFlapClient(0, rw, rw)
  365. if err := clientFlap.SendSignonFrame(nil); err != nil {
  366. return nil, fmt.Errorf("clientFlap.SendSignonFrame: %w", err)
  367. }
  368. if _, err := clientFlap.ReceiveSignonFrame(); err != nil {
  369. return nil, fmt.Errorf("clientFlap.ReceiveSignonFrame: %w", err)
  370. }
  371. return clientFlap, nil
  372. }
  373. // waitForShutdown returns when either the wg completes or 5 seconds has
  374. // passed. This is a temporary hack to ensure that the server shuts down even
  375. // if all the TCP connections do not drain. Return true if the shutdown is
  376. // clean.
  377. func waitForShutdown(wg *sync.WaitGroup) bool {
  378. ch := make(chan struct{})
  379. go func() {
  380. wg.Wait() // goroutine leak if wg never completes
  381. close(ch)
  382. }()
  383. select {
  384. case <-ch:
  385. return true
  386. case <-time.After(time.Second * 5):
  387. return false
  388. }
  389. }