udp.go 5.8 KB

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