xtcp.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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. //go:build !frps
  15. package proxy
  16. import (
  17. "io"
  18. "net"
  19. "reflect"
  20. "time"
  21. fmux "github.com/hashicorp/yamux"
  22. "github.com/quic-go/quic-go"
  23. v1 "github.com/fatedier/frp/pkg/config/v1"
  24. "github.com/fatedier/frp/pkg/msg"
  25. "github.com/fatedier/frp/pkg/nathole"
  26. "github.com/fatedier/frp/pkg/transport"
  27. netpkg "github.com/fatedier/frp/pkg/util/net"
  28. )
  29. func init() {
  30. RegisterProxyFactory(reflect.TypeOf(&v1.XTCPProxyConfig{}), NewXTCPProxy)
  31. }
  32. type XTCPProxy struct {
  33. *BaseProxy
  34. cfg *v1.XTCPProxyConfig
  35. }
  36. func NewXTCPProxy(baseProxy *BaseProxy, cfg v1.ProxyConfigurer) Proxy {
  37. unwrapped, ok := cfg.(*v1.XTCPProxyConfig)
  38. if !ok {
  39. return nil
  40. }
  41. return &XTCPProxy{
  42. BaseProxy: baseProxy,
  43. cfg: unwrapped,
  44. }
  45. }
  46. func (pxy *XTCPProxy) InWorkConn(conn net.Conn, startWorkConnMsg *msg.StartWorkConn) {
  47. xl := pxy.xl
  48. defer conn.Close()
  49. var natHoleSidMsg msg.NatHoleSid
  50. err := msg.ReadMsgInto(conn, &natHoleSidMsg)
  51. if err != nil {
  52. xl.Errorf("xtcp read from workConn error: %v", err)
  53. return
  54. }
  55. xl.Tracef("nathole prepare start")
  56. prepareResult, err := nathole.Prepare([]string{pxy.clientCfg.NatHoleSTUNServer})
  57. if err != nil {
  58. xl.Warnf("nathole prepare error: %v", err)
  59. return
  60. }
  61. xl.Infof("nathole prepare success, nat type: %s, behavior: %s, addresses: %v, assistedAddresses: %v",
  62. prepareResult.NatType, prepareResult.Behavior, prepareResult.Addrs, prepareResult.AssistedAddrs)
  63. defer prepareResult.ListenConn.Close()
  64. // send NatHoleClient msg to server
  65. transactionID := nathole.NewTransactionID()
  66. natHoleClientMsg := &msg.NatHoleClient{
  67. TransactionID: transactionID,
  68. ProxyName: pxy.cfg.Name,
  69. Sid: natHoleSidMsg.Sid,
  70. MappedAddrs: prepareResult.Addrs,
  71. AssistedAddrs: prepareResult.AssistedAddrs,
  72. }
  73. xl.Tracef("nathole exchange info start")
  74. natHoleRespMsg, err := nathole.ExchangeInfo(pxy.ctx, pxy.msgTransporter, transactionID, natHoleClientMsg, 5*time.Second)
  75. if err != nil {
  76. xl.Warnf("nathole exchange info error: %v", err)
  77. return
  78. }
  79. xl.Infof("get natHoleRespMsg, sid [%s], protocol [%s], candidate address %v, assisted address %v, detectBehavior: %+v",
  80. natHoleRespMsg.Sid, natHoleRespMsg.Protocol, natHoleRespMsg.CandidateAddrs,
  81. natHoleRespMsg.AssistedAddrs, natHoleRespMsg.DetectBehavior)
  82. listenConn := prepareResult.ListenConn
  83. newListenConn, raddr, err := nathole.MakeHole(pxy.ctx, listenConn, natHoleRespMsg, []byte(pxy.cfg.Secretkey))
  84. if err != nil {
  85. listenConn.Close()
  86. xl.Warnf("make hole error: %v", err)
  87. _ = pxy.msgTransporter.Send(&msg.NatHoleReport{
  88. Sid: natHoleRespMsg.Sid,
  89. Success: false,
  90. })
  91. return
  92. }
  93. listenConn = newListenConn
  94. xl.Infof("establishing nat hole connection successful, sid [%s], remoteAddr [%s]", natHoleRespMsg.Sid, raddr)
  95. _ = pxy.msgTransporter.Send(&msg.NatHoleReport{
  96. Sid: natHoleRespMsg.Sid,
  97. Success: true,
  98. })
  99. if natHoleRespMsg.Protocol == "kcp" {
  100. pxy.listenByKCP(listenConn, raddr, startWorkConnMsg)
  101. return
  102. }
  103. // default is quic
  104. pxy.listenByQUIC(listenConn, raddr, startWorkConnMsg)
  105. }
  106. func (pxy *XTCPProxy) listenByKCP(listenConn *net.UDPConn, raddr *net.UDPAddr, startWorkConnMsg *msg.StartWorkConn) {
  107. xl := pxy.xl
  108. listenConn.Close()
  109. laddr, _ := net.ResolveUDPAddr("udp", listenConn.LocalAddr().String())
  110. lConn, err := net.DialUDP("udp", laddr, raddr)
  111. if err != nil {
  112. xl.Warnf("dial udp error: %v", err)
  113. return
  114. }
  115. defer lConn.Close()
  116. remote, err := netpkg.NewKCPConnFromUDP(lConn, true, raddr.String())
  117. if err != nil {
  118. xl.Warnf("create kcp connection from udp connection error: %v", err)
  119. return
  120. }
  121. fmuxCfg := fmux.DefaultConfig()
  122. fmuxCfg.KeepAliveInterval = 10 * time.Second
  123. fmuxCfg.MaxStreamWindowSize = 6 * 1024 * 1024
  124. fmuxCfg.LogOutput = io.Discard
  125. session, err := fmux.Server(remote, fmuxCfg)
  126. if err != nil {
  127. xl.Errorf("create mux session error: %v", err)
  128. return
  129. }
  130. defer session.Close()
  131. for {
  132. muxConn, err := session.Accept()
  133. if err != nil {
  134. xl.Errorf("accept connection error: %v", err)
  135. return
  136. }
  137. go pxy.HandleTCPWorkConnection(muxConn, startWorkConnMsg, []byte(pxy.cfg.Secretkey))
  138. }
  139. }
  140. func (pxy *XTCPProxy) listenByQUIC(listenConn *net.UDPConn, _ *net.UDPAddr, startWorkConnMsg *msg.StartWorkConn) {
  141. xl := pxy.xl
  142. defer listenConn.Close()
  143. tlsConfig, err := transport.NewServerTLSConfig("", "", "")
  144. if err != nil {
  145. xl.Warnf("create tls config error: %v", err)
  146. return
  147. }
  148. tlsConfig.NextProtos = []string{"frp"}
  149. quicListener, err := quic.Listen(listenConn, tlsConfig,
  150. &quic.Config{
  151. MaxIdleTimeout: time.Duration(pxy.clientCfg.Transport.QUIC.MaxIdleTimeout) * time.Second,
  152. MaxIncomingStreams: int64(pxy.clientCfg.Transport.QUIC.MaxIncomingStreams),
  153. KeepAlivePeriod: time.Duration(pxy.clientCfg.Transport.QUIC.KeepalivePeriod) * time.Second,
  154. },
  155. )
  156. if err != nil {
  157. xl.Warnf("dial quic error: %v", err)
  158. return
  159. }
  160. // only accept one connection from raddr
  161. c, err := quicListener.Accept(pxy.ctx)
  162. if err != nil {
  163. xl.Errorf("quic accept connection error: %v", err)
  164. return
  165. }
  166. for {
  167. stream, err := c.AcceptStream(pxy.ctx)
  168. if err != nil {
  169. xl.Debugf("quic accept stream error: %v", err)
  170. _ = c.CloseWithError(0, "")
  171. return
  172. }
  173. go pxy.HandleTCPWorkConnection(netpkg.QuicStreamToNetConn(stream, c), startWorkConnMsg, []byte(pxy.cfg.Secretkey))
  174. }
  175. }