• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2023 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "ip_util.h"
6 
7 namespace bssl {
8 
IsValidNetmask(der::Input mask)9 bool IsValidNetmask(der::Input mask) {
10   if (mask.Length() != kIPv4AddressSize && mask.Length() != kIPv6AddressSize) {
11     return false;
12   }
13 
14   for (size_t i = 0; i < mask.Length(); i++) {
15     uint8_t b = mask[i];
16     if (b != 0xff) {
17       // b must be all ones followed by all zeros, so ~b must be all zeros
18       // followed by all ones.
19       uint8_t inv = ~b;
20       if ((inv & (inv + 1)) != 0) {
21         return false;
22       }
23       // The remaining bytes must be all zeros.
24       for (size_t j = i + 1; j < mask.Length(); j++) {
25         if (mask[j] != 0) {
26           return false;
27         }
28       }
29       return true;
30     }
31   }
32 
33   return true;
34 }
35 
IPAddressMatchesWithNetmask(der::Input addr1,der::Input addr2,der::Input mask)36 bool IPAddressMatchesWithNetmask(der::Input addr1,
37                                  der::Input addr2,
38                                  der::Input mask) {
39   if (addr1.Length() != addr2.Length() || addr1.Length() != mask.Length()) {
40     return false;
41   }
42   for (size_t i = 0; i < addr1.Length(); i++) {
43     if ((addr1[i] & mask[i]) != (addr2[i] & mask[i])) {
44       return false;
45     }
46   }
47   return true;
48 }
49 
50 }  // namespace net
51