control.go 8.8 KB

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