service.go 13 KB

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