control.go 8.4 KB

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