ValidateSubnet will validate a given Subnet. It checks if the given gateway and lease range are part of this subnet. If the gateway is empty and addGateway is true it will get the first available ip in the subnet assigned.
(s *types.Subnet, addGateway bool, usedNetworks []*net.IPNet)
| 13 | // gateway is empty and addGateway is true it will get the first |
| 14 | // available ip in the subnet assigned. |
| 15 | func ValidateSubnet(s *types.Subnet, addGateway bool, usedNetworks []*net.IPNet) error { |
| 16 | if s == nil { |
| 17 | return errors.New("subnet is nil") |
| 18 | } |
| 19 | if s.Subnet.IP == nil { |
| 20 | return errors.New("subnet ip is nil") |
| 21 | } |
| 22 | |
| 23 | // Reparse to ensure subnet is valid. |
| 24 | // Do not use types.ParseCIDR() because we want the ip to be |
| 25 | // the network address and not a random ip in the subnet. |
| 26 | _, n, err := net.ParseCIDR(s.Subnet.String()) |
| 27 | if err != nil { |
| 28 | return errors.Wrap(err, "subnet invalid") |
| 29 | } |
| 30 | |
| 31 | // check that the new subnet does not conflict with existing ones |
| 32 | if NetworkIntersectsWithNetworks(n, usedNetworks) { |
| 33 | return errors.Errorf("subnet %s is already used on the host or by another config", n.String()) |
| 34 | } |
| 35 | |
| 36 | s.Subnet = types.IPNet{IPNet: *n} |
| 37 | if s.Gateway != nil { |
| 38 | if !s.Subnet.Contains(s.Gateway) { |
| 39 | return errors.Errorf("gateway %s not in subnet %s", s.Gateway, &s.Subnet) |
| 40 | } |
| 41 | util.NormalizeIP(&s.Gateway) |
| 42 | } else if addGateway { |
| 43 | ip, err := util.FirstIPInSubnet(n) |
| 44 | if err != nil { |
| 45 | return err |
| 46 | } |
| 47 | s.Gateway = ip |
| 48 | } |
| 49 | |
| 50 | if s.LeaseRange != nil { |
| 51 | if s.LeaseRange.StartIP != nil { |
| 52 | if !s.Subnet.Contains(s.LeaseRange.StartIP) { |
| 53 | return errors.Errorf("lease range start ip %s not in subnet %s", s.LeaseRange.StartIP, &s.Subnet) |
| 54 | } |
| 55 | util.NormalizeIP(&s.LeaseRange.StartIP) |
| 56 | } |
| 57 | if s.LeaseRange.EndIP != nil { |
| 58 | if !s.Subnet.Contains(s.LeaseRange.EndIP) { |
| 59 | return errors.Errorf("lease range end ip %s not in subnet %s", s.LeaseRange.EndIP, &s.Subnet) |
| 60 | } |
| 61 | util.NormalizeIP(&s.LeaseRange.EndIP) |
| 62 | } |
| 63 | } |
| 64 | return nil |
| 65 | } |
| 66 | |
| 67 | // ValidateSubnets will validate the subnets for this network. |
| 68 | // It also sets the gateway if the gateway is empty and it sets |
no test coverage detected
searching dependent graphs…