udp_proxy.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. package main
  2. import (
  3. "encoding/binary"
  4. "log"
  5. "net"
  6. "strings"
  7. "sync"
  8. "syscall"
  9. "time"
  10. )
  11. const (
  12. // UDPConnTrackTimeout is the timeout used for UDP connection tracking
  13. UDPConnTrackTimeout = 90 * time.Second
  14. // UDPBufSize is the buffer size for the UDP proxy
  15. UDPBufSize = 65507
  16. )
  17. // A net.Addr where the IP is split into two fields so you can use it as a key
  18. // in a map:
  19. type connTrackKey struct {
  20. IPHigh uint64
  21. IPLow uint64
  22. Port int
  23. }
  24. func newConnTrackKey(addr *net.UDPAddr) *connTrackKey {
  25. if len(addr.IP) == net.IPv4len {
  26. return &connTrackKey{
  27. IPHigh: 0,
  28. IPLow: uint64(binary.BigEndian.Uint32(addr.IP)),
  29. Port: addr.Port,
  30. }
  31. }
  32. return &connTrackKey{
  33. IPHigh: binary.BigEndian.Uint64(addr.IP[:8]),
  34. IPLow: binary.BigEndian.Uint64(addr.IP[8:]),
  35. Port: addr.Port,
  36. }
  37. }
  38. type connTrackMap map[connTrackKey]*net.UDPConn
  39. // UDPProxy is proxy for which handles UDP datagrams. It implements the Proxy
  40. // interface to handle UDP traffic forwarding between the frontend and backend
  41. // addresses.
  42. type UDPProxy struct {
  43. listener *net.UDPConn
  44. frontendAddr *net.UDPAddr
  45. backendAddr *net.UDPAddr
  46. connTrackTable connTrackMap
  47. connTrackLock sync.Mutex
  48. }
  49. // NewUDPProxy creates a new UDPProxy.
  50. func NewUDPProxy(frontendAddr, backendAddr *net.UDPAddr) (*UDPProxy, error) {
  51. // detect version of hostIP to bind only to correct version
  52. ipVersion := ipv4
  53. if frontendAddr.IP.To4() == nil {
  54. ipVersion = ipv6
  55. }
  56. listener, err := net.ListenUDP("udp"+string(ipVersion), frontendAddr)
  57. if err != nil {
  58. return nil, err
  59. }
  60. return &UDPProxy{
  61. listener: listener,
  62. frontendAddr: listener.LocalAddr().(*net.UDPAddr),
  63. backendAddr: backendAddr,
  64. connTrackTable: make(connTrackMap),
  65. }, nil
  66. }
  67. func (proxy *UDPProxy) replyLoop(proxyConn *net.UDPConn, clientAddr *net.UDPAddr, clientKey *connTrackKey) {
  68. defer func() {
  69. proxy.connTrackLock.Lock()
  70. delete(proxy.connTrackTable, *clientKey)
  71. proxy.connTrackLock.Unlock()
  72. proxyConn.Close()
  73. }()
  74. readBuf := make([]byte, UDPBufSize)
  75. for {
  76. proxyConn.SetReadDeadline(time.Now().Add(UDPConnTrackTimeout))
  77. again:
  78. read, err := proxyConn.Read(readBuf)
  79. if err != nil {
  80. if err, ok := err.(*net.OpError); ok && err.Err == syscall.ECONNREFUSED {
  81. // This will happen if the last write failed
  82. // (e.g: nothing is actually listening on the
  83. // proxied port on the container), ignore it
  84. // and continue until UDPConnTrackTimeout
  85. // expires:
  86. goto again
  87. }
  88. return
  89. }
  90. for i := 0; i != read; {
  91. written, err := proxy.listener.WriteToUDP(readBuf[i:read], clientAddr)
  92. if err != nil {
  93. return
  94. }
  95. i += written
  96. }
  97. }
  98. }
  99. // Run starts forwarding the traffic using UDP.
  100. func (proxy *UDPProxy) Run() {
  101. readBuf := make([]byte, UDPBufSize)
  102. for {
  103. read, from, err := proxy.listener.ReadFromUDP(readBuf)
  104. if err != nil {
  105. // NOTE: Apparently ReadFrom doesn't return
  106. // ECONNREFUSED like Read do (see comment in
  107. // UDPProxy.replyLoop)
  108. if !isClosedError(err) {
  109. log.Printf("Stopping proxy on udp/%v for udp/%v (%s)", proxy.frontendAddr, proxy.backendAddr, err)
  110. }
  111. break
  112. }
  113. fromKey := newConnTrackKey(from)
  114. proxy.connTrackLock.Lock()
  115. proxyConn, hit := proxy.connTrackTable[*fromKey]
  116. if !hit {
  117. proxyConn, err = net.DialUDP("udp", nil, proxy.backendAddr)
  118. if err != nil {
  119. log.Printf("Can't proxy a datagram to udp/%s: %s\n", proxy.backendAddr, err)
  120. proxy.connTrackLock.Unlock()
  121. continue
  122. }
  123. proxy.connTrackTable[*fromKey] = proxyConn
  124. go proxy.replyLoop(proxyConn, from, fromKey)
  125. }
  126. proxy.connTrackLock.Unlock()
  127. for i := 0; i != read; {
  128. written, err := proxyConn.Write(readBuf[i:read])
  129. if err != nil {
  130. log.Printf("Can't proxy a datagram to udp/%s: %s\n", proxy.backendAddr, err)
  131. break
  132. }
  133. i += written
  134. }
  135. }
  136. }
  137. // Close stops forwarding the traffic.
  138. func (proxy *UDPProxy) Close() {
  139. proxy.listener.Close()
  140. proxy.connTrackLock.Lock()
  141. defer proxy.connTrackLock.Unlock()
  142. for _, conn := range proxy.connTrackTable {
  143. conn.Close()
  144. }
  145. }
  146. // FrontendAddr returns the UDP address on which the proxy is listening.
  147. func (proxy *UDPProxy) FrontendAddr() net.Addr { return proxy.frontendAddr }
  148. // BackendAddr returns the proxied UDP address.
  149. func (proxy *UDPProxy) BackendAddr() net.Addr { return proxy.backendAddr }
  150. func isClosedError(err error) bool {
  151. /* This comparison is ugly, but unfortunately, net.go doesn't export errClosing.
  152. * See:
  153. * http://golang.org/src/pkg/net/net.go
  154. * https://code.google.com/p/go/issues/detail?id=4337
  155. * https://groups.google.com/forum/#!msg/golang-nuts/0_aaCvBmOcM/SptmDyX1XJMJ
  156. */
  157. return strings.HasSuffix(err.Error(), "use of closed network connection")
  158. }