service.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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. if atomic.LoadUint32(&svr.exit) != 0 {
  173. return
  174. }
  175. xl.Info("try to reconnect to server...")
  176. conn, session, err := svr.login()
  177. if err != nil {
  178. xl.Warn("reconnect to server error: %v, wait %v for another retry", err, delayTime)
  179. util.RandomSleep(delayTime, 0.9, 1.1)
  180. delayTime = delayTime * 2
  181. if delayTime > maxDelayTime {
  182. delayTime = maxDelayTime
  183. }
  184. continue
  185. }
  186. // reconnect success, init delayTime
  187. delayTime = time.Second
  188. ctl := NewControl(svr.ctx, svr.runID, conn, session, svr.cfg, svr.pxyCfgs, svr.visitorCfgs, svr.serverUDPPort, svr.authSetter)
  189. ctl.Run()
  190. svr.ctlMu.Lock()
  191. if svr.ctl != nil {
  192. svr.ctl.Close()
  193. }
  194. svr.ctl = ctl
  195. svr.ctlMu.Unlock()
  196. break
  197. }
  198. }
  199. }
  200. // login creates a connection to frps and registers it self as a client
  201. // conn: control connection
  202. // session: if it's not nil, using tcp mux
  203. func (svr *Service) login() (conn net.Conn, session *fmux.Session, err error) {
  204. xl := xlog.FromContextSafe(svr.ctx)
  205. var tlsConfig *tls.Config
  206. if svr.cfg.TLSEnable {
  207. sn := svr.cfg.TLSServerName
  208. if sn == "" {
  209. sn = svr.cfg.ServerAddr
  210. }
  211. tlsConfig, err = transport.NewClientTLSConfig(
  212. svr.cfg.TLSCertFile,
  213. svr.cfg.TLSKeyFile,
  214. svr.cfg.TLSTrustedCaFile,
  215. sn)
  216. if err != nil {
  217. xl.Warn("fail to build tls configuration when service login, err: %v", err)
  218. return
  219. }
  220. }
  221. proxyType, addr, auth, err := libdial.ParseProxyURL(svr.cfg.HTTPProxy)
  222. if err != nil {
  223. xl.Error("fail to parse proxy url")
  224. return
  225. }
  226. dialOptions := []libdial.DialOption{}
  227. protocol := svr.cfg.Protocol
  228. if protocol == "websocket" {
  229. protocol = "tcp"
  230. dialOptions = append(dialOptions, libdial.WithAfterHook(libdial.AfterHook{Hook: frpNet.DialHookWebsocket()}))
  231. }
  232. if svr.cfg.ConnectServerLocalIP != "" {
  233. dialOptions = append(dialOptions, libdial.WithLocalAddr(svr.cfg.ConnectServerLocalIP))
  234. }
  235. dialOptions = append(dialOptions,
  236. libdial.WithProtocol(protocol),
  237. libdial.WithTimeout(time.Duration(svr.cfg.DialServerTimeout)*time.Second),
  238. libdial.WithKeepAlive(time.Duration(svr.cfg.DialServerKeepAlive)*time.Second),
  239. libdial.WithProxy(proxyType, addr),
  240. libdial.WithProxyAuth(auth),
  241. libdial.WithTLSConfig(tlsConfig),
  242. libdial.WithAfterHook(libdial.AfterHook{
  243. Hook: frpNet.DialHookCustomTLSHeadByte(tlsConfig != nil, svr.cfg.DisableCustomTLSFirstByte),
  244. }),
  245. )
  246. conn, err = libdial.Dial(
  247. net.JoinHostPort(svr.cfg.ServerAddr, strconv.Itoa(svr.cfg.ServerPort)),
  248. dialOptions...,
  249. )
  250. if err != nil {
  251. return
  252. }
  253. defer func() {
  254. if err != nil {
  255. conn.Close()
  256. if session != nil {
  257. session.Close()
  258. }
  259. }
  260. }()
  261. if svr.cfg.TCPMux {
  262. fmuxCfg := fmux.DefaultConfig()
  263. fmuxCfg.KeepAliveInterval = time.Duration(svr.cfg.TCPMuxKeepaliveInterval) * time.Second
  264. fmuxCfg.LogOutput = io.Discard
  265. session, err = fmux.Client(conn, fmuxCfg)
  266. if err != nil {
  267. return
  268. }
  269. stream, errRet := session.OpenStream()
  270. if errRet != nil {
  271. session.Close()
  272. err = errRet
  273. return
  274. }
  275. conn = stream
  276. }
  277. loginMsg := &msg.Login{
  278. Arch: runtime.GOARCH,
  279. Os: runtime.GOOS,
  280. PoolCount: svr.cfg.PoolCount,
  281. User: svr.cfg.User,
  282. Version: version.Full(),
  283. Timestamp: time.Now().Unix(),
  284. RunID: svr.runID,
  285. Metas: svr.cfg.Metas,
  286. }
  287. // Add auth
  288. if err = svr.authSetter.SetLogin(loginMsg); err != nil {
  289. return
  290. }
  291. if err = msg.WriteMsg(conn, loginMsg); err != nil {
  292. return
  293. }
  294. var loginRespMsg msg.LoginResp
  295. conn.SetReadDeadline(time.Now().Add(10 * time.Second))
  296. if err = msg.ReadMsgInto(conn, &loginRespMsg); err != nil {
  297. return
  298. }
  299. conn.SetReadDeadline(time.Time{})
  300. if loginRespMsg.Error != "" {
  301. err = fmt.Errorf("%s", loginRespMsg.Error)
  302. xl.Error("%s", loginRespMsg.Error)
  303. return
  304. }
  305. svr.runID = loginRespMsg.RunID
  306. xl.ResetPrefixes()
  307. xl.AppendPrefix(svr.runID)
  308. svr.serverUDPPort = loginRespMsg.ServerUDPPort
  309. xl.Info("login to server success, get run id [%s], server udp port [%d]", loginRespMsg.RunID, loginRespMsg.ServerUDPPort)
  310. return
  311. }
  312. func (svr *Service) ReloadConf(pxyCfgs map[string]config.ProxyConf, visitorCfgs map[string]config.VisitorConf) error {
  313. svr.cfgMu.Lock()
  314. svr.pxyCfgs = pxyCfgs
  315. svr.visitorCfgs = visitorCfgs
  316. svr.cfgMu.Unlock()
  317. svr.ctlMu.RLock()
  318. ctl := svr.ctl
  319. svr.ctlMu.RUnlock()
  320. if ctl != nil {
  321. return svr.ctl.ReloadConf(pxyCfgs, visitorCfgs)
  322. }
  323. return nil
  324. }
  325. func (svr *Service) Close() {
  326. svr.GracefulClose(time.Duration(0))
  327. }
  328. func (svr *Service) GracefulClose(d time.Duration) {
  329. atomic.StoreUint32(&svr.exit, 1)
  330. svr.ctlMu.RLock()
  331. if svr.ctl != nil {
  332. svr.ctl.GracefulClose(d)
  333. }
  334. svr.ctlMu.RUnlock()
  335. svr.cancel()
  336. }