service.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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. "errors"
  18. "fmt"
  19. "net"
  20. "runtime"
  21. "strconv"
  22. "sync"
  23. "time"
  24. "github.com/fatedier/golib/crypto"
  25. "github.com/samber/lo"
  26. "github.com/fatedier/frp/assets"
  27. "github.com/fatedier/frp/pkg/auth"
  28. v1 "github.com/fatedier/frp/pkg/config/v1"
  29. "github.com/fatedier/frp/pkg/msg"
  30. "github.com/fatedier/frp/pkg/util/log"
  31. "github.com/fatedier/frp/pkg/util/version"
  32. "github.com/fatedier/frp/pkg/util/wait"
  33. "github.com/fatedier/frp/pkg/util/xlog"
  34. )
  35. func init() {
  36. crypto.DefaultSalt = "frp"
  37. }
  38. // Service is a client service.
  39. type Service struct {
  40. // uniq id got from frps, attach it in loginMsg
  41. runID string
  42. // manager control connection with server
  43. ctl *Control
  44. ctlMu sync.RWMutex
  45. // Sets authentication based on selected method
  46. authSetter auth.Setter
  47. cfg *v1.ClientCommonConfig
  48. pxyCfgs []v1.ProxyConfigurer
  49. visitorCfgs []v1.VisitorConfigurer
  50. cfgMu sync.RWMutex
  51. // The configuration file used to initialize this client, or an empty
  52. // string if no configuration file was used.
  53. cfgFile string
  54. // service context
  55. ctx context.Context
  56. // call cancel to stop service
  57. cancel context.CancelFunc
  58. gracefulDuration time.Duration
  59. connectorCreator func(context.Context, *v1.ClientCommonConfig) Connector
  60. inWorkConnCallback func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) bool
  61. }
  62. func NewService(
  63. cfg *v1.ClientCommonConfig,
  64. pxyCfgs []v1.ProxyConfigurer,
  65. visitorCfgs []v1.VisitorConfigurer,
  66. cfgFile string,
  67. ) *Service {
  68. return &Service{
  69. authSetter: auth.NewAuthSetter(cfg.Auth),
  70. cfg: cfg,
  71. cfgFile: cfgFile,
  72. pxyCfgs: pxyCfgs,
  73. visitorCfgs: visitorCfgs,
  74. ctx: context.Background(),
  75. connectorCreator: NewConnector,
  76. }
  77. }
  78. func (svr *Service) SetConnectorCreator(h func(context.Context, *v1.ClientCommonConfig) Connector) {
  79. svr.connectorCreator = h
  80. }
  81. func (svr *Service) SetInWorkConnCallback(cb func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) bool) {
  82. svr.inWorkConnCallback = cb
  83. }
  84. func (svr *Service) GetController() *Control {
  85. svr.ctlMu.RLock()
  86. defer svr.ctlMu.RUnlock()
  87. return svr.ctl
  88. }
  89. func (svr *Service) Run(ctx context.Context) error {
  90. ctx, cancel := context.WithCancel(ctx)
  91. svr.ctx = xlog.NewContext(ctx, xlog.FromContextSafe(ctx))
  92. svr.cancel = cancel
  93. // set custom DNSServer
  94. if svr.cfg.DNSServer != "" {
  95. dnsAddr := svr.cfg.DNSServer
  96. if _, _, err := net.SplitHostPort(dnsAddr); err != nil {
  97. dnsAddr = net.JoinHostPort(dnsAddr, "53")
  98. }
  99. // Change default dns server for frpc
  100. net.DefaultResolver = &net.Resolver{
  101. PreferGo: true,
  102. Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
  103. return net.Dial("udp", dnsAddr)
  104. },
  105. }
  106. }
  107. // login to frps
  108. svr.loopLoginUntilSuccess(10*time.Second, lo.FromPtr(svr.cfg.LoginFailExit))
  109. if svr.ctl == nil {
  110. return fmt.Errorf("the process exited because the first login to the server failed, and the loginFailExit feature is enabled")
  111. }
  112. go svr.keepControllerWorking()
  113. if svr.cfg.WebServer.Port != 0 {
  114. // Init admin server assets
  115. assets.Load(svr.cfg.WebServer.AssetsDir)
  116. address := net.JoinHostPort(svr.cfg.WebServer.Addr, strconv.Itoa(svr.cfg.WebServer.Port))
  117. err := svr.RunAdminServer(address)
  118. if err != nil {
  119. log.Warn("run admin server error: %v", err)
  120. }
  121. log.Info("admin server listen on %s:%d", svr.cfg.WebServer.Addr, svr.cfg.WebServer.Port)
  122. }
  123. <-svr.ctx.Done()
  124. svr.stop()
  125. return nil
  126. }
  127. func (svr *Service) keepControllerWorking() {
  128. <-svr.ctl.Done()
  129. // There is a situation where the login is successful but due to certain reasons,
  130. // the control immediately exits. It is necessary to limit the frequency of reconnection in this case.
  131. // The interval for the first three retries in 1 minute will be very short, and then it will increase exponentially.
  132. // The maximum interval is 20 seconds.
  133. wait.BackoffUntil(func() error {
  134. // loopLoginUntilSuccess is another layer of loop that will continuously attempt to
  135. // login to the server until successful.
  136. svr.loopLoginUntilSuccess(20*time.Second, false)
  137. <-svr.ctl.Done()
  138. return errors.New("control is closed and try another loop")
  139. }, wait.NewFastBackoffManager(
  140. wait.FastBackoffOptions{
  141. Duration: time.Second,
  142. Factor: 2,
  143. Jitter: 0.1,
  144. MaxDuration: 20 * time.Second,
  145. FastRetryCount: 3,
  146. FastRetryDelay: 200 * time.Millisecond,
  147. FastRetryWindow: time.Minute,
  148. FastRetryJitter: 0.5,
  149. },
  150. ), true, svr.ctx.Done())
  151. }
  152. // login creates a connection to frps and registers it self as a client
  153. // conn: control connection
  154. // session: if it's not nil, using tcp mux
  155. func (svr *Service) login() (conn net.Conn, connector Connector, err error) {
  156. xl := xlog.FromContextSafe(svr.ctx)
  157. connector = svr.connectorCreator(svr.ctx, svr.cfg)
  158. if err = connector.Open(); err != nil {
  159. return nil, nil, err
  160. }
  161. defer func() {
  162. if err != nil {
  163. connector.Close()
  164. }
  165. }()
  166. conn, err = connector.Connect()
  167. if err != nil {
  168. return
  169. }
  170. loginMsg := &msg.Login{
  171. Arch: runtime.GOARCH,
  172. Os: runtime.GOOS,
  173. PoolCount: svr.cfg.Transport.PoolCount,
  174. User: svr.cfg.User,
  175. Version: version.Full(),
  176. Timestamp: time.Now().Unix(),
  177. RunID: svr.runID,
  178. Metas: svr.cfg.Metadatas,
  179. }
  180. // Add auth
  181. if err = svr.authSetter.SetLogin(loginMsg); err != nil {
  182. return
  183. }
  184. if err = msg.WriteMsg(conn, loginMsg); err != nil {
  185. return
  186. }
  187. var loginRespMsg msg.LoginResp
  188. _ = conn.SetReadDeadline(time.Now().Add(10 * time.Second))
  189. if err = msg.ReadMsgInto(conn, &loginRespMsg); err != nil {
  190. return
  191. }
  192. _ = conn.SetReadDeadline(time.Time{})
  193. if loginRespMsg.Error != "" {
  194. err = fmt.Errorf("%s", loginRespMsg.Error)
  195. xl.Error("%s", loginRespMsg.Error)
  196. return
  197. }
  198. svr.runID = loginRespMsg.RunID
  199. xl.AddPrefix(xlog.LogPrefix{Name: "runID", Value: svr.runID})
  200. xl.Info("login to server success, get run id [%s]", loginRespMsg.RunID)
  201. return
  202. }
  203. func (svr *Service) loopLoginUntilSuccess(maxInterval time.Duration, firstLoginExit bool) {
  204. xl := xlog.FromContextSafe(svr.ctx)
  205. successCh := make(chan struct{})
  206. loginFunc := func() error {
  207. xl.Info("try to connect to server...")
  208. conn, connector, err := svr.login()
  209. if err != nil {
  210. xl.Warn("connect to server error: %v", err)
  211. if firstLoginExit {
  212. svr.cancel()
  213. }
  214. return err
  215. }
  216. ctl, err := NewControl(svr.ctx, svr.runID, conn, connector,
  217. svr.cfg, svr.pxyCfgs, svr.visitorCfgs, svr.authSetter)
  218. if err != nil {
  219. conn.Close()
  220. xl.Error("NewControl error: %v", err)
  221. return err
  222. }
  223. ctl.SetInWorkConnCallback(svr.inWorkConnCallback)
  224. ctl.Run()
  225. // close and replace previous control
  226. svr.ctlMu.Lock()
  227. if svr.ctl != nil {
  228. svr.ctl.Close()
  229. }
  230. svr.ctl = ctl
  231. svr.ctlMu.Unlock()
  232. close(successCh)
  233. return nil
  234. }
  235. // try to reconnect to server until success
  236. wait.BackoffUntil(loginFunc, wait.NewFastBackoffManager(
  237. wait.FastBackoffOptions{
  238. Duration: time.Second,
  239. Factor: 2,
  240. Jitter: 0.1,
  241. MaxDuration: maxInterval,
  242. }),
  243. true,
  244. wait.MergeAndCloseOnAnyStopChannel(svr.ctx.Done(), successCh))
  245. }
  246. func (svr *Service) ReloadConf(pxyCfgs []v1.ProxyConfigurer, visitorCfgs []v1.VisitorConfigurer) error {
  247. svr.cfgMu.Lock()
  248. svr.pxyCfgs = pxyCfgs
  249. svr.visitorCfgs = visitorCfgs
  250. svr.cfgMu.Unlock()
  251. svr.ctlMu.RLock()
  252. ctl := svr.ctl
  253. svr.ctlMu.RUnlock()
  254. if ctl != nil {
  255. return svr.ctl.ReloadConf(pxyCfgs, visitorCfgs)
  256. }
  257. return nil
  258. }
  259. func (svr *Service) Close() {
  260. svr.GracefulClose(time.Duration(0))
  261. }
  262. func (svr *Service) GracefulClose(d time.Duration) {
  263. svr.gracefulDuration = d
  264. svr.cancel()
  265. }
  266. func (svr *Service) stop() {
  267. svr.ctlMu.Lock()
  268. defer svr.ctlMu.Unlock()
  269. if svr.ctl != nil {
  270. svr.ctl.GracefulClose(svr.gracefulDuration)
  271. svr.ctl = nil
  272. }
  273. }