control.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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. ctl.pm.Close()
  153. ctl.conn.Close()
  154. ctl.vm.Close()
  155. if ctl.session != nil {
  156. ctl.session.Close()
  157. }
  158. return nil
  159. }
  160. // ClosedDoneCh returns a channel which will be closed after all resources are released
  161. func (ctl *Control) ClosedDoneCh() <-chan struct{} {
  162. return ctl.closedDoneCh
  163. }
  164. // connectServer return a new connection to frps
  165. func (ctl *Control) connectServer() (conn net.Conn, err error) {
  166. xl := ctl.xl
  167. if ctl.clientCfg.TCPMux {
  168. stream, errRet := ctl.session.OpenStream()
  169. if errRet != nil {
  170. err = errRet
  171. xl.Warn("start new connection to server error: %v", err)
  172. return
  173. }
  174. conn = stream
  175. } else {
  176. var tlsConfig *tls.Config
  177. sn := ctl.clientCfg.TLSServerName
  178. if sn == "" {
  179. sn = ctl.clientCfg.ServerAddr
  180. }
  181. if ctl.clientCfg.TLSEnable {
  182. tlsConfig, err = transport.NewClientTLSConfig(
  183. ctl.clientCfg.TLSCertFile,
  184. ctl.clientCfg.TLSKeyFile,
  185. ctl.clientCfg.TLSTrustedCaFile,
  186. sn)
  187. if err != nil {
  188. xl.Warn("fail to build tls configuration when connecting to server, err: %v", err)
  189. return
  190. }
  191. }
  192. address := net.JoinHostPort(ctl.clientCfg.ServerAddr, strconv.Itoa(ctl.clientCfg.ServerPort))
  193. conn, err = frpNet.ConnectServerByProxyWithTLS(ctl.clientCfg.HTTPProxy, ctl.clientCfg.Protocol, address, tlsConfig)
  194. if err != nil {
  195. xl.Warn("start new connection to server error: %v", err)
  196. return
  197. }
  198. }
  199. return
  200. }
  201. // reader read all messages from frps and send to readCh
  202. func (ctl *Control) reader() {
  203. xl := ctl.xl
  204. defer func() {
  205. if err := recover(); err != nil {
  206. xl.Error("panic error: %v", err)
  207. xl.Error(string(debug.Stack()))
  208. }
  209. }()
  210. defer ctl.readerShutdown.Done()
  211. defer close(ctl.closedCh)
  212. encReader := crypto.NewReader(ctl.conn, []byte(ctl.clientCfg.Token))
  213. for {
  214. m, err := msg.ReadMsg(encReader)
  215. if err != nil {
  216. if err == io.EOF {
  217. xl.Debug("read from control connection EOF")
  218. return
  219. }
  220. xl.Warn("read error: %v", err)
  221. ctl.conn.Close()
  222. return
  223. }
  224. ctl.readCh <- m
  225. }
  226. }
  227. // writer writes messages got from sendCh to frps
  228. func (ctl *Control) writer() {
  229. xl := ctl.xl
  230. defer ctl.writerShutdown.Done()
  231. encWriter, err := crypto.NewWriter(ctl.conn, []byte(ctl.clientCfg.Token))
  232. if err != nil {
  233. xl.Error("crypto new writer error: %v", err)
  234. ctl.conn.Close()
  235. return
  236. }
  237. for {
  238. m, ok := <-ctl.sendCh
  239. if !ok {
  240. xl.Info("control writer is closing")
  241. return
  242. }
  243. if err := msg.WriteMsg(encWriter, m); err != nil {
  244. xl.Warn("write message to control connection error: %v", err)
  245. return
  246. }
  247. }
  248. }
  249. // msgHandler handles all channel events and do corresponding operations.
  250. func (ctl *Control) msgHandler() {
  251. xl := ctl.xl
  252. defer func() {
  253. if err := recover(); err != nil {
  254. xl.Error("panic error: %v", err)
  255. xl.Error(string(debug.Stack()))
  256. }
  257. }()
  258. defer ctl.msgHandlerShutdown.Done()
  259. hbSend := time.NewTicker(time.Duration(ctl.clientCfg.HeartbeatInterval) * time.Second)
  260. defer hbSend.Stop()
  261. hbCheck := time.NewTicker(time.Second)
  262. defer hbCheck.Stop()
  263. ctl.lastPong = time.Now()
  264. for {
  265. select {
  266. case <-hbSend.C:
  267. // send heartbeat to server
  268. xl.Debug("send heartbeat to server")
  269. pingMsg := &msg.Ping{}
  270. if err := ctl.authSetter.SetPing(pingMsg); err != nil {
  271. xl.Warn("error during ping authentication: %v", err)
  272. return
  273. }
  274. ctl.sendCh <- pingMsg
  275. case <-hbCheck.C:
  276. if time.Since(ctl.lastPong) > time.Duration(ctl.clientCfg.HeartbeatTimeout)*time.Second {
  277. xl.Warn("heartbeat timeout")
  278. // let reader() stop
  279. ctl.conn.Close()
  280. return
  281. }
  282. case rawMsg, ok := <-ctl.readCh:
  283. if !ok {
  284. return
  285. }
  286. switch m := rawMsg.(type) {
  287. case *msg.ReqWorkConn:
  288. go ctl.HandleReqWorkConn(m)
  289. case *msg.NewProxyResp:
  290. ctl.HandleNewProxyResp(m)
  291. case *msg.Pong:
  292. if m.Error != "" {
  293. xl.Error("Pong contains error: %s", m.Error)
  294. ctl.conn.Close()
  295. return
  296. }
  297. ctl.lastPong = time.Now()
  298. xl.Debug("receive heartbeat from server")
  299. }
  300. }
  301. }
  302. }
  303. // If controler is notified by closedCh, reader and writer and handler will exit
  304. func (ctl *Control) worker() {
  305. go ctl.msgHandler()
  306. go ctl.reader()
  307. go ctl.writer()
  308. select {
  309. case <-ctl.closedCh:
  310. // close related channels and wait until other goroutines done
  311. close(ctl.readCh)
  312. ctl.readerShutdown.WaitDone()
  313. ctl.msgHandlerShutdown.WaitDone()
  314. close(ctl.sendCh)
  315. ctl.writerShutdown.WaitDone()
  316. ctl.pm.Close()
  317. ctl.vm.Close()
  318. close(ctl.closedDoneCh)
  319. if ctl.session != nil {
  320. ctl.session.Close()
  321. }
  322. return
  323. }
  324. }
  325. func (ctl *Control) ReloadConf(pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.VisitorConf) error {
  326. ctl.vm.Reload(visitorCfgs)
  327. ctl.pm.Reload(pxyCfgs)
  328. return nil
  329. }