service.go 14 KB

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