service.go 12 KB

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