control.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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.WithTimeout(time.Duration(ctl.clientCfg.DialServerTimeout)*time.Second),
  214. libdial.WithProxy(proxyType, addr),
  215. libdial.WithProxyAuth(auth),
  216. libdial.WithTLSConfig(tlsConfig),
  217. libdial.WithAfterHook(libdial.AfterHook{
  218. Hook: frpNet.DialHookCustomTLSHeadByte(tlsConfig != nil, ctl.clientCfg.DisableCustomTLSFirstByte),
  219. }),
  220. )
  221. conn, err = libdial.Dial(
  222. net.JoinHostPort(ctl.clientCfg.ServerAddr, strconv.Itoa(ctl.clientCfg.ServerPort)),
  223. dialOptions...,
  224. )
  225. if err != nil {
  226. xl.Warn("start new connection to server error: %v", err)
  227. return nil, err
  228. }
  229. }
  230. return
  231. }
  232. // reader read all messages from frps and send to readCh
  233. func (ctl *Control) reader() {
  234. xl := ctl.xl
  235. defer func() {
  236. if err := recover(); err != nil {
  237. xl.Error("panic error: %v", err)
  238. xl.Error(string(debug.Stack()))
  239. }
  240. }()
  241. defer ctl.readerShutdown.Done()
  242. defer close(ctl.closedCh)
  243. encReader := crypto.NewReader(ctl.conn, []byte(ctl.clientCfg.Token))
  244. for {
  245. m, err := msg.ReadMsg(encReader)
  246. if err != nil {
  247. if err == io.EOF {
  248. xl.Debug("read from control connection EOF")
  249. return
  250. }
  251. xl.Warn("read error: %v", err)
  252. ctl.conn.Close()
  253. return
  254. }
  255. ctl.readCh <- m
  256. }
  257. }
  258. // writer writes messages got from sendCh to frps
  259. func (ctl *Control) writer() {
  260. xl := ctl.xl
  261. defer ctl.writerShutdown.Done()
  262. encWriter, err := crypto.NewWriter(ctl.conn, []byte(ctl.clientCfg.Token))
  263. if err != nil {
  264. xl.Error("crypto new writer error: %v", err)
  265. ctl.conn.Close()
  266. return
  267. }
  268. for {
  269. m, ok := <-ctl.sendCh
  270. if !ok {
  271. xl.Info("control writer is closing")
  272. return
  273. }
  274. if err := msg.WriteMsg(encWriter, m); err != nil {
  275. xl.Warn("write message to control connection error: %v", err)
  276. return
  277. }
  278. }
  279. }
  280. // msgHandler handles all channel events and do corresponding operations.
  281. func (ctl *Control) msgHandler() {
  282. xl := ctl.xl
  283. defer func() {
  284. if err := recover(); err != nil {
  285. xl.Error("panic error: %v", err)
  286. xl.Error(string(debug.Stack()))
  287. }
  288. }()
  289. defer ctl.msgHandlerShutdown.Done()
  290. var hbSendCh <-chan time.Time
  291. // TODO(fatedier): disable heartbeat if TCPMux is enabled.
  292. // Just keep it here to keep compatible with old version frps.
  293. if ctl.clientCfg.HeartbeatInterval > 0 {
  294. hbSend := time.NewTicker(time.Duration(ctl.clientCfg.HeartbeatInterval) * time.Second)
  295. defer hbSend.Stop()
  296. hbSendCh = hbSend.C
  297. }
  298. var hbCheckCh <-chan time.Time
  299. // Check heartbeat timeout only if TCPMux is not enabled and users don't disable heartbeat feature.
  300. if ctl.clientCfg.HeartbeatInterval > 0 && ctl.clientCfg.HeartbeatTimeout > 0 && !ctl.clientCfg.TCPMux {
  301. hbCheck := time.NewTicker(time.Second)
  302. defer hbCheck.Stop()
  303. hbCheckCh = hbCheck.C
  304. }
  305. ctl.lastPong = time.Now()
  306. for {
  307. select {
  308. case <-hbSendCh:
  309. // send heartbeat to server
  310. xl.Debug("send heartbeat to server")
  311. pingMsg := &msg.Ping{}
  312. if err := ctl.authSetter.SetPing(pingMsg); err != nil {
  313. xl.Warn("error during ping authentication: %v", err)
  314. return
  315. }
  316. ctl.sendCh <- pingMsg
  317. case <-hbCheckCh:
  318. if time.Since(ctl.lastPong) > time.Duration(ctl.clientCfg.HeartbeatTimeout)*time.Second {
  319. xl.Warn("heartbeat timeout")
  320. // let reader() stop
  321. ctl.conn.Close()
  322. return
  323. }
  324. case rawMsg, ok := <-ctl.readCh:
  325. if !ok {
  326. return
  327. }
  328. switch m := rawMsg.(type) {
  329. case *msg.ReqWorkConn:
  330. go ctl.HandleReqWorkConn(m)
  331. case *msg.NewProxyResp:
  332. ctl.HandleNewProxyResp(m)
  333. case *msg.Pong:
  334. if m.Error != "" {
  335. xl.Error("Pong contains error: %s", m.Error)
  336. ctl.conn.Close()
  337. return
  338. }
  339. ctl.lastPong = time.Now()
  340. xl.Debug("receive heartbeat from server")
  341. }
  342. }
  343. }
  344. }
  345. // If controler is notified by closedCh, reader and writer and handler will exit
  346. func (ctl *Control) worker() {
  347. go ctl.msgHandler()
  348. go ctl.reader()
  349. go ctl.writer()
  350. select {
  351. case <-ctl.closedCh:
  352. // close related channels and wait until other goroutines done
  353. close(ctl.readCh)
  354. ctl.readerShutdown.WaitDone()
  355. ctl.msgHandlerShutdown.WaitDone()
  356. close(ctl.sendCh)
  357. ctl.writerShutdown.WaitDone()
  358. ctl.pm.Close()
  359. ctl.vm.Close()
  360. close(ctl.closedDoneCh)
  361. if ctl.session != nil {
  362. ctl.session.Close()
  363. }
  364. return
  365. }
  366. }
  367. func (ctl *Control) ReloadConf(pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.VisitorConf) error {
  368. ctl.vm.Reload(visitorCfgs)
  369. ctl.pm.Reload(pxyCfgs)
  370. return nil
  371. }