control.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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 connector to create new connections, which could be real TCP connections or virtual streams.
  50. connector Connector
  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, connector Connector,
  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. connector: connector,
  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) SetInWorkConnCallback(cb func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) bool) {
  102. ctl.pm.SetInWorkConnCallback(cb)
  103. }
  104. func (ctl *Control) handleReqWorkConn(_ msg.Message) {
  105. xl := ctl.xl
  106. workConn, err := ctl.connectServer()
  107. if err != nil {
  108. xl.Warn("start new connection to server error: %v", err)
  109. return
  110. }
  111. m := &msg.NewWorkConn{
  112. RunID: ctl.runID,
  113. }
  114. if err = ctl.authSetter.SetNewWorkConn(m); err != nil {
  115. xl.Warn("error during NewWorkConn authentication: %v", err)
  116. return
  117. }
  118. if err = msg.WriteMsg(workConn, m); err != nil {
  119. xl.Warn("work connection write to server error: %v", err)
  120. workConn.Close()
  121. return
  122. }
  123. var startMsg msg.StartWorkConn
  124. if err = msg.ReadMsgInto(workConn, &startMsg); err != nil {
  125. xl.Trace("work connection closed before response StartWorkConn message: %v", err)
  126. workConn.Close()
  127. return
  128. }
  129. if startMsg.Error != "" {
  130. xl.Error("StartWorkConn contains error: %s", startMsg.Error)
  131. workConn.Close()
  132. return
  133. }
  134. // dispatch this work connection to related proxy
  135. ctl.pm.HandleWorkConn(startMsg.ProxyName, workConn, &startMsg)
  136. }
  137. func (ctl *Control) handleNewProxyResp(m msg.Message) {
  138. xl := ctl.xl
  139. inMsg := m.(*msg.NewProxyResp)
  140. // Server will return NewProxyResp message to each NewProxy message.
  141. // Start a new proxy handler if no error got
  142. err := ctl.pm.StartProxy(inMsg.ProxyName, inMsg.RemoteAddr, inMsg.Error)
  143. if err != nil {
  144. xl.Warn("[%s] start error: %v", inMsg.ProxyName, err)
  145. } else {
  146. xl.Info("[%s] start proxy success", inMsg.ProxyName)
  147. }
  148. }
  149. func (ctl *Control) handleNatHoleResp(m msg.Message) {
  150. xl := ctl.xl
  151. inMsg := m.(*msg.NatHoleResp)
  152. // Dispatch the NatHoleResp message to the related proxy.
  153. ok := ctl.msgTransporter.DispatchWithType(inMsg, msg.TypeNameNatHoleResp, inMsg.TransactionID)
  154. if !ok {
  155. xl.Trace("dispatch NatHoleResp message to related proxy error")
  156. }
  157. }
  158. func (ctl *Control) handlePong(m msg.Message) {
  159. xl := ctl.xl
  160. inMsg := m.(*msg.Pong)
  161. if inMsg.Error != "" {
  162. xl.Error("Pong message contains error: %s", inMsg.Error)
  163. ctl.conn.Close()
  164. return
  165. }
  166. ctl.lastPong.Store(time.Now())
  167. xl.Debug("receive heartbeat from server")
  168. }
  169. func (ctl *Control) Close() error {
  170. return ctl.GracefulClose(0)
  171. }
  172. func (ctl *Control) GracefulClose(d time.Duration) error {
  173. ctl.pm.Close()
  174. ctl.vm.Close()
  175. time.Sleep(d)
  176. ctl.conn.Close()
  177. ctl.connector.Close()
  178. return nil
  179. }
  180. // Done returns a channel that will be closed after all resources are released
  181. func (ctl *Control) Done() <-chan struct{} {
  182. return ctl.doneCh
  183. }
  184. // connectServer return a new connection to frps
  185. func (ctl *Control) connectServer() (conn net.Conn, err error) {
  186. return ctl.connector.Connect()
  187. }
  188. func (ctl *Control) registerMsgHandlers() {
  189. ctl.msgDispatcher.RegisterHandler(&msg.ReqWorkConn{}, msg.AsyncHandler(ctl.handleReqWorkConn))
  190. ctl.msgDispatcher.RegisterHandler(&msg.NewProxyResp{}, ctl.handleNewProxyResp)
  191. ctl.msgDispatcher.RegisterHandler(&msg.NatHoleResp{}, ctl.handleNatHoleResp)
  192. ctl.msgDispatcher.RegisterHandler(&msg.Pong{}, ctl.handlePong)
  193. }
  194. // headerWorker sends heartbeat to server and check heartbeat timeout.
  195. func (ctl *Control) heartbeatWorker() {
  196. xl := ctl.xl
  197. // TODO(fatedier): Change default value of HeartbeatInterval to -1 if tcpmux is enabled.
  198. // Users can still enable heartbeat feature by setting HeartbeatInterval to a positive value.
  199. if ctl.clientCfg.Transport.HeartbeatInterval > 0 {
  200. // send heartbeat to server
  201. sendHeartBeat := func() error {
  202. xl.Debug("send heartbeat to server")
  203. pingMsg := &msg.Ping{}
  204. if err := ctl.authSetter.SetPing(pingMsg); err != nil {
  205. xl.Warn("error during ping authentication: %v, skip sending ping message", err)
  206. return err
  207. }
  208. _ = ctl.msgDispatcher.Send(pingMsg)
  209. return nil
  210. }
  211. go wait.BackoffUntil(sendHeartBeat,
  212. wait.NewFastBackoffManager(wait.FastBackoffOptions{
  213. Duration: time.Duration(ctl.clientCfg.Transport.HeartbeatInterval) * time.Second,
  214. InitDurationIfFail: time.Second,
  215. Factor: 2.0,
  216. Jitter: 0.1,
  217. MaxDuration: time.Duration(ctl.clientCfg.Transport.HeartbeatInterval) * time.Second,
  218. }),
  219. true, ctl.doneCh,
  220. )
  221. }
  222. // Check heartbeat timeout only if TCPMux is not enabled and users don't disable heartbeat feature.
  223. if ctl.clientCfg.Transport.HeartbeatInterval > 0 && ctl.clientCfg.Transport.HeartbeatTimeout > 0 &&
  224. !lo.FromPtr(ctl.clientCfg.Transport.TCPMux) {
  225. go wait.Until(func() {
  226. if time.Since(ctl.lastPong.Load().(time.Time)) > time.Duration(ctl.clientCfg.Transport.HeartbeatTimeout)*time.Second {
  227. xl.Warn("heartbeat timeout")
  228. ctl.conn.Close()
  229. return
  230. }
  231. }, time.Second, ctl.doneCh)
  232. }
  233. }
  234. func (ctl *Control) worker() {
  235. go ctl.heartbeatWorker()
  236. go ctl.msgDispatcher.Run()
  237. <-ctl.msgDispatcher.Done()
  238. ctl.conn.Close()
  239. ctl.pm.Close()
  240. ctl.vm.Close()
  241. ctl.connector.Close()
  242. close(ctl.doneCh)
  243. }
  244. func (ctl *Control) ReloadConf(pxyCfgs []v1.ProxyConfigurer, visitorCfgs []v1.VisitorConfigurer) error {
  245. ctl.vm.Reload(visitorCfgs)
  246. ctl.pm.Reload(pxyCfgs)
  247. return nil
  248. }