Download this file
| 1 | package edgesfile |
| 2 | |
| 3 | import ( |
| 4 | "net" |
| 5 | "strings" |
| 6 | ) |
| 7 | |
| 8 | // PrivateAddress validates a box's private address against its region |
| 9 | // network's CIDR blocks (region HA spec 2 §6, census ruling region-ha-2a): |
| 10 | // a well-formed IPv4 address, in a private range, neither loopback nor |
| 11 | // link-local (169.254.0.0/16, the metadata range, included), and inside |
| 12 | // one of cidrs. It returns the address and the block that holds it, both |
| 13 | // canonical, or "", "". The writer publishes only what it passes, and a |
| 14 | // reader dials only what it passes against its own region's network. |
| 15 | func PrivateAddress(addr string, cidrs []string) (string, string) { |
| 16 | ip := net.ParseIP(strings.TrimSpace(addr)) |
| 17 | if ip == nil || ip.To4() == nil { |
| 18 | return "", "" |
| 19 | } |
| 20 | ip = ip.To4() |
| 21 | if !ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsUnspecified() { |
| 22 | return "", "" |
| 23 | } |
| 24 | for _, c := range cidrs { |
| 25 | _, block, err := net.ParseCIDR(strings.TrimSpace(c)) |
| 26 | if err != nil || block.IP.To4() == nil { |
| 27 | continue |
| 28 | } |
| 29 | if block.Contains(ip) { |
| 30 | return ip.String(), block.String() |
| 31 | } |
| 32 | } |
| 33 | return "", "" |
| 34 | } |
| 35 | |