control.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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/xtaci/smux"
  22. "github.com/fatedier/frp/g"
  23. "github.com/fatedier/frp/models/config"
  24. "github.com/fatedier/frp/models/msg"
  25. "github.com/fatedier/frp/utils/crypto"
  26. "github.com/fatedier/frp/utils/log"
  27. frpNet "github.com/fatedier/frp/utils/net"
  28. "github.com/fatedier/frp/utils/shutdown"
  29. "github.com/fatedier/frp/utils/util"
  30. "github.com/fatedier/frp/utils/version"
  31. )
  32. const (
  33. connReadTimeout time.Duration = 10 * time.Second
  34. )
  35. type Control struct {
  36. // frpc service
  37. svr *Service
  38. // login message to server, only used
  39. loginMsg *msg.Login
  40. pm *ProxyManager
  41. // control connection
  42. conn frpNet.Conn
  43. // tcp stream multiplexing, if enabled
  44. session *smux.Session
  45. // put a message in this channel to send it over control connection to server
  46. sendCh chan (msg.Message)
  47. // read from this channel to get the next message sent by server
  48. readCh chan (msg.Message)
  49. // run id got from server
  50. runId string
  51. // if we call close() in control, do not reconnect to server
  52. exit bool
  53. // goroutines can block by reading from this channel, it will be closed only in reader() when control connection is closed
  54. closedCh chan int
  55. // last time got the Pong message
  56. lastPong time.Time
  57. readerShutdown *shutdown.Shutdown
  58. writerShutdown *shutdown.Shutdown
  59. msgHandlerShutdown *shutdown.Shutdown
  60. mu sync.RWMutex
  61. log.Logger
  62. }
  63. func NewControl(svr *Service, pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.ProxyConf) *Control {
  64. loginMsg := &msg.Login{
  65. Arch: runtime.GOARCH,
  66. Os: runtime.GOOS,
  67. PoolCount: g.GlbClientCfg.PoolCount,
  68. User: g.GlbClientCfg.User,
  69. Version: version.Full(),
  70. }
  71. ctl := &Control{
  72. svr: svr,
  73. loginMsg: loginMsg,
  74. sendCh: make(chan msg.Message, 100),
  75. readCh: make(chan msg.Message, 100),
  76. closedCh: make(chan int),
  77. readerShutdown: shutdown.New(),
  78. writerShutdown: shutdown.New(),
  79. msgHandlerShutdown: shutdown.New(),
  80. Logger: log.NewPrefixLogger(""),
  81. }
  82. ctl.pm = NewProxyManager(ctl, ctl.sendCh, "")
  83. ctl.pm.Reload(pxyCfgs, visitorCfgs, false)
  84. return ctl
  85. }
  86. func (ctl *Control) Run() (err error) {
  87. for {
  88. err = ctl.login()
  89. if err != nil {
  90. ctl.Warn("login to server failed: %v", err)
  91. // if login_fail_exit is true, just exit this program
  92. // otherwise sleep a while and continues relogin to server
  93. if g.GlbClientCfg.LoginFailExit {
  94. return
  95. } else {
  96. time.Sleep(10 * time.Second)
  97. }
  98. } else {
  99. break
  100. }
  101. }
  102. go ctl.worker()
  103. // start all local visitors and send NewProxy message for all configured proxies
  104. ctl.pm.Reset(ctl.sendCh, ctl.runId)
  105. ctl.pm.CheckAndStartProxy([]string{ProxyStatusNew})
  106. return nil
  107. }
  108. func (ctl *Control) HandleReqWorkConn(inMsg *msg.ReqWorkConn) {
  109. workConn, err := ctl.connectServer()
  110. if err != nil {
  111. return
  112. }
  113. m := &msg.NewWorkConn{
  114. RunId: ctl.runId,
  115. }
  116. if err = msg.WriteMsg(workConn, m); err != nil {
  117. ctl.Warn("work connection write to server error: %v", err)
  118. workConn.Close()
  119. return
  120. }
  121. var startMsg msg.StartWorkConn
  122. if err = msg.ReadMsgInto(workConn, &startMsg); err != nil {
  123. ctl.Error("work connection closed, %v", err)
  124. workConn.Close()
  125. return
  126. }
  127. workConn.AddLogPrefix(startMsg.ProxyName)
  128. // dispatch this work connection to related proxy
  129. ctl.pm.HandleWorkConn(startMsg.ProxyName, workConn)
  130. }
  131. func (ctl *Control) HandleNewProxyResp(inMsg *msg.NewProxyResp) {
  132. // Server will return NewProxyResp message to each NewProxy message.
  133. // Start a new proxy handler if no error got
  134. err := ctl.pm.StartProxy(inMsg.ProxyName, inMsg.RemoteAddr, inMsg.Error)
  135. if err != nil {
  136. ctl.Warn("[%s] start error: %v", inMsg.ProxyName, err)
  137. } else {
  138. ctl.Info("[%s] start proxy success", inMsg.ProxyName)
  139. }
  140. }
  141. func (ctl *Control) Close() error {
  142. ctl.mu.Lock()
  143. defer ctl.mu.Unlock()
  144. ctl.exit = true
  145. ctl.pm.CloseProxies()
  146. return nil
  147. }
  148. // login send a login message to server and wait for a loginResp message.
  149. func (ctl *Control) login() (err error) {
  150. if ctl.conn != nil {
  151. ctl.conn.Close()
  152. }
  153. if ctl.session != nil {
  154. ctl.session.Close()
  155. }
  156. conn, err := frpNet.ConnectServerByHttpProxy(g.GlbClientCfg.HttpProxy, g.GlbClientCfg.Protocol,
  157. fmt.Sprintf("%s:%d", g.GlbClientCfg.ServerAddr, g.GlbClientCfg.ServerPort))
  158. if err != nil {
  159. return err
  160. }
  161. defer func() {
  162. if err != nil {
  163. conn.Close()
  164. }
  165. }()
  166. if g.GlbClientCfg.TcpMux {
  167. session, errRet := smux.Client(conn, nil)
  168. if errRet != nil {
  169. return errRet
  170. }
  171. stream, errRet := session.OpenStream()
  172. if errRet != nil {
  173. session.Close()
  174. return errRet
  175. }
  176. conn = frpNet.WrapConn(stream)
  177. ctl.session = session
  178. }
  179. now := time.Now().Unix()
  180. ctl.loginMsg.PrivilegeKey = util.GetAuthKey(g.GlbClientCfg.Token, now)
  181. ctl.loginMsg.Timestamp = now
  182. ctl.loginMsg.RunId = ctl.runId
  183. if err = msg.WriteMsg(conn, ctl.loginMsg); err != nil {
  184. return err
  185. }
  186. var loginRespMsg msg.LoginResp
  187. conn.SetReadDeadline(time.Now().Add(connReadTimeout))
  188. if err = msg.ReadMsgInto(conn, &loginRespMsg); err != nil {
  189. return err
  190. }
  191. conn.SetReadDeadline(time.Time{})
  192. if loginRespMsg.Error != "" {
  193. err = fmt.Errorf("%s", loginRespMsg.Error)
  194. ctl.Error("%s", loginRespMsg.Error)
  195. return err
  196. }
  197. ctl.conn = conn
  198. // update runId got from server
  199. ctl.runId = loginRespMsg.RunId
  200. g.GlbClientCfg.ServerUdpPort = loginRespMsg.ServerUdpPort
  201. ctl.ClearLogPrefix()
  202. ctl.AddLogPrefix(loginRespMsg.RunId)
  203. ctl.Info("login to server success, get run id [%s], server udp port [%d]", loginRespMsg.RunId, loginRespMsg.ServerUdpPort)
  204. return nil
  205. }
  206. func (ctl *Control) connectServer() (conn frpNet.Conn, err error) {
  207. if g.GlbClientCfg.TcpMux {
  208. stream, errRet := ctl.session.OpenStream()
  209. if errRet != nil {
  210. err = errRet
  211. ctl.Warn("start new connection to server error: %v", err)
  212. return
  213. }
  214. conn = frpNet.WrapConn(stream)
  215. } else {
  216. conn, err = frpNet.ConnectServerByHttpProxy(g.GlbClientCfg.HttpProxy, g.GlbClientCfg.Protocol,
  217. fmt.Sprintf("%s:%d", g.GlbClientCfg.ServerAddr, g.GlbClientCfg.ServerPort))
  218. if err != nil {
  219. ctl.Warn("start new connection to server error: %v", err)
  220. return
  221. }
  222. }
  223. return
  224. }
  225. // reader read all messages from frps and send to readCh
  226. func (ctl *Control) reader() {
  227. defer func() {
  228. if err := recover(); err != nil {
  229. ctl.Error("panic error: %v", err)
  230. }
  231. }()
  232. defer ctl.readerShutdown.Done()
  233. defer close(ctl.closedCh)
  234. encReader := crypto.NewReader(ctl.conn, []byte(g.GlbClientCfg.Token))
  235. for {
  236. if m, err := msg.ReadMsg(encReader); err != nil {
  237. if err == io.EOF {
  238. ctl.Debug("read from control connection EOF")
  239. return
  240. } else {
  241. ctl.Warn("read error: %v", err)
  242. return
  243. }
  244. } else {
  245. ctl.readCh <- m
  246. }
  247. }
  248. }
  249. // writer writes messages got from sendCh to frps
  250. func (ctl *Control) writer() {
  251. defer ctl.writerShutdown.Done()
  252. encWriter, err := crypto.NewWriter(ctl.conn, []byte(g.GlbClientCfg.Token))
  253. if err != nil {
  254. ctl.conn.Error("crypto new writer error: %v", err)
  255. ctl.conn.Close()
  256. return
  257. }
  258. for {
  259. if m, ok := <-ctl.sendCh; !ok {
  260. ctl.Info("control writer is closing")
  261. return
  262. } else {
  263. if err := msg.WriteMsg(encWriter, m); err != nil {
  264. ctl.Warn("write message to control connection error: %v", err)
  265. return
  266. }
  267. }
  268. }
  269. }
  270. // msgHandler handles all channel events and do corresponding operations.
  271. func (ctl *Control) msgHandler() {
  272. defer func() {
  273. if err := recover(); err != nil {
  274. ctl.Error("panic error: %v", err)
  275. }
  276. }()
  277. defer ctl.msgHandlerShutdown.Done()
  278. hbSend := time.NewTicker(time.Duration(g.GlbClientCfg.HeartBeatInterval) * time.Second)
  279. defer hbSend.Stop()
  280. hbCheck := time.NewTicker(time.Second)
  281. defer hbCheck.Stop()
  282. ctl.lastPong = time.Now()
  283. for {
  284. select {
  285. case <-hbSend.C:
  286. // send heartbeat to server
  287. ctl.Debug("send heartbeat to server")
  288. ctl.sendCh <- &msg.Ping{}
  289. case <-hbCheck.C:
  290. if time.Since(ctl.lastPong) > time.Duration(g.GlbClientCfg.HeartBeatTimeout)*time.Second {
  291. ctl.Warn("heartbeat timeout")
  292. // let reader() stop
  293. ctl.conn.Close()
  294. return
  295. }
  296. case rawMsg, ok := <-ctl.readCh:
  297. if !ok {
  298. return
  299. }
  300. switch m := rawMsg.(type) {
  301. case *msg.ReqWorkConn:
  302. go ctl.HandleReqWorkConn(m)
  303. case *msg.NewProxyResp:
  304. ctl.HandleNewProxyResp(m)
  305. case *msg.Pong:
  306. ctl.lastPong = time.Now()
  307. ctl.Debug("receive heartbeat from server")
  308. }
  309. }
  310. }
  311. }
  312. // controler keep watching closedCh, start a new connection if previous control connection is closed.
  313. // If controler is notified by closedCh, reader and writer and handler will exit, then recall these functions.
  314. func (ctl *Control) worker() {
  315. go ctl.msgHandler()
  316. go ctl.reader()
  317. go ctl.writer()
  318. var err error
  319. maxDelayTime := 20 * time.Second
  320. delayTime := time.Second
  321. checkInterval := 60 * time.Second
  322. checkProxyTicker := time.NewTicker(checkInterval)
  323. for {
  324. select {
  325. case <-checkProxyTicker.C:
  326. // check which proxy registered failed and reregister it to server
  327. ctl.pm.CheckAndStartProxy([]string{ProxyStatusStartErr, ProxyStatusClosed})
  328. case _, ok := <-ctl.closedCh:
  329. // we won't get any variable from this channel
  330. if !ok {
  331. // close related channels and wait until other goroutines done
  332. close(ctl.readCh)
  333. ctl.readerShutdown.WaitDone()
  334. ctl.msgHandlerShutdown.WaitDone()
  335. close(ctl.sendCh)
  336. ctl.writerShutdown.WaitDone()
  337. ctl.pm.CloseProxies()
  338. // if ctl.exit is true, just exit
  339. ctl.mu.RLock()
  340. exit := ctl.exit
  341. ctl.mu.RUnlock()
  342. if exit {
  343. return
  344. }
  345. // loop util reconnecting to server success
  346. for {
  347. ctl.Info("try to reconnect to server...")
  348. err = ctl.login()
  349. if err != nil {
  350. ctl.Warn("reconnect to server error: %v", err)
  351. time.Sleep(delayTime)
  352. delayTime = delayTime * 2
  353. if delayTime > maxDelayTime {
  354. delayTime = maxDelayTime
  355. }
  356. continue
  357. }
  358. // reconnect success, init delayTime
  359. delayTime = time.Second
  360. break
  361. }
  362. // init related channels and variables
  363. ctl.sendCh = make(chan msg.Message, 100)
  364. ctl.readCh = make(chan msg.Message, 100)
  365. ctl.closedCh = make(chan int)
  366. ctl.readerShutdown = shutdown.New()
  367. ctl.writerShutdown = shutdown.New()
  368. ctl.msgHandlerShutdown = shutdown.New()
  369. ctl.pm.Reset(ctl.sendCh, ctl.runId)
  370. // previous work goroutines should be closed and start them here
  371. go ctl.msgHandler()
  372. go ctl.writer()
  373. go ctl.reader()
  374. // start all configured proxies
  375. ctl.pm.CheckAndStartProxy([]string{ProxyStatusNew, ProxyStatusClosed})
  376. checkProxyTicker.Stop()
  377. checkProxyTicker = time.NewTicker(checkInterval)
  378. }
  379. }
  380. }
  381. }
  382. func (ctl *Control) reloadConf(pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.ProxyConf) error {
  383. err := ctl.pm.Reload(pxyCfgs, visitorCfgs, true)
  384. return err
  385. }