types.go 14 KB

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