control.go 9.4 KB

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