control.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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/fatedier/frp/client/proxy"
  21. "github.com/fatedier/frp/client/visitor"
  22. "github.com/fatedier/frp/pkg/auth"
  23. v1 "github.com/fatedier/frp/pkg/config/v1"
  24. "github.com/fatedier/frp/pkg/msg"
  25. "github.com/fatedier/frp/pkg/transport"
  26. netpkg "github.com/fatedier/frp/pkg/util/net"
  27. "github.com/fatedier/frp/pkg/util/wait"
  28. "github.com/fatedier/frp/pkg/util/xlog"
  29. )
  30. type SessionContext struct {
  31. // The client common configuration.
  32. Common *v1.ClientCommonConfig
  33. // Unique ID obtained from frps.
  34. // It should be attached to the login message when reconnecting.
  35. RunID string
  36. // Underlying control connection. Once conn is closed, the msgDispatcher and the entire Control will exit.
  37. Conn net.Conn
  38. // Indicates whether the connection is encrypted.
  39. ConnEncrypted bool
  40. // Sets authentication based on selected method
  41. AuthSetter auth.Setter
  42. // Connector is used to create new connections, which could be real TCP connections or virtual streams.
  43. Connector Connector
  44. }
  45. type Control struct {
  46. // service context
  47. ctx context.Context
  48. xl *xlog.Logger
  49. // session context
  50. sessionCtx *SessionContext
  51. // manage all proxies
  52. pm *proxy.Manager
  53. // manage all visitors
  54. vm *visitor.Manager
  55. doneCh chan struct{}
  56. // of time.Time, last time got the Pong message
  57. lastPong atomic.Value
  58. // The role of msgTransporter is similar to HTTP2.
  59. // It allows multiple messages to be sent simultaneously on the same control connection.
  60. // The server's response messages will be dispatched to the corresponding waiting goroutines based on the laneKey and message type.
  61. msgTransporter transport.MessageTransporter
  62. // msgDispatcher is a wrapper for control connection.
  63. // It provides a channel for sending messages, and you can register handlers to process messages based on their respective types.
  64. msgDispatcher *msg.Dispatcher
  65. }
  66. func NewControl(ctx context.Context, sessionCtx *SessionContext) (*Control, error) {
  67. // new xlog instance
  68. ctl := &Control{
  69. ctx: ctx,
  70. xl: xlog.FromContextSafe(ctx),
  71. sessionCtx: sessionCtx,
  72. doneCh: make(chan struct{}),
  73. }
  74. ctl.lastPong.Store(time.Now())
  75. if sessionCtx.ConnEncrypted {
  76. cryptoRW, err := netpkg.NewCryptoReadWriter(sessionCtx.Conn, []byte(sessionCtx.Common.Auth.Token))
  77. if err != nil {
  78. return nil, err
  79. }
  80. ctl.msgDispatcher = msg.NewDispatcher(cryptoRW)
  81. } else {
  82. ctl.msgDispatcher = msg.NewDispatcher(sessionCtx.Conn)
  83. }
  84. ctl.registerMsgHandlers()
  85. ctl.msgTransporter = transport.NewMessageTransporter(ctl.msgDispatcher.SendChannel())
  86. ctl.pm = proxy.NewManager(ctl.ctx, sessionCtx.Common, ctl.msgTransporter)
  87. ctl.vm = visitor.NewManager(ctl.ctx, sessionCtx.RunID, sessionCtx.Common, ctl.connectServer, ctl.msgTransporter)
  88. return ctl, nil
  89. }
  90. func (ctl *Control) Run(proxyCfgs []v1.ProxyConfigurer, visitorCfgs []v1.VisitorConfigurer) {
  91. go ctl.worker()
  92. // start all proxies
  93. ctl.pm.UpdateAll(proxyCfgs)
  94. // start all visitors
  95. ctl.vm.UpdateAll(visitorCfgs)
  96. }
  97. func (ctl *Control) SetInWorkConnCallback(cb func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) bool) {
  98. ctl.pm.SetInWorkConnCallback(cb)
  99. }
  100. func (ctl *Control) handleReqWorkConn(_ msg.Message) {
  101. xl := ctl.xl
  102. workConn, err := ctl.connectServer()
  103. if err != nil {
  104. xl.Warnf("start new connection to server error: %v", err)
  105. return
  106. }
  107. m := &msg.NewWorkConn{
  108. RunID: ctl.sessionCtx.RunID,
  109. }
  110. if err = ctl.sessionCtx.AuthSetter.SetNewWorkConn(m); err != nil {
  111. xl.Warnf("error during NewWorkConn authentication: %v", err)
  112. workConn.Close()
  113. return
  114. }
  115. if err = msg.WriteMsg(workConn, m); err != nil {
  116. xl.Warnf("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.Tracef("work connection closed before response StartWorkConn message: %v", err)
  123. workConn.Close()
  124. return
  125. }
  126. if startMsg.Error != "" {
  127. xl.Errorf("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.Warnf("[%s] start error: %v", inMsg.ProxyName, err)
  142. } else {
  143. xl.Infof("[%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.Tracef("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.Errorf("Pong message contains error: %s", inMsg.Error)
  160. ctl.closeSession()
  161. return
  162. }
  163. ctl.lastPong.Store(time.Now())
  164. xl.Debugf("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. // heartbeatWorker sends heartbeat to server and check heartbeat timeout.
  196. func (ctl *Control) heartbeatWorker() {
  197. xl := ctl.xl
  198. if ctl.sessionCtx.Common.Transport.HeartbeatInterval > 0 {
  199. // Send heartbeat to server.
  200. sendHeartBeat := func() (bool, error) {
  201. xl.Debugf("send heartbeat to server")
  202. pingMsg := &msg.Ping{}
  203. if err := ctl.sessionCtx.AuthSetter.SetPing(pingMsg); err != nil {
  204. xl.Warnf("error during ping authentication: %v, skip sending ping message", err)
  205. return false, err
  206. }
  207. _ = ctl.msgDispatcher.Send(pingMsg)
  208. return false, nil
  209. }
  210. go wait.BackoffUntil(sendHeartBeat,
  211. wait.NewFastBackoffManager(wait.FastBackoffOptions{
  212. Duration: time.Duration(ctl.sessionCtx.Common.Transport.HeartbeatInterval) * time.Second,
  213. InitDurationIfFail: time.Second,
  214. Factor: 2.0,
  215. Jitter: 0.1,
  216. MaxDuration: time.Duration(ctl.sessionCtx.Common.Transport.HeartbeatInterval) * time.Second,
  217. }),
  218. true, ctl.doneCh,
  219. )
  220. }
  221. // Check heartbeat timeout.
  222. if ctl.sessionCtx.Common.Transport.HeartbeatInterval > 0 && ctl.sessionCtx.Common.Transport.HeartbeatTimeout > 0 {
  223. go wait.Until(func() {
  224. if time.Since(ctl.lastPong.Load().(time.Time)) > time.Duration(ctl.sessionCtx.Common.Transport.HeartbeatTimeout)*time.Second {
  225. xl.Warnf("heartbeat timeout")
  226. ctl.closeSession()
  227. return
  228. }
  229. }, time.Second, ctl.doneCh)
  230. }
  231. }
  232. func (ctl *Control) worker() {
  233. go ctl.heartbeatWorker()
  234. go ctl.msgDispatcher.Run()
  235. <-ctl.msgDispatcher.Done()
  236. ctl.closeSession()
  237. ctl.pm.Close()
  238. ctl.vm.Close()
  239. close(ctl.doneCh)
  240. }
  241. func (ctl *Control) UpdateAllConfigurer(proxyCfgs []v1.ProxyConfigurer, visitorCfgs []v1.VisitorConfigurer) error {
  242. ctl.vm.UpdateAll(visitorCfgs)
  243. ctl.pm.UpdateAll(proxyCfgs)
  244. return nil
  245. }