service.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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. "sync"
  22. "time"
  23. "github.com/fatedier/golib/crypto"
  24. "github.com/samber/lo"
  25. "github.com/fatedier/frp/client/proxy"
  26. "github.com/fatedier/frp/pkg/auth"
  27. v1 "github.com/fatedier/frp/pkg/config/v1"
  28. "github.com/fatedier/frp/pkg/msg"
  29. httppkg "github.com/fatedier/frp/pkg/util/http"
  30. "github.com/fatedier/frp/pkg/util/log"
  31. netpkg "github.com/fatedier/frp/pkg/util/net"
  32. "github.com/fatedier/frp/pkg/util/version"
  33. "github.com/fatedier/frp/pkg/util/wait"
  34. "github.com/fatedier/frp/pkg/util/xlog"
  35. )
  36. func init() {
  37. crypto.DefaultSalt = "frp"
  38. }
  39. // ServiceOptions contains options for creating a new client service.
  40. type ServiceOptions struct {
  41. Common *v1.ClientCommonConfig
  42. ProxyCfgs []v1.ProxyConfigurer
  43. VisitorCfgs []v1.VisitorConfigurer
  44. // ConfigFilePath is the path to the configuration file used to initialize.
  45. // If it is empty, it means that the configuration file is not used for initialization.
  46. // It may be initialized using command line parameters or called directly.
  47. ConfigFilePath string
  48. // ClientSpec is the client specification that control the client behavior.
  49. ClientSpec *msg.ClientSpec
  50. // ConnectorCreator is a function that creates a new connector to make connections to the server.
  51. // The Connector shields the underlying connection details, whether it is through TCP or QUIC connection,
  52. // and regardless of whether multiplexing is used.
  53. //
  54. // If it is not set, the default frpc connector will be used.
  55. // By using a custom Connector, it can be used to implement a VirtualClient, which connects to frps
  56. // through a pipe instead of a real physical connection.
  57. ConnectorCreator func(context.Context, *v1.ClientCommonConfig) Connector
  58. // HandleWorkConnCb is a callback function that is called when a new work connection is created.
  59. //
  60. // If it is not set, the default frpc implementation will be used.
  61. HandleWorkConnCb func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) bool
  62. }
  63. // setServiceOptionsDefault sets the default values for ServiceOptions.
  64. func setServiceOptionsDefault(options *ServiceOptions) {
  65. if options.Common != nil {
  66. options.Common.Complete()
  67. }
  68. if options.ConnectorCreator == nil {
  69. options.ConnectorCreator = NewConnector
  70. }
  71. }
  72. // Service is the client service that connects to frps and provides proxy services.
  73. type Service struct {
  74. ctlMu sync.RWMutex
  75. // manager control connection with server
  76. ctl *Control
  77. // Uniq id got from frps, it will be attached to loginMsg.
  78. runID string
  79. // Sets authentication based on selected method
  80. authSetter auth.Setter
  81. // web server for admin UI and apis
  82. webServer *httppkg.Server
  83. cfgMu sync.RWMutex
  84. common *v1.ClientCommonConfig
  85. proxyCfgs []v1.ProxyConfigurer
  86. visitorCfgs []v1.VisitorConfigurer
  87. clientSpec *msg.ClientSpec
  88. // The configuration file used to initialize this client, or an empty
  89. // string if no configuration file was used.
  90. configFilePath string
  91. // service context
  92. ctx context.Context
  93. // call cancel to stop service
  94. cancel context.CancelFunc
  95. gracefulShutdownDuration time.Duration
  96. connectorCreator func(context.Context, *v1.ClientCommonConfig) Connector
  97. handleWorkConnCb func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) bool
  98. }
  99. func NewService(options ServiceOptions) (*Service, error) {
  100. setServiceOptionsDefault(&options)
  101. var webServer *httppkg.Server
  102. if options.Common.WebServer.Port > 0 {
  103. ws, err := httppkg.NewServer(options.Common.WebServer)
  104. if err != nil {
  105. return nil, err
  106. }
  107. webServer = ws
  108. }
  109. s := &Service{
  110. ctx: context.Background(),
  111. authSetter: auth.NewAuthSetter(options.Common.Auth),
  112. webServer: webServer,
  113. common: options.Common,
  114. configFilePath: options.ConfigFilePath,
  115. proxyCfgs: options.ProxyCfgs,
  116. visitorCfgs: options.VisitorCfgs,
  117. clientSpec: options.ClientSpec,
  118. connectorCreator: options.ConnectorCreator,
  119. handleWorkConnCb: options.HandleWorkConnCb,
  120. }
  121. if webServer != nil {
  122. webServer.RouteRegister(s.registerRouteHandlers)
  123. }
  124. return s, nil
  125. }
  126. func (svr *Service) Run(ctx context.Context) error {
  127. ctx, cancel := context.WithCancel(ctx)
  128. svr.ctx = xlog.NewContext(ctx, xlog.FromContextSafe(ctx))
  129. svr.cancel = cancel
  130. // set custom DNSServer
  131. if svr.common.DNSServer != "" {
  132. netpkg.SetDefaultDNSAddress(svr.common.DNSServer)
  133. }
  134. // first login to frps
  135. svr.loopLoginUntilSuccess(10*time.Second, lo.FromPtr(svr.common.LoginFailExit))
  136. if svr.ctl == nil {
  137. return fmt.Errorf("the process exited because the first login to the server failed, and the loginFailExit feature is enabled")
  138. }
  139. go svr.keepControllerWorking()
  140. if svr.webServer != nil {
  141. go func() {
  142. log.Info("admin server listen on %s", svr.webServer.Address())
  143. if err := svr.webServer.Run(); err != nil {
  144. log.Warn("admin server exit with error: %v", err)
  145. }
  146. }()
  147. }
  148. <-svr.ctx.Done()
  149. svr.stop()
  150. return nil
  151. }
  152. func (svr *Service) keepControllerWorking() {
  153. <-svr.ctl.Done()
  154. // There is a situation where the login is successful but due to certain reasons,
  155. // the control immediately exits. It is necessary to limit the frequency of reconnection in this case.
  156. // The interval for the first three retries in 1 minute will be very short, and then it will increase exponentially.
  157. // The maximum interval is 20 seconds.
  158. wait.BackoffUntil(func() error {
  159. // loopLoginUntilSuccess is another layer of loop that will continuously attempt to
  160. // login to the server until successful.
  161. svr.loopLoginUntilSuccess(20*time.Second, false)
  162. if svr.ctl != nil {
  163. <-svr.ctl.Done()
  164. return errors.New("control is closed and try another loop")
  165. }
  166. // If the control is nil, it means that the login failed and the service is also closed.
  167. return nil
  168. }, wait.NewFastBackoffManager(
  169. wait.FastBackoffOptions{
  170. Duration: time.Second,
  171. Factor: 2,
  172. Jitter: 0.1,
  173. MaxDuration: 20 * time.Second,
  174. FastRetryCount: 3,
  175. FastRetryDelay: 200 * time.Millisecond,
  176. FastRetryWindow: time.Minute,
  177. FastRetryJitter: 0.5,
  178. },
  179. ), true, svr.ctx.Done())
  180. }
  181. // login creates a connection to frps and registers it self as a client
  182. // conn: control connection
  183. // session: if it's not nil, using tcp mux
  184. func (svr *Service) login() (conn net.Conn, connector Connector, err error) {
  185. xl := xlog.FromContextSafe(svr.ctx)
  186. connector = svr.connectorCreator(svr.ctx, svr.common)
  187. if err = connector.Open(); err != nil {
  188. return nil, nil, err
  189. }
  190. defer func() {
  191. if err != nil {
  192. connector.Close()
  193. }
  194. }()
  195. conn, err = connector.Connect()
  196. if err != nil {
  197. return
  198. }
  199. loginMsg := &msg.Login{
  200. Arch: runtime.GOARCH,
  201. Os: runtime.GOOS,
  202. PoolCount: svr.common.Transport.PoolCount,
  203. User: svr.common.User,
  204. Version: version.Full(),
  205. Timestamp: time.Now().Unix(),
  206. RunID: svr.runID,
  207. Metas: svr.common.Metadatas,
  208. }
  209. if svr.clientSpec != nil {
  210. loginMsg.ClientSpec = *svr.clientSpec
  211. }
  212. // Add auth
  213. if err = svr.authSetter.SetLogin(loginMsg); err != nil {
  214. return
  215. }
  216. if err = msg.WriteMsg(conn, loginMsg); err != nil {
  217. return
  218. }
  219. var loginRespMsg msg.LoginResp
  220. _ = conn.SetReadDeadline(time.Now().Add(10 * time.Second))
  221. if err = msg.ReadMsgInto(conn, &loginRespMsg); err != nil {
  222. return
  223. }
  224. _ = conn.SetReadDeadline(time.Time{})
  225. if loginRespMsg.Error != "" {
  226. err = fmt.Errorf("%s", loginRespMsg.Error)
  227. xl.Error("%s", loginRespMsg.Error)
  228. return
  229. }
  230. svr.runID = loginRespMsg.RunID
  231. xl.AddPrefix(xlog.LogPrefix{Name: "runID", Value: svr.runID})
  232. xl.Info("login to server success, get run id [%s]", loginRespMsg.RunID)
  233. return
  234. }
  235. func (svr *Service) loopLoginUntilSuccess(maxInterval time.Duration, firstLoginExit bool) {
  236. xl := xlog.FromContextSafe(svr.ctx)
  237. successCh := make(chan struct{})
  238. loginFunc := func() error {
  239. xl.Info("try to connect to server...")
  240. conn, connector, err := svr.login()
  241. if err != nil {
  242. xl.Warn("connect to server error: %v", err)
  243. if firstLoginExit {
  244. svr.cancel()
  245. }
  246. return err
  247. }
  248. svr.cfgMu.RLock()
  249. proxyCfgs := svr.proxyCfgs
  250. visitorCfgs := svr.visitorCfgs
  251. svr.cfgMu.RUnlock()
  252. connEncrypted := true
  253. if svr.clientSpec != nil && svr.clientSpec.Type == "ssh-tunnel" {
  254. connEncrypted = false
  255. }
  256. sessionCtx := &SessionContext{
  257. Common: svr.common,
  258. RunID: svr.runID,
  259. Conn: conn,
  260. ConnEncrypted: connEncrypted,
  261. AuthSetter: svr.authSetter,
  262. Connector: connector,
  263. }
  264. ctl, err := NewControl(svr.ctx, sessionCtx)
  265. if err != nil {
  266. conn.Close()
  267. xl.Error("NewControl error: %v", err)
  268. return err
  269. }
  270. ctl.SetInWorkConnCallback(svr.handleWorkConnCb)
  271. ctl.Run(proxyCfgs, visitorCfgs)
  272. // close and replace previous control
  273. svr.ctlMu.Lock()
  274. if svr.ctl != nil {
  275. svr.ctl.Close()
  276. }
  277. svr.ctl = ctl
  278. svr.ctlMu.Unlock()
  279. close(successCh)
  280. return nil
  281. }
  282. // try to reconnect to server until success
  283. wait.BackoffUntil(loginFunc, wait.NewFastBackoffManager(
  284. wait.FastBackoffOptions{
  285. Duration: time.Second,
  286. Factor: 2,
  287. Jitter: 0.1,
  288. MaxDuration: maxInterval,
  289. }),
  290. true,
  291. wait.MergeAndCloseOnAnyStopChannel(svr.ctx.Done(), successCh))
  292. }
  293. func (svr *Service) UpdateAllConfigurer(proxyCfgs []v1.ProxyConfigurer, visitorCfgs []v1.VisitorConfigurer) error {
  294. svr.cfgMu.Lock()
  295. svr.proxyCfgs = proxyCfgs
  296. svr.visitorCfgs = visitorCfgs
  297. svr.cfgMu.Unlock()
  298. svr.ctlMu.RLock()
  299. ctl := svr.ctl
  300. svr.ctlMu.RUnlock()
  301. if ctl != nil {
  302. return svr.ctl.UpdateAllConfigurer(proxyCfgs, visitorCfgs)
  303. }
  304. return nil
  305. }
  306. func (svr *Service) Close() {
  307. svr.GracefulClose(time.Duration(0))
  308. }
  309. func (svr *Service) GracefulClose(d time.Duration) {
  310. svr.gracefulShutdownDuration = d
  311. svr.cancel()
  312. }
  313. func (svr *Service) stop() {
  314. svr.ctlMu.Lock()
  315. defer svr.ctlMu.Unlock()
  316. if svr.ctl != nil {
  317. svr.ctl.GracefulClose(svr.gracefulShutdownDuration)
  318. svr.ctl = nil
  319. }
  320. }
  321. // TODO(fatedier): Use StatusExporter to provide query interfaces instead of directly using methods from the Service.
  322. func (svr *Service) GetProxyStatus(name string) (*proxy.WorkingStatus, error) {
  323. svr.ctlMu.RLock()
  324. ctl := svr.ctl
  325. svr.ctlMu.RUnlock()
  326. if ctl == nil {
  327. return nil, fmt.Errorf("control is not running")
  328. }
  329. ws, ok := ctl.pm.GetProxyStatus(name)
  330. if !ok {
  331. return nil, fmt.Errorf("proxy [%s] is not found", name)
  332. }
  333. return ws, nil
  334. }