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