1
0

controller.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. // Copyright 2023 The frp Authors
  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 nathole
  15. import (
  16. "context"
  17. "crypto/md5"
  18. "encoding/hex"
  19. "fmt"
  20. "net"
  21. "strconv"
  22. "sync"
  23. "time"
  24. "github.com/fatedier/golib/errors"
  25. "github.com/samber/lo"
  26. "golang.org/x/sync/errgroup"
  27. "github.com/fatedier/frp/pkg/msg"
  28. "github.com/fatedier/frp/pkg/transport"
  29. "github.com/fatedier/frp/pkg/util/log"
  30. "github.com/fatedier/frp/pkg/util/util"
  31. )
  32. // NatHoleTimeout seconds.
  33. var NatHoleTimeout int64 = 10
  34. func NewTransactionID() string {
  35. id, _ := util.RandID()
  36. return fmt.Sprintf("%d%s", time.Now().Unix(), id)
  37. }
  38. type ClientCfg struct {
  39. name string
  40. sk string
  41. sidCh chan string
  42. }
  43. type Session struct {
  44. sid string
  45. analysisKey string
  46. recommandMode int
  47. recommandIndex int
  48. visitorMsg *msg.NatHoleVisitor
  49. visitorTransporter transport.MessageTransporter
  50. vResp *msg.NatHoleResp
  51. vNatFeature *NatFeature
  52. vBehavior RecommandBehavior
  53. clientMsg *msg.NatHoleClient
  54. clientTransporter transport.MessageTransporter
  55. cResp *msg.NatHoleResp
  56. cNatFeature *NatFeature
  57. cBehavior RecommandBehavior
  58. notifyCh chan struct{}
  59. }
  60. func (s *Session) genAnalysisKey() {
  61. hash := md5.New()
  62. vIPs := lo.Uniq(parseIPs(s.visitorMsg.MappedAddrs))
  63. if len(vIPs) > 0 {
  64. hash.Write([]byte(vIPs[0]))
  65. }
  66. hash.Write([]byte(s.vNatFeature.NatType))
  67. hash.Write([]byte(s.vNatFeature.Behavior))
  68. hash.Write([]byte(strconv.FormatBool(s.vNatFeature.RegularPortsChange)))
  69. cIPs := lo.Uniq(parseIPs(s.clientMsg.MappedAddrs))
  70. if len(cIPs) > 0 {
  71. hash.Write([]byte(cIPs[0]))
  72. }
  73. hash.Write([]byte(s.cNatFeature.NatType))
  74. hash.Write([]byte(s.cNatFeature.Behavior))
  75. hash.Write([]byte(strconv.FormatBool(s.cNatFeature.RegularPortsChange)))
  76. s.analysisKey = hex.EncodeToString(hash.Sum(nil))
  77. }
  78. type Controller struct {
  79. clientCfgs map[string]*ClientCfg
  80. sessions map[string]*Session
  81. analyzer *Analyzer
  82. mu sync.RWMutex
  83. }
  84. func NewController(analysisDataReserveDuration time.Duration) (*Controller, error) {
  85. return &Controller{
  86. clientCfgs: make(map[string]*ClientCfg),
  87. sessions: make(map[string]*Session),
  88. analyzer: NewAnalyzer(analysisDataReserveDuration),
  89. }, nil
  90. }
  91. func (c *Controller) CleanWorker(ctx context.Context) {
  92. ticker := time.NewTicker(time.Hour)
  93. defer ticker.Stop()
  94. for {
  95. select {
  96. case <-ticker.C:
  97. start := time.Now()
  98. count, total := c.analyzer.Clean()
  99. log.Trace("clean %d/%d nathole analysis data, cost %v", count, total, time.Since(start))
  100. case <-ctx.Done():
  101. return
  102. }
  103. }
  104. }
  105. func (c *Controller) ListenClient(name string, sk string) chan string {
  106. cfg := &ClientCfg{
  107. name: name,
  108. sk: sk,
  109. sidCh: make(chan string),
  110. }
  111. c.mu.Lock()
  112. defer c.mu.Unlock()
  113. c.clientCfgs[name] = cfg
  114. return cfg.sidCh
  115. }
  116. func (c *Controller) CloseClient(name string) {
  117. c.mu.Lock()
  118. defer c.mu.Unlock()
  119. delete(c.clientCfgs, name)
  120. }
  121. func (c *Controller) GenSid() string {
  122. t := time.Now().Unix()
  123. id, _ := util.RandID()
  124. return fmt.Sprintf("%d%s", t, id)
  125. }
  126. func (c *Controller) HandleVisitor(m *msg.NatHoleVisitor, transporter transport.MessageTransporter) {
  127. if m.PreCheck {
  128. _, ok := c.clientCfgs[m.ProxyName]
  129. if !ok {
  130. _ = transporter.Send(c.GenNatHoleResponse(m.TransactionID, nil, fmt.Sprintf("xtcp server for [%s] doesn't exist", m.ProxyName)))
  131. } else {
  132. _ = transporter.Send(c.GenNatHoleResponse(m.TransactionID, nil, ""))
  133. }
  134. return
  135. }
  136. sid := c.GenSid()
  137. session := &Session{
  138. sid: sid,
  139. visitorMsg: m,
  140. visitorTransporter: transporter,
  141. notifyCh: make(chan struct{}, 1),
  142. }
  143. var (
  144. clientCfg *ClientCfg
  145. ok bool
  146. )
  147. err := func() error {
  148. c.mu.Lock()
  149. defer c.mu.Unlock()
  150. clientCfg, ok = c.clientCfgs[m.ProxyName]
  151. if !ok {
  152. return fmt.Errorf("xtcp server for [%s] doesn't exist", m.ProxyName)
  153. }
  154. if !util.ConstantTimeEqString(m.SignKey, util.GetAuthKey(clientCfg.sk, m.Timestamp)) {
  155. return fmt.Errorf("xtcp connection of [%s] auth failed", m.ProxyName)
  156. }
  157. c.sessions[sid] = session
  158. return nil
  159. }()
  160. if err != nil {
  161. log.Warn("handle visitorMsg error: %v", err)
  162. _ = transporter.Send(c.GenNatHoleResponse(m.TransactionID, nil, err.Error()))
  163. return
  164. }
  165. log.Trace("handle visitor message, sid [%s]", sid)
  166. defer func() {
  167. c.mu.Lock()
  168. defer c.mu.Unlock()
  169. delete(c.sessions, sid)
  170. }()
  171. if err := errors.PanicToError(func() {
  172. clientCfg.sidCh <- sid
  173. }); err != nil {
  174. return
  175. }
  176. // wait for NatHoleClient message
  177. select {
  178. case <-session.notifyCh:
  179. case <-time.After(time.Duration(NatHoleTimeout) * time.Second):
  180. log.Debug("wait for NatHoleClient message timeout, sid [%s]", sid)
  181. return
  182. }
  183. // Make hole-punching decisions based on the NAT information of the client and visitor.
  184. vResp, cResp, err := c.analysis(session)
  185. if err != nil {
  186. log.Debug("sid [%s] analysis error: %v", err)
  187. vResp = c.GenNatHoleResponse(session.visitorMsg.TransactionID, nil, err.Error())
  188. cResp = c.GenNatHoleResponse(session.clientMsg.TransactionID, nil, err.Error())
  189. }
  190. session.cResp = cResp
  191. session.vResp = vResp
  192. // send response to visitor and client
  193. var g errgroup.Group
  194. g.Go(func() error {
  195. // if it's sender, wait for a while to make sure the client has send the detect messages
  196. if vResp.DetectBehavior.Role == "sender" {
  197. time.Sleep(1 * time.Second)
  198. }
  199. _ = session.visitorTransporter.Send(vResp)
  200. return nil
  201. })
  202. g.Go(func() error {
  203. // if it's sender, wait for a while to make sure the client has send the detect messages
  204. if cResp.DetectBehavior.Role == "sender" {
  205. time.Sleep(1 * time.Second)
  206. }
  207. _ = session.clientTransporter.Send(cResp)
  208. return nil
  209. })
  210. _ = g.Wait()
  211. time.Sleep(time.Duration(cResp.DetectBehavior.ReadTimeoutMs+30000) * time.Millisecond)
  212. }
  213. func (c *Controller) HandleClient(m *msg.NatHoleClient, transporter transport.MessageTransporter) {
  214. c.mu.RLock()
  215. session, ok := c.sessions[m.Sid]
  216. c.mu.RUnlock()
  217. if !ok {
  218. return
  219. }
  220. log.Trace("handle client message, sid [%s]", session.sid)
  221. session.clientMsg = m
  222. session.clientTransporter = transporter
  223. select {
  224. case session.notifyCh <- struct{}{}:
  225. default:
  226. }
  227. }
  228. func (c *Controller) HandleReport(m *msg.NatHoleReport) {
  229. c.mu.RLock()
  230. session, ok := c.sessions[m.Sid]
  231. c.mu.RUnlock()
  232. if !ok {
  233. log.Trace("sid [%s] report make hole success: %v, but session not found", m.Sid, m.Success)
  234. return
  235. }
  236. if m.Success {
  237. c.analyzer.ReportSuccess(session.analysisKey, session.recommandMode, session.recommandIndex)
  238. }
  239. log.Info("sid [%s] report make hole success: %v, mode %v, index %v",
  240. m.Sid, m.Success, session.recommandMode, session.recommandIndex)
  241. }
  242. func (c *Controller) GenNatHoleResponse(transactionID string, session *Session, errInfo string) *msg.NatHoleResp {
  243. var sid string
  244. if session != nil {
  245. sid = session.sid
  246. }
  247. return &msg.NatHoleResp{
  248. TransactionID: transactionID,
  249. Sid: sid,
  250. Error: errInfo,
  251. }
  252. }
  253. // analysis analyzes the NAT type and behavior of the visitor and client, then makes hole-punching decisions.
  254. // return the response to the visitor and client.
  255. func (c *Controller) analysis(session *Session) (*msg.NatHoleResp, *msg.NatHoleResp, error) {
  256. cm := session.clientMsg
  257. vm := session.visitorMsg
  258. cNatFeature, err := ClassifyNATFeature(cm.MappedAddrs, parseIPs(cm.AssistedAddrs))
  259. if err != nil {
  260. return nil, nil, fmt.Errorf("classify client nat feature error: %v", err)
  261. }
  262. vNatFeature, err := ClassifyNATFeature(vm.MappedAddrs, parseIPs(vm.AssistedAddrs))
  263. if err != nil {
  264. return nil, nil, fmt.Errorf("classify visitor nat feature error: %v", err)
  265. }
  266. session.cNatFeature = cNatFeature
  267. session.vNatFeature = vNatFeature
  268. session.genAnalysisKey()
  269. mode, index, cBehavior, vBehavior := c.analyzer.GetRecommandBehaviors(session.analysisKey, cNatFeature, vNatFeature)
  270. session.recommandMode = mode
  271. session.recommandIndex = index
  272. session.cBehavior = cBehavior
  273. session.vBehavior = vBehavior
  274. timeoutMs := lo.Max([]int{cBehavior.SendDelayMs, vBehavior.SendDelayMs}) + 5000
  275. if cBehavior.ListenRandomPorts > 0 || vBehavior.ListenRandomPorts > 0 {
  276. timeoutMs += 30000
  277. }
  278. protocol := vm.Protocol
  279. vResp := &msg.NatHoleResp{
  280. TransactionID: vm.TransactionID,
  281. Sid: session.sid,
  282. Protocol: protocol,
  283. CandidateAddrs: lo.Uniq(cm.MappedAddrs),
  284. AssistedAddrs: lo.Uniq(cm.AssistedAddrs),
  285. DetectBehavior: msg.NatHoleDetectBehavior{
  286. Mode: mode,
  287. Role: vBehavior.Role,
  288. TTL: vBehavior.TTL,
  289. SendDelayMs: vBehavior.SendDelayMs,
  290. ReadTimeoutMs: timeoutMs - vBehavior.SendDelayMs,
  291. SendRandomPorts: vBehavior.PortsRandomNumber,
  292. ListenRandomPorts: vBehavior.ListenRandomPorts,
  293. CandidatePorts: getRangePorts(cm.MappedAddrs, cNatFeature.PortsDifference, vBehavior.PortsRangeNumber),
  294. },
  295. }
  296. cResp := &msg.NatHoleResp{
  297. TransactionID: cm.TransactionID,
  298. Sid: session.sid,
  299. Protocol: protocol,
  300. CandidateAddrs: lo.Uniq(vm.MappedAddrs),
  301. AssistedAddrs: lo.Uniq(vm.AssistedAddrs),
  302. DetectBehavior: msg.NatHoleDetectBehavior{
  303. Mode: mode,
  304. Role: cBehavior.Role,
  305. TTL: cBehavior.TTL,
  306. SendDelayMs: cBehavior.SendDelayMs,
  307. ReadTimeoutMs: timeoutMs - cBehavior.SendDelayMs,
  308. SendRandomPorts: cBehavior.PortsRandomNumber,
  309. ListenRandomPorts: cBehavior.ListenRandomPorts,
  310. CandidatePorts: getRangePorts(vm.MappedAddrs, vNatFeature.PortsDifference, cBehavior.PortsRangeNumber),
  311. },
  312. }
  313. log.Debug("sid [%s] visitor nat: %+v, candidateAddrs: %v; client nat: %+v, candidateAddrs: %v, protocol: %s",
  314. session.sid, *vNatFeature, vm.MappedAddrs, *cNatFeature, cm.MappedAddrs, protocol)
  315. log.Debug("sid [%s] visitor detect behavior: %+v", session.sid, vResp.DetectBehavior)
  316. log.Debug("sid [%s] client detect behavior: %+v", session.sid, cResp.DetectBehavior)
  317. return vResp, cResp, nil
  318. }
  319. func getRangePorts(addrs []string, difference, maxNumber int) []msg.PortsRange {
  320. if maxNumber <= 0 {
  321. return nil
  322. }
  323. addr, err := lo.Last(addrs)
  324. if err != nil {
  325. return nil
  326. }
  327. var ports []msg.PortsRange
  328. _, portStr, err := net.SplitHostPort(addr)
  329. if err != nil {
  330. return nil
  331. }
  332. port, err := strconv.Atoi(portStr)
  333. if err != nil {
  334. return nil
  335. }
  336. ports = append(ports, msg.PortsRange{
  337. From: lo.Max([]int{port - difference - 5, port - maxNumber, 1}),
  338. To: lo.Min([]int{port + difference + 5, port + maxNumber, 65535}),
  339. })
  340. return ports
  341. }