control.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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. func (ctl *Control) connectServer() (conn frpNet.Conn, err error) {
  217. if g.GlbClientCfg.TcpMux {
  218. stream, errRet := ctl.session.OpenStream()
  219. if errRet != nil {
  220. err = errRet
  221. ctl.Warn("start new connection to server error: %v", err)
  222. return
  223. }
  224. conn = frpNet.WrapConn(stream)
  225. } else {
  226. conn, err = frpNet.ConnectServerByProxy(g.GlbClientCfg.HttpProxy, g.GlbClientCfg.Protocol,
  227. fmt.Sprintf("%s:%d", g.GlbClientCfg.ServerAddr, g.GlbClientCfg.ServerPort))
  228. if err != nil {
  229. ctl.Warn("start new connection to server error: %v", err)
  230. return
  231. }
  232. }
  233. return
  234. }
  235. // reader read all messages from frps and send to readCh
  236. func (ctl *Control) reader() {
  237. defer func() {
  238. if err := recover(); err != nil {
  239. ctl.Error("panic error: %v", err)
  240. ctl.Error(string(debug.Stack()))
  241. }
  242. }()
  243. defer ctl.readerShutdown.Done()
  244. defer close(ctl.closedCh)
  245. encReader := crypto.NewReader(ctl.conn, []byte(g.GlbClientCfg.Token))
  246. for {
  247. if m, err := msg.ReadMsg(encReader); err != nil {
  248. if err == io.EOF {
  249. ctl.Debug("read from control connection EOF")
  250. return
  251. } else {
  252. ctl.Warn("read error: %v", err)
  253. return
  254. }
  255. } else {
  256. ctl.readCh <- m
  257. }
  258. }
  259. }
  260. // writer writes messages got from sendCh to frps
  261. func (ctl *Control) writer() {
  262. defer ctl.writerShutdown.Done()
  263. encWriter, err := crypto.NewWriter(ctl.conn, []byte(g.GlbClientCfg.Token))
  264. if err != nil {
  265. ctl.conn.Error("crypto new writer error: %v", err)
  266. ctl.conn.Close()
  267. return
  268. }
  269. for {
  270. if m, ok := <-ctl.sendCh; !ok {
  271. ctl.Info("control writer is closing")
  272. return
  273. } else {
  274. if err := msg.WriteMsg(encWriter, m); err != nil {
  275. ctl.Warn("write message to control connection error: %v", err)
  276. return
  277. }
  278. }
  279. }
  280. }
  281. // msgHandler handles all channel events and do corresponding operations.
  282. func (ctl *Control) msgHandler() {
  283. defer func() {
  284. if err := recover(); err != nil {
  285. ctl.Error("panic error: %v", err)
  286. ctl.Error(string(debug.Stack()))
  287. }
  288. }()
  289. defer ctl.msgHandlerShutdown.Done()
  290. hbSend := time.NewTicker(time.Duration(g.GlbClientCfg.HeartBeatInterval) * time.Second)
  291. defer hbSend.Stop()
  292. hbCheck := time.NewTicker(time.Second)
  293. defer hbCheck.Stop()
  294. ctl.lastPong = time.Now()
  295. for {
  296. select {
  297. case <-hbSend.C:
  298. // send heartbeat to server
  299. ctl.Debug("send heartbeat to server")
  300. ctl.sendCh <- &msg.Ping{}
  301. case <-hbCheck.C:
  302. if time.Since(ctl.lastPong) > time.Duration(g.GlbClientCfg.HeartBeatTimeout)*time.Second {
  303. ctl.Warn("heartbeat timeout")
  304. // let reader() stop
  305. ctl.conn.Close()
  306. return
  307. }
  308. case rawMsg, ok := <-ctl.readCh:
  309. if !ok {
  310. return
  311. }
  312. switch m := rawMsg.(type) {
  313. case *msg.ReqWorkConn:
  314. go ctl.HandleReqWorkConn(m)
  315. case *msg.NewProxyResp:
  316. ctl.HandleNewProxyResp(m)
  317. case *msg.Pong:
  318. ctl.lastPong = time.Now()
  319. ctl.Debug("receive heartbeat from server")
  320. }
  321. }
  322. }
  323. }
  324. // controler keep watching closedCh, start a new connection if previous control connection is closed.
  325. // If controler is notified by closedCh, reader and writer and handler will exit, then recall these functions.
  326. func (ctl *Control) worker() {
  327. go ctl.msgHandler()
  328. go ctl.reader()
  329. go ctl.writer()
  330. var err error
  331. maxDelayTime := 20 * time.Second
  332. delayTime := time.Second
  333. checkInterval := 60 * time.Second
  334. checkProxyTicker := time.NewTicker(checkInterval)
  335. for {
  336. select {
  337. case <-checkProxyTicker.C:
  338. // check which proxy registered failed and reregister it to server
  339. ctl.pm.CheckAndStartProxy([]string{ProxyStatusStartErr, ProxyStatusClosed})
  340. case _, ok := <-ctl.closedCh:
  341. // we won't get any variable from this channel
  342. if !ok {
  343. // close related channels and wait until other goroutines done
  344. close(ctl.readCh)
  345. ctl.readerShutdown.WaitDone()
  346. ctl.msgHandlerShutdown.WaitDone()
  347. close(ctl.sendCh)
  348. ctl.writerShutdown.WaitDone()
  349. ctl.pm.CloseProxies()
  350. // if ctl.exit is true, just exit
  351. ctl.mu.RLock()
  352. exit := ctl.exit
  353. ctl.mu.RUnlock()
  354. if exit {
  355. return
  356. }
  357. // loop util reconnecting to server success
  358. for {
  359. ctl.Info("try to reconnect to server...")
  360. err = ctl.login()
  361. if err != nil {
  362. ctl.Warn("reconnect to server error: %v", err)
  363. time.Sleep(delayTime)
  364. delayTime = delayTime * 2
  365. if delayTime > maxDelayTime {
  366. delayTime = maxDelayTime
  367. }
  368. continue
  369. }
  370. // reconnect success, init delayTime
  371. delayTime = time.Second
  372. break
  373. }
  374. // init related channels and variables
  375. ctl.sendCh = make(chan msg.Message, 100)
  376. ctl.readCh = make(chan msg.Message, 100)
  377. ctl.closedCh = make(chan int)
  378. ctl.readerShutdown = shutdown.New()
  379. ctl.writerShutdown = shutdown.New()
  380. ctl.msgHandlerShutdown = shutdown.New()
  381. ctl.pm.Reset(ctl.sendCh, ctl.runId)
  382. // previous work goroutines should be closed and start them here
  383. go ctl.msgHandler()
  384. go ctl.writer()
  385. go ctl.reader()
  386. // start all configured proxies
  387. ctl.pm.CheckAndStartProxy([]string{ProxyStatusNew, ProxyStatusClosed})
  388. checkProxyTicker.Stop()
  389. checkProxyTicker = time.NewTicker(checkInterval)
  390. }
  391. }
  392. }
  393. }
  394. func (ctl *Control) reloadConf(pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.VisitorConf) error {
  395. ctl.vm.Reload(visitorCfgs)
  396. err := ctl.pm.Reload(pxyCfgs, true)
  397. return err
  398. }