control.go 9.9 KB

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