control.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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/errors"
  25. "github.com/fatedier/frp/utils/log"
  26. frpNet "github.com/fatedier/frp/utils/net"
  27. "github.com/fatedier/frp/utils/util"
  28. "github.com/fatedier/frp/utils/version"
  29. "github.com/xtaci/smux"
  30. )
  31. const (
  32. connReadTimeout time.Duration = 10 * time.Second
  33. )
  34. type Control struct {
  35. // frpc service
  36. svr *Service
  37. // login message to server
  38. loginMsg *msg.Login
  39. // proxy configures
  40. pxyCfgs map[string]config.ProxyConf
  41. // proxies
  42. proxies map[string]Proxy
  43. // vistor configures
  44. vistorCfgs map[string]config.ProxyConf
  45. // vistors
  46. vistors map[string]Vistor
  47. // control connection
  48. conn frpNet.Conn
  49. // tcp stream multiplexing, if enabled
  50. session *smux.Session
  51. // put a message in this channel to send it over control connection to server
  52. sendCh chan (msg.Message)
  53. // read from this channel to get the next message sent by server
  54. readCh chan (msg.Message)
  55. // run id got from server
  56. runId string
  57. // if we call close() in control, do not reconnect to server
  58. exit bool
  59. // goroutines can block by reading from this channel, it will be closed only in reader() when control connection is closed
  60. closedCh chan int
  61. // last time got the Pong message
  62. lastPong time.Time
  63. mu sync.RWMutex
  64. log.Logger
  65. }
  66. func NewControl(svr *Service, pxyCfgs map[string]config.ProxyConf, vistorCfgs map[string]config.ProxyConf) *Control {
  67. loginMsg := &msg.Login{
  68. Arch: runtime.GOARCH,
  69. Os: runtime.GOOS,
  70. PoolCount: config.ClientCommonCfg.PoolCount,
  71. User: config.ClientCommonCfg.User,
  72. Version: version.Full(),
  73. }
  74. return &Control{
  75. svr: svr,
  76. loginMsg: loginMsg,
  77. pxyCfgs: pxyCfgs,
  78. vistorCfgs: vistorCfgs,
  79. proxies: make(map[string]Proxy),
  80. vistors: make(map[string]Vistor),
  81. sendCh: make(chan msg.Message, 10),
  82. readCh: make(chan msg.Message, 10),
  83. closedCh: make(chan int),
  84. Logger: log.NewPrefixLogger(""),
  85. }
  86. }
  87. // 1. login
  88. // 2. start reader() writer() manager()
  89. // 3. connection closed
  90. // 4. In reader(): close closedCh and exit, controler() get it
  91. // 5. In controler(): close readCh and sendCh, manager() and writer() will exit
  92. // 6. In controler(): ini readCh, sendCh, closedCh
  93. // 7. In controler(): start new reader(), writer(), manager()
  94. // controler() will keep running
  95. func (ctl *Control) Run() (err error) {
  96. for {
  97. err = ctl.login()
  98. if err != nil {
  99. ctl.Warn("login to server failed: %v", err)
  100. // if login_fail_exit is true, just exit this program
  101. // otherwise sleep a while and continues relogin to server
  102. if config.ClientCommonCfg.LoginFailExit {
  103. return
  104. } else {
  105. time.Sleep(30 * time.Second)
  106. }
  107. } else {
  108. break
  109. }
  110. }
  111. go ctl.controler()
  112. go ctl.manager()
  113. go ctl.writer()
  114. go ctl.reader()
  115. // start all local vistors
  116. for _, cfg := range ctl.vistorCfgs {
  117. vistor := NewVistor(ctl, cfg)
  118. err = vistor.Run()
  119. if err != nil {
  120. vistor.Warn("start error: %v", err)
  121. continue
  122. }
  123. ctl.vistors[cfg.GetName()] = vistor
  124. vistor.Info("start vistor success")
  125. }
  126. // send NewProxy message for all configured proxies
  127. for _, cfg := range ctl.pxyCfgs {
  128. var newProxyMsg msg.NewProxy
  129. cfg.UnMarshalToMsg(&newProxyMsg)
  130. ctl.sendCh <- &newProxyMsg
  131. }
  132. return nil
  133. }
  134. func (ctl *Control) NewWorkConn() {
  135. workConn, err := ctl.connectServer()
  136. if err != nil {
  137. return
  138. }
  139. m := &msg.NewWorkConn{
  140. RunId: ctl.getRunId(),
  141. }
  142. if err = msg.WriteMsg(workConn, m); err != nil {
  143. ctl.Warn("work connection write to server error: %v", err)
  144. workConn.Close()
  145. return
  146. }
  147. var startMsg msg.StartWorkConn
  148. if err = msg.ReadMsgInto(workConn, &startMsg); err != nil {
  149. ctl.Error("work connection closed, %v", err)
  150. workConn.Close()
  151. return
  152. }
  153. workConn.AddLogPrefix(startMsg.ProxyName)
  154. // dispatch this work connection to related proxy
  155. pxy, ok := ctl.getProxy(startMsg.ProxyName)
  156. if ok {
  157. workConn.Debug("start a new work connection, localAddr: %s remoteAddr: %s", workConn.LocalAddr().String(), workConn.RemoteAddr().String())
  158. go pxy.InWorkConn(workConn)
  159. } else {
  160. workConn.Close()
  161. }
  162. }
  163. func (ctl *Control) Close() error {
  164. ctl.mu.Lock()
  165. ctl.exit = true
  166. err := errors.PanicToError(func() {
  167. for name, _ := range ctl.proxies {
  168. ctl.sendCh <- &msg.CloseProxy{
  169. ProxyName: name,
  170. }
  171. }
  172. })
  173. ctl.mu.Unlock()
  174. return err
  175. }
  176. func (ctl *Control) init() {
  177. ctl.sendCh = make(chan msg.Message, 10)
  178. ctl.readCh = make(chan msg.Message, 10)
  179. ctl.closedCh = make(chan int)
  180. }
  181. // login send a login message to server and wait for a loginResp message.
  182. func (ctl *Control) login() (err error) {
  183. if ctl.conn != nil {
  184. ctl.conn.Close()
  185. }
  186. if ctl.session != nil {
  187. ctl.session.Close()
  188. }
  189. conn, err := frpNet.ConnectServerByHttpProxy(config.ClientCommonCfg.HttpProxy, config.ClientCommonCfg.Protocol,
  190. fmt.Sprintf("%s:%d", config.ClientCommonCfg.ServerAddr, config.ClientCommonCfg.ServerPort))
  191. if err != nil {
  192. return err
  193. }
  194. defer func() {
  195. if err != nil {
  196. conn.Close()
  197. }
  198. }()
  199. if config.ClientCommonCfg.TcpMux {
  200. session, errRet := smux.Client(conn, nil)
  201. if errRet != nil {
  202. return errRet
  203. }
  204. stream, errRet := session.OpenStream()
  205. if errRet != nil {
  206. session.Close()
  207. return errRet
  208. }
  209. conn = frpNet.WrapConn(stream)
  210. ctl.session = session
  211. }
  212. now := time.Now().Unix()
  213. ctl.loginMsg.PrivilegeKey = util.GetAuthKey(config.ClientCommonCfg.PrivilegeToken, now)
  214. ctl.loginMsg.Timestamp = now
  215. ctl.loginMsg.RunId = ctl.getRunId()
  216. if err = msg.WriteMsg(conn, ctl.loginMsg); err != nil {
  217. return err
  218. }
  219. var loginRespMsg msg.LoginResp
  220. conn.SetReadDeadline(time.Now().Add(connReadTimeout))
  221. if err = msg.ReadMsgInto(conn, &loginRespMsg); err != nil {
  222. return err
  223. }
  224. conn.SetReadDeadline(time.Time{})
  225. if loginRespMsg.Error != "" {
  226. err = fmt.Errorf("%s", loginRespMsg.Error)
  227. ctl.Error("%s", loginRespMsg.Error)
  228. return err
  229. }
  230. ctl.conn = conn
  231. // update runId got from server
  232. ctl.setRunId(loginRespMsg.RunId)
  233. ctl.ClearLogPrefix()
  234. ctl.AddLogPrefix(loginRespMsg.RunId)
  235. ctl.Info("login to server success, get run id [%s]", loginRespMsg.RunId)
  236. // login success, so we let closedCh available again
  237. ctl.closedCh = make(chan int)
  238. ctl.lastPong = time.Now()
  239. return nil
  240. }
  241. func (ctl *Control) connectServer() (conn frpNet.Conn, err error) {
  242. if config.ClientCommonCfg.TcpMux {
  243. stream, errRet := ctl.session.OpenStream()
  244. if errRet != nil {
  245. err = errRet
  246. ctl.Warn("start new connection to server error: %v", err)
  247. return
  248. }
  249. conn = frpNet.WrapConn(stream)
  250. } else {
  251. conn, err = frpNet.ConnectServerByHttpProxy(config.ClientCommonCfg.HttpProxy, config.ClientCommonCfg.Protocol,
  252. fmt.Sprintf("%s:%d", config.ClientCommonCfg.ServerAddr, config.ClientCommonCfg.ServerPort))
  253. if err != nil {
  254. ctl.Warn("start new connection to server error: %v", err)
  255. return
  256. }
  257. }
  258. return
  259. }
  260. func (ctl *Control) reader() {
  261. defer func() {
  262. if err := recover(); err != nil {
  263. ctl.Error("panic error: %v", err)
  264. }
  265. }()
  266. defer close(ctl.closedCh)
  267. encReader := crypto.NewReader(ctl.conn, []byte(config.ClientCommonCfg.PrivilegeToken))
  268. for {
  269. if m, err := msg.ReadMsg(encReader); err != nil {
  270. if err == io.EOF {
  271. ctl.Debug("read from control connection EOF")
  272. return
  273. } else {
  274. ctl.Warn("read error: %v", err)
  275. return
  276. }
  277. } else {
  278. ctl.readCh <- m
  279. }
  280. }
  281. }
  282. func (ctl *Control) writer() {
  283. encWriter, err := crypto.NewWriter(ctl.conn, []byte(config.ClientCommonCfg.PrivilegeToken))
  284. if err != nil {
  285. ctl.conn.Error("crypto new writer error: %v", err)
  286. ctl.conn.Close()
  287. return
  288. }
  289. for {
  290. if m, ok := <-ctl.sendCh; !ok {
  291. ctl.Info("control writer is closing")
  292. return
  293. } else {
  294. if err := msg.WriteMsg(encWriter, m); err != nil {
  295. ctl.Warn("write message to control connection error: %v", err)
  296. return
  297. }
  298. }
  299. }
  300. }
  301. // manager handles all channel events and do corresponding process
  302. func (ctl *Control) manager() {
  303. defer func() {
  304. if err := recover(); err != nil {
  305. ctl.Error("panic error: %v", err)
  306. }
  307. }()
  308. hbSend := time.NewTicker(time.Duration(config.ClientCommonCfg.HeartBeatInterval) * time.Second)
  309. defer hbSend.Stop()
  310. hbCheck := time.NewTicker(time.Second)
  311. defer hbCheck.Stop()
  312. for {
  313. select {
  314. case <-hbSend.C:
  315. // send heartbeat to server
  316. ctl.Debug("send heartbeat to server")
  317. ctl.sendCh <- &msg.Ping{}
  318. case <-hbCheck.C:
  319. if time.Since(ctl.lastPong) > time.Duration(config.ClientCommonCfg.HeartBeatTimeout)*time.Second {
  320. ctl.Warn("heartbeat timeout")
  321. // let reader() stop
  322. ctl.conn.Close()
  323. return
  324. }
  325. case rawMsg, ok := <-ctl.readCh:
  326. if !ok {
  327. return
  328. }
  329. switch m := rawMsg.(type) {
  330. case *msg.ReqWorkConn:
  331. go ctl.NewWorkConn()
  332. case *msg.NewProxyResp:
  333. // Server will return NewProxyResp message to each NewProxy message.
  334. // Start a new proxy handler if no error got
  335. if m.Error != "" {
  336. ctl.Warn("[%s] start error: %s", m.ProxyName, m.Error)
  337. continue
  338. }
  339. cfg, ok := ctl.pxyCfgs[m.ProxyName]
  340. if !ok {
  341. // it will never go to this branch now
  342. ctl.Warn("[%s] no proxy conf found", m.ProxyName)
  343. continue
  344. }
  345. oldPxy, ok := ctl.getProxy(m.ProxyName)
  346. if ok {
  347. oldPxy.Close()
  348. }
  349. pxy := NewProxy(ctl, cfg)
  350. if err := pxy.Run(); err != nil {
  351. ctl.Warn("[%s] proxy start running error: %v", m.ProxyName, err)
  352. ctl.sendCh <- &msg.CloseProxy{
  353. ProxyName: m.ProxyName,
  354. }
  355. continue
  356. }
  357. ctl.addProxy(m.ProxyName, pxy)
  358. ctl.Info("[%s] start proxy success", m.ProxyName)
  359. case *msg.Pong:
  360. ctl.lastPong = time.Now()
  361. ctl.Debug("receive heartbeat from server")
  362. }
  363. }
  364. }
  365. }
  366. // controler keep watching closedCh, start a new connection if previous control connection is closed.
  367. // If controler is notified by closedCh, reader and writer and manager will exit, then recall these functions.
  368. func (ctl *Control) controler() {
  369. var err error
  370. maxDelayTime := 30 * time.Second
  371. delayTime := time.Second
  372. checkInterval := 30 * time.Second
  373. checkProxyTicker := time.NewTicker(checkInterval)
  374. for {
  375. select {
  376. case <-checkProxyTicker.C:
  377. // Every 30 seconds, check which proxy registered failed and reregister it to server.
  378. for _, cfg := range ctl.pxyCfgs {
  379. if _, exist := ctl.getProxy(cfg.GetName()); !exist {
  380. ctl.Info("try to reregister proxy [%s]", cfg.GetName())
  381. var newProxyMsg msg.NewProxy
  382. cfg.UnMarshalToMsg(&newProxyMsg)
  383. ctl.sendCh <- &newProxyMsg
  384. }
  385. }
  386. case _, ok := <-ctl.closedCh:
  387. // we won't get any variable from this channel
  388. if !ok {
  389. // close related channels
  390. close(ctl.readCh)
  391. close(ctl.sendCh)
  392. for _, pxy := range ctl.proxies {
  393. pxy.Close()
  394. }
  395. // if ctl.exit is true, just exit
  396. ctl.mu.RLock()
  397. exit := ctl.exit
  398. ctl.mu.RUnlock()
  399. if exit {
  400. return
  401. }
  402. time.Sleep(time.Second)
  403. // loop util reconnect to server success
  404. for {
  405. ctl.Info("try to reconnect to server...")
  406. err = ctl.login()
  407. if err != nil {
  408. ctl.Warn("reconnect to server error: %v", err)
  409. time.Sleep(delayTime)
  410. delayTime = delayTime * 2
  411. if delayTime > maxDelayTime {
  412. delayTime = maxDelayTime
  413. }
  414. continue
  415. }
  416. // reconnect success, init the delayTime
  417. delayTime = time.Second
  418. break
  419. }
  420. // init related channels and variables
  421. ctl.init()
  422. // previous work goroutines should be closed and start them here
  423. go ctl.manager()
  424. go ctl.writer()
  425. go ctl.reader()
  426. // send NewProxy message for all configured proxies
  427. for _, cfg := range ctl.pxyCfgs {
  428. var newProxyMsg msg.NewProxy
  429. cfg.UnMarshalToMsg(&newProxyMsg)
  430. ctl.sendCh <- &newProxyMsg
  431. }
  432. checkProxyTicker.Stop()
  433. checkProxyTicker = time.NewTicker(checkInterval)
  434. }
  435. }
  436. }
  437. }
  438. func (ctl *Control) setRunId(runId string) {
  439. ctl.mu.Lock()
  440. defer ctl.mu.Unlock()
  441. ctl.runId = runId
  442. }
  443. func (ctl *Control) getRunId() string {
  444. ctl.mu.RLock()
  445. defer ctl.mu.RUnlock()
  446. return ctl.runId
  447. }
  448. func (ctl *Control) getProxy(name string) (pxy Proxy, ok bool) {
  449. ctl.mu.RLock()
  450. defer ctl.mu.RUnlock()
  451. pxy, ok = ctl.proxies[name]
  452. return
  453. }
  454. func (ctl *Control) addProxy(name string, pxy Proxy) {
  455. ctl.mu.Lock()
  456. defer ctl.mu.Unlock()
  457. ctl.proxies[name] = pxy
  458. }