server.go 11 KB

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