mapper.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. package portmapper
  2. import (
  3. "errors"
  4. "fmt"
  5. "net"
  6. "sync"
  7. "github.com/Sirupsen/logrus"
  8. "github.com/docker/libnetwork/iptables"
  9. "github.com/docker/libnetwork/portallocator"
  10. )
  11. type mapping struct {
  12. proto string
  13. userlandProxy userlandProxy
  14. host net.Addr
  15. container net.Addr
  16. }
  17. var newProxy = newProxyCommand
  18. var (
  19. // ErrUnknownBackendAddressType refers to an unknown container or unsupported address type
  20. ErrUnknownBackendAddressType = errors.New("unknown container address type not supported")
  21. // ErrPortMappedForIP refers to a port already mapped to an ip address
  22. ErrPortMappedForIP = errors.New("port is already mapped to ip")
  23. // ErrPortNotMapped refers to an unmapped port
  24. ErrPortNotMapped = errors.New("port is not mapped")
  25. )
  26. // PortMapper manages the network address translation
  27. type PortMapper struct {
  28. chain *iptables.ChainInfo
  29. bridgeName string
  30. // udp:ip:port
  31. currentMappings map[string]*mapping
  32. lock sync.Mutex
  33. Allocator *portallocator.PortAllocator
  34. }
  35. // New returns a new instance of PortMapper
  36. func New() *PortMapper {
  37. return NewWithPortAllocator(portallocator.Get())
  38. }
  39. // NewWithPortAllocator returns a new instance of PortMapper which will use the specified PortAllocator
  40. func NewWithPortAllocator(allocator *portallocator.PortAllocator) *PortMapper {
  41. return &PortMapper{
  42. currentMappings: make(map[string]*mapping),
  43. Allocator: allocator,
  44. }
  45. }
  46. // SetIptablesChain sets the specified chain into portmapper
  47. func (pm *PortMapper) SetIptablesChain(c *iptables.ChainInfo, bridgeName string) {
  48. pm.chain = c
  49. pm.bridgeName = bridgeName
  50. }
  51. // Map maps the specified container transport address to the host's network address and transport port
  52. func (pm *PortMapper) Map(container net.Addr, hostIP net.IP, hostPort int, useProxy bool) (host net.Addr, err error) {
  53. return pm.MapRange(container, hostIP, hostPort, hostPort, useProxy)
  54. }
  55. // MapRange maps the specified container transport address to the host's network address and transport port range
  56. func (pm *PortMapper) MapRange(container net.Addr, hostIP net.IP, hostPortStart, hostPortEnd int, useProxy bool) (host net.Addr, err error) {
  57. pm.lock.Lock()
  58. defer pm.lock.Unlock()
  59. var (
  60. m *mapping
  61. proto string
  62. allocatedHostPort int
  63. )
  64. switch container.(type) {
  65. case *net.TCPAddr:
  66. proto = "tcp"
  67. if allocatedHostPort, err = pm.Allocator.RequestPortInRange(hostIP, proto, hostPortStart, hostPortEnd); err != nil {
  68. return nil, err
  69. }
  70. m = &mapping{
  71. proto: proto,
  72. host: &net.TCPAddr{IP: hostIP, Port: allocatedHostPort},
  73. container: container,
  74. }
  75. if useProxy {
  76. m.userlandProxy = newProxy(proto, hostIP, allocatedHostPort, container.(*net.TCPAddr).IP, container.(*net.TCPAddr).Port)
  77. } else {
  78. m.userlandProxy = newDummyProxy(proto, hostIP, allocatedHostPort)
  79. }
  80. case *net.UDPAddr:
  81. proto = "udp"
  82. if allocatedHostPort, err = pm.Allocator.RequestPortInRange(hostIP, proto, hostPortStart, hostPortEnd); err != nil {
  83. return nil, err
  84. }
  85. m = &mapping{
  86. proto: proto,
  87. host: &net.UDPAddr{IP: hostIP, Port: allocatedHostPort},
  88. container: container,
  89. }
  90. if useProxy {
  91. m.userlandProxy = newProxy(proto, hostIP, allocatedHostPort, container.(*net.UDPAddr).IP, container.(*net.UDPAddr).Port)
  92. } else {
  93. m.userlandProxy = newDummyProxy(proto, hostIP, allocatedHostPort)
  94. }
  95. default:
  96. return nil, ErrUnknownBackendAddressType
  97. }
  98. // release the allocated port on any further error during return.
  99. defer func() {
  100. if err != nil {
  101. pm.Allocator.ReleasePort(hostIP, proto, allocatedHostPort)
  102. }
  103. }()
  104. key := getKey(m.host)
  105. if _, exists := pm.currentMappings[key]; exists {
  106. return nil, ErrPortMappedForIP
  107. }
  108. containerIP, containerPort := getIPAndPort(m.container)
  109. if err := pm.forward(iptables.Append, m.proto, hostIP, allocatedHostPort, containerIP.String(), containerPort); err != nil {
  110. return nil, err
  111. }
  112. cleanup := func() error {
  113. // need to undo the iptables rules before we return
  114. m.userlandProxy.Stop()
  115. pm.forward(iptables.Delete, m.proto, hostIP, allocatedHostPort, containerIP.String(), containerPort)
  116. if err := pm.Allocator.ReleasePort(hostIP, m.proto, allocatedHostPort); err != nil {
  117. return err
  118. }
  119. return nil
  120. }
  121. if err := m.userlandProxy.Start(); err != nil {
  122. if err := cleanup(); err != nil {
  123. return nil, fmt.Errorf("Error during port allocation cleanup: %v", err)
  124. }
  125. return nil, err
  126. }
  127. pm.currentMappings[key] = m
  128. return m.host, nil
  129. }
  130. // Unmap removes stored mapping for the specified host transport address
  131. func (pm *PortMapper) Unmap(host net.Addr) error {
  132. pm.lock.Lock()
  133. defer pm.lock.Unlock()
  134. key := getKey(host)
  135. data, exists := pm.currentMappings[key]
  136. if !exists {
  137. return ErrPortNotMapped
  138. }
  139. if data.userlandProxy != nil {
  140. data.userlandProxy.Stop()
  141. }
  142. delete(pm.currentMappings, key)
  143. containerIP, containerPort := getIPAndPort(data.container)
  144. hostIP, hostPort := getIPAndPort(data.host)
  145. if err := pm.forward(iptables.Delete, data.proto, hostIP, hostPort, containerIP.String(), containerPort); err != nil {
  146. logrus.Errorf("Error on iptables delete: %s", err)
  147. }
  148. switch a := host.(type) {
  149. case *net.TCPAddr:
  150. return pm.Allocator.ReleasePort(a.IP, "tcp", a.Port)
  151. case *net.UDPAddr:
  152. return pm.Allocator.ReleasePort(a.IP, "udp", a.Port)
  153. }
  154. return nil
  155. }
  156. //ReMapAll will re-apply all port mappings
  157. func (pm *PortMapper) ReMapAll() {
  158. logrus.Debugln("Re-applying all port mappings.")
  159. for _, data := range pm.currentMappings {
  160. containerIP, containerPort := getIPAndPort(data.container)
  161. hostIP, hostPort := getIPAndPort(data.host)
  162. if err := pm.forward(iptables.Append, data.proto, hostIP, hostPort, containerIP.String(), containerPort); err != nil {
  163. logrus.Errorf("Error on iptables add: %s", err)
  164. }
  165. }
  166. }
  167. func getKey(a net.Addr) string {
  168. switch t := a.(type) {
  169. case *net.TCPAddr:
  170. return fmt.Sprintf("%s:%d/%s", t.IP.String(), t.Port, "tcp")
  171. case *net.UDPAddr:
  172. return fmt.Sprintf("%s:%d/%s", t.IP.String(), t.Port, "udp")
  173. }
  174. return ""
  175. }
  176. func getIPAndPort(a net.Addr) (net.IP, int) {
  177. switch t := a.(type) {
  178. case *net.TCPAddr:
  179. return t.IP, t.Port
  180. case *net.UDPAddr:
  181. return t.IP, t.Port
  182. }
  183. return nil, 0
  184. }
  185. func (pm *PortMapper) forward(action iptables.Action, proto string, sourceIP net.IP, sourcePort int, containerIP string, containerPort int) error {
  186. if pm.chain == nil {
  187. return nil
  188. }
  189. return pm.chain.Forward(action, sourceIP, sourcePort, proto, containerIP, containerPort, pm.bridgeName)
  190. }