control.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. "crypto/tls"
  18. "io"
  19. "net"
  20. "runtime/debug"
  21. "strconv"
  22. "sync"
  23. "time"
  24. "github.com/fatedier/frp/client/proxy"
  25. "github.com/fatedier/frp/pkg/auth"
  26. "github.com/fatedier/frp/pkg/config"
  27. "github.com/fatedier/frp/pkg/msg"
  28. "github.com/fatedier/frp/pkg/transport"
  29. frpNet "github.com/fatedier/frp/pkg/util/net"
  30. "github.com/fatedier/frp/pkg/util/xlog"
  31. "github.com/fatedier/golib/control/shutdown"
  32. "github.com/fatedier/golib/crypto"
  33. fmux "github.com/hashicorp/yamux"
  34. )
  35. type Control struct {
  36. // uniq id got from frps, attach it in loginMsg
  37. runID string
  38. // manage all proxies
  39. pxyCfgs map[string]config.ProxyConf
  40. pm *proxy.Manager
  41. // manage all visitors
  42. vm *VisitorManager
  43. // control connection
  44. conn net.Conn
  45. // tcp stream multiplexing, if enabled
  46. session *fmux.Session
  47. // put a message in this channel to send it over control connection to server
  48. sendCh chan (msg.Message)
  49. // read from this channel to get the next message sent by server
  50. readCh chan (msg.Message)
  51. // goroutines can block by reading from this channel, it will be closed only in reader() when control connection is closed
  52. closedCh chan struct{}
  53. closedDoneCh chan struct{}
  54. // last time got the Pong message
  55. lastPong time.Time
  56. // The client configuration
  57. clientCfg config.ClientCommonConf
  58. readerShutdown *shutdown.Shutdown
  59. writerShutdown *shutdown.Shutdown
  60. msgHandlerShutdown *shutdown.Shutdown
  61. // The UDP port that the server is listening on
  62. serverUDPPort int
  63. mu sync.RWMutex
  64. xl *xlog.Logger
  65. // service context
  66. ctx context.Context
  67. // sets authentication based on selected method
  68. authSetter auth.Setter
  69. }
  70. func NewControl(ctx context.Context, runID string, conn net.Conn, session *fmux.Session,
  71. clientCfg config.ClientCommonConf,
  72. pxyCfgs map[string]config.ProxyConf,
  73. visitorCfgs map[string]config.VisitorConf,
  74. serverUDPPort int,
  75. authSetter auth.Setter) *Control {
  76. // new xlog instance
  77. ctl := &Control{
  78. runID: runID,
  79. conn: conn,
  80. session: session,
  81. pxyCfgs: pxyCfgs,
  82. sendCh: make(chan msg.Message, 100),
  83. readCh: make(chan msg.Message, 100),
  84. closedCh: make(chan struct{}),
  85. closedDoneCh: make(chan struct{}),
  86. clientCfg: clientCfg,
  87. readerShutdown: shutdown.New(),
  88. writerShutdown: shutdown.New(),
  89. msgHandlerShutdown: shutdown.New(),
  90. serverUDPPort: serverUDPPort,
  91. xl: xlog.FromContextSafe(ctx),
  92. ctx: ctx,
  93. authSetter: authSetter,
  94. }
  95. ctl.pm = proxy.NewManager(ctl.ctx, ctl.sendCh, clientCfg, serverUDPPort)
  96. ctl.vm = NewVisitorManager(ctl.ctx, ctl)
  97. ctl.vm.Reload(visitorCfgs)
  98. return ctl
  99. }
  100. func (ctl *Control) Run() {
  101. go ctl.worker()
  102. // start all proxies
  103. ctl.pm.Reload(ctl.pxyCfgs)
  104. // start all visitors
  105. go ctl.vm.Run()
  106. return
  107. }
  108. func (ctl *Control) HandleReqWorkConn(inMsg *msg.ReqWorkConn) {
  109. xl := ctl.xl
  110. workConn, err := ctl.connectServer()
  111. if err != nil {
  112. return
  113. }
  114. m := &msg.NewWorkConn{
  115. RunID: ctl.runID,
  116. }
  117. if err = ctl.authSetter.SetNewWorkConn(m); err != nil {
  118. xl.Warn("error during NewWorkConn authentication: %v", err)
  119. return
  120. }
  121. if err = msg.WriteMsg(workConn, m); err != nil {
  122. xl.Warn("work connection write to server error: %v", err)
  123. workConn.Close()
  124. return
  125. }
  126. var startMsg msg.StartWorkConn
  127. if err = msg.ReadMsgInto(workConn, &startMsg); err != nil {
  128. xl.Error("work connection closed before response StartWorkConn message: %v", err)
  129. workConn.Close()
  130. return
  131. }
  132. if startMsg.Error != "" {
  133. xl.Error("StartWorkConn contains error: %s", startMsg.Error)
  134. workConn.Close()
  135. return
  136. }
  137. // dispatch this work connection to related proxy
  138. ctl.pm.HandleWorkConn(startMsg.ProxyName, workConn, &startMsg)
  139. }
  140. func (ctl *Control) HandleNewProxyResp(inMsg *msg.NewProxyResp) {
  141. xl := ctl.xl
  142. // Server will return NewProxyResp message to each NewProxy message.
  143. // Start a new proxy handler if no error got
  144. err := ctl.pm.StartProxy(inMsg.ProxyName, inMsg.RemoteAddr, inMsg.Error)
  145. if err != nil {
  146. xl.Warn("[%s] start error: %v", inMsg.ProxyName, err)
  147. } else {
  148. xl.Info("[%s] start proxy success", inMsg.ProxyName)
  149. }
  150. }
  151. func (ctl *Control) Close() error {
  152. return ctl.GracefulClose(0)
  153. }
  154. func (ctl *Control) GracefulClose(d time.Duration) error {
  155. ctl.pm.Close()
  156. ctl.vm.Close()
  157. time.Sleep(d)
  158. ctl.conn.Close()
  159. if ctl.session != nil {
  160. ctl.session.Close()
  161. }
  162. return nil
  163. }
  164. // ClosedDoneCh returns a channel which will be closed after all resources are released
  165. func (ctl *Control) ClosedDoneCh() <-chan struct{} {
  166. return ctl.closedDoneCh
  167. }
  168. // connectServer return a new connection to frps
  169. func (ctl *Control) connectServer() (conn net.Conn, err error) {
  170. xl := ctl.xl
  171. if ctl.clientCfg.TCPMux {
  172. stream, errRet := ctl.session.OpenStream()
  173. if errRet != nil {
  174. err = errRet
  175. xl.Warn("start new connection to server error: %v", err)
  176. return
  177. }
  178. conn = stream
  179. } else {
  180. var tlsConfig *tls.Config
  181. sn := ctl.clientCfg.TLSServerName
  182. if sn == "" {
  183. sn = ctl.clientCfg.ServerAddr
  184. }
  185. if ctl.clientCfg.TLSEnable {
  186. tlsConfig, err = transport.NewClientTLSConfig(
  187. ctl.clientCfg.TLSCertFile,
  188. ctl.clientCfg.TLSKeyFile,
  189. ctl.clientCfg.TLSTrustedCaFile,
  190. sn)
  191. if err != nil {
  192. xl.Warn("fail to build tls configuration when connecting to server, err: %v", err)
  193. return
  194. }
  195. }
  196. address := net.JoinHostPort(ctl.clientCfg.ServerAddr, strconv.Itoa(ctl.clientCfg.ServerPort))
  197. conn, err = frpNet.ConnectServerByProxyWithTLS(ctl.clientCfg.HTTPProxy, ctl.clientCfg.Protocol, address, tlsConfig, ctl.clientCfg.DisableCustomTLSFirstByte)
  198. if err != nil {
  199. xl.Warn("start new connection to server error: %v", err)
  200. return
  201. }
  202. }
  203. return
  204. }
  205. // reader read all messages from frps and send to readCh
  206. func (ctl *Control) reader() {
  207. xl := ctl.xl
  208. defer func() {
  209. if err := recover(); err != nil {
  210. xl.Error("panic error: %v", err)
  211. xl.Error(string(debug.Stack()))
  212. }
  213. }()
  214. defer ctl.readerShutdown.Done()
  215. defer close(ctl.closedCh)
  216. encReader := crypto.NewReader(ctl.conn, []byte(ctl.clientCfg.Token))
  217. for {
  218. m, err := msg.ReadMsg(encReader)
  219. if err != nil {
  220. if err == io.EOF {
  221. xl.Debug("read from control connection EOF")
  222. return
  223. }
  224. xl.Warn("read error: %v", err)
  225. ctl.conn.Close()
  226. return
  227. }
  228. ctl.readCh <- m
  229. }
  230. }
  231. // writer writes messages got from sendCh to frps
  232. func (ctl *Control) writer() {
  233. xl := ctl.xl
  234. defer ctl.writerShutdown.Done()
  235. encWriter, err := crypto.NewWriter(ctl.conn, []byte(ctl.clientCfg.Token))
  236. if err != nil {
  237. xl.Error("crypto new writer error: %v", err)
  238. ctl.conn.Close()
  239. return
  240. }
  241. for {
  242. m, ok := <-ctl.sendCh
  243. if !ok {
  244. xl.Info("control writer is closing")
  245. return
  246. }
  247. if err := msg.WriteMsg(encWriter, m); err != nil {
  248. xl.Warn("write message to control connection error: %v", err)
  249. return
  250. }
  251. }
  252. }
  253. // msgHandler handles all channel events and do corresponding operations.
  254. func (ctl *Control) msgHandler() {
  255. xl := ctl.xl
  256. defer func() {
  257. if err := recover(); err != nil {
  258. xl.Error("panic error: %v", err)
  259. xl.Error(string(debug.Stack()))
  260. }
  261. }()
  262. defer ctl.msgHandlerShutdown.Done()
  263. hbSend := time.NewTicker(time.Duration(ctl.clientCfg.HeartbeatInterval) * time.Second)
  264. defer hbSend.Stop()
  265. hbCheck := time.NewTicker(time.Second)
  266. defer hbCheck.Stop()
  267. ctl.lastPong = time.Now()
  268. for {
  269. select {
  270. case <-hbSend.C:
  271. // send heartbeat to server
  272. xl.Debug("send heartbeat to server")
  273. pingMsg := &msg.Ping{}
  274. if err := ctl.authSetter.SetPing(pingMsg); err != nil {
  275. xl.Warn("error during ping authentication: %v", err)
  276. return
  277. }
  278. ctl.sendCh <- pingMsg
  279. case <-hbCheck.C:
  280. if time.Since(ctl.lastPong) > time.Duration(ctl.clientCfg.HeartbeatTimeout)*time.Second {
  281. xl.Warn("heartbeat timeout")
  282. // let reader() stop
  283. ctl.conn.Close()
  284. return
  285. }
  286. case rawMsg, ok := <-ctl.readCh:
  287. if !ok {
  288. return
  289. }
  290. switch m := rawMsg.(type) {
  291. case *msg.ReqWorkConn:
  292. go ctl.HandleReqWorkConn(m)
  293. case *msg.NewProxyResp:
  294. ctl.HandleNewProxyResp(m)
  295. case *msg.Pong:
  296. if m.Error != "" {
  297. xl.Error("Pong contains error: %s", m.Error)
  298. ctl.conn.Close()
  299. return
  300. }
  301. ctl.lastPong = time.Now()
  302. xl.Debug("receive heartbeat from server")
  303. }
  304. }
  305. }
  306. }
  307. // If controler is notified by closedCh, reader and writer and handler will exit
  308. func (ctl *Control) worker() {
  309. go ctl.msgHandler()
  310. go ctl.reader()
  311. go ctl.writer()
  312. select {
  313. case <-ctl.closedCh:
  314. // close related channels and wait until other goroutines done
  315. close(ctl.readCh)
  316. ctl.readerShutdown.WaitDone()
  317. ctl.msgHandlerShutdown.WaitDone()
  318. close(ctl.sendCh)
  319. ctl.writerShutdown.WaitDone()
  320. ctl.pm.Close()
  321. ctl.vm.Close()
  322. close(ctl.closedDoneCh)
  323. if ctl.session != nil {
  324. ctl.session.Close()
  325. }
  326. return
  327. }
  328. }
  329. func (ctl *Control) ReloadConf(pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.VisitorConf) error {
  330. ctl.vm.Reload(visitorCfgs)
  331. ctl.pm.Reload(pxyCfgs)
  332. return nil
  333. }