1
0

udp.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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. v1 "github.com/fatedier/frp/pkg/config/v1"
  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(&v1.UDPProxyConfig{}), NewUDPProxy)
  31. }
  32. type UDPProxy struct {
  33. *BaseProxy
  34. cfg *v1.UDPProxyConfig
  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 v1.ProxyConfigurer) Proxy {
  43. unwrapped, ok := cfg.(*v1.UDPProxyConfig)
  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.Transport.UseEncryption {
  88. rwc, err = libio.WithEncryption(rwc, []byte(pxy.clientCfg.Auth.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.Transport.UseCompression {
  96. rwc = libio.WithCompression(rwc)
  97. }
  98. conn = utilnet.WrapReadWriteCloserToConn(rwc, conn)
  99. pxy.mu.Lock()
  100. pxy.workConn = conn
  101. pxy.readCh = make(chan *msg.UDPPacket, 1024)
  102. pxy.sendCh = make(chan msg.Message, 1024)
  103. pxy.closed = false
  104. pxy.mu.Unlock()
  105. workConnReaderFn := func(conn net.Conn, readCh chan *msg.UDPPacket) {
  106. for {
  107. var udpMsg msg.UDPPacket
  108. if errRet := msg.ReadMsgInto(conn, &udpMsg); errRet != nil {
  109. xl.Warn("read from workConn for udp error: %v", errRet)
  110. return
  111. }
  112. if errRet := errors.PanicToError(func() {
  113. xl.Trace("get udp package from workConn: %s", udpMsg.Content)
  114. readCh <- &udpMsg
  115. }); errRet != nil {
  116. xl.Info("reader goroutine for udp work connection closed: %v", errRet)
  117. return
  118. }
  119. }
  120. }
  121. workConnSenderFn := func(conn net.Conn, sendCh chan msg.Message) {
  122. defer func() {
  123. xl.Info("writer goroutine for udp work connection closed")
  124. }()
  125. var errRet error
  126. for rawMsg := range sendCh {
  127. switch m := rawMsg.(type) {
  128. case *msg.UDPPacket:
  129. xl.Trace("send udp package to workConn: %s", m.Content)
  130. case *msg.Ping:
  131. xl.Trace("send ping message to udp workConn")
  132. }
  133. if errRet = msg.WriteMsg(conn, rawMsg); errRet != nil {
  134. xl.Error("udp work write error: %v", errRet)
  135. return
  136. }
  137. }
  138. }
  139. heartbeatFn := func(sendCh chan msg.Message) {
  140. var errRet error
  141. for {
  142. time.Sleep(time.Duration(30) * time.Second)
  143. if errRet = errors.PanicToError(func() {
  144. sendCh <- &msg.Ping{}
  145. }); errRet != nil {
  146. xl.Trace("heartbeat goroutine for udp work connection closed")
  147. break
  148. }
  149. }
  150. }
  151. go workConnSenderFn(pxy.workConn, pxy.sendCh)
  152. go workConnReaderFn(pxy.workConn, pxy.readCh)
  153. go heartbeatFn(pxy.sendCh)
  154. udp.Forwarder(pxy.localAddr, pxy.readCh, pxy.sendCh, int(pxy.clientCfg.UDPPacketSize))
  155. }