types.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. // Package types contains types that are common across libnetwork project
  2. package types
  3. import (
  4. "bytes"
  5. "fmt"
  6. "net"
  7. "strconv"
  8. "strings"
  9. "github.com/docker/docker/errdefs"
  10. "github.com/ishidawataru/sctp"
  11. )
  12. // constants for the IP address type
  13. // Deprecated: use the consts defined in github.com/docker/docker/libnetwork/resolvconf
  14. const (
  15. IP = iota // IPv4 and IPv6
  16. IPv4
  17. IPv6
  18. )
  19. // EncryptionKey is the libnetwork representation of the key distributed by the lead
  20. // manager.
  21. type EncryptionKey struct {
  22. Subsystem string
  23. Algorithm int32
  24. Key []byte
  25. LamportTime uint64
  26. }
  27. // QosPolicy represents a quality of service policy on an endpoint
  28. type QosPolicy struct {
  29. MaxEgressBandwidth uint64
  30. }
  31. // TransportPort represents a local Layer 4 endpoint
  32. type TransportPort struct {
  33. Proto Protocol
  34. Port uint16
  35. }
  36. // Equal checks if this instance of Transportport is equal to the passed one
  37. func (t *TransportPort) Equal(o *TransportPort) bool {
  38. if t == o {
  39. return true
  40. }
  41. if o == nil {
  42. return false
  43. }
  44. if t.Proto != o.Proto || t.Port != o.Port {
  45. return false
  46. }
  47. return true
  48. }
  49. // GetCopy returns a copy of this TransportPort structure instance
  50. func (t *TransportPort) GetCopy() TransportPort {
  51. return TransportPort{Proto: t.Proto, Port: t.Port}
  52. }
  53. // String returns the TransportPort structure in string form
  54. func (t *TransportPort) String() string {
  55. return fmt.Sprintf("%s/%d", t.Proto.String(), t.Port)
  56. }
  57. // PortBinding represents a port binding between the container and the host
  58. type PortBinding struct {
  59. Proto Protocol
  60. IP net.IP
  61. Port uint16
  62. HostIP net.IP
  63. HostPort uint16
  64. HostPortEnd uint16
  65. }
  66. // HostAddr returns the host side transport address
  67. func (p PortBinding) HostAddr() (net.Addr, error) {
  68. switch p.Proto {
  69. case UDP:
  70. return &net.UDPAddr{IP: p.HostIP, Port: int(p.HostPort)}, nil
  71. case TCP:
  72. return &net.TCPAddr{IP: p.HostIP, Port: int(p.HostPort)}, nil
  73. case SCTP:
  74. return &sctp.SCTPAddr{IPAddrs: []net.IPAddr{{IP: p.HostIP}}, Port: int(p.HostPort)}, nil
  75. default:
  76. return nil, fmt.Errorf("invalid transport protocol: %s", p.Proto.String())
  77. }
  78. }
  79. // ContainerAddr returns the container side transport address
  80. func (p PortBinding) ContainerAddr() (net.Addr, error) {
  81. switch p.Proto {
  82. case UDP:
  83. return &net.UDPAddr{IP: p.IP, Port: int(p.Port)}, nil
  84. case TCP:
  85. return &net.TCPAddr{IP: p.IP, Port: int(p.Port)}, nil
  86. case SCTP:
  87. return &sctp.SCTPAddr{IPAddrs: []net.IPAddr{{IP: p.IP}}, Port: int(p.Port)}, nil
  88. default:
  89. return nil, fmt.Errorf("invalid transport protocol: %s", p.Proto.String())
  90. }
  91. }
  92. // GetCopy returns a copy of this PortBinding structure instance
  93. func (p *PortBinding) GetCopy() PortBinding {
  94. return PortBinding{
  95. Proto: p.Proto,
  96. IP: GetIPCopy(p.IP),
  97. Port: p.Port,
  98. HostIP: GetIPCopy(p.HostIP),
  99. HostPort: p.HostPort,
  100. HostPortEnd: p.HostPortEnd,
  101. }
  102. }
  103. // String returns the PortBinding structure in string form
  104. func (p *PortBinding) String() string {
  105. ret := fmt.Sprintf("%s/", p.Proto)
  106. if p.IP != nil {
  107. ret += p.IP.String()
  108. }
  109. ret = fmt.Sprintf("%s:%d/", ret, p.Port)
  110. if p.HostIP != nil {
  111. ret += p.HostIP.String()
  112. }
  113. ret = fmt.Sprintf("%s:%d", ret, p.HostPort)
  114. return ret
  115. }
  116. const (
  117. // ICMP is for the ICMP ip protocol
  118. ICMP = 1
  119. // TCP is for the TCP ip protocol
  120. TCP = 6
  121. // UDP is for the UDP ip protocol
  122. UDP = 17
  123. // SCTP is for the SCTP ip protocol
  124. SCTP = 132
  125. )
  126. // Protocol represents an IP protocol number
  127. type Protocol uint8
  128. func (p Protocol) String() string {
  129. switch p {
  130. case ICMP:
  131. return "icmp"
  132. case TCP:
  133. return "tcp"
  134. case UDP:
  135. return "udp"
  136. case SCTP:
  137. return "sctp"
  138. default:
  139. return strconv.Itoa(int(p))
  140. }
  141. }
  142. // ParseProtocol returns the respective Protocol type for the passed string
  143. func ParseProtocol(s string) Protocol {
  144. switch strings.ToLower(s) {
  145. case "icmp":
  146. return ICMP
  147. case "udp":
  148. return UDP
  149. case "tcp":
  150. return TCP
  151. case "sctp":
  152. return SCTP
  153. default:
  154. return 0
  155. }
  156. }
  157. // GetMacCopy returns a copy of the passed MAC address
  158. func GetMacCopy(from net.HardwareAddr) net.HardwareAddr {
  159. if from == nil {
  160. return nil
  161. }
  162. to := make(net.HardwareAddr, len(from))
  163. copy(to, from)
  164. return to
  165. }
  166. // GetIPCopy returns a copy of the passed IP address
  167. func GetIPCopy(from net.IP) net.IP {
  168. if from == nil {
  169. return nil
  170. }
  171. to := make(net.IP, len(from))
  172. copy(to, from)
  173. return to
  174. }
  175. // GetIPNetCopy returns a copy of the passed IP Network
  176. func GetIPNetCopy(from *net.IPNet) *net.IPNet {
  177. if from == nil {
  178. return nil
  179. }
  180. bm := make(net.IPMask, len(from.Mask))
  181. copy(bm, from.Mask)
  182. return &net.IPNet{IP: GetIPCopy(from.IP), Mask: bm}
  183. }
  184. // GetIPNetCanonical returns the canonical form for the passed network
  185. func GetIPNetCanonical(nw *net.IPNet) *net.IPNet {
  186. if nw == nil {
  187. return nil
  188. }
  189. c := GetIPNetCopy(nw)
  190. c.IP = c.IP.Mask(nw.Mask)
  191. return c
  192. }
  193. // CompareIPNet returns equal if the two IP Networks are equal
  194. func CompareIPNet(a, b *net.IPNet) bool {
  195. if a == b {
  196. return true
  197. }
  198. if a == nil || b == nil {
  199. return false
  200. }
  201. return a.IP.Equal(b.IP) && bytes.Equal(a.Mask, b.Mask)
  202. }
  203. // IsIPNetValid returns true if the ipnet is a valid network/mask
  204. // combination. Otherwise returns false.
  205. func IsIPNetValid(nw *net.IPNet) bool {
  206. return nw.String() != "0.0.0.0/0"
  207. }
  208. var v4inV6MaskPrefix = []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
  209. // compareIPMask checks if the passed ip and mask are semantically compatible.
  210. // It returns the byte indexes for the address and mask so that caller can
  211. // do bitwise operations without modifying address representation.
  212. func compareIPMask(ip net.IP, mask net.IPMask) (is int, ms int, err error) {
  213. // Find the effective starting of address and mask
  214. if len(ip) == net.IPv6len && ip.To4() != nil {
  215. is = 12
  216. }
  217. if len(ip[is:]) == net.IPv4len && len(mask) == net.IPv6len && bytes.Equal(mask[:12], v4inV6MaskPrefix) {
  218. ms = 12
  219. }
  220. // Check if address and mask are semantically compatible
  221. if len(ip[is:]) != len(mask[ms:]) {
  222. err = fmt.Errorf("ip and mask are not compatible: (%#v, %#v)", ip, mask)
  223. }
  224. return
  225. }
  226. // GetHostPartIP returns the host portion of the ip address identified by the mask.
  227. // IP address representation is not modified. If address and mask are not compatible
  228. // an error is returned.
  229. func GetHostPartIP(ip net.IP, mask net.IPMask) (net.IP, error) {
  230. // Find the effective starting of address and mask
  231. is, ms, err := compareIPMask(ip, mask)
  232. if err != nil {
  233. return nil, fmt.Errorf("cannot compute host portion ip address because %s", err)
  234. }
  235. // Compute host portion
  236. out := GetIPCopy(ip)
  237. for i := 0; i < len(mask[ms:]); i++ {
  238. out[is+i] &= ^mask[ms+i]
  239. }
  240. return out, nil
  241. }
  242. // GetBroadcastIP returns the broadcast ip address for the passed network (ip and mask).
  243. // IP address representation is not modified. If address and mask are not compatible
  244. // an error is returned.
  245. func GetBroadcastIP(ip net.IP, mask net.IPMask) (net.IP, error) {
  246. // Find the effective starting of address and mask
  247. is, ms, err := compareIPMask(ip, mask)
  248. if err != nil {
  249. return nil, fmt.Errorf("cannot compute broadcast ip address because %s", err)
  250. }
  251. // Compute broadcast address
  252. out := GetIPCopy(ip)
  253. for i := 0; i < len(mask[ms:]); i++ {
  254. out[is+i] |= ^mask[ms+i]
  255. }
  256. return out, nil
  257. }
  258. // ParseCIDR returns the *net.IPNet represented by the passed CIDR notation
  259. func ParseCIDR(cidr string) (n *net.IPNet, e error) {
  260. var i net.IP
  261. if i, n, e = net.ParseCIDR(cidr); e == nil {
  262. n.IP = i
  263. }
  264. return
  265. }
  266. const (
  267. // NEXTHOP indicates a StaticRoute with an IP next hop.
  268. NEXTHOP = iota
  269. // CONNECTED indicates a StaticRoute with an interface for directly connected peers.
  270. CONNECTED
  271. )
  272. // StaticRoute is a statically-provisioned IP route.
  273. type StaticRoute struct {
  274. Destination *net.IPNet
  275. RouteType int // NEXT_HOP or CONNECTED
  276. // NextHop will be resolved by the kernel (i.e. as a loose hop).
  277. NextHop net.IP
  278. }
  279. // GetCopy returns a copy of this StaticRoute structure
  280. func (r *StaticRoute) GetCopy() *StaticRoute {
  281. d := GetIPNetCopy(r.Destination)
  282. nh := GetIPCopy(r.NextHop)
  283. return &StaticRoute{
  284. Destination: d,
  285. RouteType: r.RouteType,
  286. NextHop: nh,
  287. }
  288. }
  289. // InterfaceStatistics represents the interface's statistics
  290. type InterfaceStatistics struct {
  291. RxBytes uint64
  292. RxPackets uint64
  293. RxErrors uint64
  294. RxDropped uint64
  295. TxBytes uint64
  296. TxPackets uint64
  297. TxErrors uint64
  298. TxDropped uint64
  299. }
  300. func (is *InterfaceStatistics) String() string {
  301. return fmt.Sprintf("\nRxBytes: %d, RxPackets: %d, RxErrors: %d, RxDropped: %d, TxBytes: %d, TxPackets: %d, TxErrors: %d, TxDropped: %d",
  302. is.RxBytes, is.RxPackets, is.RxErrors, is.RxDropped, is.TxBytes, is.TxPackets, is.TxErrors, is.TxDropped)
  303. }
  304. /******************************
  305. * Well-known Error Interfaces
  306. ******************************/
  307. // MaskableError is an interface for errors which can be ignored by caller
  308. type MaskableError interface {
  309. // Maskable makes implementer into MaskableError type
  310. Maskable()
  311. }
  312. // InvalidParameterError is an interface for errors originated by a bad request
  313. type InvalidParameterError interface {
  314. // InvalidParameter makes implementer into InvalidParameterError type
  315. InvalidParameter()
  316. }
  317. // NotFoundError is an interface for errors raised because a needed resource is not available
  318. type NotFoundError interface {
  319. // NotFound makes implementer into NotFoundError type
  320. NotFound()
  321. }
  322. // ForbiddenError is an interface for errors which denote a valid request that cannot be honored
  323. type ForbiddenError interface {
  324. // Forbidden makes implementer into ForbiddenError type
  325. Forbidden()
  326. }
  327. // UnavailableError is an interface for errors returned when the required service is not available
  328. type UnavailableError interface {
  329. // Unavailable makes implementer into UnavailableError type
  330. Unavailable()
  331. }
  332. // NotImplementedError is an interface for errors raised because of requested functionality is not yet implemented
  333. type NotImplementedError interface {
  334. // NotImplemented makes implementer into NotImplementedError type
  335. NotImplemented()
  336. }
  337. // InternalError is an interface for errors raised because of an internal error
  338. type InternalError interface {
  339. // Internal makes implementer into InternalError type
  340. Internal()
  341. }
  342. /******************************
  343. * Well-known Error Formatters
  344. ******************************/
  345. // InvalidParameterErrorf creates an instance of InvalidParameterError
  346. func InvalidParameterErrorf(format string, params ...interface{}) error {
  347. return errdefs.InvalidParameter(fmt.Errorf(format, params...))
  348. }
  349. // NotFoundErrorf creates an instance of NotFoundError
  350. func NotFoundErrorf(format string, params ...interface{}) error {
  351. return notFound(fmt.Sprintf(format, params...))
  352. }
  353. // ForbiddenErrorf creates an instance of ForbiddenError
  354. func ForbiddenErrorf(format string, params ...interface{}) error {
  355. return forbidden(fmt.Sprintf(format, params...))
  356. }
  357. // UnavailableErrorf creates an instance of UnavailableError
  358. func UnavailableErrorf(format string, params ...interface{}) error {
  359. return unavailable(fmt.Sprintf(format, params...))
  360. }
  361. // NotImplementedErrorf creates an instance of NotImplementedError
  362. func NotImplementedErrorf(format string, params ...interface{}) error {
  363. return notImpl(fmt.Sprintf(format, params...))
  364. }
  365. // InternalErrorf creates an instance of InternalError
  366. func InternalErrorf(format string, params ...interface{}) error {
  367. return internal(fmt.Sprintf(format, params...))
  368. }
  369. // InternalMaskableErrorf creates an instance of InternalError and MaskableError
  370. func InternalMaskableErrorf(format string, params ...interface{}) error {
  371. return maskInternal(fmt.Sprintf(format, params...))
  372. }
  373. /***********************
  374. * Internal Error Types
  375. ***********************/
  376. type notFound string
  377. func (nf notFound) Error() string {
  378. return string(nf)
  379. }
  380. func (nf notFound) NotFound() {}
  381. type forbidden string
  382. func (frb forbidden) Error() string {
  383. return string(frb)
  384. }
  385. func (frb forbidden) Forbidden() {}
  386. type unavailable string
  387. func (ns unavailable) Error() string {
  388. return string(ns)
  389. }
  390. func (ns unavailable) Unavailable() {}
  391. type notImpl string
  392. func (ni notImpl) Error() string {
  393. return string(ni)
  394. }
  395. func (ni notImpl) NotImplemented() {}
  396. type internal string
  397. func (nt internal) Error() string {
  398. return string(nt)
  399. }
  400. func (nt internal) Internal() {}
  401. type maskInternal string
  402. func (mnt maskInternal) Error() string {
  403. return string(mnt)
  404. }
  405. func (mnt maskInternal) Internal() {}
  406. func (mnt maskInternal) Maskable() {}