1
0

xtcp.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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 visitor
  15. import (
  16. "context"
  17. "errors"
  18. "fmt"
  19. "io"
  20. "net"
  21. "strconv"
  22. "sync"
  23. "time"
  24. libio "github.com/fatedier/golib/io"
  25. fmux "github.com/hashicorp/yamux"
  26. quic "github.com/quic-go/quic-go"
  27. "golang.org/x/time/rate"
  28. v1 "github.com/fatedier/frp/pkg/config/v1"
  29. "github.com/fatedier/frp/pkg/msg"
  30. "github.com/fatedier/frp/pkg/nathole"
  31. "github.com/fatedier/frp/pkg/transport"
  32. netpkg "github.com/fatedier/frp/pkg/util/net"
  33. "github.com/fatedier/frp/pkg/util/util"
  34. "github.com/fatedier/frp/pkg/util/xlog"
  35. )
  36. var ErrNoTunnelSession = errors.New("no tunnel session")
  37. type XTCPVisitor struct {
  38. *BaseVisitor
  39. session TunnelSession
  40. startTunnelCh chan struct{}
  41. retryLimiter *rate.Limiter
  42. cancel context.CancelFunc
  43. cfg *v1.XTCPVisitorConfig
  44. }
  45. func (sv *XTCPVisitor) Run() (err error) {
  46. sv.ctx, sv.cancel = context.WithCancel(sv.ctx)
  47. if sv.cfg.Protocol == "kcp" {
  48. sv.session = NewKCPTunnelSession()
  49. } else {
  50. sv.session = NewQUICTunnelSession(sv.clientCfg)
  51. }
  52. if sv.cfg.BindPort > 0 {
  53. sv.l, err = net.Listen("tcp", net.JoinHostPort(sv.cfg.BindAddr, strconv.Itoa(sv.cfg.BindPort)))
  54. if err != nil {
  55. return
  56. }
  57. go sv.worker()
  58. }
  59. go sv.internalConnWorker()
  60. go sv.processTunnelStartEvents()
  61. if sv.cfg.KeepTunnelOpen {
  62. sv.retryLimiter = rate.NewLimiter(rate.Every(time.Hour/time.Duration(sv.cfg.MaxRetriesAnHour)), sv.cfg.MaxRetriesAnHour)
  63. go sv.keepTunnelOpenWorker()
  64. }
  65. return
  66. }
  67. func (sv *XTCPVisitor) Close() {
  68. sv.mu.Lock()
  69. defer sv.mu.Unlock()
  70. sv.BaseVisitor.Close()
  71. if sv.cancel != nil {
  72. sv.cancel()
  73. }
  74. if sv.session != nil {
  75. sv.session.Close()
  76. }
  77. }
  78. func (sv *XTCPVisitor) worker() {
  79. xl := xlog.FromContextSafe(sv.ctx)
  80. for {
  81. conn, err := sv.l.Accept()
  82. if err != nil {
  83. xl.Warnf("xtcp local listener closed")
  84. return
  85. }
  86. go sv.handleConn(conn)
  87. }
  88. }
  89. func (sv *XTCPVisitor) internalConnWorker() {
  90. xl := xlog.FromContextSafe(sv.ctx)
  91. for {
  92. conn, err := sv.internalLn.Accept()
  93. if err != nil {
  94. xl.Warnf("xtcp internal listener closed")
  95. return
  96. }
  97. go sv.handleConn(conn)
  98. }
  99. }
  100. func (sv *XTCPVisitor) processTunnelStartEvents() {
  101. for {
  102. select {
  103. case <-sv.ctx.Done():
  104. return
  105. case <-sv.startTunnelCh:
  106. start := time.Now()
  107. sv.makeNatHole()
  108. duration := time.Since(start)
  109. // avoid too frequently
  110. if duration < 10*time.Second {
  111. time.Sleep(10*time.Second - duration)
  112. }
  113. }
  114. }
  115. }
  116. func (sv *XTCPVisitor) keepTunnelOpenWorker() {
  117. xl := xlog.FromContextSafe(sv.ctx)
  118. ticker := time.NewTicker(time.Duration(sv.cfg.MinRetryInterval) * time.Second)
  119. defer ticker.Stop()
  120. sv.startTunnelCh <- struct{}{}
  121. for {
  122. select {
  123. case <-sv.ctx.Done():
  124. return
  125. case <-ticker.C:
  126. xl.Debugf("keepTunnelOpenWorker try to check tunnel...")
  127. conn, err := sv.getTunnelConn()
  128. if err != nil {
  129. xl.Warnf("keepTunnelOpenWorker get tunnel connection error: %v", err)
  130. _ = sv.retryLimiter.Wait(sv.ctx)
  131. continue
  132. }
  133. xl.Debugf("keepTunnelOpenWorker check success")
  134. if conn != nil {
  135. conn.Close()
  136. }
  137. }
  138. }
  139. }
  140. func (sv *XTCPVisitor) handleConn(userConn net.Conn) {
  141. xl := xlog.FromContextSafe(sv.ctx)
  142. isConnTrasfered := false
  143. defer func() {
  144. if !isConnTrasfered {
  145. userConn.Close()
  146. }
  147. }()
  148. xl.Debugf("get a new xtcp user connection")
  149. // Open a tunnel connection to the server. If there is already a successful hole-punching connection,
  150. // it will be reused. Otherwise, it will block and wait for a successful hole-punching connection until timeout.
  151. ctx := context.Background()
  152. if sv.cfg.FallbackTo != "" {
  153. timeoutCtx, cancel := context.WithTimeout(ctx, time.Duration(sv.cfg.FallbackTimeoutMs)*time.Millisecond)
  154. defer cancel()
  155. ctx = timeoutCtx
  156. }
  157. tunnelConn, err := sv.openTunnel(ctx)
  158. if err != nil {
  159. xl.Errorf("open tunnel error: %v", err)
  160. // no fallback, just return
  161. if sv.cfg.FallbackTo == "" {
  162. return
  163. }
  164. xl.Debugf("try to transfer connection to visitor: %s", sv.cfg.FallbackTo)
  165. if err := sv.helper.TransferConn(sv.cfg.FallbackTo, userConn); err != nil {
  166. xl.Errorf("transfer connection to visitor %s error: %v", sv.cfg.FallbackTo, err)
  167. return
  168. }
  169. isConnTrasfered = true
  170. return
  171. }
  172. var muxConnRWCloser io.ReadWriteCloser = tunnelConn
  173. if sv.cfg.Transport.UseEncryption {
  174. muxConnRWCloser, err = libio.WithEncryption(muxConnRWCloser, []byte(sv.cfg.SecretKey))
  175. if err != nil {
  176. xl.Errorf("create encryption stream error: %v", err)
  177. return
  178. }
  179. }
  180. if sv.cfg.Transport.UseCompression {
  181. var recycleFn func()
  182. muxConnRWCloser, recycleFn = libio.WithCompressionFromPool(muxConnRWCloser)
  183. defer recycleFn()
  184. }
  185. _, _, errs := libio.Join(userConn, muxConnRWCloser)
  186. xl.Debugf("join connections closed")
  187. if len(errs) > 0 {
  188. xl.Tracef("join connections errors: %v", errs)
  189. }
  190. }
  191. // openTunnel will open a tunnel connection to the target server.
  192. func (sv *XTCPVisitor) openTunnel(ctx context.Context) (conn net.Conn, err error) {
  193. xl := xlog.FromContextSafe(sv.ctx)
  194. ticker := time.NewTicker(500 * time.Millisecond)
  195. defer ticker.Stop()
  196. timeoutC := time.After(20 * time.Second)
  197. immediateTrigger := make(chan struct{}, 1)
  198. defer close(immediateTrigger)
  199. immediateTrigger <- struct{}{}
  200. for {
  201. select {
  202. case <-sv.ctx.Done():
  203. return nil, sv.ctx.Err()
  204. case <-ctx.Done():
  205. return nil, ctx.Err()
  206. case <-immediateTrigger:
  207. conn, err = sv.getTunnelConn()
  208. case <-ticker.C:
  209. conn, err = sv.getTunnelConn()
  210. case <-timeoutC:
  211. return nil, fmt.Errorf("open tunnel timeout")
  212. }
  213. if err != nil {
  214. if err != ErrNoTunnelSession {
  215. xl.Warnf("get tunnel connection error: %v", err)
  216. }
  217. continue
  218. }
  219. return conn, nil
  220. }
  221. }
  222. func (sv *XTCPVisitor) getTunnelConn() (net.Conn, error) {
  223. conn, err := sv.session.OpenConn(sv.ctx)
  224. if err == nil {
  225. return conn, nil
  226. }
  227. sv.session.Close()
  228. select {
  229. case sv.startTunnelCh <- struct{}{}:
  230. default:
  231. }
  232. return nil, err
  233. }
  234. // 0. PreCheck
  235. // 1. Prepare
  236. // 2. ExchangeInfo
  237. // 3. MakeNATHole
  238. // 4. Create a tunnel session using an underlying UDP connection.
  239. func (sv *XTCPVisitor) makeNatHole() {
  240. xl := xlog.FromContextSafe(sv.ctx)
  241. xl.Tracef("makeNatHole start")
  242. if err := nathole.PreCheck(sv.ctx, sv.helper.MsgTransporter(), sv.cfg.ServerName, 5*time.Second); err != nil {
  243. xl.Warnf("nathole precheck error: %v", err)
  244. return
  245. }
  246. xl.Tracef("nathole prepare start")
  247. prepareResult, err := nathole.Prepare([]string{sv.clientCfg.NatHoleSTUNServer})
  248. if err != nil {
  249. xl.Warnf("nathole prepare error: %v", err)
  250. return
  251. }
  252. xl.Infof("nathole prepare success, nat type: %s, behavior: %s, addresses: %v, assistedAddresses: %v",
  253. prepareResult.NatType, prepareResult.Behavior, prepareResult.Addrs, prepareResult.AssistedAddrs)
  254. listenConn := prepareResult.ListenConn
  255. // send NatHoleVisitor to server
  256. now := time.Now().Unix()
  257. transactionID := nathole.NewTransactionID()
  258. natHoleVisitorMsg := &msg.NatHoleVisitor{
  259. TransactionID: transactionID,
  260. ProxyName: sv.cfg.ServerName,
  261. Protocol: sv.cfg.Protocol,
  262. SignKey: util.GetAuthKey(sv.cfg.SecretKey, now),
  263. Timestamp: now,
  264. MappedAddrs: prepareResult.Addrs,
  265. AssistedAddrs: prepareResult.AssistedAddrs,
  266. }
  267. xl.Tracef("nathole exchange info start")
  268. natHoleRespMsg, err := nathole.ExchangeInfo(sv.ctx, sv.helper.MsgTransporter(), transactionID, natHoleVisitorMsg, 5*time.Second)
  269. if err != nil {
  270. listenConn.Close()
  271. xl.Warnf("nathole exchange info error: %v", err)
  272. return
  273. }
  274. xl.Infof("get natHoleRespMsg, sid [%s], protocol [%s], candidate address %v, assisted address %v, detectBehavior: %+v",
  275. natHoleRespMsg.Sid, natHoleRespMsg.Protocol, natHoleRespMsg.CandidateAddrs,
  276. natHoleRespMsg.AssistedAddrs, natHoleRespMsg.DetectBehavior)
  277. newListenConn, raddr, err := nathole.MakeHole(sv.ctx, listenConn, natHoleRespMsg, []byte(sv.cfg.SecretKey))
  278. if err != nil {
  279. listenConn.Close()
  280. xl.Warnf("make hole error: %v", err)
  281. return
  282. }
  283. listenConn = newListenConn
  284. xl.Infof("establishing nat hole connection successful, sid [%s], remoteAddr [%s]", natHoleRespMsg.Sid, raddr)
  285. if err := sv.session.Init(listenConn, raddr); err != nil {
  286. listenConn.Close()
  287. xl.Warnf("init tunnel session error: %v", err)
  288. return
  289. }
  290. }
  291. type TunnelSession interface {
  292. Init(listenConn *net.UDPConn, raddr *net.UDPAddr) error
  293. OpenConn(context.Context) (net.Conn, error)
  294. Close()
  295. }
  296. type KCPTunnelSession struct {
  297. session *fmux.Session
  298. lConn *net.UDPConn
  299. mu sync.RWMutex
  300. }
  301. func NewKCPTunnelSession() TunnelSession {
  302. return &KCPTunnelSession{}
  303. }
  304. func (ks *KCPTunnelSession) Init(listenConn *net.UDPConn, raddr *net.UDPAddr) error {
  305. listenConn.Close()
  306. laddr, _ := net.ResolveUDPAddr("udp", listenConn.LocalAddr().String())
  307. lConn, err := net.DialUDP("udp", laddr, raddr)
  308. if err != nil {
  309. return fmt.Errorf("dial udp error: %v", err)
  310. }
  311. remote, err := netpkg.NewKCPConnFromUDP(lConn, true, raddr.String())
  312. if err != nil {
  313. return fmt.Errorf("create kcp connection from udp connection error: %v", err)
  314. }
  315. fmuxCfg := fmux.DefaultConfig()
  316. fmuxCfg.KeepAliveInterval = 10 * time.Second
  317. fmuxCfg.MaxStreamWindowSize = 6 * 1024 * 1024
  318. fmuxCfg.LogOutput = io.Discard
  319. session, err := fmux.Client(remote, fmuxCfg)
  320. if err != nil {
  321. remote.Close()
  322. return fmt.Errorf("initial client session error: %v", err)
  323. }
  324. ks.mu.Lock()
  325. ks.session = session
  326. ks.lConn = lConn
  327. ks.mu.Unlock()
  328. return nil
  329. }
  330. func (ks *KCPTunnelSession) OpenConn(_ context.Context) (net.Conn, error) {
  331. ks.mu.RLock()
  332. defer ks.mu.RUnlock()
  333. session := ks.session
  334. if session == nil {
  335. return nil, ErrNoTunnelSession
  336. }
  337. return session.Open()
  338. }
  339. func (ks *KCPTunnelSession) Close() {
  340. ks.mu.Lock()
  341. defer ks.mu.Unlock()
  342. if ks.session != nil {
  343. _ = ks.session.Close()
  344. ks.session = nil
  345. }
  346. if ks.lConn != nil {
  347. _ = ks.lConn.Close()
  348. ks.lConn = nil
  349. }
  350. }
  351. type QUICTunnelSession struct {
  352. session quic.Connection
  353. listenConn *net.UDPConn
  354. mu sync.RWMutex
  355. clientCfg *v1.ClientCommonConfig
  356. }
  357. func NewQUICTunnelSession(clientCfg *v1.ClientCommonConfig) TunnelSession {
  358. return &QUICTunnelSession{
  359. clientCfg: clientCfg,
  360. }
  361. }
  362. func (qs *QUICTunnelSession) Init(listenConn *net.UDPConn, raddr *net.UDPAddr) error {
  363. tlsConfig, err := transport.NewClientTLSConfig("", "", "", raddr.String())
  364. if err != nil {
  365. return fmt.Errorf("create tls config error: %v", err)
  366. }
  367. tlsConfig.NextProtos = []string{"frp"}
  368. quicConn, err := quic.Dial(context.Background(), listenConn, raddr, tlsConfig,
  369. &quic.Config{
  370. MaxIdleTimeout: time.Duration(qs.clientCfg.Transport.QUIC.MaxIdleTimeout) * time.Second,
  371. MaxIncomingStreams: int64(qs.clientCfg.Transport.QUIC.MaxIncomingStreams),
  372. KeepAlivePeriod: time.Duration(qs.clientCfg.Transport.QUIC.KeepalivePeriod) * time.Second,
  373. })
  374. if err != nil {
  375. return fmt.Errorf("dial quic error: %v", err)
  376. }
  377. qs.mu.Lock()
  378. qs.session = quicConn
  379. qs.listenConn = listenConn
  380. qs.mu.Unlock()
  381. return nil
  382. }
  383. func (qs *QUICTunnelSession) OpenConn(ctx context.Context) (net.Conn, error) {
  384. qs.mu.RLock()
  385. defer qs.mu.RUnlock()
  386. session := qs.session
  387. if session == nil {
  388. return nil, ErrNoTunnelSession
  389. }
  390. stream, err := session.OpenStreamSync(ctx)
  391. if err != nil {
  392. return nil, err
  393. }
  394. return netpkg.QuicStreamToNetConn(stream, session), nil
  395. }
  396. func (qs *QUICTunnelSession) Close() {
  397. qs.mu.Lock()
  398. defer qs.mu.Unlock()
  399. if qs.session != nil {
  400. _ = qs.session.CloseWithError(0, "")
  401. qs.session = nil
  402. }
  403. if qs.listenConn != nil {
  404. _ = qs.listenConn.Close()
  405. qs.listenConn = nil
  406. }
  407. }