control.go 11 KB

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