server.go 15 KB

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