control.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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. "context"
  17. "crypto/tls"
  18. "io"
  19. "net"
  20. "runtime/debug"
  21. "strconv"
  22. "sync"
  23. "time"
  24. "github.com/fatedier/frp/client/proxy"
  25. "github.com/fatedier/frp/pkg/auth"
  26. "github.com/fatedier/frp/pkg/config"
  27. "github.com/fatedier/frp/pkg/msg"
  28. "github.com/fatedier/frp/pkg/transport"
  29. frpNet "github.com/fatedier/frp/pkg/util/net"
  30. "github.com/fatedier/frp/pkg/util/xlog"
  31. "github.com/fatedier/golib/control/shutdown"
  32. "github.com/fatedier/golib/crypto"
  33. libdial "github.com/fatedier/golib/net/dial"
  34. fmux "github.com/hashicorp/yamux"
  35. )
  36. type Control struct {
  37. // uniq id got from frps, attach it in loginMsg
  38. runID string
  39. // manage all proxies
  40. pxyCfgs map[string]config.ProxyConf
  41. pm *proxy.Manager
  42. // manage all visitors
  43. vm *VisitorManager
  44. // control connection
  45. conn net.Conn
  46. // tcp stream multiplexing, if enabled
  47. session *fmux.Session
  48. // put a message in this channel to send it over control connection to server
  49. sendCh chan (msg.Message)
  50. // read from this channel to get the next message sent by server
  51. readCh chan (msg.Message)
  52. // goroutines can block by reading from this channel, it will be closed only in reader() when control connection is closed
  53. closedCh chan struct{}
  54. closedDoneCh chan struct{}
  55. // last time got the Pong message
  56. lastPong time.Time
  57. // The client configuration
  58. clientCfg config.ClientCommonConf
  59. readerShutdown *shutdown.Shutdown
  60. writerShutdown *shutdown.Shutdown
  61. msgHandlerShutdown *shutdown.Shutdown
  62. // The UDP port that the server is listening on
  63. serverUDPPort int
  64. mu sync.RWMutex
  65. xl *xlog.Logger
  66. // service context
  67. ctx context.Context
  68. // sets authentication based on selected method
  69. authSetter auth.Setter
  70. }
  71. func NewControl(ctx context.Context, runID string, conn net.Conn, session *fmux.Session,
  72. clientCfg config.ClientCommonConf,
  73. pxyCfgs map[string]config.ProxyConf,
  74. visitorCfgs map[string]config.VisitorConf,
  75. serverUDPPort int,
  76. authSetter auth.Setter) *Control {
  77. // new xlog instance
  78. ctl := &Control{
  79. runID: runID,
  80. conn: conn,
  81. session: session,
  82. pxyCfgs: pxyCfgs,
  83. sendCh: make(chan msg.Message, 100),
  84. readCh: make(chan msg.Message, 100),
  85. closedCh: make(chan struct{}),
  86. closedDoneCh: make(chan struct{}),
  87. clientCfg: clientCfg,
  88. readerShutdown: shutdown.New(),
  89. writerShutdown: shutdown.New(),
  90. msgHandlerShutdown: shutdown.New(),
  91. serverUDPPort: serverUDPPort,
  92. xl: xlog.FromContextSafe(ctx),
  93. ctx: ctx,
  94. authSetter: authSetter,
  95. }
  96. ctl.pm = proxy.NewManager(ctl.ctx, ctl.sendCh, clientCfg, serverUDPPort)
  97. ctl.vm = NewVisitorManager(ctl.ctx, ctl)
  98. ctl.vm.Reload(visitorCfgs)
  99. return ctl
  100. }
  101. func (ctl *Control) Run() {
  102. go ctl.worker()
  103. // start all proxies
  104. ctl.pm.Reload(ctl.pxyCfgs)
  105. // start all visitors
  106. go ctl.vm.Run()
  107. return
  108. }
  109. func (ctl *Control) HandleReqWorkConn(inMsg *msg.ReqWorkConn) {
  110. xl := ctl.xl
  111. workConn, err := ctl.connectServer()
  112. if err != nil {
  113. return
  114. }
  115. m := &msg.NewWorkConn{
  116. RunID: ctl.runID,
  117. }
  118. if err = ctl.authSetter.SetNewWorkConn(m); err != nil {
  119. xl.Warn("error during NewWorkConn authentication: %v", err)
  120. return
  121. }
  122. if err = msg.WriteMsg(workConn, m); err != nil {
  123. xl.Warn("work connection write to server error: %v", err)
  124. workConn.Close()
  125. return
  126. }
  127. var startMsg msg.StartWorkConn
  128. if err = msg.ReadMsgInto(workConn, &startMsg); err != nil {
  129. xl.Error("work connection closed before response StartWorkConn message: %v", err)
  130. workConn.Close()
  131. return
  132. }
  133. if startMsg.Error != "" {
  134. xl.Error("StartWorkConn contains error: %s", startMsg.Error)
  135. workConn.Close()
  136. return
  137. }
  138. // dispatch this work connection to related proxy
  139. ctl.pm.HandleWorkConn(startMsg.ProxyName, workConn, &startMsg)
  140. }
  141. func (ctl *Control) HandleNewProxyResp(inMsg *msg.NewProxyResp) {
  142. xl := ctl.xl
  143. // Server will return NewProxyResp message to each NewProxy message.
  144. // Start a new proxy handler if no error got
  145. err := ctl.pm.StartProxy(inMsg.ProxyName, inMsg.RemoteAddr, inMsg.Error)
  146. if err != nil {
  147. xl.Warn("[%s] start error: %v", inMsg.ProxyName, err)
  148. } else {
  149. xl.Info("[%s] start proxy success", inMsg.ProxyName)
  150. }
  151. }
  152. func (ctl *Control) Close() error {
  153. return ctl.GracefulClose(0)
  154. }
  155. func (ctl *Control) GracefulClose(d time.Duration) error {
  156. ctl.pm.Close()
  157. ctl.vm.Close()
  158. time.Sleep(d)
  159. ctl.conn.Close()
  160. if ctl.session != nil {
  161. ctl.session.Close()
  162. }
  163. return nil
  164. }
  165. // ClosedDoneCh returns a channel which will be closed after all resources are released
  166. func (ctl *Control) ClosedDoneCh() <-chan struct{} {
  167. return ctl.closedDoneCh
  168. }
  169. // connectServer return a new connection to frps
  170. func (ctl *Control) connectServer() (conn net.Conn, err error) {
  171. xl := ctl.xl
  172. if ctl.clientCfg.TCPMux {
  173. stream, errRet := ctl.session.OpenStream()
  174. if errRet != nil {
  175. err = errRet
  176. xl.Warn("start new connection to server error: %v", err)
  177. return
  178. }
  179. conn = stream
  180. } else {
  181. var tlsConfig *tls.Config
  182. sn := ctl.clientCfg.TLSServerName
  183. if sn == "" {
  184. sn = ctl.clientCfg.ServerAddr
  185. }
  186. if ctl.clientCfg.TLSEnable {
  187. tlsConfig, err = transport.NewClientTLSConfig(
  188. ctl.clientCfg.TLSCertFile,
  189. ctl.clientCfg.TLSKeyFile,
  190. ctl.clientCfg.TLSTrustedCaFile,
  191. sn)
  192. if err != nil {
  193. xl.Warn("fail to build tls configuration when connecting to server, err: %v", err)
  194. return
  195. }
  196. }
  197. proxyType, addr, auth, err := libdial.ParseProxyURL(ctl.clientCfg.HTTPProxy)
  198. if err != nil {
  199. xl.Error("fail to parse proxy url")
  200. return nil, err
  201. }
  202. dialOptions := []libdial.DialOption{}
  203. protocol := ctl.clientCfg.Protocol
  204. if protocol == "websocket" {
  205. protocol = "tcp"
  206. dialOptions = append(dialOptions, libdial.WithAfterHook(libdial.AfterHook{Hook: frpNet.DialHookWebsocket()}))
  207. }
  208. if ctl.clientCfg.ConnectServerLocalIP != "" {
  209. dialOptions = append(dialOptions, libdial.WithLocalAddr(ctl.clientCfg.ConnectServerLocalIP))
  210. }
  211. dialOptions = append(dialOptions,
  212. libdial.WithProtocol(protocol),
  213. libdial.WithProxy(proxyType, addr),
  214. libdial.WithProxyAuth(auth),
  215. libdial.WithTLSConfig(tlsConfig),
  216. libdial.WithAfterHook(libdial.AfterHook{
  217. Hook: frpNet.DialHookCustomTLSHeadByte(tlsConfig != nil, ctl.clientCfg.DisableCustomTLSFirstByte),
  218. }),
  219. )
  220. conn, err = libdial.Dial(
  221. net.JoinHostPort(ctl.clientCfg.ServerAddr, strconv.Itoa(ctl.clientCfg.ServerPort)),
  222. dialOptions...,
  223. )
  224. if err != nil {
  225. xl.Warn("start new connection to server error: %v", err)
  226. return nil, err
  227. }
  228. }
  229. return
  230. }
  231. // reader read all messages from frps and send to readCh
  232. func (ctl *Control) reader() {
  233. xl := ctl.xl
  234. defer func() {
  235. if err := recover(); err != nil {
  236. xl.Error("panic error: %v", err)
  237. xl.Error(string(debug.Stack()))
  238. }
  239. }()
  240. defer ctl.readerShutdown.Done()
  241. defer close(ctl.closedCh)
  242. encReader := crypto.NewReader(ctl.conn, []byte(ctl.clientCfg.Token))
  243. for {
  244. m, err := msg.ReadMsg(encReader)
  245. if err != nil {
  246. if err == io.EOF {
  247. xl.Debug("read from control connection EOF")
  248. return
  249. }
  250. xl.Warn("read error: %v", err)
  251. ctl.conn.Close()
  252. return
  253. }
  254. ctl.readCh <- m
  255. }
  256. }
  257. // writer writes messages got from sendCh to frps
  258. func (ctl *Control) writer() {
  259. xl := ctl.xl
  260. defer ctl.writerShutdown.Done()
  261. encWriter, err := crypto.NewWriter(ctl.conn, []byte(ctl.clientCfg.Token))
  262. if err != nil {
  263. xl.Error("crypto new writer error: %v", err)
  264. ctl.conn.Close()
  265. return
  266. }
  267. for {
  268. m, ok := <-ctl.sendCh
  269. if !ok {
  270. xl.Info("control writer is closing")
  271. return
  272. }
  273. if err := msg.WriteMsg(encWriter, m); err != nil {
  274. xl.Warn("write message to control connection error: %v", err)
  275. return
  276. }
  277. }
  278. }
  279. // msgHandler handles all channel events and do corresponding operations.
  280. func (ctl *Control) msgHandler() {
  281. xl := ctl.xl
  282. defer func() {
  283. if err := recover(); err != nil {
  284. xl.Error("panic error: %v", err)
  285. xl.Error(string(debug.Stack()))
  286. }
  287. }()
  288. defer ctl.msgHandlerShutdown.Done()
  289. var hbSendCh <-chan time.Time
  290. // TODO(fatedier): disable heartbeat if TCPMux is enabled.
  291. // Just keep it here to keep compatible with old version frps.
  292. if ctl.clientCfg.HeartbeatInterval > 0 {
  293. hbSend := time.NewTicker(time.Duration(ctl.clientCfg.HeartbeatInterval) * time.Second)
  294. defer hbSend.Stop()
  295. hbSendCh = hbSend.C
  296. }
  297. var hbCheckCh <-chan time.Time
  298. // Check heartbeat timeout only if TCPMux is not enabled and users don't disable heartbeat feature.
  299. if ctl.clientCfg.HeartbeatInterval > 0 && ctl.clientCfg.HeartbeatTimeout > 0 && !ctl.clientCfg.TCPMux {
  300. hbCheck := time.NewTicker(time.Second)
  301. defer hbCheck.Stop()
  302. hbCheckCh = hbCheck.C
  303. }
  304. ctl.lastPong = time.Now()
  305. for {
  306. select {
  307. case <-hbSendCh:
  308. // send heartbeat to server
  309. xl.Debug("send heartbeat to server")
  310. pingMsg := &msg.Ping{}
  311. if err := ctl.authSetter.SetPing(pingMsg); err != nil {
  312. xl.Warn("error during ping authentication: %v", err)
  313. return
  314. }
  315. ctl.sendCh <- pingMsg
  316. case <-hbCheckCh:
  317. if time.Since(ctl.lastPong) > time.Duration(ctl.clientCfg.HeartbeatTimeout)*time.Second {
  318. xl.Warn("heartbeat timeout")
  319. // let reader() stop
  320. ctl.conn.Close()
  321. return
  322. }
  323. case rawMsg, ok := <-ctl.readCh:
  324. if !ok {
  325. return
  326. }
  327. switch m := rawMsg.(type) {
  328. case *msg.ReqWorkConn:
  329. go ctl.HandleReqWorkConn(m)
  330. case *msg.NewProxyResp:
  331. ctl.HandleNewProxyResp(m)
  332. case *msg.Pong:
  333. if m.Error != "" {
  334. xl.Error("Pong contains error: %s", m.Error)
  335. ctl.conn.Close()
  336. return
  337. }
  338. ctl.lastPong = time.Now()
  339. xl.Debug("receive heartbeat from server")
  340. }
  341. }
  342. }
  343. }
  344. // If controler is notified by closedCh, reader and writer and handler will exit
  345. func (ctl *Control) worker() {
  346. go ctl.msgHandler()
  347. go ctl.reader()
  348. go ctl.writer()
  349. select {
  350. case <-ctl.closedCh:
  351. // close related channels and wait until other goroutines done
  352. close(ctl.readCh)
  353. ctl.readerShutdown.WaitDone()
  354. ctl.msgHandlerShutdown.WaitDone()
  355. close(ctl.sendCh)
  356. ctl.writerShutdown.WaitDone()
  357. ctl.pm.Close()
  358. ctl.vm.Close()
  359. close(ctl.closedDoneCh)
  360. if ctl.session != nil {
  361. ctl.session.Close()
  362. }
  363. return
  364. }
  365. }
  366. func (ctl *Control) ReloadConf(pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.VisitorConf) error {
  367. ctl.vm.Reload(visitorCfgs)
  368. ctl.pm.Reload(pxyCfgs)
  369. return nil
  370. }