server.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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. "strings"
  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. bufCon := newBufferedConn(conn)
  110. b, err := bufCon.Peek(6)
  111. if err != nil {
  112. rt.Logger.ErrorContext(ctx, "peek failed", "err", err.Error())
  113. return
  114. }
  115. switch {
  116. case string(b) == "FLAPON":
  117. ctx = context.WithValue(ctx, "ip", conn.RemoteAddr().String())
  118. if err := rt.handleTOCOverFLAP(ctx, bufCon); err != nil {
  119. rt.Logger.ErrorContext(ctx, "handleTOCOverFLAP failed", "err", err.Error())
  120. return
  121. }
  122. case strings.HasPrefix(string(b), "GET /"):
  123. select {
  124. case httpCh <- bufCon:
  125. case <-ctx.Done():
  126. return
  127. }
  128. }
  129. }()
  130. }
  131. if !waitForShutdown(&wg) {
  132. rt.Logger.ErrorContext(ctx, "shutdown complete, but connections didn't close cleanly")
  133. } else {
  134. rt.Logger.InfoContext(ctx, "shutdown complete")
  135. }
  136. return nil
  137. }
  138. func (rt Server) handleTOCOverFLAP(ctx context.Context, conn io.ReadWriteCloser) error {
  139. defer func() {
  140. conn.Close()
  141. }()
  142. if err := rt.handshake(conn); err != nil {
  143. return fmt.Errorf("handshake failed: %w", err)
  144. }
  145. clientFlap, err := rt.initFLAP(conn)
  146. if err != nil {
  147. return err
  148. }
  149. sessBOS, err := rt.login(ctx, clientFlap)
  150. if err != nil {
  151. return fmt.Errorf("rt.login: %w", err)
  152. }
  153. if sessBOS == nil {
  154. return nil // user not found
  155. }
  156. ctx = context.WithValue(ctx, "screenName", sessBOS.IdentScreenName())
  157. defer rt.BOSProxy.Signout(ctx, sessBOS)
  158. // messages from TOC client
  159. fromCh := make(chan wire.FLAPFrame, 1)
  160. // messages to TOC client
  161. toCh := make(chan []byte, 2)
  162. // read in messages from client. when client disconnects, it closes fromCh.
  163. go rt.readFromClient(ctx, fromCh, clientFlap)
  164. g, gCtx := errgroup.WithContext(ctx)
  165. chatRegistry := NewChatRegistry()
  166. g.Go(func() error {
  167. return rt.BOSProxy.RecvBOS(gCtx, sessBOS, chatRegistry, toCh)
  168. })
  169. g.Go(func() error {
  170. return rt.sendToClient(gCtx, toCh, clientFlap)
  171. })
  172. g.Go(func() error {
  173. return rt.processCommands(gCtx, g.Go, sessBOS, chatRegistry, fromCh, toCh)
  174. })
  175. err = g.Wait()
  176. if errors.Is(err, errDisconnect) {
  177. err = nil
  178. }
  179. return err
  180. }
  181. func (rt Server) processCommands(
  182. ctx context.Context,
  183. doAsync func(f func() error),
  184. sessBOS *state.Session,
  185. chatRegistry *ChatRegistry,
  186. fromCh <-chan wire.FLAPFrame,
  187. toCh chan<- []byte,
  188. ) error {
  189. for {
  190. select {
  191. case <-ctx.Done():
  192. return nil
  193. case clientFrame, ok := <-fromCh:
  194. if !ok {
  195. return errDisconnect
  196. }
  197. clientFrame.Payload = bytes.TrimRight(clientFrame.Payload, "\x00") // trim null terminator
  198. if len(clientFrame.Payload) == 0 {
  199. return errors.New("no givenPayload in flapon signal")
  200. }
  201. msg, ok := rt.BOSProxy.RecvClientCmd(ctx, sessBOS, chatRegistry, clientFrame.Payload, toCh, doAsync)
  202. if !ok {
  203. return nil
  204. }
  205. if len(msg) > 0 {
  206. select {
  207. case toCh <- []byte(msg):
  208. case <-ctx.Done():
  209. return nil
  210. }
  211. }
  212. }
  213. }
  214. return nil
  215. }
  216. func (rt Server) sendToClient(ctx context.Context, toClient <-chan []byte, clientFlap *wire.FlapClient) error {
  217. for {
  218. select {
  219. case <-ctx.Done():
  220. return nil
  221. case msg := <-toClient:
  222. if err := clientFlap.SendDataFrame(msg); err != nil {
  223. return fmt.Errorf("clientFlap.SendDataFrame: %w", err)
  224. }
  225. if rt.Logger.Enabled(ctx, slog.LevelDebug) {
  226. rt.Logger.DebugContext(ctx, "server response", "command", msg)
  227. } else {
  228. // just log the command, omit params
  229. idx := len(msg)
  230. if col := bytes.IndexByte(msg, ':'); col > -1 {
  231. idx = col
  232. }
  233. rt.Logger.InfoContext(ctx, "server response", "command", msg[0:idx])
  234. }
  235. }
  236. }
  237. }
  238. func (rt Server) login(ctx context.Context, clientFlap *wire.FlapClient) (*state.Session, error) {
  239. clientFrame, err := clientFlap.ReceiveFLAP()
  240. if err != nil {
  241. if errors.Is(err, io.EOF) {
  242. return nil, nil
  243. }
  244. return nil, fmt.Errorf("clientFlap.ReceiveFLAP: %w", err)
  245. }
  246. sessBOS, reply := rt.BOSProxy.Signon(ctx, clientFrame.Payload)
  247. for _, m := range reply {
  248. if err := clientFlap.SendDataFrame([]byte(m)); err != nil {
  249. return nil, fmt.Errorf("clientFlap.SendDataFrame: %w", err)
  250. }
  251. }
  252. return sessBOS, nil
  253. }
  254. func (rt Server) readFromClient(ctx context.Context, msgCh chan<- wire.FLAPFrame, clientFlap *wire.FlapClient) {
  255. defer close(msgCh)
  256. for {
  257. clientFrame, err := clientFlap.ReceiveFLAP()
  258. if err != nil {
  259. if !(errors.Is(err, io.EOF) || errors.Is(err, net.ErrClosed)) {
  260. rt.Logger.ErrorContext(ctx, "ReceiveFLAP error", "err", err.Error())
  261. }
  262. break
  263. }
  264. if clientFrame.FrameType == wire.FLAPFrameSignoff {
  265. break // client disconnected
  266. }
  267. if clientFrame.FrameType == wire.FLAPFrameKeepAlive {
  268. continue // keep alive heartbeat
  269. }
  270. if clientFrame.FrameType != wire.FLAPFrameData {
  271. rt.Logger.ErrorContext(ctx, "unexpected clientFlap clientFrame type", "type", clientFrame.FrameType)
  272. break
  273. }
  274. msgCh <- clientFrame
  275. }
  276. }
  277. func (rt Server) handshake(clientConn io.ReadWriter) error {
  278. reader := bufio.NewReader(clientConn)
  279. line, _, err := reader.ReadLine()
  280. if err != nil {
  281. return fmt.Errorf("read line failed: %w", err)
  282. }
  283. if string(line) != "FLAPON" {
  284. return fmt.Errorf("unexpected line: %s", string(line))
  285. }
  286. line, _, err = reader.ReadLine()
  287. if err != nil {
  288. return fmt.Errorf("read line failed: %w", err)
  289. }
  290. return nil
  291. }
  292. func (rt Server) initFLAP(clientConn io.ReadWriter) (*wire.FlapClient, error) {
  293. clientFlap := wire.NewFlapClient(0, clientConn, clientConn)
  294. if err := clientFlap.SendSignonFrame(nil); err != nil {
  295. return nil, fmt.Errorf("send flapon signal failed: %w", err)
  296. }
  297. _, err := clientFlap.ReceiveSignonFrame()
  298. if err != nil {
  299. return nil, fmt.Errorf("send flapon signal failed: %w", err)
  300. }
  301. return clientFlap, nil
  302. }
  303. // waitForShutdown returns when either the wg completes or 5 seconds has
  304. // passed. This is a temporary hack to ensure that the server shuts down even
  305. // if all the TCP connections do not drain. Return true if the shutdown is
  306. // clean.
  307. func waitForShutdown(wg *sync.WaitGroup) bool {
  308. ch := make(chan struct{})
  309. go func() {
  310. wg.Wait() // goroutine leak if wg never completes
  311. close(ch)
  312. }()
  313. select {
  314. case <-ch:
  315. return true
  316. case <-time.After(time.Second * 5):
  317. return false
  318. }
  319. }