control.go 11 KB

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