control.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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. "fmt"
  17. "io"
  18. "io/ioutil"
  19. "runtime"
  20. "runtime/debug"
  21. "sync"
  22. "time"
  23. "github.com/fatedier/frp/g"
  24. "github.com/fatedier/frp/models/config"
  25. "github.com/fatedier/frp/models/msg"
  26. "github.com/fatedier/frp/utils/log"
  27. frpNet "github.com/fatedier/frp/utils/net"
  28. "github.com/fatedier/frp/utils/util"
  29. "github.com/fatedier/frp/utils/version"
  30. "github.com/fatedier/golib/control/shutdown"
  31. "github.com/fatedier/golib/crypto"
  32. fmux "github.com/hashicorp/yamux"
  33. )
  34. const (
  35. connReadTimeout time.Duration = 10 * time.Second
  36. )
  37. type Control struct {
  38. // frpc service
  39. svr *Service
  40. // login message to server, only used
  41. loginMsg *msg.Login
  42. // manage all proxies
  43. pm *ProxyManager
  44. // manage all visitors
  45. vm *VisitorManager
  46. // control connection
  47. conn frpNet.Conn
  48. // tcp stream multiplexing, if enabled
  49. session *fmux.Session
  50. // put a message in this channel to send it over control connection to server
  51. sendCh chan (msg.Message)
  52. // read from this channel to get the next message sent by server
  53. readCh chan (msg.Message)
  54. // run id got from server
  55. runId string
  56. // if we call close() in control, do not reconnect to server
  57. exit bool
  58. // goroutines can block by reading from this channel, it will be closed only in reader() when control connection is closed
  59. closedCh chan int
  60. // last time got the Pong message
  61. lastPong time.Time
  62. readerShutdown *shutdown.Shutdown
  63. writerShutdown *shutdown.Shutdown
  64. msgHandlerShutdown *shutdown.Shutdown
  65. mu sync.RWMutex
  66. log.Logger
  67. }
  68. func NewControl(svr *Service, pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.VisitorConf) *Control {
  69. loginMsg := &msg.Login{
  70. Arch: runtime.GOARCH,
  71. Os: runtime.GOOS,
  72. PoolCount: g.GlbClientCfg.PoolCount,
  73. User: g.GlbClientCfg.User,
  74. Version: version.Full(),
  75. }
  76. ctl := &Control{
  77. svr: svr,
  78. loginMsg: loginMsg,
  79. sendCh: make(chan msg.Message, 100),
  80. readCh: make(chan msg.Message, 100),
  81. closedCh: make(chan int),
  82. readerShutdown: shutdown.New(),
  83. writerShutdown: shutdown.New(),
  84. msgHandlerShutdown: shutdown.New(),
  85. Logger: log.NewPrefixLogger(""),
  86. }
  87. ctl.pm = NewProxyManager(ctl, ctl.sendCh, "")
  88. ctl.pm.Reload(pxyCfgs, false)
  89. ctl.vm = NewVisitorManager(ctl)
  90. ctl.vm.Reload(visitorCfgs)
  91. return ctl
  92. }
  93. func (ctl *Control) Run() (err error) {
  94. for {
  95. err = ctl.login()
  96. if err != nil {
  97. ctl.Warn("login to server failed: %v", err)
  98. // if login_fail_exit is true, just exit this program
  99. // otherwise sleep a while and continues relogin to server
  100. if g.GlbClientCfg.LoginFailExit {
  101. return
  102. } else {
  103. time.Sleep(10 * time.Second)
  104. }
  105. } else {
  106. break
  107. }
  108. }
  109. go ctl.worker()
  110. // start all local visitors and send NewProxy message for all configured proxies
  111. ctl.pm.Reset(ctl.sendCh, ctl.runId)
  112. ctl.pm.CheckAndStartProxy([]string{ProxyStatusNew})
  113. go ctl.vm.Run()
  114. return nil
  115. }
  116. func (ctl *Control) HandleReqWorkConn(inMsg *msg.ReqWorkConn) {
  117. workConn, err := ctl.connectServer()
  118. if err != nil {
  119. return
  120. }
  121. m := &msg.NewWorkConn{
  122. RunId: ctl.runId,
  123. }
  124. if err = msg.WriteMsg(workConn, m); err != nil {
  125. ctl.Warn("work connection write to server error: %v", err)
  126. workConn.Close()
  127. return
  128. }
  129. var startMsg msg.StartWorkConn
  130. if err = msg.ReadMsgInto(workConn, &startMsg); err != nil {
  131. ctl.Error("work connection closed, %v", err)
  132. workConn.Close()
  133. return
  134. }
  135. workConn.AddLogPrefix(startMsg.ProxyName)
  136. // dispatch this work connection to related proxy
  137. ctl.pm.HandleWorkConn(startMsg.ProxyName, workConn)
  138. }
  139. func (ctl *Control) HandleNewProxyResp(inMsg *msg.NewProxyResp) {
  140. // Server will return NewProxyResp message to each NewProxy message.
  141. // Start a new proxy handler if no error got
  142. err := ctl.pm.StartProxy(inMsg.ProxyName, inMsg.RemoteAddr, inMsg.Error)
  143. if err != nil {
  144. ctl.Warn("[%s] start error: %v", inMsg.ProxyName, err)
  145. } else {
  146. ctl.Info("[%s] start proxy success", inMsg.ProxyName)
  147. }
  148. }
  149. func (ctl *Control) Close() error {
  150. ctl.mu.Lock()
  151. defer ctl.mu.Unlock()
  152. ctl.exit = true
  153. ctl.pm.CloseProxies()
  154. return nil
  155. }
  156. // login send a login message to server and wait for a loginResp message.
  157. func (ctl *Control) login() (err error) {
  158. if ctl.conn != nil {
  159. ctl.conn.Close()
  160. }
  161. if ctl.session != nil {
  162. ctl.session.Close()
  163. }
  164. conn, err := frpNet.ConnectServerByProxy(g.GlbClientCfg.HttpProxy, g.GlbClientCfg.Protocol,
  165. fmt.Sprintf("%s:%d", g.GlbClientCfg.ServerAddr, g.GlbClientCfg.ServerPort))
  166. if err != nil {
  167. return err
  168. }
  169. defer func() {
  170. if err != nil {
  171. conn.Close()
  172. }
  173. }()
  174. if g.GlbClientCfg.TcpMux {
  175. fmuxCfg := fmux.DefaultConfig()
  176. fmuxCfg.LogOutput = ioutil.Discard
  177. session, errRet := fmux.Client(conn, fmuxCfg)
  178. if errRet != nil {
  179. return errRet
  180. }
  181. stream, errRet := session.OpenStream()
  182. if errRet != nil {
  183. session.Close()
  184. return errRet
  185. }
  186. conn = frpNet.WrapConn(stream)
  187. ctl.session = session
  188. }
  189. now := time.Now().Unix()
  190. ctl.loginMsg.PrivilegeKey = util.GetAuthKey(g.GlbClientCfg.Token, now)
  191. ctl.loginMsg.Timestamp = now
  192. ctl.loginMsg.RunId = ctl.runId
  193. if err = msg.WriteMsg(conn, ctl.loginMsg); err != nil {
  194. return err
  195. }
  196. var loginRespMsg msg.LoginResp
  197. conn.SetReadDeadline(time.Now().Add(connReadTimeout))
  198. if err = msg.ReadMsgInto(conn, &loginRespMsg); err != nil {
  199. return err
  200. }
  201. conn.SetReadDeadline(time.Time{})
  202. if loginRespMsg.Error != "" {
  203. err = fmt.Errorf("%s", loginRespMsg.Error)
  204. ctl.Error("%s", loginRespMsg.Error)
  205. return err
  206. }
  207. ctl.conn = conn
  208. // update runId got from server
  209. ctl.runId = loginRespMsg.RunId
  210. g.GlbClientCfg.ServerUdpPort = loginRespMsg.ServerUdpPort
  211. ctl.ClearLogPrefix()
  212. ctl.AddLogPrefix(loginRespMsg.RunId)
  213. ctl.Info("login to server success, get run id [%s], server udp port [%d]", loginRespMsg.RunId, loginRespMsg.ServerUdpPort)
  214. return nil
  215. }
  216. // connectServer return a new connection to frps
  217. func (ctl *Control) connectServer() (conn frpNet.Conn, err error) {
  218. if g.GlbClientCfg.TcpMux {
  219. stream, errRet := ctl.session.OpenStream()
  220. if errRet != nil {
  221. err = errRet
  222. ctl.Warn("start new connection to server error: %v", err)
  223. return
  224. }
  225. conn = frpNet.WrapConn(stream)
  226. } else {
  227. conn, err = frpNet.ConnectServerByProxy(g.GlbClientCfg.HttpProxy, g.GlbClientCfg.Protocol,
  228. fmt.Sprintf("%s:%d", g.GlbClientCfg.ServerAddr, g.GlbClientCfg.ServerPort))
  229. if err != nil {
  230. ctl.Warn("start new connection to server error: %v", err)
  231. return
  232. }
  233. }
  234. return
  235. }
  236. // reader read all messages from frps and send to readCh
  237. func (ctl *Control) reader() {
  238. defer func() {
  239. if err := recover(); err != nil {
  240. ctl.Error("panic error: %v", err)
  241. ctl.Error(string(debug.Stack()))
  242. }
  243. }()
  244. defer ctl.readerShutdown.Done()
  245. defer close(ctl.closedCh)
  246. encReader := crypto.NewReader(ctl.conn, []byte(g.GlbClientCfg.Token))
  247. for {
  248. if m, err := msg.ReadMsg(encReader); err != nil {
  249. if err == io.EOF {
  250. ctl.Debug("read from control connection EOF")
  251. return
  252. } else {
  253. ctl.Warn("read error: %v", err)
  254. return
  255. }
  256. } else {
  257. ctl.readCh <- m
  258. }
  259. }
  260. }
  261. // writer writes messages got from sendCh to frps
  262. func (ctl *Control) writer() {
  263. defer ctl.writerShutdown.Done()
  264. encWriter, err := crypto.NewWriter(ctl.conn, []byte(g.GlbClientCfg.Token))
  265. if err != nil {
  266. ctl.conn.Error("crypto new writer error: %v", err)
  267. ctl.conn.Close()
  268. return
  269. }
  270. for {
  271. if m, ok := <-ctl.sendCh; !ok {
  272. ctl.Info("control writer is closing")
  273. return
  274. } else {
  275. if err := msg.WriteMsg(encWriter, m); err != nil {
  276. ctl.Warn("write message to control connection error: %v", err)
  277. return
  278. }
  279. }
  280. }
  281. }
  282. // msgHandler handles all channel events and do corresponding operations.
  283. func (ctl *Control) msgHandler() {
  284. defer func() {
  285. if err := recover(); err != nil {
  286. ctl.Error("panic error: %v", err)
  287. ctl.Error(string(debug.Stack()))
  288. }
  289. }()
  290. defer ctl.msgHandlerShutdown.Done()
  291. hbSend := time.NewTicker(time.Duration(g.GlbClientCfg.HeartBeatInterval) * time.Second)
  292. defer hbSend.Stop()
  293. hbCheck := time.NewTicker(time.Second)
  294. defer hbCheck.Stop()
  295. ctl.lastPong = time.Now()
  296. for {
  297. select {
  298. case <-hbSend.C:
  299. // send heartbeat to server
  300. ctl.Debug("send heartbeat to server")
  301. ctl.sendCh <- &msg.Ping{}
  302. case <-hbCheck.C:
  303. if time.Since(ctl.lastPong) > time.Duration(g.GlbClientCfg.HeartBeatTimeout)*time.Second {
  304. ctl.Warn("heartbeat timeout")
  305. // let reader() stop
  306. ctl.conn.Close()
  307. return
  308. }
  309. case rawMsg, ok := <-ctl.readCh:
  310. if !ok {
  311. return
  312. }
  313. switch m := rawMsg.(type) {
  314. case *msg.ReqWorkConn:
  315. go ctl.HandleReqWorkConn(m)
  316. case *msg.NewProxyResp:
  317. ctl.HandleNewProxyResp(m)
  318. case *msg.Pong:
  319. ctl.lastPong = time.Now()
  320. ctl.Debug("receive heartbeat from server")
  321. }
  322. }
  323. }
  324. }
  325. // controler keep watching closedCh, start a new connection if previous control connection is closed.
  326. // If controler is notified by closedCh, reader and writer and handler will exit, then recall these functions.
  327. func (ctl *Control) worker() {
  328. go ctl.msgHandler()
  329. go ctl.reader()
  330. go ctl.writer()
  331. var err error
  332. maxDelayTime := 20 * time.Second
  333. delayTime := time.Second
  334. checkInterval := 60 * time.Second
  335. checkProxyTicker := time.NewTicker(checkInterval)
  336. for {
  337. select {
  338. case <-checkProxyTicker.C:
  339. // check which proxy registered failed and reregister it to server
  340. ctl.pm.CheckAndStartProxy([]string{ProxyStatusStartErr, ProxyStatusClosed})
  341. case _, ok := <-ctl.closedCh:
  342. // we won't get any variable from this channel
  343. if !ok {
  344. // close related channels and wait until other goroutines done
  345. close(ctl.readCh)
  346. ctl.readerShutdown.WaitDone()
  347. ctl.msgHandlerShutdown.WaitDone()
  348. close(ctl.sendCh)
  349. ctl.writerShutdown.WaitDone()
  350. ctl.pm.CloseProxies()
  351. // if ctl.exit is true, just exit
  352. ctl.mu.RLock()
  353. exit := ctl.exit
  354. ctl.mu.RUnlock()
  355. if exit {
  356. return
  357. }
  358. // loop util reconnecting to server success
  359. for {
  360. ctl.Info("try to reconnect to server...")
  361. err = ctl.login()
  362. if err != nil {
  363. ctl.Warn("reconnect to server error: %v", err)
  364. time.Sleep(delayTime)
  365. delayTime = delayTime * 2
  366. if delayTime > maxDelayTime {
  367. delayTime = maxDelayTime
  368. }
  369. continue
  370. }
  371. // reconnect success, init delayTime
  372. delayTime = time.Second
  373. break
  374. }
  375. // init related channels and variables
  376. ctl.sendCh = make(chan msg.Message, 100)
  377. ctl.readCh = make(chan msg.Message, 100)
  378. ctl.closedCh = make(chan int)
  379. ctl.readerShutdown = shutdown.New()
  380. ctl.writerShutdown = shutdown.New()
  381. ctl.msgHandlerShutdown = shutdown.New()
  382. ctl.pm.Reset(ctl.sendCh, ctl.runId)
  383. // previous work goroutines should be closed and start them here
  384. go ctl.msgHandler()
  385. go ctl.writer()
  386. go ctl.reader()
  387. // start all configured proxies
  388. ctl.pm.CheckAndStartProxy([]string{ProxyStatusNew, ProxyStatusClosed})
  389. checkProxyTicker.Stop()
  390. checkProxyTicker = time.NewTicker(checkInterval)
  391. }
  392. }
  393. }
  394. }
  395. func (ctl *Control) reloadConf(pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.VisitorConf) error {
  396. ctl.vm.Reload(visitorCfgs)
  397. err := ctl.pm.Reload(pxyCfgs, true)
  398. return err
  399. }