server.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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. "time"
  15. "golang.org/x/sync/errgroup"
  16. "github.com/mk6i/retro-aim-server/state"
  17. "github.com/mk6i/retro-aim-server/wire"
  18. )
  19. var (
  20. // errClientReq indicates that an error occurred while reading a client request
  21. errClientReq = errors.New("failed to read client request")
  22. // errServerWrite indicates that an error occurred while writing a server response
  23. errServerWrite = errors.New("failed to send server response")
  24. // errTOCProcessing indicates that an error occurred in the TOC handler
  25. errTOCProcessing = errors.New("failed to process TOC request")
  26. )
  27. // bufferedConn is a wrapper around net.Conn that allows peeking into the
  28. // incoming connection without consuming data. It is useful for multiplexing
  29. // TOC/HTTP and TOC/FLAP connections.
  30. //
  31. // It embeds net.Conn, so all standard connection methods remain available.
  32. type bufferedConn struct {
  33. r *bufio.Reader
  34. net.Conn
  35. }
  36. // newBufferedConn wraps a net.Conn with buffered reading capabilities.
  37. func newBufferedConn(c net.Conn) bufferedConn {
  38. return bufferedConn{bufio.NewReader(c), c}
  39. }
  40. // Peek returns the next n bytes from the buffer without advancing the reader.
  41. // If fewer than n bytes are available, it returns an error.
  42. func (b bufferedConn) Peek(n int) ([]byte, error) {
  43. return b.r.Peek(n)
  44. }
  45. // Read reads data into p from the buffered connection.
  46. // It prioritizes buffered data before reading from the underlying connection.
  47. func (b bufferedConn) Read(p []byte) (int, error) {
  48. return b.r.Read(p)
  49. }
  50. // channelListener is an implementation of net.Listener that accepts connections
  51. // from a channel instead of a network socket. It is useful for attaching an
  52. // HTTP service to a connection on the fly.
  53. type channelListener struct {
  54. ch chan net.Conn // Channel used to receive connections.
  55. }
  56. // Accept waits for and returns the next connection from the channel.
  57. // If the channel is closed, it returns io.EOF to indicate no more connections.
  58. func (l *channelListener) Accept() (net.Conn, error) {
  59. ch, ok := <-l.ch
  60. if !ok {
  61. return nil, io.EOF
  62. }
  63. return ch, nil
  64. }
  65. // Close closes the listener. Since channelListener does not manage an actual
  66. // network connection, this is a no-op and always returns nil.
  67. func (l *channelListener) Close() error {
  68. return nil
  69. }
  70. // Addr returns the network address of the listener.
  71. // Since channelListener is not bound to a real network address, it returns nil.
  72. func (l *channelListener) Addr() net.Addr {
  73. return nil
  74. }
  75. // Server implements a TOC protocol server that multiplexes TOC/HTTP and
  76. // TOC/FLAP requests. It acts as a gateway, forwarding all TOC requests
  77. // to the OSCAR server for processing.
  78. type Server struct {
  79. BOSProxy OSCARProxy
  80. ListenAddr string
  81. Logger *slog.Logger
  82. }
  83. func (rt Server) Start(ctx context.Context) error {
  84. listener, err := net.Listen("tcp", rt.ListenAddr)
  85. if err != nil {
  86. return fmt.Errorf("unable to start TOC server: %w", err)
  87. }
  88. rt.Logger.InfoContext(ctx, "starting server", "listen_host", rt.ListenAddr)
  89. go func() {
  90. <-ctx.Done()
  91. _ = listener.Close()
  92. }()
  93. httpServer := &http.Server{
  94. Handler: rt.BOSProxy.NewServeMux(),
  95. BaseContext: func(net.Listener) context.Context {
  96. return ctx
  97. },
  98. }
  99. httpCh := make(chan net.Conn)
  100. defer close(httpCh)
  101. go func() {
  102. _ = httpServer.Serve(&channelListener{ch: httpCh})
  103. }()
  104. wg := sync.WaitGroup{}
  105. for {
  106. conn, err := listener.Accept()
  107. if err != nil {
  108. if errors.Is(err, net.ErrClosed) {
  109. break
  110. }
  111. rt.Logger.ErrorContext(ctx, "accept failed", "err", err.Error())
  112. continue
  113. }
  114. wg.Add(1)
  115. go func() {
  116. defer wg.Done()
  117. rt.dispatchConn(conn, ctx, httpCh)
  118. }()
  119. }
  120. if !waitForShutdown(&wg) {
  121. rt.Logger.ErrorContext(ctx, "shutdown complete, but connections didn't close cleanly")
  122. } else {
  123. rt.Logger.InfoContext(ctx, "shutdown complete")
  124. }
  125. return nil
  126. }
  127. // dispatchConn inspects and routes an incoming connection. If the connection
  128. // starts with "FLAP", handle as TOC/FLAP; otherwise, dispatch for HTTP
  129. // processing.
  130. func (rt Server) dispatchConn(conn net.Conn, ctx context.Context, httpCh chan net.Conn) error {
  131. bufCon := newBufferedConn(conn)
  132. doFlap := "FLAP"
  133. buf, err := bufCon.Peek(len(doFlap))
  134. if err != nil {
  135. return fmt.Errorf("bufCon.Peek: %w", err)
  136. }
  137. if string(buf) == doFlap {
  138. if err = rt.dispatchFLAP(ctx, bufCon); err != nil {
  139. if !(errors.Is(err, io.EOF) || errors.Is(err, net.ErrClosed)) {
  140. return fmt.Errorf("rt.dispatchFLAP: %w", err)
  141. }
  142. }
  143. return nil
  144. }
  145. select {
  146. case httpCh <- bufCon:
  147. return nil
  148. case <-ctx.Done():
  149. return nil
  150. }
  151. }
  152. func (rt Server) dispatchFLAP(ctx context.Context, conn net.Conn) error {
  153. var once sync.Once
  154. closeConn := func() {
  155. once.Do(func() {
  156. _ = conn.Close()
  157. })
  158. }
  159. defer closeConn()
  160. ctx = context.WithValue(ctx, "ip", conn.RemoteAddr().String())
  161. clientFlap, err := rt.initFLAP(conn)
  162. if err != nil {
  163. return err
  164. }
  165. sessBOS, err := rt.login(ctx, clientFlap)
  166. if err != nil {
  167. return fmt.Errorf("rt.login: %w", err)
  168. }
  169. if sessBOS == nil {
  170. return nil // user not found
  171. }
  172. ctx = context.WithValue(ctx, "screenName", sessBOS.IdentScreenName())
  173. remoteAddr, ok := ctx.Value("ip").(string)
  174. if ok {
  175. ip, err := netip.ParseAddrPort(remoteAddr)
  176. if err != nil {
  177. return errors.New("unable to parse ip addr")
  178. }
  179. sessBOS.SetRemoteAddr(&ip)
  180. }
  181. chatRegistry := NewChatRegistry()
  182. defer rt.BOSProxy.Signout(ctx, sessBOS, chatRegistry)
  183. return rt.handleTOCRequest(ctx, closeConn, sessBOS, chatRegistry, clientFlap)
  184. }
  185. // handleTOCRequest processes incoming TOC requests and coordinates their handling.
  186. // It reads client requests, processes TOC commands, and sends responses back to the client.
  187. //
  188. // Returns:
  189. // - errClientReq if an error occurs while reading the TOC request. wraps
  190. // io.EOF if the client disconnected.
  191. // - errTOCProcessing if an error occurs while processing the TOC command.
  192. // - errServerWrite if an error occurs while sending the TOC response.
  193. func (rt Server) handleTOCRequest(
  194. ctx context.Context,
  195. closeConn func(),
  196. sessBOS *state.Session,
  197. chatRegistry *ChatRegistry,
  198. clientFlap *wire.FlapClient,
  199. ) error {
  200. // TOC response queue
  201. msgCh := make(chan []byte, 1)
  202. g, ctx := errgroup.WithContext(ctx)
  203. // process TOC client requests and enqueue TOC server responses
  204. g.Go(func() error {
  205. err := rt.runClientCommands(ctx, g.Go, sessBOS, chatRegistry, clientFlap, msgCh)
  206. return errors.Join(err, errClientReq)
  207. })
  208. // translate OSCAR server responses to TOC responses and enqueue them
  209. g.Go(func() error {
  210. err := rt.BOSProxy.RecvBOS(ctx, sessBOS, chatRegistry, msgCh)
  211. closeConn() // unblock runClientCommands
  212. return errors.Join(err, errTOCProcessing)
  213. })
  214. // send TOC server responses to the client
  215. g.Go(func() error {
  216. err := rt.sendToClient(ctx, msgCh, clientFlap)
  217. closeConn() // unblock runClientCommands
  218. return errors.Join(err, errServerWrite)
  219. })
  220. return g.Wait()
  221. }
  222. func (rt Server) runClientCommands(ctx context.Context, doAsync func(f func() error), sessBOS *state.Session, chatRegistry *ChatRegistry, clientFlap *wire.FlapClient, toCh chan<- []byte) error {
  223. for {
  224. clientFrame, err := clientFlap.ReceiveFLAP()
  225. if err != nil {
  226. return err
  227. }
  228. switch clientFrame.FrameType {
  229. case wire.FLAPFrameSignoff:
  230. return io.EOF // client disconnected
  231. case wire.FLAPFrameKeepAlive:
  232. // keep alive heartbeat, do nothing for now.
  233. // todo set connection deadline to future time
  234. case wire.FLAPFrameData:
  235. clientFrame.Payload = bytes.TrimRight(clientFrame.Payload, "\x00") // trim null terminator
  236. if len(clientFrame.Payload) == 0 {
  237. return errors.New("TOC command is empty")
  238. }
  239. if len(clientFrame.Payload) > 2048 {
  240. return errors.New("TOC command exceeds maximum length (2048)")
  241. }
  242. msg, ok := rt.BOSProxy.RecvClientCmd(ctx, sessBOS, chatRegistry, clientFrame.Payload, toCh, doAsync)
  243. if !ok {
  244. return io.EOF
  245. }
  246. if len(msg) > 0 {
  247. select {
  248. case toCh <- []byte(msg):
  249. case <-ctx.Done():
  250. return nil
  251. }
  252. }
  253. default:
  254. return fmt.Errorf("unexpected clientFlap clientFrame type %d", clientFrame.FrameType)
  255. }
  256. }
  257. }
  258. func (rt Server) sendToClient(ctx context.Context, toClient <-chan []byte, clientFlap *wire.FlapClient) error {
  259. for {
  260. select {
  261. case <-ctx.Done():
  262. return nil
  263. case msg := <-toClient:
  264. if err := clientFlap.SendDataFrame(msg); err != nil {
  265. return fmt.Errorf("clientFlap.SendDataFrame: %w", err)
  266. }
  267. if rt.Logger.Enabled(ctx, slog.LevelDebug) {
  268. rt.Logger.DebugContext(ctx, "server response", "command", msg)
  269. } else {
  270. // just log the command, omit params
  271. idx := len(msg)
  272. if col := bytes.IndexByte(msg, ':'); col > -1 {
  273. idx = col
  274. }
  275. rt.Logger.InfoContext(ctx, "server response", "command", msg[0:idx])
  276. }
  277. }
  278. }
  279. }
  280. func (rt Server) login(ctx context.Context, clientFlap *wire.FlapClient) (*state.Session, error) {
  281. clientFrame, err := clientFlap.ReceiveFLAP()
  282. if err != nil {
  283. if errors.Is(err, io.EOF) {
  284. return nil, nil
  285. }
  286. return nil, fmt.Errorf("clientFlap.ReceiveFLAP: %w", err)
  287. }
  288. sessBOS, reply := rt.BOSProxy.Signon(ctx, clientFrame.Payload)
  289. for _, m := range reply {
  290. if err := clientFlap.SendDataFrame([]byte(m)); err != nil {
  291. return nil, fmt.Errorf("clientFlap.SendDataFrame: %w", err)
  292. }
  293. }
  294. return sessBOS, nil
  295. }
  296. // initFLAP sets up a new FLAP connection. It returns a flap client if the
  297. // connection successfully initialized.
  298. func (rt Server) initFLAP(rw io.ReadWriter) (*wire.FlapClient, error) {
  299. expected := "FLAPON\r\n\r\n"
  300. buf := make([]byte, len(expected))
  301. _, err := io.ReadFull(rw, buf)
  302. if err != nil {
  303. return nil, fmt.Errorf("io.ReadFull: %w", err)
  304. }
  305. if expected != string(buf) {
  306. return nil, fmt.Errorf("expected FLAPON, got %s", buf)
  307. }
  308. clientFlap := wire.NewFlapClient(0, rw, rw)
  309. if err := clientFlap.SendSignonFrame(nil); err != nil {
  310. return nil, fmt.Errorf("clientFlap.SendSignonFrame: %w", err)
  311. }
  312. if _, err := clientFlap.ReceiveSignonFrame(); err != nil {
  313. return nil, fmt.Errorf("clientFlap.ReceiveSignonFrame: %w", err)
  314. }
  315. return clientFlap, nil
  316. }
  317. // waitForShutdown returns when either the wg completes or 5 seconds has
  318. // passed. This is a temporary hack to ensure that the server shuts down even
  319. // if all the TCP connections do not drain. Return true if the shutdown is
  320. // clean.
  321. func waitForShutdown(wg *sync.WaitGroup) bool {
  322. ch := make(chan struct{})
  323. go func() {
  324. wg.Wait() // goroutine leak if wg never completes
  325. close(ch)
  326. }()
  327. select {
  328. case <-ch:
  329. return true
  330. case <-time.After(time.Second * 5):
  331. return false
  332. }
  333. }