github.com/epfl-dcsl/gotee@v0.0.0-20200909122901-014b35f5e5e9/src/gnet/ip.go (about) 1 // Copyright 2009 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // IP address manipulations 6 // 7 // IPv4 addresses are 4 bytes; IPv6 addresses are 16 bytes. 8 // An IPv4 address can be converted to an IPv6 address by 9 // adding a canonical prefix (10 zeros, 2 0xFFs). 10 // This library accepts either size of byte slice but always 11 // returns 16-byte addresses. 12 13 package gnet 14 15 import _ "unsafe" // for go:linkname 16 17 import "bytes" 18 19 // IP address lengths (bytes). 20 const ( 21 IPv4len = 4 22 IPv6len = 16 23 ) 24 25 // An IP is a single IP address, a slice of bytes. 26 // Functions in this package accept either 4-byte (IPv4) 27 // or 16-byte (IPv6) slices as input. 28 // 29 // Note that in this documentation, referring to an 30 // IP address as an IPv4 address or an IPv6 address 31 // is a semantic property of the address, not just the 32 // length of the byte slice: a 16-byte slice can still 33 // be an IPv4 address. 34 type IP []byte 35 36 // An IP mask is an IP address. 37 type IPMask []byte 38 39 // An IPNet represents an IP network. 40 type IPNet struct { 41 IP IP // network number 42 Mask IPMask // network mask 43 } 44 45 // IPv4 returns the IP address (in 16-byte form) of the 46 // IPv4 address a.b.c.d. 47 func IPv4(a, b, c, d byte) IP { 48 p := make(IP, IPv6len) 49 copy(p, v4InV6Prefix) 50 p[12] = a 51 p[13] = b 52 p[14] = c 53 p[15] = d 54 return p 55 } 56 57 var v4InV6Prefix = []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff} 58 59 // IPv4Mask returns the IP mask (in 4-byte form) of the 60 // IPv4 mask a.b.c.d. 61 func IPv4Mask(a, b, c, d byte) IPMask { 62 p := make(IPMask, IPv4len) 63 p[0] = a 64 p[1] = b 65 p[2] = c 66 p[3] = d 67 return p 68 } 69 70 // CIDRMask returns an IPMask consisting of `ones' 1 bits 71 // followed by 0s up to a total length of `bits' bits. 72 // For a mask of this form, CIDRMask is the inverse of IPMask.Size. 73 func CIDRMask(ones, bits int) IPMask { 74 if bits != 8*IPv4len && bits != 8*IPv6len { 75 return nil 76 } 77 if ones < 0 || ones > bits { 78 return nil 79 } 80 l := bits / 8 81 m := make(IPMask, l) 82 n := uint(ones) 83 for i := 0; i < l; i++ { 84 if n >= 8 { 85 m[i] = 0xff 86 n -= 8 87 continue 88 } 89 m[i] = ^byte(0xff >> n) 90 n = 0 91 } 92 return m 93 } 94 95 // Well-known IPv4 addresses 96 var ( 97 IPv4bcast = IPv4(255, 255, 255, 255) // limited broadcast 98 IPv4allsys = IPv4(224, 0, 0, 1) // all systems 99 IPv4allrouter = IPv4(224, 0, 0, 2) // all routers 100 IPv4zero = IPv4(0, 0, 0, 0) // all zeros 101 ) 102 103 // Well-known IPv6 addresses 104 var ( 105 IPv6zero = IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} 106 IPv6unspecified = IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} 107 IPv6loopback = IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1} 108 IPv6interfacelocalallnodes = IP{0xff, 0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x01} 109 IPv6linklocalallnodes = IP{0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x01} 110 IPv6linklocalallrouters = IP{0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x02} 111 ) 112 113 // IsUnspecified reports whether ip is an unspecified address, either 114 // the IPv4 address "0.0.0.0" or the IPv6 address "::". 115 func (ip IP) IsUnspecified() bool { 116 return ip.Equal(IPv4zero) || ip.Equal(IPv6unspecified) 117 } 118 119 // IsLoopback reports whether ip is a loopback address. 120 func (ip IP) IsLoopback() bool { 121 if ip4 := ip.To4(); ip4 != nil { 122 return ip4[0] == 127 123 } 124 return ip.Equal(IPv6loopback) 125 } 126 127 // IsMulticast reports whether ip is a multicast address. 128 func (ip IP) IsMulticast() bool { 129 if ip4 := ip.To4(); ip4 != nil { 130 return ip4[0]&0xf0 == 0xe0 131 } 132 return len(ip) == IPv6len && ip[0] == 0xff 133 } 134 135 // IsInterfaceLocalMulticast reports whether ip is 136 // an interface-local multicast address. 137 func (ip IP) IsInterfaceLocalMulticast() bool { 138 return len(ip) == IPv6len && ip[0] == 0xff && ip[1]&0x0f == 0x01 139 } 140 141 // IsLinkLocalMulticast reports whether ip is a link-local 142 // multicast address. 143 func (ip IP) IsLinkLocalMulticast() bool { 144 if ip4 := ip.To4(); ip4 != nil { 145 return ip4[0] == 224 && ip4[1] == 0 && ip4[2] == 0 146 } 147 return len(ip) == IPv6len && ip[0] == 0xff && ip[1]&0x0f == 0x02 148 } 149 150 // IsLinkLocalUnicast reports whether ip is a link-local 151 // unicast address. 152 func (ip IP) IsLinkLocalUnicast() bool { 153 if ip4 := ip.To4(); ip4 != nil { 154 return ip4[0] == 169 && ip4[1] == 254 155 } 156 return len(ip) == IPv6len && ip[0] == 0xfe && ip[1]&0xc0 == 0x80 157 } 158 159 // IsGlobalUnicast reports whether ip is a global unicast 160 // address. 161 // 162 // The identification of global unicast addresses uses address type 163 // identification as defined in RFC 1122, RFC 4632 and RFC 4291 with 164 // the exception of IPv4 directed broadcast addresses. 165 // It returns true even if ip is in IPv4 private address space or 166 // local IPv6 unicast address space. 167 func (ip IP) IsGlobalUnicast() bool { 168 return (len(ip) == IPv4len || len(ip) == IPv6len) && 169 !ip.Equal(IPv4bcast) && 170 !ip.IsUnspecified() && 171 !ip.IsLoopback() && 172 !ip.IsMulticast() && 173 !ip.IsLinkLocalUnicast() 174 } 175 176 // Is p all zeros? 177 func isZeros(p IP) bool { 178 for i := 0; i < len(p); i++ { 179 if p[i] != 0 { 180 return false 181 } 182 } 183 return true 184 } 185 186 // To4 converts the IPv4 address ip to a 4-byte representation. 187 // If ip is not an IPv4 address, To4 returns nil. 188 func (ip IP) To4() IP { 189 if len(ip) == IPv4len { 190 return ip 191 } 192 if len(ip) == IPv6len && 193 isZeros(ip[0:10]) && 194 ip[10] == 0xff && 195 ip[11] == 0xff { 196 return ip[12:16] 197 } 198 return nil 199 } 200 201 // To16 converts the IP address ip to a 16-byte representation. 202 // If ip is not an IP address (it is the wrong length), To16 returns nil. 203 func (ip IP) To16() IP { 204 if len(ip) == IPv4len { 205 return IPv4(ip[0], ip[1], ip[2], ip[3]) 206 } 207 if len(ip) == IPv6len { 208 return ip 209 } 210 return nil 211 } 212 213 // Default route masks for IPv4. 214 var ( 215 classAMask = IPv4Mask(0xff, 0, 0, 0) 216 classBMask = IPv4Mask(0xff, 0xff, 0, 0) 217 classCMask = IPv4Mask(0xff, 0xff, 0xff, 0) 218 ) 219 220 // DefaultMask returns the default IP mask for the IP address ip. 221 // Only IPv4 addresses have default masks; DefaultMask returns 222 // nil if ip is not a valid IPv4 address. 223 func (ip IP) DefaultMask() IPMask { 224 if ip = ip.To4(); ip == nil { 225 return nil 226 } 227 switch true { 228 case ip[0] < 0x80: 229 return classAMask 230 case ip[0] < 0xC0: 231 return classBMask 232 default: 233 return classCMask 234 } 235 } 236 237 func allFF(b []byte) bool { 238 for _, c := range b { 239 if c != 0xff { 240 return false 241 } 242 } 243 return true 244 } 245 246 // Mask returns the result of masking the IP address ip with mask. 247 func (ip IP) Mask(mask IPMask) IP { 248 if len(mask) == IPv6len && len(ip) == IPv4len && allFF(mask[:12]) { 249 mask = mask[12:] 250 } 251 if len(mask) == IPv4len && len(ip) == IPv6len && bytesEqual(ip[:12], v4InV6Prefix) { 252 ip = ip[12:] 253 } 254 n := len(ip) 255 if n != len(mask) { 256 return nil 257 } 258 out := make(IP, n) 259 for i := 0; i < n; i++ { 260 out[i] = ip[i] & mask[i] 261 } 262 return out 263 } 264 265 // String returns the string form of the IP address ip. 266 // It returns one of 4 forms: 267 // - "<nil>", if ip has length 0 268 // - dotted decimal ("192.0.2.1"), if ip is an IPv4 or IP4-mapped IPv6 address 269 // - IPv6 ("2001:db8::1"), if ip is a valid IPv6 address 270 // - the hexadecimal form of ip, without punctuation, if no other cases apply 271 func (ip IP) String() string { 272 p := ip 273 274 if len(ip) == 0 { 275 return "<nil>" 276 } 277 278 // If IPv4, use dotted notation. 279 if p4 := p.To4(); len(p4) == IPv4len { 280 return uitoa(uint(p4[0])) + "." + 281 uitoa(uint(p4[1])) + "." + 282 uitoa(uint(p4[2])) + "." + 283 uitoa(uint(p4[3])) 284 } 285 if len(p) != IPv6len { 286 return "?" + hexString(ip) 287 } 288 289 // Find longest run of zeros. 290 e0 := -1 291 e1 := -1 292 for i := 0; i < IPv6len; i += 2 { 293 j := i 294 for j < IPv6len && p[j] == 0 && p[j+1] == 0 { 295 j += 2 296 } 297 if j > i && j-i > e1-e0 { 298 e0 = i 299 e1 = j 300 i = j 301 } 302 } 303 // The symbol "::" MUST NOT be used to shorten just one 16 bit 0 field. 304 if e1-e0 <= 2 { 305 e0 = -1 306 e1 = -1 307 } 308 309 const maxLen = len("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff") 310 b := make([]byte, 0, maxLen) 311 312 // Print with possible :: in place of run of zeros 313 for i := 0; i < IPv6len; i += 2 { 314 if i == e0 { 315 b = append(b, ':', ':') 316 i = e1 317 if i >= IPv6len { 318 break 319 } 320 } else if i > 0 { 321 b = append(b, ':') 322 } 323 b = appendHex(b, (uint32(p[i])<<8)|uint32(p[i+1])) 324 } 325 return string(b) 326 } 327 328 func hexString(b []byte) string { 329 s := make([]byte, len(b)*2) 330 for i, tn := range b { 331 s[i*2], s[i*2+1] = hexDigit[tn>>4], hexDigit[tn&0xf] 332 } 333 return string(s) 334 } 335 336 // ipEmptyString is like ip.String except that it returns 337 // an empty string when ip is unset. 338 func ipEmptyString(ip IP) string { 339 if len(ip) == 0 { 340 return "" 341 } 342 return ip.String() 343 } 344 345 // MarshalText implements the encoding.TextMarshaler interface. 346 // The encoding is the same as returned by String, with one exception: 347 // When len(ip) is zero, it returns an empty slice. 348 func (ip IP) MarshalText() ([]byte, error) { 349 if len(ip) == 0 { 350 return []byte(""), nil 351 } 352 if len(ip) != IPv4len && len(ip) != IPv6len { 353 return nil, &AddrError{Err: "invalid IP address", Addr: hexString(ip)} 354 } 355 return []byte(ip.String()), nil 356 } 357 358 // UnmarshalText implements the encoding.TextUnmarshaler interface. 359 // The IP address is expected in a form accepted by ParseIP. 360 func (ip *IP) UnmarshalText(text []byte) error { 361 if len(text) == 0 { 362 *ip = nil 363 return nil 364 } 365 s := string(text) 366 x := ParseIP(s) 367 if x == nil { 368 return &ParseError{Type: "IP address", Text: s} 369 } 370 *ip = x 371 return nil 372 } 373 374 // Equal reports whether ip and x are the same IP address. 375 // An IPv4 address and that same address in IPv6 form are 376 // considered to be equal. 377 func (ip IP) Equal(x IP) bool { 378 if len(ip) == len(x) { 379 return bytesEqual(ip, x) 380 } 381 if len(ip) == IPv4len && len(x) == IPv6len { 382 return bytesEqual(x[0:12], v4InV6Prefix) && bytesEqual(ip, x[12:]) 383 } 384 if len(ip) == IPv6len && len(x) == IPv4len { 385 return bytesEqual(ip[0:12], v4InV6Prefix) && bytesEqual(ip[12:], x) 386 } 387 return false 388 } 389 390 // bytes.Equal is implemented in runtime/asm_$goarch.s 391 func bytesEqual(x, y []byte) bool { 392 //panic("TODO implement") 393 return bytes.Equal(x, y) 394 } 395 396 func (ip IP) matchAddrFamily(x IP) bool { 397 return ip.To4() != nil && x.To4() != nil || ip.To16() != nil && ip.To4() == nil && x.To16() != nil && x.To4() == nil 398 } 399 400 // If mask is a sequence of 1 bits followed by 0 bits, 401 // return the number of 1 bits. 402 func simpleMaskLength(mask IPMask) int { 403 var n int 404 for i, v := range mask { 405 if v == 0xff { 406 n += 8 407 continue 408 } 409 // found non-ff byte 410 // count 1 bits 411 for v&0x80 != 0 { 412 n++ 413 v <<= 1 414 } 415 // rest must be 0 bits 416 if v != 0 { 417 return -1 418 } 419 for i++; i < len(mask); i++ { 420 if mask[i] != 0 { 421 return -1 422 } 423 } 424 break 425 } 426 return n 427 } 428 429 // Size returns the number of leading ones and total bits in the mask. 430 // If the mask is not in the canonical form--ones followed by zeros--then 431 // Size returns 0, 0. 432 func (m IPMask) Size() (ones, bits int) { 433 ones, bits = simpleMaskLength(m), len(m)*8 434 if ones == -1 { 435 return 0, 0 436 } 437 return 438 } 439 440 // String returns the hexadecimal form of m, with no punctuation. 441 func (m IPMask) String() string { 442 if len(m) == 0 { 443 return "<nil>" 444 } 445 return hexString(m) 446 } 447 448 func networkNumberAndMask(n *IPNet) (ip IP, m IPMask) { 449 if ip = n.IP.To4(); ip == nil { 450 ip = n.IP 451 if len(ip) != IPv6len { 452 return nil, nil 453 } 454 } 455 m = n.Mask 456 switch len(m) { 457 case IPv4len: 458 if len(ip) != IPv4len { 459 return nil, nil 460 } 461 case IPv6len: 462 if len(ip) == IPv4len { 463 m = m[12:] 464 } 465 default: 466 return nil, nil 467 } 468 return 469 } 470 471 // Contains reports whether the network includes ip. 472 func (n *IPNet) Contains(ip IP) bool { 473 nn, m := networkNumberAndMask(n) 474 if x := ip.To4(); x != nil { 475 ip = x 476 } 477 l := len(ip) 478 if l != len(nn) { 479 return false 480 } 481 for i := 0; i < l; i++ { 482 if nn[i]&m[i] != ip[i]&m[i] { 483 return false 484 } 485 } 486 return true 487 } 488 489 // Network returns the address's network name, "ip+net". 490 func (n *IPNet) Network() string { return "ip+net" } 491 492 // String returns the CIDR notation of n like "192.0.2.1/24" 493 // or "2001:db8::/48" as defined in RFC 4632 and RFC 4291. 494 // If the mask is not in the canonical form, it returns the 495 // string which consists of an IP address, followed by a slash 496 // character and a mask expressed as hexadecimal form with no 497 // punctuation like "198.51.100.1/c000ff00". 498 func (n *IPNet) String() string { 499 nn, m := networkNumberAndMask(n) 500 if nn == nil || m == nil { 501 return "<nil>" 502 } 503 l := simpleMaskLength(m) 504 if l == -1 { 505 return nn.String() + "/" + m.String() 506 } 507 return nn.String() + "/" + uitoa(uint(l)) 508 } 509 510 // Parse IPv4 address (d.d.d.d). 511 func parseIPv4(s string) IP { 512 var p [IPv4len]byte 513 for i := 0; i < IPv4len; i++ { 514 if len(s) == 0 { 515 // Missing octets. 516 return nil 517 } 518 if i > 0 { 519 if s[0] != '.' { 520 return nil 521 } 522 s = s[1:] 523 } 524 n, c, ok := dtoi(s) 525 if !ok || n > 0xFF { 526 return nil 527 } 528 s = s[c:] 529 p[i] = byte(n) 530 } 531 if len(s) != 0 { 532 return nil 533 } 534 return IPv4(p[0], p[1], p[2], p[3]) 535 } 536 537 // parseIPv6 parses s as a literal IPv6 address described in RFC 4291 538 // and RFC 5952. It can also parse a literal scoped IPv6 address with 539 // zone identifier which is described in RFC 4007 when zoneAllowed is 540 // true. 541 func parseIPv6(s string, zoneAllowed bool) (ip IP, zone string) { 542 ip = make(IP, IPv6len) 543 ellipsis := -1 // position of ellipsis in ip 544 545 if zoneAllowed { 546 s, zone = splitHostZone(s) 547 } 548 549 // Might have leading ellipsis 550 if len(s) >= 2 && s[0] == ':' && s[1] == ':' { 551 ellipsis = 0 552 s = s[2:] 553 // Might be only ellipsis 554 if len(s) == 0 { 555 return ip, zone 556 } 557 } 558 559 // Loop, parsing hex numbers followed by colon. 560 i := 0 561 for i < IPv6len { 562 // Hex number. 563 n, c, ok := xtoi(s) 564 if !ok || n > 0xFFFF { 565 return nil, zone 566 } 567 568 // If followed by dot, might be in trailing IPv4. 569 if c < len(s) && s[c] == '.' { 570 if ellipsis < 0 && i != IPv6len-IPv4len { 571 // Not the right place. 572 return nil, zone 573 } 574 if i+IPv4len > IPv6len { 575 // Not enough room. 576 return nil, zone 577 } 578 ip4 := parseIPv4(s) 579 if ip4 == nil { 580 return nil, zone 581 } 582 ip[i] = ip4[12] 583 ip[i+1] = ip4[13] 584 ip[i+2] = ip4[14] 585 ip[i+3] = ip4[15] 586 s = "" 587 i += IPv4len 588 break 589 } 590 591 // Save this 16-bit chunk. 592 ip[i] = byte(n >> 8) 593 ip[i+1] = byte(n) 594 i += 2 595 596 // Stop at end of string. 597 s = s[c:] 598 if len(s) == 0 { 599 break 600 } 601 602 // Otherwise must be followed by colon and more. 603 if s[0] != ':' || len(s) == 1 { 604 return nil, zone 605 } 606 s = s[1:] 607 608 // Look for ellipsis. 609 if s[0] == ':' { 610 if ellipsis >= 0 { // already have one 611 return nil, zone 612 } 613 ellipsis = i 614 s = s[1:] 615 if len(s) == 0 { // can be at end 616 break 617 } 618 } 619 } 620 621 // Must have used entire string. 622 if len(s) != 0 { 623 return nil, zone 624 } 625 626 // If didn't parse enough, expand ellipsis. 627 if i < IPv6len { 628 if ellipsis < 0 { 629 return nil, zone 630 } 631 n := IPv6len - i 632 for j := i - 1; j >= ellipsis; j-- { 633 ip[j+n] = ip[j] 634 } 635 for j := ellipsis + n - 1; j >= ellipsis; j-- { 636 ip[j] = 0 637 } 638 } else if ellipsis >= 0 { 639 // Ellipsis must represent at least one 0 group. 640 return nil, zone 641 } 642 return ip, zone 643 } 644 645 // ParseIP parses s as an IP address, returning the result. 646 // The string s can be in dotted decimal ("192.0.2.1") 647 // or IPv6 ("2001:db8::68") form. 648 // If s is not a valid textual representation of an IP address, 649 // ParseIP returns nil. 650 func ParseIP(s string) IP { 651 for i := 0; i < len(s); i++ { 652 switch s[i] { 653 case '.': 654 return parseIPv4(s) 655 case ':': 656 ip, _ := parseIPv6(s, false) 657 return ip 658 } 659 } 660 return nil 661 } 662 663 // ParseCIDR parses s as a CIDR notation IP address and prefix length, 664 // like "192.0.2.0/24" or "2001:db8::/32", as defined in 665 // RFC 4632 and RFC 4291. 666 // 667 // It returns the IP address and the network implied by the IP and 668 // prefix length. 669 // For example, ParseCIDR("192.0.2.1/24") returns the IP address 670 // 192.0.2.1 and the network 192.0.2.0/24. 671 func ParseCIDR(s string) (IP, *IPNet, error) { 672 i := byteIndex(s, '/') 673 if i < 0 { 674 return nil, nil, &ParseError{Type: "CIDR address", Text: s} 675 } 676 addr, mask := s[:i], s[i+1:] 677 iplen := IPv4len 678 ip := parseIPv4(addr) 679 if ip == nil { 680 iplen = IPv6len 681 ip, _ = parseIPv6(addr, false) 682 } 683 n, i, ok := dtoi(mask) 684 if ip == nil || !ok || i != len(mask) || n < 0 || n > 8*iplen { 685 return nil, nil, &ParseError{Type: "CIDR address", Text: s} 686 } 687 m := CIDRMask(n, 8*iplen) 688 return ip, &IPNet{IP: ip.Mask(m), Mask: m}, nil 689 }