port_mapping.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. package bridge
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "net"
  7. "github.com/docker/libnetwork/types"
  8. "github.com/ishidawataru/sctp"
  9. "github.com/sirupsen/logrus"
  10. )
  11. func (n *bridgeNetwork) allocatePorts(ep *bridgeEndpoint, reqDefBindIP net.IP, ulPxyEnabled bool) ([]types.PortBinding, error) {
  12. if ep.extConnConfig == nil || ep.extConnConfig.PortBindings == nil {
  13. return nil, nil
  14. }
  15. defHostIP := net.IPv4zero // 0.0.0.0
  16. if reqDefBindIP != nil {
  17. defHostIP = reqDefBindIP
  18. }
  19. var containerIPv6 net.IP
  20. if ep.addrv6 != nil {
  21. containerIPv6 = ep.addrv6.IP
  22. }
  23. pb, err := n.allocatePortsInternal(ep.extConnConfig.PortBindings, ep.addr.IP, containerIPv6, defHostIP, ulPxyEnabled)
  24. if err != nil {
  25. return nil, err
  26. }
  27. return pb, nil
  28. }
  29. func (n *bridgeNetwork) allocatePortsInternal(bindings []types.PortBinding, containerIPv4, containerIPv6, defHostIP net.IP, ulPxyEnabled bool) ([]types.PortBinding, error) {
  30. bs := make([]types.PortBinding, 0, len(bindings))
  31. for _, c := range bindings {
  32. bIPv4 := c.GetCopy()
  33. bIPv6 := c.GetCopy()
  34. // Allocate IPv4 Port mappings
  35. if ok := n.validatePortBindingIPv4(&bIPv4, containerIPv4, defHostIP); ok {
  36. if err := n.allocatePort(&bIPv4, ulPxyEnabled); err != nil {
  37. // On allocation failure, release previously allocated ports. On cleanup error, just log a warning message
  38. if cuErr := n.releasePortsInternal(bs); cuErr != nil {
  39. logrus.Warnf("allocation failure for %v, failed to clear previously allocated ipv4 port bindings: %v", bIPv4, cuErr)
  40. }
  41. return nil, err
  42. }
  43. bs = append(bs, bIPv4)
  44. }
  45. // Allocate IPv6 Port mappings
  46. // If the container has no IPv6 address, allow proxying host IPv6 traffic to it
  47. // by setting up the binding with the IPv4 interface if the userland proxy is enabled
  48. // This change was added to keep backward compatibility
  49. containerIP := containerIPv6
  50. if ulPxyEnabled && (containerIPv6 == nil) {
  51. containerIP = containerIPv4
  52. }
  53. if ok := n.validatePortBindingIPv6(&bIPv6, containerIP, defHostIP); ok {
  54. if err := n.allocatePort(&bIPv6, ulPxyEnabled); err != nil {
  55. // On allocation failure, release previously allocated ports. On cleanup error, just log a warning message
  56. if cuErr := n.releasePortsInternal(bs); cuErr != nil {
  57. logrus.Warnf("allocation failure for %v, failed to clear previously allocated ipv6 port bindings: %v", bIPv6, cuErr)
  58. }
  59. return nil, err
  60. }
  61. bs = append(bs, bIPv6)
  62. }
  63. }
  64. return bs, nil
  65. }
  66. // validatePortBindingIPv4 validates the port binding, populates the missing Host IP field and returns true
  67. // if this is a valid IPv4 binding, else returns false
  68. func (n *bridgeNetwork) validatePortBindingIPv4(bnd *types.PortBinding, containerIPv4, defHostIP net.IP) bool {
  69. //Return early if there is a valid Host IP, but its not a IPv4 address
  70. if len(bnd.HostIP) > 0 && bnd.HostIP.To4() == nil {
  71. return false
  72. }
  73. // Adjust the host address in the operational binding
  74. if len(bnd.HostIP) == 0 {
  75. // Return early if the default binding address is an IPv6 address
  76. if defHostIP.To4() == nil {
  77. return false
  78. }
  79. bnd.HostIP = defHostIP
  80. }
  81. bnd.IP = containerIPv4
  82. return true
  83. }
  84. // validatePortBindingIPv6 validates the port binding, populates the missing Host IP field and returns true
  85. // if this is a valid IPv6 binding, else returns false
  86. func (n *bridgeNetwork) validatePortBindingIPv6(bnd *types.PortBinding, containerIP, defHostIP net.IP) bool {
  87. // Return early if there is no container endpoint
  88. if containerIP == nil {
  89. return false
  90. }
  91. // Return early if there is a valid Host IP, which is a IPv4 address
  92. if len(bnd.HostIP) > 0 && bnd.HostIP.To4() != nil {
  93. return false
  94. }
  95. // Setup a binding to "::" if Host IP is empty and the default binding IP is 0.0.0.0
  96. if len(bnd.HostIP) == 0 {
  97. if defHostIP.Equal(net.IPv4zero) {
  98. bnd.HostIP = net.IPv6zero
  99. // If the default binding IP is an IPv6 address, use it
  100. } else if defHostIP.To4() == nil {
  101. bnd.HostIP = defHostIP
  102. // Return false if default binding ip is an IPv4 address
  103. } else {
  104. return false
  105. }
  106. }
  107. bnd.IP = containerIP
  108. return true
  109. }
  110. func (n *bridgeNetwork) allocatePort(bnd *types.PortBinding, ulPxyEnabled bool) error {
  111. var (
  112. host net.Addr
  113. err error
  114. )
  115. // Adjust HostPortEnd if this is not a range.
  116. if bnd.HostPortEnd == 0 {
  117. bnd.HostPortEnd = bnd.HostPort
  118. }
  119. // Construct the container side transport address
  120. container, err := bnd.ContainerAddr()
  121. if err != nil {
  122. return err
  123. }
  124. portmapper := n.portMapper
  125. if bnd.IP.To4() == nil {
  126. portmapper = n.portMapperV6
  127. }
  128. // Try up to maxAllocatePortAttempts times to get a port that's not already allocated.
  129. for i := 0; i < maxAllocatePortAttempts; i++ {
  130. if host, err = portmapper.MapRange(container, bnd.HostIP, int(bnd.HostPort), int(bnd.HostPortEnd), ulPxyEnabled); err == nil {
  131. break
  132. }
  133. // There is no point in immediately retrying to map an explicitly chosen port.
  134. if bnd.HostPort != 0 {
  135. logrus.Warnf("Failed to allocate and map port %d-%d: %s", bnd.HostPort, bnd.HostPortEnd, err)
  136. break
  137. }
  138. logrus.Warnf("Failed to allocate and map port: %s, retry: %d", err, i+1)
  139. }
  140. if err != nil {
  141. return err
  142. }
  143. // Save the host port (regardless it was or not specified in the binding)
  144. switch netAddr := host.(type) {
  145. case *net.TCPAddr:
  146. bnd.HostPort = uint16(host.(*net.TCPAddr).Port)
  147. return nil
  148. case *net.UDPAddr:
  149. bnd.HostPort = uint16(host.(*net.UDPAddr).Port)
  150. return nil
  151. case *sctp.SCTPAddr:
  152. bnd.HostPort = uint16(host.(*sctp.SCTPAddr).Port)
  153. return nil
  154. default:
  155. // For completeness
  156. return ErrUnsupportedAddressType(fmt.Sprintf("%T", netAddr))
  157. }
  158. }
  159. func (n *bridgeNetwork) releasePorts(ep *bridgeEndpoint) error {
  160. return n.releasePortsInternal(ep.portMapping)
  161. }
  162. func (n *bridgeNetwork) releasePortsInternal(bindings []types.PortBinding) error {
  163. var errorBuf bytes.Buffer
  164. // Attempt to release all port bindings, do not stop on failure
  165. for _, m := range bindings {
  166. if err := n.releasePort(m); err != nil {
  167. errorBuf.WriteString(fmt.Sprintf("\ncould not release %v because of %v", m, err))
  168. }
  169. }
  170. if errorBuf.Len() != 0 {
  171. return errors.New(errorBuf.String())
  172. }
  173. return nil
  174. }
  175. func (n *bridgeNetwork) releasePort(bnd types.PortBinding) error {
  176. // Construct the host side transport address
  177. host, err := bnd.HostAddr()
  178. if err != nil {
  179. return err
  180. }
  181. portmapper := n.portMapper
  182. if bnd.HostIP.To4() == nil {
  183. portmapper = n.portMapperV6
  184. }
  185. return portmapper.Unmap(host)
  186. }