1
0

udp.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. // Copyright 2019 fatedier, fatedier@gmail.com
  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. "context"
  17. "fmt"
  18. "io"
  19. "net"
  20. "strconv"
  21. "time"
  22. "github.com/fatedier/golib/errors"
  23. frpIo "github.com/fatedier/golib/io"
  24. "github.com/fatedier/frp/pkg/config"
  25. "github.com/fatedier/frp/pkg/msg"
  26. "github.com/fatedier/frp/pkg/proto/udp"
  27. frpNet "github.com/fatedier/frp/pkg/util/net"
  28. "github.com/fatedier/frp/server/metrics"
  29. )
  30. type UDPProxy struct {
  31. *BaseProxy
  32. cfg *config.UDPProxyConf
  33. realPort int
  34. // udpConn is the listener of udp packages
  35. udpConn *net.UDPConn
  36. // there are always only one workConn at the same time
  37. // get another one if it closed
  38. workConn net.Conn
  39. // sendCh is used for sending packages to workConn
  40. sendCh chan *msg.UDPPacket
  41. // readCh is used for reading packages from workConn
  42. readCh chan *msg.UDPPacket
  43. // checkCloseCh is used for watching if workConn is closed
  44. checkCloseCh chan int
  45. isClosed bool
  46. }
  47. func (pxy *UDPProxy) Run() (remoteAddr string, err error) {
  48. xl := pxy.xl
  49. pxy.realPort, err = pxy.rc.UDPPortManager.Acquire(pxy.name, pxy.cfg.RemotePort)
  50. if err != nil {
  51. return "", fmt.Errorf("acquire port %d error: %v", pxy.cfg.RemotePort, err)
  52. }
  53. defer func() {
  54. if err != nil {
  55. pxy.rc.UDPPortManager.Release(pxy.realPort)
  56. }
  57. }()
  58. remoteAddr = fmt.Sprintf(":%d", pxy.realPort)
  59. pxy.cfg.RemotePort = pxy.realPort
  60. addr, errRet := net.ResolveUDPAddr("udp", net.JoinHostPort(pxy.serverCfg.ProxyBindAddr, strconv.Itoa(pxy.realPort)))
  61. if errRet != nil {
  62. err = errRet
  63. return
  64. }
  65. udpConn, errRet := net.ListenUDP("udp", addr)
  66. if errRet != nil {
  67. err = errRet
  68. xl.Warn("listen udp port error: %v", err)
  69. return
  70. }
  71. xl.Info("udp proxy listen port [%d]", pxy.cfg.RemotePort)
  72. pxy.udpConn = udpConn
  73. pxy.sendCh = make(chan *msg.UDPPacket, 1024)
  74. pxy.readCh = make(chan *msg.UDPPacket, 1024)
  75. pxy.checkCloseCh = make(chan int)
  76. // read message from workConn, if it returns any error, notify proxy to start a new workConn
  77. workConnReaderFn := func(conn net.Conn) {
  78. for {
  79. var (
  80. rawMsg msg.Message
  81. errRet error
  82. )
  83. xl.Trace("loop waiting message from udp workConn")
  84. // client will send heartbeat in workConn for keeping alive
  85. _ = conn.SetReadDeadline(time.Now().Add(time.Duration(60) * time.Second))
  86. if rawMsg, errRet = msg.ReadMsg(conn); errRet != nil {
  87. xl.Warn("read from workConn for udp error: %v", errRet)
  88. _ = conn.Close()
  89. // notify proxy to start a new work connection
  90. // ignore error here, it means the proxy is closed
  91. _ = errors.PanicToError(func() {
  92. pxy.checkCloseCh <- 1
  93. })
  94. return
  95. }
  96. if err := conn.SetReadDeadline(time.Time{}); err != nil {
  97. xl.Warn("set read deadline error: %v", err)
  98. }
  99. switch m := rawMsg.(type) {
  100. case *msg.Ping:
  101. xl.Trace("udp work conn get ping message")
  102. continue
  103. case *msg.UDPPacket:
  104. if errRet := errors.PanicToError(func() {
  105. xl.Trace("get udp message from workConn: %s", m.Content)
  106. pxy.readCh <- m
  107. metrics.Server.AddTrafficOut(
  108. pxy.GetName(),
  109. pxy.GetConf().GetBaseInfo().ProxyType,
  110. int64(len(m.Content)),
  111. )
  112. }); errRet != nil {
  113. conn.Close()
  114. xl.Info("reader goroutine for udp work connection closed")
  115. return
  116. }
  117. }
  118. }
  119. }
  120. // send message to workConn
  121. workConnSenderFn := func(conn net.Conn, ctx context.Context) {
  122. var errRet error
  123. for {
  124. select {
  125. case udpMsg, ok := <-pxy.sendCh:
  126. if !ok {
  127. xl.Info("sender goroutine for udp work connection closed")
  128. return
  129. }
  130. if errRet = msg.WriteMsg(conn, udpMsg); errRet != nil {
  131. xl.Info("sender goroutine for udp work connection closed: %v", errRet)
  132. conn.Close()
  133. return
  134. }
  135. xl.Trace("send message to udp workConn: %s", udpMsg.Content)
  136. metrics.Server.AddTrafficIn(
  137. pxy.GetName(),
  138. pxy.GetConf().GetBaseInfo().ProxyType,
  139. int64(len(udpMsg.Content)),
  140. )
  141. continue
  142. case <-ctx.Done():
  143. xl.Info("sender goroutine for udp work connection closed")
  144. return
  145. }
  146. }
  147. }
  148. go func() {
  149. // Sleep a while for waiting control send the NewProxyResp to client.
  150. time.Sleep(500 * time.Millisecond)
  151. for {
  152. workConn, err := pxy.GetWorkConnFromPool(nil, nil)
  153. if err != nil {
  154. time.Sleep(1 * time.Second)
  155. // check if proxy is closed
  156. select {
  157. case _, ok := <-pxy.checkCloseCh:
  158. if !ok {
  159. return
  160. }
  161. default:
  162. }
  163. continue
  164. }
  165. // close the old workConn and replace it with a new one
  166. if pxy.workConn != nil {
  167. pxy.workConn.Close()
  168. }
  169. var rwc io.ReadWriteCloser = workConn
  170. if pxy.cfg.UseEncryption {
  171. rwc, err = frpIo.WithEncryption(rwc, []byte(pxy.serverCfg.Token))
  172. if err != nil {
  173. xl.Error("create encryption stream error: %v", err)
  174. workConn.Close()
  175. continue
  176. }
  177. }
  178. if pxy.cfg.UseCompression {
  179. rwc = frpIo.WithCompression(rwc)
  180. }
  181. pxy.workConn = frpNet.WrapReadWriteCloserToConn(rwc, workConn)
  182. ctx, cancel := context.WithCancel(context.Background())
  183. go workConnReaderFn(pxy.workConn)
  184. go workConnSenderFn(pxy.workConn, ctx)
  185. _, ok := <-pxy.checkCloseCh
  186. cancel()
  187. if !ok {
  188. return
  189. }
  190. }
  191. }()
  192. // Read from user connections and send wrapped udp message to sendCh (forwarded by workConn).
  193. // Client will transfor udp message to local udp service and waiting for response for a while.
  194. // Response will be wrapped to be forwarded by work connection to server.
  195. // Close readCh and sendCh at the end.
  196. go func() {
  197. udp.ForwardUserConn(udpConn, pxy.readCh, pxy.sendCh, int(pxy.serverCfg.UDPPacketSize))
  198. pxy.Close()
  199. }()
  200. return remoteAddr, nil
  201. }
  202. func (pxy *UDPProxy) GetConf() config.ProxyConf {
  203. return pxy.cfg
  204. }
  205. func (pxy *UDPProxy) Close() {
  206. pxy.mu.Lock()
  207. defer pxy.mu.Unlock()
  208. if !pxy.isClosed {
  209. pxy.isClosed = true
  210. pxy.BaseProxy.Close()
  211. if pxy.workConn != nil {
  212. pxy.workConn.Close()
  213. }
  214. pxy.udpConn.Close()
  215. // all channels only closed here
  216. close(pxy.checkCloseCh)
  217. close(pxy.readCh)
  218. close(pxy.sendCh)
  219. }
  220. pxy.rc.UDPPortManager.Release(pxy.realPort)
  221. }