udp.go 5.8 KB

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