service.go 11 KB

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