control.go 8.6 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/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. "github.com/fatedier/frp/pkg/vnet"
  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. // Virtual net controller
  46. VnetController *vnet.Controller
  47. }
  48. type Control struct {
  49. // service context
  50. ctx context.Context
  51. xl *xlog.Logger
  52. // session context
  53. sessionCtx *SessionContext
  54. // manage all proxies
  55. pm *proxy.Manager
  56. // manage all visitors
  57. vm *visitor.Manager
  58. doneCh chan struct{}
  59. // of time.Time, last time got the Pong message
  60. lastPong atomic.Value
  61. // The role of msgTransporter is similar to HTTP2.
  62. // It allows multiple messages to be sent simultaneously on the same control connection.
  63. // The server's response messages will be dispatched to the corresponding waiting goroutines based on the laneKey and message type.
  64. msgTransporter transport.MessageTransporter
  65. // msgDispatcher is a wrapper for control connection.
  66. // It provides a channel for sending messages, and you can register handlers to process messages based on their respective types.
  67. msgDispatcher *msg.Dispatcher
  68. }
  69. func NewControl(ctx context.Context, sessionCtx *SessionContext) (*Control, error) {
  70. // new xlog instance
  71. ctl := &Control{
  72. ctx: ctx,
  73. xl: xlog.FromContextSafe(ctx),
  74. sessionCtx: sessionCtx,
  75. doneCh: make(chan struct{}),
  76. }
  77. ctl.lastPong.Store(time.Now())
  78. if sessionCtx.ConnEncrypted {
  79. cryptoRW, err := netpkg.NewCryptoReadWriter(sessionCtx.Conn, []byte(sessionCtx.Common.Auth.Token))
  80. if err != nil {
  81. return nil, err
  82. }
  83. ctl.msgDispatcher = msg.NewDispatcher(cryptoRW)
  84. } else {
  85. ctl.msgDispatcher = msg.NewDispatcher(sessionCtx.Conn)
  86. }
  87. ctl.registerMsgHandlers()
  88. ctl.msgTransporter = transport.NewMessageTransporter(ctl.msgDispatcher.SendChannel())
  89. ctl.pm = proxy.NewManager(ctl.ctx, sessionCtx.Common, ctl.msgTransporter, sessionCtx.VnetController)
  90. ctl.vm = visitor.NewManager(ctl.ctx, sessionCtx.RunID, sessionCtx.Common,
  91. ctl.connectServer, ctl.msgTransporter, sessionCtx.VnetController)
  92. return ctl, nil
  93. }
  94. func (ctl *Control) Run(proxyCfgs []v1.ProxyConfigurer, visitorCfgs []v1.VisitorConfigurer) {
  95. go ctl.worker()
  96. // start all proxies
  97. ctl.pm.UpdateAll(proxyCfgs)
  98. // start all visitors
  99. ctl.vm.UpdateAll(visitorCfgs)
  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.Warnf("start new connection to server error: %v", err)
  109. return
  110. }
  111. m := &msg.NewWorkConn{
  112. RunID: ctl.sessionCtx.RunID,
  113. }
  114. if err = ctl.sessionCtx.AuthSetter.SetNewWorkConn(m); err != nil {
  115. xl.Warnf("error during NewWorkConn authentication: %v", err)
  116. workConn.Close()
  117. return
  118. }
  119. if err = msg.WriteMsg(workConn, m); err != nil {
  120. xl.Warnf("work connection write to server error: %v", err)
  121. workConn.Close()
  122. return
  123. }
  124. var startMsg msg.StartWorkConn
  125. if err = msg.ReadMsgInto(workConn, &startMsg); err != nil {
  126. xl.Tracef("work connection closed before response StartWorkConn message: %v", err)
  127. workConn.Close()
  128. return
  129. }
  130. if startMsg.Error != "" {
  131. xl.Errorf("StartWorkConn contains error: %s", startMsg.Error)
  132. workConn.Close()
  133. return
  134. }
  135. // dispatch this work connection to related proxy
  136. ctl.pm.HandleWorkConn(startMsg.ProxyName, workConn, &startMsg)
  137. }
  138. func (ctl *Control) handleNewProxyResp(m msg.Message) {
  139. xl := ctl.xl
  140. inMsg := m.(*msg.NewProxyResp)
  141. // Server will return NewProxyResp message to each NewProxy message.
  142. // Start a new proxy handler if no error got
  143. err := ctl.pm.StartProxy(inMsg.ProxyName, inMsg.RemoteAddr, inMsg.Error)
  144. if err != nil {
  145. xl.Warnf("[%s] start error: %v", inMsg.ProxyName, err)
  146. } else {
  147. xl.Infof("[%s] start proxy success", inMsg.ProxyName)
  148. }
  149. }
  150. func (ctl *Control) handleNatHoleResp(m msg.Message) {
  151. xl := ctl.xl
  152. inMsg := m.(*msg.NatHoleResp)
  153. // Dispatch the NatHoleResp message to the related proxy.
  154. ok := ctl.msgTransporter.DispatchWithType(inMsg, msg.TypeNameNatHoleResp, inMsg.TransactionID)
  155. if !ok {
  156. xl.Tracef("dispatch NatHoleResp message to related proxy error")
  157. }
  158. }
  159. func (ctl *Control) handlePong(m msg.Message) {
  160. xl := ctl.xl
  161. inMsg := m.(*msg.Pong)
  162. if inMsg.Error != "" {
  163. xl.Errorf("Pong message contains error: %s", inMsg.Error)
  164. ctl.closeSession()
  165. return
  166. }
  167. ctl.lastPong.Store(time.Now())
  168. xl.Debugf("receive heartbeat from server")
  169. }
  170. // closeSession closes the control connection.
  171. func (ctl *Control) closeSession() {
  172. ctl.sessionCtx.Conn.Close()
  173. ctl.sessionCtx.Connector.Close()
  174. }
  175. func (ctl *Control) Close() error {
  176. return ctl.GracefulClose(0)
  177. }
  178. func (ctl *Control) GracefulClose(d time.Duration) error {
  179. ctl.pm.Close()
  180. ctl.vm.Close()
  181. time.Sleep(d)
  182. ctl.closeSession()
  183. return nil
  184. }
  185. // Done returns a channel that will be closed after all resources are released
  186. func (ctl *Control) Done() <-chan struct{} {
  187. return ctl.doneCh
  188. }
  189. // connectServer return a new connection to frps
  190. func (ctl *Control) connectServer() (net.Conn, error) {
  191. return ctl.sessionCtx.Connector.Connect()
  192. }
  193. func (ctl *Control) registerMsgHandlers() {
  194. ctl.msgDispatcher.RegisterHandler(&msg.ReqWorkConn{}, msg.AsyncHandler(ctl.handleReqWorkConn))
  195. ctl.msgDispatcher.RegisterHandler(&msg.NewProxyResp{}, ctl.handleNewProxyResp)
  196. ctl.msgDispatcher.RegisterHandler(&msg.NatHoleResp{}, ctl.handleNatHoleResp)
  197. ctl.msgDispatcher.RegisterHandler(&msg.Pong{}, ctl.handlePong)
  198. }
  199. // heartbeatWorker sends heartbeat to server and check heartbeat timeout.
  200. func (ctl *Control) heartbeatWorker() {
  201. xl := ctl.xl
  202. if ctl.sessionCtx.Common.Transport.HeartbeatInterval > 0 {
  203. // Send heartbeat to server.
  204. sendHeartBeat := func() (bool, error) {
  205. xl.Debugf("send heartbeat to server")
  206. pingMsg := &msg.Ping{}
  207. if err := ctl.sessionCtx.AuthSetter.SetPing(pingMsg); err != nil {
  208. xl.Warnf("error during ping authentication: %v, skip sending ping message", err)
  209. return false, err
  210. }
  211. _ = ctl.msgDispatcher.Send(pingMsg)
  212. return false, nil
  213. }
  214. go wait.BackoffUntil(sendHeartBeat,
  215. wait.NewFastBackoffManager(wait.FastBackoffOptions{
  216. Duration: time.Duration(ctl.sessionCtx.Common.Transport.HeartbeatInterval) * time.Second,
  217. InitDurationIfFail: time.Second,
  218. Factor: 2.0,
  219. Jitter: 0.1,
  220. MaxDuration: time.Duration(ctl.sessionCtx.Common.Transport.HeartbeatInterval) * time.Second,
  221. }),
  222. true, ctl.doneCh,
  223. )
  224. }
  225. // Check heartbeat timeout.
  226. if ctl.sessionCtx.Common.Transport.HeartbeatInterval > 0 && ctl.sessionCtx.Common.Transport.HeartbeatTimeout > 0 {
  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. }