server.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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/open-oscar-server/state"
  20. "github.com/mk6i/open-oscar-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, nil
  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, instance *state.SessionInstance) error,
  113. lowerWarnLevel func(ctx context.Context, instance *state.SessionInstance),
  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, instance *state.SessionInstance) error
  146. lowerWarnLevel func(ctx context.Context, instance *state.SessionInstance)
  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(ctx, 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. s.logger.InfoContext(ctx, "user rate limited at login, dropping connection")
  299. if err := clientFlap.SendDataFrame([]byte("ERROR:983")); err != nil {
  300. return fmt.Errorf("clientFlap.SendDataFrame: %w", err)
  301. }
  302. return nil
  303. }
  304. chatRegistry := NewChatRegistry()
  305. sessBOS, err := s.login(ctx, clientFlap, chatRegistry)
  306. if err != nil {
  307. return fmt.Errorf("s.login: %w", err)
  308. }
  309. if sessBOS == nil {
  310. return nil // user not found
  311. }
  312. ctx = context.WithValue(ctx, "screenName", sessBOS.IdentScreenName())
  313. remoteAddr, ok := ctx.Value("ip").(string)
  314. if ok {
  315. ip, err := netip.ParseAddrPort(remoteAddr)
  316. if err != nil {
  317. return errors.New("unable to parse ip addr")
  318. }
  319. sessBOS.SetRemoteAddr(&ip)
  320. }
  321. return s.handleTOCRequest(ctx, closeConn, sessBOS, chatRegistry, clientFlap)
  322. }
  323. // handleTOCRequest processes incoming TOC requests and coordinates their handling.
  324. // It reads client requests, processes TOC commands, and sends responses back to the client.
  325. //
  326. // Returns:
  327. // - errClientReq if an error occurs while reading the TOC request. wraps
  328. // io.EOF if the client disconnected.
  329. // - errTOCProcessing if an error occurs while processing the TOC command.
  330. // - errServerWrite if an error occurs while sending the TOC response.
  331. func (s *Server) handleTOCRequest(
  332. ctx context.Context,
  333. closeConn func(),
  334. sessBOS *state.SessionInstance,
  335. chatRegistry *ChatRegistry,
  336. clientFlap *wire.FlapClient,
  337. ) error {
  338. // TOC response queue
  339. msgCh := make(chan []string, 1)
  340. g, ctx := errgroup.WithContext(ctx)
  341. // process TOC client requests and enqueue TOC server responses
  342. g.Go(func() error {
  343. err := s.runClientCommands(ctx, g.Go, sessBOS, chatRegistry, clientFlap, msgCh)
  344. return errors.Join(err, errClientReq)
  345. })
  346. // translate OSCAR server responses to TOC responses and enqueue them
  347. g.Go(func() error {
  348. err := s.bosProxy.RecvBOS(ctx, sessBOS, chatRegistry, msgCh)
  349. closeConn() // unblock runClientCommands
  350. return errors.Join(err, errTOCProcessing)
  351. })
  352. // send TOC server responses to the client
  353. g.Go(func() error {
  354. err := s.sendToClient(ctx, msgCh, clientFlap)
  355. closeConn() // unblock runClientCommands
  356. return errors.Join(err, errServerWrite)
  357. })
  358. return g.Wait()
  359. }
  360. func (s *Server) runClientCommands(ctx context.Context, doAsync func(f func() error), sessBOS *state.SessionInstance, chatRegistry *ChatRegistry, clientFlap *wire.FlapClient, toCh chan<- []string) error {
  361. for {
  362. clientFrame, err := clientFlap.ReceiveFLAP()
  363. if err != nil {
  364. return err
  365. }
  366. switch clientFrame.FrameType {
  367. case wire.FLAPFrameSignoff:
  368. return io.EOF // client disconnected
  369. case wire.FLAPFrameKeepAlive:
  370. // keep alive heartbeat, do nothing for now.
  371. // todo set connection deadline to future time
  372. case wire.FLAPFrameData:
  373. clientFrame.Payload = bytes.TrimRight(clientFrame.Payload, "\x00") // trim null terminator
  374. if len(clientFrame.Payload) == 0 {
  375. return errors.New("TOC command is empty")
  376. }
  377. if len(clientFrame.Payload) > 2048 {
  378. return errors.New("TOC command exceeds maximum length (2048)")
  379. }
  380. msg := s.bosProxy.RecvClientCmd(ctx, sessBOS, chatRegistry, clientFrame.Payload, toCh, doAsync)
  381. if len(msg) > 0 {
  382. select {
  383. case toCh <- msg:
  384. case <-ctx.Done():
  385. return nil
  386. }
  387. }
  388. default:
  389. return fmt.Errorf("unexpected clientFlap clientFrame type %d", clientFrame.FrameType)
  390. }
  391. }
  392. }
  393. func (s *Server) sendToClient(ctx context.Context, toClient <-chan []string, clientFlap *wire.FlapClient) error {
  394. for {
  395. select {
  396. case <-ctx.Done():
  397. return nil
  398. case msgs := <-toClient:
  399. for _, m := range msgs {
  400. if err := clientFlap.SendDataFrame([]byte(m)); err != nil {
  401. return fmt.Errorf("clientFlap.SendDataFrame: %w", err)
  402. }
  403. if s.logger.Enabled(ctx, slog.LevelDebug) {
  404. s.logger.DebugContext(ctx, "server response", "command", m)
  405. } else {
  406. // just log the command, omit params
  407. idx := len(m)
  408. if col := bytes.IndexByte([]byte(m), ':'); col > -1 {
  409. idx = col
  410. }
  411. s.logger.InfoContext(ctx, "server response", "command", m[0:idx])
  412. }
  413. }
  414. }
  415. }
  416. }
  417. func (s *Server) login(ctx context.Context, clientFlap *wire.FlapClient, chatRegistry *ChatRegistry) (*state.SessionInstance, 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. sessBOS, reply := s.bosProxy.Signon(ctx, clientFrame.Payload, s.recalcWarning, s.lowerWarnLevel, chatRegistry)
  426. for _, m := range reply {
  427. if err := clientFlap.SendDataFrame([]byte(m)); err != nil {
  428. return nil, fmt.Errorf("clientFlap.SendDataFrame: %w", err)
  429. }
  430. }
  431. return sessBOS, nil
  432. }
  433. // initFLAP sets up a new FLAP connection. It returns a flap client if the
  434. // connection successfully initialized. It accepts either "FLAPON\n\n" or
  435. // "FLAPON\r\n\r\n".
  436. func (s *Server) initFLAP(ctx context.Context, rw io.ReadWriter) (*wire.FlapClient, error) {
  437. buf := make([]byte, 8)
  438. _, err := io.ReadFull(rw, buf)
  439. if err != nil {
  440. return nil, fmt.Errorf("io.ReadFull: %w", err)
  441. }
  442. if string(buf[:6]) != "FLAPON" {
  443. return nil, fmt.Errorf("expected FLAPON, got %s", buf)
  444. }
  445. if buf[6] == '\r' && buf[7] == '\n' {
  446. crlf := make([]byte, 2)
  447. _, err := io.ReadFull(rw, crlf)
  448. if err != nil {
  449. return nil, fmt.Errorf("io.ReadFull: %w", err)
  450. }
  451. if crlf[0] != '\r' || crlf[1] != '\n' {
  452. return nil, fmt.Errorf("expected \\r\\n after FLAPON\\r\\n, got %s", crlf)
  453. }
  454. } else if buf[6] != '\n' || buf[7] != '\n' {
  455. return nil, fmt.Errorf("expected FLAPON then \\n\\n or \\r\\n\\r\\n, got %s", buf)
  456. }
  457. clientFlap := wire.NewFlapClient(0, rw, rw)
  458. if err := clientFlap.SendSignonFrame(nil); err != nil {
  459. return nil, fmt.Errorf("clientFlap.SendSignonFrame: %w", err)
  460. }
  461. frame, err := clientFlap.ReceiveSignonFrame()
  462. if err != nil {
  463. return nil, fmt.Errorf("clientFlap.ReceiveSignonFrame: %w", err)
  464. }
  465. if sn, hasSn := frame.String(0x01); hasSn {
  466. s.logger.DebugContext(ctx, "new connection", "screen_name", sn)
  467. } else {
  468. s.logger.DebugContext(ctx, "new connection from unknown screen name")
  469. }
  470. return clientFlap, nil
  471. }