service.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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. "crypto/tls"
  18. "errors"
  19. "fmt"
  20. "io"
  21. "net"
  22. "runtime"
  23. "strconv"
  24. "strings"
  25. "sync"
  26. "time"
  27. "github.com/fatedier/golib/crypto"
  28. libdial "github.com/fatedier/golib/net/dial"
  29. fmux "github.com/hashicorp/yamux"
  30. quic "github.com/quic-go/quic-go"
  31. "github.com/samber/lo"
  32. "github.com/fatedier/frp/assets"
  33. "github.com/fatedier/frp/pkg/auth"
  34. v1 "github.com/fatedier/frp/pkg/config/v1"
  35. "github.com/fatedier/frp/pkg/msg"
  36. "github.com/fatedier/frp/pkg/transport"
  37. "github.com/fatedier/frp/pkg/util/log"
  38. utilnet "github.com/fatedier/frp/pkg/util/net"
  39. "github.com/fatedier/frp/pkg/util/version"
  40. "github.com/fatedier/frp/pkg/util/wait"
  41. "github.com/fatedier/frp/pkg/util/xlog"
  42. )
  43. func init() {
  44. crypto.DefaultSalt = "frp"
  45. }
  46. // Service is a client service.
  47. type Service struct {
  48. // uniq id got from frps, attach it in loginMsg
  49. runID string
  50. // manager control connection with server
  51. ctl *Control
  52. ctlMu sync.RWMutex
  53. // Sets authentication based on selected method
  54. authSetter auth.Setter
  55. cfg *v1.ClientCommonConfig
  56. pxyCfgs []v1.ProxyConfigurer
  57. visitorCfgs []v1.VisitorConfigurer
  58. cfgMu sync.RWMutex
  59. // The configuration file used to initialize this client, or an empty
  60. // string if no configuration file was used.
  61. cfgFile string
  62. // service context
  63. ctx context.Context
  64. // call cancel to stop service
  65. cancel context.CancelFunc
  66. gracefulDuration time.Duration
  67. }
  68. func NewService(
  69. cfg *v1.ClientCommonConfig,
  70. pxyCfgs []v1.ProxyConfigurer,
  71. visitorCfgs []v1.VisitorConfigurer,
  72. cfgFile string,
  73. ) *Service {
  74. return &Service{
  75. authSetter: auth.NewAuthSetter(cfg.Auth),
  76. cfg: cfg,
  77. cfgFile: cfgFile,
  78. pxyCfgs: pxyCfgs,
  79. visitorCfgs: visitorCfgs,
  80. ctx: context.Background(),
  81. }
  82. }
  83. func (svr *Service) GetController() *Control {
  84. svr.ctlMu.RLock()
  85. defer svr.ctlMu.RUnlock()
  86. return svr.ctl
  87. }
  88. func (svr *Service) Run(ctx context.Context) error {
  89. ctx, cancel := context.WithCancel(ctx)
  90. svr.ctx = xlog.NewContext(ctx, xlog.New())
  91. svr.cancel = cancel
  92. // set custom DNSServer
  93. if svr.cfg.DNSServer != "" {
  94. dnsAddr := svr.cfg.DNSServer
  95. if _, _, err := net.SplitHostPort(dnsAddr); err != nil {
  96. dnsAddr = net.JoinHostPort(dnsAddr, "53")
  97. }
  98. // Change default dns server for frpc
  99. net.DefaultResolver = &net.Resolver{
  100. PreferGo: true,
  101. Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
  102. return net.Dial("udp", dnsAddr)
  103. },
  104. }
  105. }
  106. // login to frps
  107. svr.loopLoginUntilSuccess(10*time.Second, lo.FromPtr(svr.cfg.LoginFailExit))
  108. if svr.ctl == nil {
  109. return fmt.Errorf("the process exited because the first login to the server failed, and the loginFailExit feature is enabled")
  110. }
  111. go svr.keepControllerWorking()
  112. if svr.cfg.WebServer.Port != 0 {
  113. // Init admin server assets
  114. assets.Load(svr.cfg.WebServer.AssetsDir)
  115. address := net.JoinHostPort(svr.cfg.WebServer.Addr, strconv.Itoa(svr.cfg.WebServer.Port))
  116. err := svr.RunAdminServer(address)
  117. if err != nil {
  118. log.Warn("run admin server error: %v", err)
  119. }
  120. log.Info("admin server listen on %s:%d", svr.cfg.WebServer.Addr, svr.cfg.WebServer.Port)
  121. }
  122. <-svr.ctx.Done()
  123. svr.stop()
  124. return nil
  125. }
  126. func (svr *Service) keepControllerWorking() {
  127. <-svr.ctl.Done()
  128. // There is a situation where the login is successful but due to certain reasons,
  129. // the control immediately exits. It is necessary to limit the frequency of reconnection in this case.
  130. // The interval for the first three retries in 1 minute will be very short, and then it will increase exponentially.
  131. // The maximum interval is 20 seconds.
  132. wait.BackoffUntil(func() error {
  133. // loopLoginUntilSuccess is another layer of loop that will continuously attempt to
  134. // login to the server until successful.
  135. svr.loopLoginUntilSuccess(20*time.Second, false)
  136. <-svr.ctl.Done()
  137. return errors.New("control is closed and try another loop")
  138. }, wait.NewFastBackoffManager(
  139. wait.FastBackoffOptions{
  140. Duration: time.Second,
  141. Factor: 2,
  142. Jitter: 0.1,
  143. MaxDuration: 20 * time.Second,
  144. FastRetryCount: 3,
  145. FastRetryDelay: 200 * time.Millisecond,
  146. FastRetryWindow: time.Minute,
  147. FastRetryJitter: 0.5,
  148. },
  149. ), true, svr.ctx.Done())
  150. }
  151. // login creates a connection to frps and registers it self as a client
  152. // conn: control connection
  153. // session: if it's not nil, using tcp mux
  154. func (svr *Service) login() (conn net.Conn, cm *ConnectionManager, err error) {
  155. xl := xlog.FromContextSafe(svr.ctx)
  156. cm = NewConnectionManager(svr.ctx, svr.cfg)
  157. if err = cm.OpenConnection(); err != nil {
  158. return nil, nil, err
  159. }
  160. defer func() {
  161. if err != nil {
  162. cm.Close()
  163. }
  164. }()
  165. conn, err = cm.Connect()
  166. if err != nil {
  167. return
  168. }
  169. loginMsg := &msg.Login{
  170. Arch: runtime.GOARCH,
  171. Os: runtime.GOOS,
  172. PoolCount: svr.cfg.Transport.PoolCount,
  173. User: svr.cfg.User,
  174. Version: version.Full(),
  175. Timestamp: time.Now().Unix(),
  176. RunID: svr.runID,
  177. Metas: svr.cfg.Metadatas,
  178. }
  179. // Add auth
  180. if err = svr.authSetter.SetLogin(loginMsg); err != nil {
  181. return
  182. }
  183. if err = msg.WriteMsg(conn, loginMsg); err != nil {
  184. return
  185. }
  186. var loginRespMsg msg.LoginResp
  187. _ = conn.SetReadDeadline(time.Now().Add(10 * time.Second))
  188. if err = msg.ReadMsgInto(conn, &loginRespMsg); err != nil {
  189. return
  190. }
  191. _ = conn.SetReadDeadline(time.Time{})
  192. if loginRespMsg.Error != "" {
  193. err = fmt.Errorf("%s", loginRespMsg.Error)
  194. xl.Error("%s", loginRespMsg.Error)
  195. return
  196. }
  197. svr.runID = loginRespMsg.RunID
  198. xl.ResetPrefixes()
  199. xl.AppendPrefix(svr.runID)
  200. xl.Info("login to server success, get run id [%s]", loginRespMsg.RunID)
  201. return
  202. }
  203. func (svr *Service) loopLoginUntilSuccess(maxInterval time.Duration, firstLoginExit bool) {
  204. xl := xlog.FromContextSafe(svr.ctx)
  205. successCh := make(chan struct{})
  206. loginFunc := func() error {
  207. xl.Info("try to connect to server...")
  208. conn, cm, err := svr.login()
  209. if err != nil {
  210. xl.Warn("connect to server error: %v", err)
  211. if firstLoginExit {
  212. svr.cancel()
  213. }
  214. return err
  215. }
  216. ctl, err := NewControl(svr.ctx, svr.runID, conn, cm,
  217. svr.cfg, svr.pxyCfgs, svr.visitorCfgs, svr.authSetter)
  218. if err != nil {
  219. conn.Close()
  220. xl.Error("NewControl error: %v", err)
  221. return err
  222. }
  223. ctl.Run()
  224. // close and replace previous control
  225. svr.ctlMu.Lock()
  226. if svr.ctl != nil {
  227. svr.ctl.Close()
  228. }
  229. svr.ctl = ctl
  230. svr.ctlMu.Unlock()
  231. close(successCh)
  232. return nil
  233. }
  234. // try to reconnect to server until success
  235. wait.BackoffUntil(loginFunc, wait.NewFastBackoffManager(
  236. wait.FastBackoffOptions{
  237. Duration: time.Second,
  238. Factor: 2,
  239. Jitter: 0.1,
  240. MaxDuration: maxInterval,
  241. }),
  242. true,
  243. wait.MergeAndCloseOnAnyStopChannel(svr.ctx.Done(), successCh))
  244. }
  245. func (svr *Service) ReloadConf(pxyCfgs []v1.ProxyConfigurer, visitorCfgs []v1.VisitorConfigurer) error {
  246. svr.cfgMu.Lock()
  247. svr.pxyCfgs = pxyCfgs
  248. svr.visitorCfgs = visitorCfgs
  249. svr.cfgMu.Unlock()
  250. svr.ctlMu.RLock()
  251. ctl := svr.ctl
  252. svr.ctlMu.RUnlock()
  253. if ctl != nil {
  254. return svr.ctl.ReloadConf(pxyCfgs, visitorCfgs)
  255. }
  256. return nil
  257. }
  258. func (svr *Service) Close() {
  259. svr.GracefulClose(time.Duration(0))
  260. }
  261. func (svr *Service) GracefulClose(d time.Duration) {
  262. svr.gracefulDuration = d
  263. svr.cancel()
  264. }
  265. func (svr *Service) stop() {
  266. svr.ctlMu.Lock()
  267. defer svr.ctlMu.Unlock()
  268. if svr.ctl != nil {
  269. svr.ctl.GracefulClose(svr.gracefulDuration)
  270. svr.ctl = nil
  271. }
  272. }
  273. // ConnectionManager is a wrapper for establishing connections to the server.
  274. type ConnectionManager struct {
  275. ctx context.Context
  276. cfg *v1.ClientCommonConfig
  277. muxSession *fmux.Session
  278. quicConn quic.Connection
  279. }
  280. func NewConnectionManager(ctx context.Context, cfg *v1.ClientCommonConfig) *ConnectionManager {
  281. return &ConnectionManager{
  282. ctx: ctx,
  283. cfg: cfg,
  284. }
  285. }
  286. // OpenConnection opens a underlying connection to the server.
  287. // The underlying connection is either a TCP connection or a QUIC connection.
  288. // After the underlying connection is established, you can call Connect() to get a stream.
  289. // If TCPMux isn't enabled, the underlying connection is nil, you will get a new real TCP connection every time you call Connect().
  290. func (cm *ConnectionManager) OpenConnection() error {
  291. xl := xlog.FromContextSafe(cm.ctx)
  292. // special for quic
  293. if strings.EqualFold(cm.cfg.Transport.Protocol, "quic") {
  294. var tlsConfig *tls.Config
  295. var err error
  296. sn := cm.cfg.Transport.TLS.ServerName
  297. if sn == "" {
  298. sn = cm.cfg.ServerAddr
  299. }
  300. if lo.FromPtr(cm.cfg.Transport.TLS.Enable) {
  301. tlsConfig, err = transport.NewClientTLSConfig(
  302. cm.cfg.Transport.TLS.CertFile,
  303. cm.cfg.Transport.TLS.KeyFile,
  304. cm.cfg.Transport.TLS.TrustedCaFile,
  305. sn)
  306. } else {
  307. tlsConfig, err = transport.NewClientTLSConfig("", "", "", sn)
  308. }
  309. if err != nil {
  310. xl.Warn("fail to build tls configuration, err: %v", err)
  311. return err
  312. }
  313. tlsConfig.NextProtos = []string{"frp"}
  314. conn, err := quic.DialAddr(
  315. cm.ctx,
  316. net.JoinHostPort(cm.cfg.ServerAddr, strconv.Itoa(cm.cfg.ServerPort)),
  317. tlsConfig, &quic.Config{
  318. MaxIdleTimeout: time.Duration(cm.cfg.Transport.QUIC.MaxIdleTimeout) * time.Second,
  319. MaxIncomingStreams: int64(cm.cfg.Transport.QUIC.MaxIncomingStreams),
  320. KeepAlivePeriod: time.Duration(cm.cfg.Transport.QUIC.KeepalivePeriod) * time.Second,
  321. })
  322. if err != nil {
  323. return err
  324. }
  325. cm.quicConn = conn
  326. return nil
  327. }
  328. if !lo.FromPtr(cm.cfg.Transport.TCPMux) {
  329. return nil
  330. }
  331. conn, err := cm.realConnect()
  332. if err != nil {
  333. return err
  334. }
  335. fmuxCfg := fmux.DefaultConfig()
  336. fmuxCfg.KeepAliveInterval = time.Duration(cm.cfg.Transport.TCPMuxKeepaliveInterval) * time.Second
  337. fmuxCfg.LogOutput = io.Discard
  338. fmuxCfg.MaxStreamWindowSize = 6 * 1024 * 1024
  339. session, err := fmux.Client(conn, fmuxCfg)
  340. if err != nil {
  341. return err
  342. }
  343. cm.muxSession = session
  344. return nil
  345. }
  346. // Connect returns a stream from the underlying connection, or a new TCP connection if TCPMux isn't enabled.
  347. func (cm *ConnectionManager) Connect() (net.Conn, error) {
  348. if cm.quicConn != nil {
  349. stream, err := cm.quicConn.OpenStreamSync(context.Background())
  350. if err != nil {
  351. return nil, err
  352. }
  353. return utilnet.QuicStreamToNetConn(stream, cm.quicConn), nil
  354. } else if cm.muxSession != nil {
  355. stream, err := cm.muxSession.OpenStream()
  356. if err != nil {
  357. return nil, err
  358. }
  359. return stream, nil
  360. }
  361. return cm.realConnect()
  362. }
  363. func (cm *ConnectionManager) realConnect() (net.Conn, error) {
  364. xl := xlog.FromContextSafe(cm.ctx)
  365. var tlsConfig *tls.Config
  366. var err error
  367. tlsEnable := lo.FromPtr(cm.cfg.Transport.TLS.Enable)
  368. if cm.cfg.Transport.Protocol == "wss" {
  369. tlsEnable = true
  370. }
  371. if tlsEnable {
  372. sn := cm.cfg.Transport.TLS.ServerName
  373. if sn == "" {
  374. sn = cm.cfg.ServerAddr
  375. }
  376. tlsConfig, err = transport.NewClientTLSConfig(
  377. cm.cfg.Transport.TLS.CertFile,
  378. cm.cfg.Transport.TLS.KeyFile,
  379. cm.cfg.Transport.TLS.TrustedCaFile,
  380. sn)
  381. if err != nil {
  382. xl.Warn("fail to build tls configuration, err: %v", err)
  383. return nil, err
  384. }
  385. }
  386. proxyType, addr, auth, err := libdial.ParseProxyURL(cm.cfg.Transport.ProxyURL)
  387. if err != nil {
  388. xl.Error("fail to parse proxy url")
  389. return nil, err
  390. }
  391. dialOptions := []libdial.DialOption{}
  392. protocol := cm.cfg.Transport.Protocol
  393. switch protocol {
  394. case "websocket":
  395. protocol = "tcp"
  396. dialOptions = append(dialOptions, libdial.WithAfterHook(libdial.AfterHook{Hook: utilnet.DialHookWebsocket(protocol, "")}))
  397. dialOptions = append(dialOptions, libdial.WithAfterHook(libdial.AfterHook{
  398. Hook: utilnet.DialHookCustomTLSHeadByte(tlsConfig != nil, lo.FromPtr(cm.cfg.Transport.TLS.DisableCustomTLSFirstByte)),
  399. }))
  400. dialOptions = append(dialOptions, libdial.WithTLSConfig(tlsConfig))
  401. case "wss":
  402. protocol = "tcp"
  403. dialOptions = append(dialOptions, libdial.WithTLSConfigAndPriority(100, tlsConfig))
  404. // Make sure that if it is wss, the websocket hook is executed after the tls hook.
  405. dialOptions = append(dialOptions, libdial.WithAfterHook(libdial.AfterHook{Hook: utilnet.DialHookWebsocket(protocol, tlsConfig.ServerName), Priority: 110}))
  406. default:
  407. dialOptions = append(dialOptions, libdial.WithAfterHook(libdial.AfterHook{
  408. Hook: utilnet.DialHookCustomTLSHeadByte(tlsConfig != nil, lo.FromPtr(cm.cfg.Transport.TLS.DisableCustomTLSFirstByte)),
  409. }))
  410. dialOptions = append(dialOptions, libdial.WithTLSConfig(tlsConfig))
  411. }
  412. if cm.cfg.Transport.ConnectServerLocalIP != "" {
  413. dialOptions = append(dialOptions, libdial.WithLocalAddr(cm.cfg.Transport.ConnectServerLocalIP))
  414. }
  415. dialOptions = append(dialOptions,
  416. libdial.WithProtocol(protocol),
  417. libdial.WithTimeout(time.Duration(cm.cfg.Transport.DialServerTimeout)*time.Second),
  418. libdial.WithKeepAlive(time.Duration(cm.cfg.Transport.DialServerKeepAlive)*time.Second),
  419. libdial.WithProxy(proxyType, addr),
  420. libdial.WithProxyAuth(auth),
  421. )
  422. conn, err := libdial.DialContext(
  423. cm.ctx,
  424. net.JoinHostPort(cm.cfg.ServerAddr, strconv.Itoa(cm.cfg.ServerPort)),
  425. dialOptions...,
  426. )
  427. return conn, err
  428. }
  429. func (cm *ConnectionManager) Close() error {
  430. if cm.quicConn != nil {
  431. _ = cm.quicConn.CloseWithError(0, "")
  432. }
  433. if cm.muxSession != nil {
  434. _ = cm.muxSession.Close()
  435. }
  436. return nil
  437. }