control.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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. conn, err = frpNet.DialWithOptions(net.JoinHostPort(ctl.clientCfg.ServerAddr, strconv.Itoa(ctl.clientCfg.ServerPort)),
  197. frpNet.WithProxyURL(ctl.clientCfg.HTTPProxy),
  198. frpNet.WithProtocol(ctl.clientCfg.Protocol),
  199. frpNet.WithTLSConfig(tlsConfig),
  200. frpNet.WithDisableCustomTLSHeadByte(ctl.clientCfg.DisableCustomTLSFirstByte))
  201. if err != nil {
  202. xl.Warn("start new connection to server error: %v", err)
  203. return
  204. }
  205. }
  206. return
  207. }
  208. // reader read all messages from frps and send to readCh
  209. func (ctl *Control) reader() {
  210. xl := ctl.xl
  211. defer func() {
  212. if err := recover(); err != nil {
  213. xl.Error("panic error: %v", err)
  214. xl.Error(string(debug.Stack()))
  215. }
  216. }()
  217. defer ctl.readerShutdown.Done()
  218. defer close(ctl.closedCh)
  219. encReader := crypto.NewReader(ctl.conn, []byte(ctl.clientCfg.Token))
  220. for {
  221. m, err := msg.ReadMsg(encReader)
  222. if err != nil {
  223. if err == io.EOF {
  224. xl.Debug("read from control connection EOF")
  225. return
  226. }
  227. xl.Warn("read error: %v", err)
  228. ctl.conn.Close()
  229. return
  230. }
  231. ctl.readCh <- m
  232. }
  233. }
  234. // writer writes messages got from sendCh to frps
  235. func (ctl *Control) writer() {
  236. xl := ctl.xl
  237. defer ctl.writerShutdown.Done()
  238. encWriter, err := crypto.NewWriter(ctl.conn, []byte(ctl.clientCfg.Token))
  239. if err != nil {
  240. xl.Error("crypto new writer error: %v", err)
  241. ctl.conn.Close()
  242. return
  243. }
  244. for {
  245. m, ok := <-ctl.sendCh
  246. if !ok {
  247. xl.Info("control writer is closing")
  248. return
  249. }
  250. if err := msg.WriteMsg(encWriter, m); err != nil {
  251. xl.Warn("write message to control connection error: %v", err)
  252. return
  253. }
  254. }
  255. }
  256. // msgHandler handles all channel events and do corresponding operations.
  257. func (ctl *Control) msgHandler() {
  258. xl := ctl.xl
  259. defer func() {
  260. if err := recover(); err != nil {
  261. xl.Error("panic error: %v", err)
  262. xl.Error(string(debug.Stack()))
  263. }
  264. }()
  265. defer ctl.msgHandlerShutdown.Done()
  266. hbSend := time.NewTicker(time.Duration(ctl.clientCfg.HeartbeatInterval) * time.Second)
  267. defer hbSend.Stop()
  268. hbCheck := time.NewTicker(time.Second)
  269. defer hbCheck.Stop()
  270. ctl.lastPong = time.Now()
  271. for {
  272. select {
  273. case <-hbSend.C:
  274. // send heartbeat to server
  275. xl.Debug("send heartbeat to server")
  276. pingMsg := &msg.Ping{}
  277. if err := ctl.authSetter.SetPing(pingMsg); err != nil {
  278. xl.Warn("error during ping authentication: %v", err)
  279. return
  280. }
  281. ctl.sendCh <- pingMsg
  282. case <-hbCheck.C:
  283. if time.Since(ctl.lastPong) > time.Duration(ctl.clientCfg.HeartbeatTimeout)*time.Second {
  284. xl.Warn("heartbeat timeout")
  285. // let reader() stop
  286. ctl.conn.Close()
  287. return
  288. }
  289. case rawMsg, ok := <-ctl.readCh:
  290. if !ok {
  291. return
  292. }
  293. switch m := rawMsg.(type) {
  294. case *msg.ReqWorkConn:
  295. go ctl.HandleReqWorkConn(m)
  296. case *msg.NewProxyResp:
  297. ctl.HandleNewProxyResp(m)
  298. case *msg.Pong:
  299. if m.Error != "" {
  300. xl.Error("Pong contains error: %s", m.Error)
  301. ctl.conn.Close()
  302. return
  303. }
  304. ctl.lastPong = time.Now()
  305. xl.Debug("receive heartbeat from server")
  306. }
  307. }
  308. }
  309. }
  310. // If controler is notified by closedCh, reader and writer and handler will exit
  311. func (ctl *Control) worker() {
  312. go ctl.msgHandler()
  313. go ctl.reader()
  314. go ctl.writer()
  315. select {
  316. case <-ctl.closedCh:
  317. // close related channels and wait until other goroutines done
  318. close(ctl.readCh)
  319. ctl.readerShutdown.WaitDone()
  320. ctl.msgHandlerShutdown.WaitDone()
  321. close(ctl.sendCh)
  322. ctl.writerShutdown.WaitDone()
  323. ctl.pm.Close()
  324. ctl.vm.Close()
  325. close(ctl.closedDoneCh)
  326. if ctl.session != nil {
  327. ctl.session.Close()
  328. }
  329. return
  330. }
  331. }
  332. func (ctl *Control) ReloadConf(pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.VisitorConf) error {
  333. ctl.vm.Reload(visitorCfgs)
  334. ctl.pm.Reload(pxyCfgs)
  335. return nil
  336. }