udp.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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 proxy
  15. import (
  16. "io"
  17. "net"
  18. "reflect"
  19. "strconv"
  20. "time"
  21. "github.com/fatedier/golib/errors"
  22. libio "github.com/fatedier/golib/io"
  23. "github.com/fatedier/frp/pkg/config"
  24. "github.com/fatedier/frp/pkg/msg"
  25. "github.com/fatedier/frp/pkg/proto/udp"
  26. "github.com/fatedier/frp/pkg/util/limit"
  27. utilnet "github.com/fatedier/frp/pkg/util/net"
  28. )
  29. func init() {
  30. RegisterProxyFactory(reflect.TypeOf(&config.UDPProxyConf{}), NewUDPProxy)
  31. }
  32. type UDPProxy struct {
  33. *BaseProxy
  34. cfg *config.UDPProxyConf
  35. localAddr *net.UDPAddr
  36. readCh chan *msg.UDPPacket
  37. // include msg.UDPPacket and msg.Ping
  38. sendCh chan msg.Message
  39. workConn net.Conn
  40. closed bool
  41. }
  42. func NewUDPProxy(baseProxy *BaseProxy, cfg config.ProxyConf) Proxy {
  43. unwrapped, ok := cfg.(*config.UDPProxyConf)
  44. if !ok {
  45. return nil
  46. }
  47. return &UDPProxy{
  48. BaseProxy: baseProxy,
  49. cfg: unwrapped,
  50. }
  51. }
  52. func (pxy *UDPProxy) Run() (err error) {
  53. pxy.localAddr, err = net.ResolveUDPAddr("udp", net.JoinHostPort(pxy.cfg.LocalIP, strconv.Itoa(pxy.cfg.LocalPort)))
  54. if err != nil {
  55. return
  56. }
  57. return
  58. }
  59. func (pxy *UDPProxy) Close() {
  60. pxy.mu.Lock()
  61. defer pxy.mu.Unlock()
  62. if !pxy.closed {
  63. pxy.closed = true
  64. if pxy.workConn != nil {
  65. pxy.workConn.Close()
  66. }
  67. if pxy.readCh != nil {
  68. close(pxy.readCh)
  69. }
  70. if pxy.sendCh != nil {
  71. close(pxy.sendCh)
  72. }
  73. }
  74. }
  75. func (pxy *UDPProxy) InWorkConn(conn net.Conn, _ *msg.StartWorkConn) {
  76. xl := pxy.xl
  77. xl.Info("incoming a new work connection for udp proxy, %s", conn.RemoteAddr().String())
  78. // close resources releated with old workConn
  79. pxy.Close()
  80. var rwc io.ReadWriteCloser = conn
  81. var err error
  82. if pxy.limiter != nil {
  83. rwc = libio.WrapReadWriteCloser(limit.NewReader(conn, pxy.limiter), limit.NewWriter(conn, pxy.limiter), func() error {
  84. return conn.Close()
  85. })
  86. }
  87. if pxy.cfg.UseEncryption {
  88. rwc, err = libio.WithEncryption(rwc, []byte(pxy.clientCfg.Token))
  89. if err != nil {
  90. conn.Close()
  91. xl.Error("create encryption stream error: %v", err)
  92. return
  93. }
  94. }
  95. if pxy.cfg.UseCompression {
  96. var releaseFn func()
  97. rwc, releaseFn = libio.WithCompressionFromPool(rwc)
  98. defer releaseFn()
  99. }
  100. conn = utilnet.WrapReadWriteCloserToConn(rwc, conn)
  101. pxy.mu.Lock()
  102. pxy.workConn = conn
  103. pxy.readCh = make(chan *msg.UDPPacket, 1024)
  104. pxy.sendCh = make(chan msg.Message, 1024)
  105. pxy.closed = false
  106. pxy.mu.Unlock()
  107. workConnReaderFn := func(conn net.Conn, readCh chan *msg.UDPPacket) {
  108. for {
  109. var udpMsg msg.UDPPacket
  110. if errRet := msg.ReadMsgInto(conn, &udpMsg); errRet != nil {
  111. xl.Warn("read from workConn for udp error: %v", errRet)
  112. return
  113. }
  114. if errRet := errors.PanicToError(func() {
  115. xl.Trace("get udp package from workConn: %s", udpMsg.Content)
  116. readCh <- &udpMsg
  117. }); errRet != nil {
  118. xl.Info("reader goroutine for udp work connection closed: %v", errRet)
  119. return
  120. }
  121. }
  122. }
  123. workConnSenderFn := func(conn net.Conn, sendCh chan msg.Message) {
  124. defer func() {
  125. xl.Info("writer goroutine for udp work connection closed")
  126. }()
  127. var errRet error
  128. for rawMsg := range sendCh {
  129. switch m := rawMsg.(type) {
  130. case *msg.UDPPacket:
  131. xl.Trace("send udp package to workConn: %s", m.Content)
  132. case *msg.Ping:
  133. xl.Trace("send ping message to udp workConn")
  134. }
  135. if errRet = msg.WriteMsg(conn, rawMsg); errRet != nil {
  136. xl.Error("udp work write error: %v", errRet)
  137. return
  138. }
  139. }
  140. }
  141. heartbeatFn := func(sendCh chan msg.Message) {
  142. var errRet error
  143. for {
  144. time.Sleep(time.Duration(30) * time.Second)
  145. if errRet = errors.PanicToError(func() {
  146. sendCh <- &msg.Ping{}
  147. }); errRet != nil {
  148. xl.Trace("heartbeat goroutine for udp work connection closed")
  149. break
  150. }
  151. }
  152. }
  153. go workConnSenderFn(pxy.workConn, pxy.sendCh)
  154. go workConnReaderFn(pxy.workConn, pxy.readCh)
  155. go heartbeatFn(pxy.sendCh)
  156. udp.Forwarder(pxy.localAddr, pxy.readCh, pxy.sendCh, int(pxy.clientCfg.UDPPacketSize))
  157. }