service.go 9.5 KB

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