service.go 13 KB

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