service.go 9.5 KB

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