control.go 11 KB

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