1
0

sudp.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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. "strconv"
  21. "sync"
  22. "time"
  23. "github.com/fatedier/golib/errors"
  24. libio "github.com/fatedier/golib/io"
  25. v1 "github.com/fatedier/frp/pkg/config/v1"
  26. "github.com/fatedier/frp/pkg/msg"
  27. "github.com/fatedier/frp/pkg/proto/udp"
  28. "github.com/fatedier/frp/pkg/util/limit"
  29. netpkg "github.com/fatedier/frp/pkg/util/net"
  30. )
  31. func init() {
  32. RegisterProxyFactory(reflect.TypeOf(&v1.SUDPProxyConfig{}), NewSUDPProxy)
  33. }
  34. type SUDPProxy struct {
  35. *BaseProxy
  36. cfg *v1.SUDPProxyConfig
  37. localAddr *net.UDPAddr
  38. closeCh chan struct{}
  39. }
  40. func NewSUDPProxy(baseProxy *BaseProxy, cfg v1.ProxyConfigurer) Proxy {
  41. unwrapped, ok := cfg.(*v1.SUDPProxyConfig)
  42. if !ok {
  43. return nil
  44. }
  45. return &SUDPProxy{
  46. BaseProxy: baseProxy,
  47. cfg: unwrapped,
  48. closeCh: make(chan struct{}),
  49. }
  50. }
  51. func (pxy *SUDPProxy) Run() (err error) {
  52. pxy.localAddr, err = net.ResolveUDPAddr("udp", net.JoinHostPort(pxy.cfg.LocalIP, strconv.Itoa(pxy.cfg.LocalPort)))
  53. if err != nil {
  54. return
  55. }
  56. return
  57. }
  58. func (pxy *SUDPProxy) Close() {
  59. pxy.mu.Lock()
  60. defer pxy.mu.Unlock()
  61. select {
  62. case <-pxy.closeCh:
  63. return
  64. default:
  65. close(pxy.closeCh)
  66. }
  67. }
  68. func (pxy *SUDPProxy) InWorkConn(conn net.Conn, _ *msg.StartWorkConn) {
  69. xl := pxy.xl
  70. xl.Infof("incoming a new work connection for sudp proxy, %s", conn.RemoteAddr().String())
  71. var rwc io.ReadWriteCloser = conn
  72. var err error
  73. if pxy.limiter != nil {
  74. rwc = libio.WrapReadWriteCloser(limit.NewReader(conn, pxy.limiter), limit.NewWriter(conn, pxy.limiter), func() error {
  75. return conn.Close()
  76. })
  77. }
  78. if pxy.cfg.Transport.UseEncryption {
  79. rwc, err = libio.WithEncryption(rwc, []byte(pxy.clientCfg.Auth.Token))
  80. if err != nil {
  81. conn.Close()
  82. xl.Errorf("create encryption stream error: %v", err)
  83. return
  84. }
  85. }
  86. if pxy.cfg.Transport.UseCompression {
  87. rwc = libio.WithCompression(rwc)
  88. }
  89. conn = netpkg.WrapReadWriteCloserToConn(rwc, conn)
  90. workConn := conn
  91. readCh := make(chan *msg.UDPPacket, 1024)
  92. sendCh := make(chan msg.Message, 1024)
  93. isClose := false
  94. mu := &sync.Mutex{}
  95. closeFn := func() {
  96. mu.Lock()
  97. defer mu.Unlock()
  98. if isClose {
  99. return
  100. }
  101. isClose = true
  102. if workConn != nil {
  103. workConn.Close()
  104. }
  105. close(readCh)
  106. close(sendCh)
  107. }
  108. // udp service <- frpc <- frps <- frpc visitor <- user
  109. workConnReaderFn := func(conn net.Conn, readCh chan *msg.UDPPacket) {
  110. defer closeFn()
  111. for {
  112. // first to check sudp proxy is closed or not
  113. select {
  114. case <-pxy.closeCh:
  115. xl.Tracef("frpc sudp proxy is closed")
  116. return
  117. default:
  118. }
  119. var udpMsg msg.UDPPacket
  120. if errRet := msg.ReadMsgInto(conn, &udpMsg); errRet != nil {
  121. xl.Warnf("read from workConn for sudp error: %v", errRet)
  122. return
  123. }
  124. if errRet := errors.PanicToError(func() {
  125. readCh <- &udpMsg
  126. }); errRet != nil {
  127. xl.Warnf("reader goroutine for sudp work connection closed: %v", errRet)
  128. return
  129. }
  130. }
  131. }
  132. // udp service -> frpc -> frps -> frpc visitor -> user
  133. workConnSenderFn := func(conn net.Conn, sendCh chan msg.Message) {
  134. defer func() {
  135. closeFn()
  136. xl.Infof("writer goroutine for sudp work connection closed")
  137. }()
  138. var errRet error
  139. for rawMsg := range sendCh {
  140. switch m := rawMsg.(type) {
  141. case *msg.UDPPacket:
  142. xl.Tracef("frpc send udp package to frpc visitor, [udp local: %v, remote: %v], [tcp work conn local: %v, remote: %v]",
  143. m.LocalAddr.String(), m.RemoteAddr.String(), conn.LocalAddr().String(), conn.RemoteAddr().String())
  144. case *msg.Ping:
  145. xl.Tracef("frpc send ping message to frpc visitor")
  146. }
  147. if errRet = msg.WriteMsg(conn, rawMsg); errRet != nil {
  148. xl.Errorf("sudp work write error: %v", errRet)
  149. return
  150. }
  151. }
  152. }
  153. heartbeatFn := func(sendCh chan msg.Message) {
  154. ticker := time.NewTicker(30 * time.Second)
  155. defer func() {
  156. ticker.Stop()
  157. closeFn()
  158. }()
  159. var errRet error
  160. for {
  161. select {
  162. case <-ticker.C:
  163. if errRet = errors.PanicToError(func() {
  164. sendCh <- &msg.Ping{}
  165. }); errRet != nil {
  166. xl.Warnf("heartbeat goroutine for sudp work connection closed")
  167. return
  168. }
  169. case <-pxy.closeCh:
  170. xl.Tracef("frpc sudp proxy is closed")
  171. return
  172. }
  173. }
  174. }
  175. go workConnSenderFn(workConn, sendCh)
  176. go workConnReaderFn(workConn, readCh)
  177. go heartbeatFn(sendCh)
  178. udp.Forwarder(pxy.localAddr, readCh, sendCh, int(pxy.clientCfg.UDPPacketSize))
  179. }