4
0

server.go 13 KB

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