2
0

service.go 12 KB

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