server.go 9.2 KB

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