control.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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. "io"
  18. "net"
  19. "runtime/debug"
  20. "time"
  21. "github.com/fatedier/golib/control/shutdown"
  22. "github.com/fatedier/golib/crypto"
  23. "github.com/fatedier/frp/client/proxy"
  24. "github.com/fatedier/frp/pkg/auth"
  25. "github.com/fatedier/frp/pkg/config"
  26. "github.com/fatedier/frp/pkg/msg"
  27. "github.com/fatedier/frp/pkg/util/xlog"
  28. )
  29. type Control struct {
  30. // uniq id got from frps, attach it in loginMsg
  31. runID string
  32. // manage all proxies
  33. pxyCfgs map[string]config.ProxyConf
  34. pm *proxy.Manager
  35. // manage all visitors
  36. vm *VisitorManager
  37. // control connection
  38. conn net.Conn
  39. cm *ConnectionManager
  40. // put a message in this channel to send it over control connection to server
  41. sendCh chan (msg.Message)
  42. // read from this channel to get the next message sent by server
  43. readCh chan (msg.Message)
  44. // goroutines can block by reading from this channel, it will be closed only in reader() when control connection is closed
  45. closedCh chan struct{}
  46. closedDoneCh chan struct{}
  47. // last time got the Pong message
  48. lastPong time.Time
  49. // The client configuration
  50. clientCfg config.ClientCommonConf
  51. readerShutdown *shutdown.Shutdown
  52. writerShutdown *shutdown.Shutdown
  53. msgHandlerShutdown *shutdown.Shutdown
  54. // The UDP port that the server is listening on
  55. serverUDPPort int
  56. xl *xlog.Logger
  57. // service context
  58. ctx context.Context
  59. // sets authentication based on selected method
  60. authSetter auth.Setter
  61. }
  62. func NewControl(
  63. ctx context.Context, runID string, conn net.Conn, cm *ConnectionManager,
  64. clientCfg config.ClientCommonConf,
  65. pxyCfgs map[string]config.ProxyConf,
  66. visitorCfgs map[string]config.VisitorConf,
  67. serverUDPPort int,
  68. authSetter auth.Setter,
  69. ) *Control {
  70. // new xlog instance
  71. ctl := &Control{
  72. runID: runID,
  73. conn: conn,
  74. cm: cm,
  75. pxyCfgs: pxyCfgs,
  76. sendCh: make(chan msg.Message, 100),
  77. readCh: make(chan msg.Message, 100),
  78. closedCh: make(chan struct{}),
  79. closedDoneCh: make(chan struct{}),
  80. clientCfg: clientCfg,
  81. readerShutdown: shutdown.New(),
  82. writerShutdown: shutdown.New(),
  83. msgHandlerShutdown: shutdown.New(),
  84. serverUDPPort: serverUDPPort,
  85. xl: xlog.FromContextSafe(ctx),
  86. ctx: ctx,
  87. authSetter: authSetter,
  88. }
  89. ctl.pm = proxy.NewManager(ctl.ctx, ctl.sendCh, clientCfg, serverUDPPort)
  90. ctl.vm = NewVisitorManager(ctl.ctx, ctl)
  91. ctl.vm.Reload(visitorCfgs)
  92. return ctl
  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) HandleReqWorkConn(inMsg *msg.ReqWorkConn) {
  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.runID,
  110. }
  111. if err = ctl.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(inMsg *msg.NewProxyResp) {
  135. xl := ctl.xl
  136. // Server will return NewProxyResp message to each NewProxy message.
  137. // Start a new proxy handler if no error got
  138. err := ctl.pm.StartProxy(inMsg.ProxyName, inMsg.RemoteAddr, inMsg.Error)
  139. if err != nil {
  140. xl.Warn("[%s] start error: %v", inMsg.ProxyName, err)
  141. } else {
  142. xl.Info("[%s] start proxy success", inMsg.ProxyName)
  143. }
  144. }
  145. func (ctl *Control) Close() error {
  146. return ctl.GracefulClose(0)
  147. }
  148. func (ctl *Control) GracefulClose(d time.Duration) error {
  149. ctl.pm.Close()
  150. ctl.vm.Close()
  151. time.Sleep(d)
  152. ctl.conn.Close()
  153. ctl.cm.Close()
  154. return nil
  155. }
  156. // ClosedDoneCh returns a channel which will be closed after all resources are released
  157. func (ctl *Control) ClosedDoneCh() <-chan struct{} {
  158. return ctl.closedDoneCh
  159. }
  160. // connectServer return a new connection to frps
  161. func (ctl *Control) connectServer() (conn net.Conn, err error) {
  162. return ctl.cm.Connect()
  163. }
  164. // reader read all messages from frps and send to readCh
  165. func (ctl *Control) reader() {
  166. xl := ctl.xl
  167. defer func() {
  168. if err := recover(); err != nil {
  169. xl.Error("panic error: %v", err)
  170. xl.Error(string(debug.Stack()))
  171. }
  172. }()
  173. defer ctl.readerShutdown.Done()
  174. defer close(ctl.closedCh)
  175. encReader := crypto.NewReader(ctl.conn, []byte(ctl.clientCfg.Token))
  176. for {
  177. m, err := msg.ReadMsg(encReader)
  178. if err != nil {
  179. if err == io.EOF {
  180. xl.Debug("read from control connection EOF")
  181. return
  182. }
  183. xl.Warn("read error: %v", err)
  184. ctl.conn.Close()
  185. return
  186. }
  187. ctl.readCh <- m
  188. }
  189. }
  190. // writer writes messages got from sendCh to frps
  191. func (ctl *Control) writer() {
  192. xl := ctl.xl
  193. defer ctl.writerShutdown.Done()
  194. encWriter, err := crypto.NewWriter(ctl.conn, []byte(ctl.clientCfg.Token))
  195. if err != nil {
  196. xl.Error("crypto new writer error: %v", err)
  197. ctl.conn.Close()
  198. return
  199. }
  200. for {
  201. m, ok := <-ctl.sendCh
  202. if !ok {
  203. xl.Info("control writer is closing")
  204. return
  205. }
  206. if err := msg.WriteMsg(encWriter, m); err != nil {
  207. xl.Warn("write message to control connection error: %v", err)
  208. return
  209. }
  210. }
  211. }
  212. // msgHandler handles all channel events and do corresponding operations.
  213. func (ctl *Control) msgHandler() {
  214. xl := ctl.xl
  215. defer func() {
  216. if err := recover(); err != nil {
  217. xl.Error("panic error: %v", err)
  218. xl.Error(string(debug.Stack()))
  219. }
  220. }()
  221. defer ctl.msgHandlerShutdown.Done()
  222. var hbSendCh <-chan time.Time
  223. // TODO(fatedier): disable heartbeat if TCPMux is enabled.
  224. // Just keep it here to keep compatible with old version frps.
  225. if ctl.clientCfg.HeartbeatInterval > 0 {
  226. hbSend := time.NewTicker(time.Duration(ctl.clientCfg.HeartbeatInterval) * time.Second)
  227. defer hbSend.Stop()
  228. hbSendCh = hbSend.C
  229. }
  230. var hbCheckCh <-chan time.Time
  231. // Check heartbeat timeout only if TCPMux is not enabled and users don't disable heartbeat feature.
  232. if ctl.clientCfg.HeartbeatInterval > 0 && ctl.clientCfg.HeartbeatTimeout > 0 && !ctl.clientCfg.TCPMux {
  233. hbCheck := time.NewTicker(time.Second)
  234. defer hbCheck.Stop()
  235. hbCheckCh = hbCheck.C
  236. }
  237. ctl.lastPong = time.Now()
  238. for {
  239. select {
  240. case <-hbSendCh:
  241. // send heartbeat to server
  242. xl.Debug("send heartbeat to server")
  243. pingMsg := &msg.Ping{}
  244. if err := ctl.authSetter.SetPing(pingMsg); err != nil {
  245. xl.Warn("error during ping authentication: %v", err)
  246. return
  247. }
  248. ctl.sendCh <- pingMsg
  249. case <-hbCheckCh:
  250. if time.Since(ctl.lastPong) > time.Duration(ctl.clientCfg.HeartbeatTimeout)*time.Second {
  251. xl.Warn("heartbeat timeout")
  252. // let reader() stop
  253. ctl.conn.Close()
  254. return
  255. }
  256. case rawMsg, ok := <-ctl.readCh:
  257. if !ok {
  258. return
  259. }
  260. switch m := rawMsg.(type) {
  261. case *msg.ReqWorkConn:
  262. go ctl.HandleReqWorkConn(m)
  263. case *msg.NewProxyResp:
  264. ctl.HandleNewProxyResp(m)
  265. case *msg.Pong:
  266. if m.Error != "" {
  267. xl.Error("Pong contains error: %s", m.Error)
  268. ctl.conn.Close()
  269. return
  270. }
  271. ctl.lastPong = time.Now()
  272. xl.Debug("receive heartbeat from server")
  273. }
  274. }
  275. }
  276. }
  277. // If controler is notified by closedCh, reader and writer and handler will exit
  278. func (ctl *Control) worker() {
  279. go ctl.msgHandler()
  280. go ctl.reader()
  281. go ctl.writer()
  282. <-ctl.closedCh
  283. // close related channels and wait until other goroutines done
  284. close(ctl.readCh)
  285. ctl.readerShutdown.WaitDone()
  286. ctl.msgHandlerShutdown.WaitDone()
  287. close(ctl.sendCh)
  288. ctl.writerShutdown.WaitDone()
  289. ctl.pm.Close()
  290. ctl.vm.Close()
  291. close(ctl.closedDoneCh)
  292. ctl.cm.Close()
  293. }
  294. func (ctl *Control) ReloadConf(pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.VisitorConf) error {
  295. ctl.vm.Reload(visitorCfgs)
  296. ctl.pm.Reload(pxyCfgs)
  297. return nil
  298. }