service.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. // Copyright 2017 fatedier, [email protected]
  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. "sync"
  25. "sync/atomic"
  26. "time"
  27. "github.com/fatedier/frp/assets"
  28. "github.com/fatedier/frp/pkg/auth"
  29. "github.com/fatedier/frp/pkg/config"
  30. "github.com/fatedier/frp/pkg/msg"
  31. "github.com/fatedier/frp/pkg/transport"
  32. "github.com/fatedier/frp/pkg/util/log"
  33. frpNet "github.com/fatedier/frp/pkg/util/net"
  34. "github.com/fatedier/frp/pkg/util/version"
  35. "github.com/fatedier/frp/pkg/util/xlog"
  36. libdial "github.com/fatedier/golib/net/dial"
  37. fmux "github.com/hashicorp/yamux"
  38. )
  39. // Service is a client service.
  40. type Service struct {
  41. // uniq id got from frps, attach it in loginMsg
  42. runID string
  43. // manager control connection with server
  44. ctl *Control
  45. ctlMu sync.RWMutex
  46. // Sets authentication based on selected method
  47. authSetter auth.Setter
  48. cfg config.ClientCommonConf
  49. pxyCfgs map[string]config.ProxyConf
  50. visitorCfgs map[string]config.VisitorConf
  51. cfgMu sync.RWMutex
  52. // The configuration file used to initialize this client, or an empty
  53. // string if no configuration file was used.
  54. cfgFile string
  55. // This is configured by the login response from frps
  56. serverUDPPort int
  57. exit uint32 // 0 means not exit
  58. // service context
  59. ctx context.Context
  60. // call cancel to stop service
  61. cancel context.CancelFunc
  62. }
  63. func NewService(cfg config.ClientCommonConf, pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.VisitorConf, cfgFile string) (svr *Service, err error) {
  64. ctx, cancel := context.WithCancel(context.Background())
  65. svr = &Service{
  66. authSetter: auth.NewAuthSetter(cfg.ClientConfig),
  67. cfg: cfg,
  68. cfgFile: cfgFile,
  69. pxyCfgs: pxyCfgs,
  70. visitorCfgs: visitorCfgs,
  71. exit: 0,
  72. ctx: xlog.NewContext(ctx, xlog.New()),
  73. cancel: cancel,
  74. }
  75. return
  76. }
  77. func (svr *Service) GetController() *Control {
  78. svr.ctlMu.RLock()
  79. defer svr.ctlMu.RUnlock()
  80. return svr.ctl
  81. }
  82. func (svr *Service) Run() error {
  83. xl := xlog.FromContextSafe(svr.ctx)
  84. // login to frps
  85. for {
  86. conn, session, err := svr.login()
  87. if err != nil {
  88. xl.Warn("login to server failed: %v", err)
  89. // if login_fail_exit is true, just exit this program
  90. // otherwise sleep a while and try again to connect to server
  91. if svr.cfg.LoginFailExit {
  92. return err
  93. }
  94. time.Sleep(10 * time.Second)
  95. } else {
  96. // login success
  97. ctl := NewControl(svr.ctx, svr.runID, conn, session, svr.cfg, svr.pxyCfgs, svr.visitorCfgs, svr.serverUDPPort, svr.authSetter)
  98. ctl.Run()
  99. svr.ctlMu.Lock()
  100. svr.ctl = ctl
  101. svr.ctlMu.Unlock()
  102. break
  103. }
  104. }
  105. go svr.keepControllerWorking()
  106. if svr.cfg.AdminPort != 0 {
  107. // Init admin server assets
  108. assets.Load(svr.cfg.AssetsDir)
  109. address := net.JoinHostPort(svr.cfg.AdminAddr, strconv.Itoa(svr.cfg.AdminPort))
  110. err := svr.RunAdminServer(address)
  111. if err != nil {
  112. log.Warn("run admin server error: %v", err)
  113. }
  114. log.Info("admin server listen on %s:%d", svr.cfg.AdminAddr, svr.cfg.AdminPort)
  115. }
  116. <-svr.ctx.Done()
  117. return nil
  118. }
  119. func (svr *Service) keepControllerWorking() {
  120. xl := xlog.FromContextSafe(svr.ctx)
  121. maxDelayTime := 20 * time.Second
  122. delayTime := time.Second
  123. // if frpc reconnect frps, we need to limit retry times in 1min
  124. // current retry logic is sleep 0s, 0s, 0s, 1s, 2s, 4s, 8s, ...
  125. // when exceed 1min, we will reset delay and counts
  126. cutoffTime := time.Now().Add(time.Minute)
  127. reconnectDelay := time.Second
  128. reconnectCounts := 1
  129. for {
  130. <-svr.ctl.ClosedDoneCh()
  131. if atomic.LoadUint32(&svr.exit) != 0 {
  132. return
  133. }
  134. // the first three retry with no delay
  135. if reconnectCounts > 3 {
  136. time.Sleep(reconnectDelay)
  137. reconnectDelay *= 2
  138. }
  139. reconnectCounts++
  140. now := time.Now()
  141. if now.After(cutoffTime) {
  142. // reset
  143. cutoffTime = now.Add(time.Minute)
  144. reconnectDelay = time.Second
  145. reconnectCounts = 1
  146. }
  147. for {
  148. xl.Info("try to reconnect to server...")
  149. conn, session, err := svr.login()
  150. if err != nil {
  151. xl.Warn("reconnect to server error: %v", err)
  152. time.Sleep(delayTime)
  153. opErr := &net.OpError{}
  154. // quick retry for dial error
  155. if errors.As(err, &opErr) && opErr.Op == "dial" {
  156. delayTime = 2 * time.Second
  157. } else {
  158. delayTime = delayTime * 2
  159. if delayTime > maxDelayTime {
  160. delayTime = maxDelayTime
  161. }
  162. }
  163. continue
  164. }
  165. // reconnect success, init delayTime
  166. delayTime = time.Second
  167. ctl := NewControl(svr.ctx, svr.runID, conn, session, svr.cfg, svr.pxyCfgs, svr.visitorCfgs, svr.serverUDPPort, svr.authSetter)
  168. ctl.Run()
  169. svr.ctlMu.Lock()
  170. if svr.ctl != nil {
  171. svr.ctl.Close()
  172. }
  173. svr.ctl = ctl
  174. svr.ctlMu.Unlock()
  175. break
  176. }
  177. }
  178. }
  179. // login creates a connection to frps and registers it self as a client
  180. // conn: control connection
  181. // session: if it's not nil, using tcp mux
  182. func (svr *Service) login() (conn net.Conn, session *fmux.Session, err error) {
  183. xl := xlog.FromContextSafe(svr.ctx)
  184. var tlsConfig *tls.Config
  185. if svr.cfg.TLSEnable {
  186. sn := svr.cfg.TLSServerName
  187. if sn == "" {
  188. sn = svr.cfg.ServerAddr
  189. }
  190. tlsConfig, err = transport.NewClientTLSConfig(
  191. svr.cfg.TLSCertFile,
  192. svr.cfg.TLSKeyFile,
  193. svr.cfg.TLSTrustedCaFile,
  194. sn)
  195. if err != nil {
  196. xl.Warn("fail to build tls configuration when service login, err: %v", err)
  197. return
  198. }
  199. }
  200. proxyType, addr, auth, err := libdial.ParseProxyURL(svr.cfg.HTTPProxy)
  201. if err != nil {
  202. xl.Error("fail to parse proxy url")
  203. return
  204. }
  205. dialOptions := []libdial.DialOption{}
  206. protocol := svr.cfg.Protocol
  207. if protocol == "websocket" {
  208. protocol = "tcp"
  209. dialOptions = append(dialOptions, libdial.WithAfterHook(libdial.AfterHook{Hook: frpNet.DialHookWebsocket()}))
  210. }
  211. if svr.cfg.ConnectServerLocalIP != "" {
  212. dialOptions = append(dialOptions, libdial.WithLocalAddr(svr.cfg.ConnectServerLocalIP))
  213. }
  214. dialOptions = append(dialOptions,
  215. libdial.WithProtocol(protocol),
  216. libdial.WithProxy(proxyType, addr),
  217. libdial.WithProxyAuth(auth),
  218. libdial.WithTLSConfig(tlsConfig),
  219. libdial.WithAfterHook(libdial.AfterHook{
  220. Hook: frpNet.DialHookCustomTLSHeadByte(tlsConfig != nil, svr.cfg.DisableCustomTLSFirstByte),
  221. }),
  222. )
  223. conn, err = libdial.Dial(
  224. net.JoinHostPort(svr.cfg.ServerAddr, strconv.Itoa(svr.cfg.ServerPort)),
  225. dialOptions...,
  226. )
  227. if err != nil {
  228. return
  229. }
  230. defer func() {
  231. if err != nil {
  232. conn.Close()
  233. if session != nil {
  234. session.Close()
  235. }
  236. }
  237. }()
  238. if svr.cfg.TCPMux {
  239. fmuxCfg := fmux.DefaultConfig()
  240. fmuxCfg.KeepAliveInterval = time.Duration(svr.cfg.TCPMuxKeepaliveInterval) * time.Second
  241. fmuxCfg.LogOutput = io.Discard
  242. session, err = fmux.Client(conn, fmuxCfg)
  243. if err != nil {
  244. return
  245. }
  246. stream, errRet := session.OpenStream()
  247. if errRet != nil {
  248. session.Close()
  249. err = errRet
  250. return
  251. }
  252. conn = stream
  253. }
  254. loginMsg := &msg.Login{
  255. Arch: runtime.GOARCH,
  256. Os: runtime.GOOS,
  257. PoolCount: svr.cfg.PoolCount,
  258. User: svr.cfg.User,
  259. Version: version.Full(),
  260. Timestamp: time.Now().Unix(),
  261. RunID: svr.runID,
  262. Metas: svr.cfg.Metas,
  263. }
  264. // Add auth
  265. if err = svr.authSetter.SetLogin(loginMsg); err != nil {
  266. return
  267. }
  268. if err = msg.WriteMsg(conn, loginMsg); err != nil {
  269. return
  270. }
  271. var loginRespMsg msg.LoginResp
  272. conn.SetReadDeadline(time.Now().Add(10 * time.Second))
  273. if err = msg.ReadMsgInto(conn, &loginRespMsg); err != nil {
  274. return
  275. }
  276. conn.SetReadDeadline(time.Time{})
  277. if loginRespMsg.Error != "" {
  278. err = fmt.Errorf("%s", loginRespMsg.Error)
  279. xl.Error("%s", loginRespMsg.Error)
  280. return
  281. }
  282. svr.runID = loginRespMsg.RunID
  283. xl.ResetPrefixes()
  284. xl.AppendPrefix(svr.runID)
  285. svr.serverUDPPort = loginRespMsg.ServerUDPPort
  286. xl.Info("login to server success, get run id [%s], server udp port [%d]", loginRespMsg.RunID, loginRespMsg.ServerUDPPort)
  287. return
  288. }
  289. func (svr *Service) ReloadConf(pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.VisitorConf) error {
  290. svr.cfgMu.Lock()
  291. svr.pxyCfgs = pxyCfgs
  292. svr.visitorCfgs = visitorCfgs
  293. svr.cfgMu.Unlock()
  294. return svr.ctl.ReloadConf(pxyCfgs, visitorCfgs)
  295. }
  296. func (svr *Service) Close() {
  297. svr.GracefulClose(time.Duration(0))
  298. }
  299. func (svr *Service) GracefulClose(d time.Duration) {
  300. atomic.StoreUint32(&svr.exit, 1)
  301. if svr.ctl != nil {
  302. svr.ctl.GracefulClose(d)
  303. }
  304. svr.cancel()
  305. }