control.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. // Copyright 2017 fatedier, fatedier@gmail.com
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package client
  15. import (
  16. "context"
  17. "net"
  18. "sync/atomic"
  19. "time"
  20. "github.com/samber/lo"
  21. "github.com/fatedier/frp/client/proxy"
  22. "github.com/fatedier/frp/client/visitor"
  23. "github.com/fatedier/frp/pkg/auth"
  24. v1 "github.com/fatedier/frp/pkg/config/v1"
  25. "github.com/fatedier/frp/pkg/msg"
  26. "github.com/fatedier/frp/pkg/transport"
  27. utilnet "github.com/fatedier/frp/pkg/util/net"
  28. "github.com/fatedier/frp/pkg/util/wait"
  29. "github.com/fatedier/frp/pkg/util/xlog"
  30. )
  31. type Control struct {
  32. // service context
  33. ctx context.Context
  34. xl *xlog.Logger
  35. // The client configuration
  36. clientCfg *v1.ClientCommonConfig
  37. // sets authentication based on selected method
  38. authSetter auth.Setter
  39. // Unique ID obtained from frps.
  40. // It should be attached to the login message when reconnecting.
  41. runID string
  42. // manage all proxies
  43. pxyCfgs []v1.ProxyConfigurer
  44. pm *proxy.Manager
  45. // manage all visitors
  46. vm *visitor.Manager
  47. // control connection. Once conn is closed, the msgDispatcher and the entire Control will exit.
  48. conn net.Conn
  49. // use cm to create new connections, which could be real TCP connections or virtual streams.
  50. cm *ConnectionManager
  51. doneCh chan struct{}
  52. // of time.Time, last time got the Pong message
  53. lastPong atomic.Value
  54. // The role of msgTransporter is similar to HTTP2.
  55. // It allows multiple messages to be sent simultaneously on the same control connection.
  56. // The server's response messages will be dispatched to the corresponding waiting goroutines based on the laneKey and message type.
  57. msgTransporter transport.MessageTransporter
  58. // msgDispatcher is a wrapper for control connection.
  59. // It provides a channel for sending messages, and you can register handlers to process messages based on their respective types.
  60. msgDispatcher *msg.Dispatcher
  61. }
  62. func NewControl(
  63. ctx context.Context, runID string, conn net.Conn, cm *ConnectionManager,
  64. clientCfg *v1.ClientCommonConfig,
  65. pxyCfgs []v1.ProxyConfigurer,
  66. visitorCfgs []v1.VisitorConfigurer,
  67. authSetter auth.Setter,
  68. ) (*Control, error) {
  69. // new xlog instance
  70. ctl := &Control{
  71. ctx: ctx,
  72. xl: xlog.FromContextSafe(ctx),
  73. clientCfg: clientCfg,
  74. authSetter: authSetter,
  75. runID: runID,
  76. pxyCfgs: pxyCfgs,
  77. conn: conn,
  78. cm: cm,
  79. doneCh: make(chan struct{}),
  80. }
  81. ctl.lastPong.Store(time.Now())
  82. cryptoRW, err := utilnet.NewCryptoReadWriter(conn, []byte(clientCfg.Auth.Token))
  83. if err != nil {
  84. return nil, err
  85. }
  86. ctl.msgDispatcher = msg.NewDispatcher(cryptoRW)
  87. ctl.registerMsgHandlers()
  88. ctl.msgTransporter = transport.NewMessageTransporter(ctl.msgDispatcher.SendChannel())
  89. ctl.pm = proxy.NewManager(ctl.ctx, clientCfg, ctl.msgTransporter)
  90. ctl.vm = visitor.NewManager(ctl.ctx, ctl.runID, ctl.clientCfg, ctl.connectServer, ctl.msgTransporter)
  91. ctl.vm.Reload(visitorCfgs)
  92. return ctl, nil
  93. }
  94. func (ctl *Control) Run() {
  95. go ctl.worker()
  96. // start all proxies
  97. ctl.pm.Reload(ctl.pxyCfgs)
  98. // start all visitors
  99. go ctl.vm.Run()
  100. }
  101. func (ctl *Control) handleReqWorkConn(_ msg.Message) {
  102. xl := ctl.xl
  103. workConn, err := ctl.connectServer()
  104. if err != nil {
  105. xl.Warn("start new connection to server error: %v", err)
  106. return
  107. }
  108. m := &msg.NewWorkConn{
  109. RunID: ctl.runID,
  110. }
  111. if err = ctl.authSetter.SetNewWorkConn(m); err != nil {
  112. xl.Warn("error during NewWorkConn authentication: %v", err)
  113. return
  114. }
  115. if err = msg.WriteMsg(workConn, m); err != nil {
  116. xl.Warn("work connection write to server error: %v", err)
  117. workConn.Close()
  118. return
  119. }
  120. var startMsg msg.StartWorkConn
  121. if err = msg.ReadMsgInto(workConn, &startMsg); err != nil {
  122. xl.Trace("work connection closed before response StartWorkConn message: %v", err)
  123. workConn.Close()
  124. return
  125. }
  126. if startMsg.Error != "" {
  127. xl.Error("StartWorkConn contains error: %s", startMsg.Error)
  128. workConn.Close()
  129. return
  130. }
  131. // dispatch this work connection to related proxy
  132. ctl.pm.HandleWorkConn(startMsg.ProxyName, workConn, &startMsg)
  133. }
  134. func (ctl *Control) handleNewProxyResp(m msg.Message) {
  135. xl := ctl.xl
  136. inMsg := m.(*msg.NewProxyResp)
  137. // Server will return NewProxyResp message to each NewProxy message.
  138. // Start a new proxy handler if no error got
  139. err := ctl.pm.StartProxy(inMsg.ProxyName, inMsg.RemoteAddr, inMsg.Error)
  140. if err != nil {
  141. xl.Warn("[%s] start error: %v", inMsg.ProxyName, err)
  142. } else {
  143. xl.Info("[%s] start proxy success", inMsg.ProxyName)
  144. }
  145. }
  146. func (ctl *Control) handleNatHoleResp(m msg.Message) {
  147. xl := ctl.xl
  148. inMsg := m.(*msg.NatHoleResp)
  149. // Dispatch the NatHoleResp message to the related proxy.
  150. ok := ctl.msgTransporter.DispatchWithType(inMsg, msg.TypeNameNatHoleResp, inMsg.TransactionID)
  151. if !ok {
  152. xl.Trace("dispatch NatHoleResp message to related proxy error")
  153. }
  154. }
  155. func (ctl *Control) handlePong(m msg.Message) {
  156. xl := ctl.xl
  157. inMsg := m.(*msg.Pong)
  158. if inMsg.Error != "" {
  159. xl.Error("Pong message contains error: %s", inMsg.Error)
  160. ctl.conn.Close()
  161. return
  162. }
  163. ctl.lastPong.Store(time.Now())
  164. xl.Debug("receive heartbeat from server")
  165. }
  166. func (ctl *Control) Close() error {
  167. return ctl.GracefulClose(0)
  168. }
  169. func (ctl *Control) GracefulClose(d time.Duration) error {
  170. ctl.pm.Close()
  171. ctl.vm.Close()
  172. time.Sleep(d)
  173. ctl.conn.Close()
  174. ctl.cm.Close()
  175. return nil
  176. }
  177. // Done returns a channel that will be closed after all resources are released
  178. func (ctl *Control) Done() <-chan struct{} {
  179. return ctl.doneCh
  180. }
  181. // connectServer return a new connection to frps
  182. func (ctl *Control) connectServer() (conn net.Conn, err error) {
  183. return ctl.cm.Connect()
  184. }
  185. func (ctl *Control) registerMsgHandlers() {
  186. ctl.msgDispatcher.RegisterHandler(&msg.ReqWorkConn{}, msg.AsyncHandler(ctl.handleReqWorkConn))
  187. ctl.msgDispatcher.RegisterHandler(&msg.NewProxyResp{}, ctl.handleNewProxyResp)
  188. ctl.msgDispatcher.RegisterHandler(&msg.NatHoleResp{}, ctl.handleNatHoleResp)
  189. ctl.msgDispatcher.RegisterHandler(&msg.Pong{}, ctl.handlePong)
  190. }
  191. // headerWorker sends heartbeat to server and check heartbeat timeout.
  192. func (ctl *Control) heartbeatWorker() {
  193. xl := ctl.xl
  194. // TODO(fatedier): Change default value of HeartbeatInterval to -1 if tcpmux is enabled.
  195. // Users can still enable heartbeat feature by setting HeartbeatInterval to a positive value.
  196. if ctl.clientCfg.Transport.HeartbeatInterval > 0 {
  197. // send heartbeat to server
  198. sendHeartBeat := func() error {
  199. xl.Debug("send heartbeat to server")
  200. pingMsg := &msg.Ping{}
  201. if err := ctl.authSetter.SetPing(pingMsg); err != nil {
  202. xl.Warn("error during ping authentication: %v, skip sending ping message", err)
  203. return err
  204. }
  205. _ = ctl.msgDispatcher.Send(pingMsg)
  206. return nil
  207. }
  208. go wait.BackoffUntil(sendHeartBeat,
  209. wait.NewFastBackoffManager(wait.FastBackoffOptions{
  210. Duration: time.Duration(ctl.clientCfg.Transport.HeartbeatInterval) * time.Second,
  211. InitDurationIfFail: time.Second,
  212. Factor: 2.0,
  213. Jitter: 0.1,
  214. MaxDuration: time.Duration(ctl.clientCfg.Transport.HeartbeatInterval) * time.Second,
  215. }),
  216. true, ctl.doneCh,
  217. )
  218. }
  219. // Check heartbeat timeout only if TCPMux is not enabled and users don't disable heartbeat feature.
  220. if ctl.clientCfg.Transport.HeartbeatInterval > 0 && ctl.clientCfg.Transport.HeartbeatTimeout > 0 &&
  221. !lo.FromPtr(ctl.clientCfg.Transport.TCPMux) {
  222. go wait.Until(func() {
  223. if time.Since(ctl.lastPong.Load().(time.Time)) > time.Duration(ctl.clientCfg.Transport.HeartbeatTimeout)*time.Second {
  224. xl.Warn("heartbeat timeout")
  225. ctl.conn.Close()
  226. return
  227. }
  228. }, time.Second, ctl.doneCh)
  229. }
  230. }
  231. func (ctl *Control) worker() {
  232. go ctl.heartbeatWorker()
  233. go ctl.msgDispatcher.Run()
  234. <-ctl.msgDispatcher.Done()
  235. ctl.conn.Close()
  236. ctl.pm.Close()
  237. ctl.vm.Close()
  238. ctl.cm.Close()
  239. close(ctl.doneCh)
  240. }
  241. func (ctl *Control) ReloadConf(pxyCfgs []v1.ProxyConfigurer, visitorCfgs []v1.VisitorConfigurer) error {
  242. ctl.vm.Reload(visitorCfgs)
  243. ctl.pm.Reload(pxyCfgs)
  244. return nil
  245. }