1
0

control.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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. }
  126. }
  127. func (ctl *Control) init() {
  128. ctl.sendCh = make(chan msg.Message, 10)
  129. ctl.readCh = make(chan msg.Message, 10)
  130. ctl.closedCh = make(chan int)
  131. }
  132. // login send a login message to server and wait for a loginResp message.
  133. func (ctl *Control) login() (err error) {
  134. if ctl.conn != nil {
  135. ctl.conn.Close()
  136. }
  137. conn, err := net.ConnectTcpServerByHttpProxy(config.ClientCommonCfg.HttpProxy,
  138. fmt.Sprintf("%s:%d", config.ClientCommonCfg.ServerAddr, config.ClientCommonCfg.ServerPort))
  139. if err != nil {
  140. return err
  141. }
  142. now := time.Now().Unix()
  143. ctl.loginMsg.PrivilegeKey = util.GetAuthKey(config.ClientCommonCfg.PrivilegeToken, now)
  144. ctl.loginMsg.Timestamp = now
  145. ctl.loginMsg.RunId = ctl.runId
  146. if err = msg.WriteMsg(conn, ctl.loginMsg); err != nil {
  147. return err
  148. }
  149. var loginRespMsg msg.LoginResp
  150. if err = msg.ReadMsgInto(conn, &loginRespMsg); err != nil {
  151. return err
  152. }
  153. if loginRespMsg.Error != "" {
  154. err = fmt.Errorf("%s", loginRespMsg.Error)
  155. ctl.Error("%s", loginRespMsg.Error)
  156. return err
  157. }
  158. ctl.conn = conn
  159. // update runId got from server
  160. ctl.runId = loginRespMsg.RunId
  161. ctl.ClearLogPrefix()
  162. ctl.AddLogPrefix(loginRespMsg.RunId)
  163. ctl.Info("login to server success, get run id [%s]", loginRespMsg.RunId)
  164. // login success, so we let closedCh available again
  165. ctl.closedCh = make(chan int)
  166. ctl.lastPong = time.Now()
  167. return nil
  168. }
  169. func (ctl *Control) reader() {
  170. defer func() {
  171. if err := recover(); err != nil {
  172. ctl.Error("panic error: %v", err)
  173. }
  174. }()
  175. defer close(ctl.closedCh)
  176. encReader, err := crypto.NewReader(ctl.conn, []byte(config.ClientCommonCfg.PrivilegeToken))
  177. if err != nil {
  178. ctl.conn.Error("crypto new reader error: %v", err)
  179. return
  180. }
  181. for {
  182. if m, err := msg.ReadMsg(encReader); err != nil {
  183. if err == io.EOF {
  184. ctl.Debug("read from control connection EOF")
  185. return
  186. } else {
  187. ctl.Warn("read error: %v", err)
  188. continue
  189. }
  190. } else {
  191. ctl.readCh <- m
  192. }
  193. }
  194. }
  195. func (ctl *Control) writer() {
  196. encWriter, err := crypto.NewWriter(ctl.conn, []byte(config.ClientCommonCfg.PrivilegeToken))
  197. if err != nil {
  198. ctl.conn.Error("crypto new writer error: %v", err)
  199. ctl.conn.Close()
  200. return
  201. }
  202. for {
  203. if m, ok := <-ctl.sendCh; !ok {
  204. ctl.Info("control writer is closing")
  205. return
  206. } else {
  207. if err := msg.WriteMsg(encWriter, m); err != nil {
  208. ctl.Warn("write message to control connection error: %v", err)
  209. return
  210. }
  211. }
  212. }
  213. }
  214. func (ctl *Control) manager() {
  215. defer func() {
  216. if err := recover(); err != nil {
  217. ctl.Error("panic error: %v", err)
  218. }
  219. }()
  220. hbSend := time.NewTicker(time.Duration(config.ClientCommonCfg.HeartBeatInterval) * time.Second)
  221. defer hbSend.Stop()
  222. hbCheck := time.NewTicker(time.Second)
  223. defer hbCheck.Stop()
  224. for {
  225. select {
  226. case <-hbSend.C:
  227. // send heartbeat to server
  228. ctl.sendCh <- &msg.Ping{}
  229. case <-hbCheck.C:
  230. if time.Since(ctl.lastPong) > time.Duration(config.ClientCommonCfg.HeartBeatTimeout)*time.Second {
  231. ctl.Warn("heartbeat timeout")
  232. return
  233. }
  234. case rawMsg, ok := <-ctl.readCh:
  235. if !ok {
  236. return
  237. }
  238. switch m := rawMsg.(type) {
  239. case *msg.ReqWorkConn:
  240. go ctl.NewWorkConn()
  241. case *msg.NewProxyResp:
  242. // Server will return NewProxyResp message to each NewProxy message.
  243. // Start a new proxy handler if no error got
  244. if m.Error != "" {
  245. ctl.Warn("[%s] start error: %s", m.ProxyName, m.Error)
  246. continue
  247. }
  248. oldPxy, ok := ctl.proxies[m.ProxyName]
  249. if ok {
  250. oldPxy.Close()
  251. }
  252. cfg, ok := ctl.pxyCfgs[m.ProxyName]
  253. if !ok {
  254. // it will never go to this branch
  255. ctl.Warn("[%s] no proxy conf found", m.ProxyName)
  256. continue
  257. }
  258. pxy := NewProxy(ctl, cfg)
  259. pxy.Run()
  260. ctl.proxies[m.ProxyName] = pxy
  261. ctl.Info("[%s] start proxy success", m.ProxyName)
  262. case *msg.Pong:
  263. ctl.lastPong = time.Now()
  264. }
  265. }
  266. }
  267. }
  268. // control keep watching closedCh, start a new connection if previous control connection is closed
  269. func (ctl *Control) controler() {
  270. var err error
  271. maxDelayTime := 30 * time.Second
  272. delayTime := time.Second
  273. for {
  274. // we won't get any variable from this channel
  275. _, ok := <-ctl.closedCh
  276. if !ok {
  277. // close related channels
  278. close(ctl.readCh)
  279. close(ctl.sendCh)
  280. time.Sleep(time.Second)
  281. // loop util reconnect to server success
  282. for {
  283. ctl.Info("try to reconnect to server...")
  284. err = ctl.login()
  285. if err != nil {
  286. ctl.Warn("reconnect to server error: %v", err)
  287. time.Sleep(delayTime)
  288. delayTime = delayTime * 2
  289. if delayTime > maxDelayTime {
  290. delayTime = maxDelayTime
  291. }
  292. continue
  293. }
  294. // reconnect success, init the delayTime
  295. delayTime = time.Second
  296. break
  297. }
  298. // init related channels and variables
  299. ctl.init()
  300. // previous work goroutines should be closed and start them here
  301. go ctl.manager()
  302. go ctl.writer()
  303. go ctl.reader()
  304. // send NewProxy message for all configured proxies
  305. for _, cfg := range ctl.pxyCfgs {
  306. var newProxyMsg msg.NewProxy
  307. cfg.UnMarshalToMsg(&newProxyMsg)
  308. ctl.sendCh <- &newProxyMsg
  309. }
  310. }
  311. }
  312. }