control.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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. netpkg "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 SessionContext struct {
  32. // The client common configuration.
  33. Common *v1.ClientCommonConfig
  34. // Unique ID obtained from frps.
  35. // It should be attached to the login message when reconnecting.
  36. RunID string
  37. // Underlying control connection. Once conn is closed, the msgDispatcher and the entire Control will exit.
  38. Conn net.Conn
  39. // Indicates whether the connection is encrypted.
  40. ConnEncrypted bool
  41. // Sets authentication based on selected method
  42. AuthSetter auth.Setter
  43. // Connector is used to create new connections, which could be real TCP connections or virtual streams.
  44. Connector Connector
  45. }
  46. type Control struct {
  47. // service context
  48. ctx context.Context
  49. xl *xlog.Logger
  50. // session context
  51. sessionCtx *SessionContext
  52. // manage all proxies
  53. pm *proxy.Manager
  54. // manage all visitors
  55. vm *visitor.Manager
  56. doneCh chan struct{}
  57. // of time.Time, last time got the Pong message
  58. lastPong atomic.Value
  59. // The role of msgTransporter is similar to HTTP2.
  60. // It allows multiple messages to be sent simultaneously on the same control connection.
  61. // The server's response messages will be dispatched to the corresponding waiting goroutines based on the laneKey and message type.
  62. msgTransporter transport.MessageTransporter
  63. // msgDispatcher is a wrapper for control connection.
  64. // It provides a channel for sending messages, and you can register handlers to process messages based on their respective types.
  65. msgDispatcher *msg.Dispatcher
  66. }
  67. func NewControl(ctx context.Context, sessionCtx *SessionContext) (*Control, error) {
  68. // new xlog instance
  69. ctl := &Control{
  70. ctx: ctx,
  71. xl: xlog.FromContextSafe(ctx),
  72. sessionCtx: sessionCtx,
  73. doneCh: make(chan struct{}),
  74. }
  75. ctl.lastPong.Store(time.Now())
  76. if sessionCtx.ConnEncrypted {
  77. cryptoRW, err := netpkg.NewCryptoReadWriter(sessionCtx.Conn, []byte(sessionCtx.Common.Auth.Token))
  78. if err != nil {
  79. return nil, err
  80. }
  81. ctl.msgDispatcher = msg.NewDispatcher(cryptoRW)
  82. } else {
  83. ctl.msgDispatcher = msg.NewDispatcher(sessionCtx.Conn)
  84. }
  85. ctl.registerMsgHandlers()
  86. ctl.msgTransporter = transport.NewMessageTransporter(ctl.msgDispatcher.SendChannel())
  87. ctl.pm = proxy.NewManager(ctl.ctx, sessionCtx.Common, ctl.msgTransporter)
  88. ctl.vm = visitor.NewManager(ctl.ctx, sessionCtx.RunID, sessionCtx.Common, ctl.connectServer, ctl.msgTransporter)
  89. return ctl, nil
  90. }
  91. func (ctl *Control) Run(proxyCfgs []v1.ProxyConfigurer, visitorCfgs []v1.VisitorConfigurer) {
  92. go ctl.worker()
  93. // start all proxies
  94. ctl.pm.UpdateAll(proxyCfgs)
  95. // start all visitors
  96. ctl.vm.UpdateAll(visitorCfgs)
  97. }
  98. func (ctl *Control) SetInWorkConnCallback(cb func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) bool) {
  99. ctl.pm.SetInWorkConnCallback(cb)
  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.sessionCtx.RunID,
  110. }
  111. if err = ctl.sessionCtx.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.closeSession()
  161. return
  162. }
  163. ctl.lastPong.Store(time.Now())
  164. xl.Debug("receive heartbeat from server")
  165. }
  166. // closeSession closes the control connection.
  167. func (ctl *Control) closeSession() {
  168. ctl.sessionCtx.Conn.Close()
  169. ctl.sessionCtx.Connector.Close()
  170. }
  171. func (ctl *Control) Close() error {
  172. return ctl.GracefulClose(0)
  173. }
  174. func (ctl *Control) GracefulClose(d time.Duration) error {
  175. ctl.pm.Close()
  176. ctl.vm.Close()
  177. time.Sleep(d)
  178. ctl.closeSession()
  179. return nil
  180. }
  181. // Done returns a channel that will be closed after all resources are released
  182. func (ctl *Control) Done() <-chan struct{} {
  183. return ctl.doneCh
  184. }
  185. // connectServer return a new connection to frps
  186. func (ctl *Control) connectServer() (net.Conn, error) {
  187. return ctl.sessionCtx.Connector.Connect()
  188. }
  189. func (ctl *Control) registerMsgHandlers() {
  190. ctl.msgDispatcher.RegisterHandler(&msg.ReqWorkConn{}, msg.AsyncHandler(ctl.handleReqWorkConn))
  191. ctl.msgDispatcher.RegisterHandler(&msg.NewProxyResp{}, ctl.handleNewProxyResp)
  192. ctl.msgDispatcher.RegisterHandler(&msg.NatHoleResp{}, ctl.handleNatHoleResp)
  193. ctl.msgDispatcher.RegisterHandler(&msg.Pong{}, ctl.handlePong)
  194. }
  195. // headerWorker sends heartbeat to server and check heartbeat timeout.
  196. func (ctl *Control) heartbeatWorker() {
  197. xl := ctl.xl
  198. // TODO(fatedier): Change default value of HeartbeatInterval to -1 if tcpmux is enabled.
  199. // Users can still enable heartbeat feature by setting HeartbeatInterval to a positive value.
  200. if ctl.sessionCtx.Common.Transport.HeartbeatInterval > 0 {
  201. // send heartbeat to server
  202. sendHeartBeat := func() (bool, error) {
  203. xl.Debug("send heartbeat to server")
  204. pingMsg := &msg.Ping{}
  205. if err := ctl.sessionCtx.AuthSetter.SetPing(pingMsg); err != nil {
  206. xl.Warn("error during ping authentication: %v, skip sending ping message", err)
  207. return false, err
  208. }
  209. _ = ctl.msgDispatcher.Send(pingMsg)
  210. return false, nil
  211. }
  212. go wait.BackoffUntil(sendHeartBeat,
  213. wait.NewFastBackoffManager(wait.FastBackoffOptions{
  214. Duration: time.Duration(ctl.sessionCtx.Common.Transport.HeartbeatInterval) * time.Second,
  215. InitDurationIfFail: time.Second,
  216. Factor: 2.0,
  217. Jitter: 0.1,
  218. MaxDuration: time.Duration(ctl.sessionCtx.Common.Transport.HeartbeatInterval) * time.Second,
  219. }),
  220. true, ctl.doneCh,
  221. )
  222. }
  223. // Check heartbeat timeout only if TCPMux is not enabled and users don't disable heartbeat feature.
  224. if ctl.sessionCtx.Common.Transport.HeartbeatInterval > 0 && ctl.sessionCtx.Common.Transport.HeartbeatTimeout > 0 &&
  225. !lo.FromPtr(ctl.sessionCtx.Common.Transport.TCPMux) {
  226. go wait.Until(func() {
  227. if time.Since(ctl.lastPong.Load().(time.Time)) > time.Duration(ctl.sessionCtx.Common.Transport.HeartbeatTimeout)*time.Second {
  228. xl.Warn("heartbeat timeout")
  229. ctl.closeSession()
  230. return
  231. }
  232. }, time.Second, ctl.doneCh)
  233. }
  234. }
  235. func (ctl *Control) worker() {
  236. go ctl.heartbeatWorker()
  237. go ctl.msgDispatcher.Run()
  238. <-ctl.msgDispatcher.Done()
  239. ctl.closeSession()
  240. ctl.pm.Close()
  241. ctl.vm.Close()
  242. close(ctl.doneCh)
  243. }
  244. func (ctl *Control) UpdateAllConfigurer(proxyCfgs []v1.ProxyConfigurer, visitorCfgs []v1.VisitorConfigurer) error {
  245. ctl.vm.UpdateAll(visitorCfgs)
  246. ctl.pm.UpdateAll(proxyCfgs)
  247. return nil
  248. }