service.go 11 KB

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