server.go 9.4 KB

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