Debian Codegraph @

lib/ansible/module_utils/common/network.py

raw
1 # Copyright (c) 2016 Red Hat Inc
2 # Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
3
4 # General networking tools that may be used by all modules
5
6 from __future__ import annotations
7
8 import re
9
10 # backward compat
11 from builtins import zip # pylint: disable=unused-import
12
13 from struct import pack
14 from socket import inet_ntoa
15
16
17 VALID_MASKS = [2**8 - 2**i for i in range(0, 9)]
18
19
20 def is_netmask(val):
21 parts = str(val).split('.')
22 if not len(parts) == 4:
23 return False
24 mask = 0
25 for part in parts:
26 try:
27 octet = int(part)
28 except ValueError:
29 return False
30 if octet not in VALID_MASKS:
31 return False
32 mask = (mask << 8) | octet
33 inverted = mask ^ 0xFFFFFFFF
34 return inverted & (inverted + 1) == 0
35
36
37 def is_masklen(val):
38 try:
39 return 0 <= int(val) <= 32
40 except ValueError:
41 return False
42
43
44 def to_netmask(val):
45 """ converts a masklen to a netmask """
46 if not is_masklen(val):
47 raise ValueError('invalid value for masklen')
48
49 bits = 0
50 for i in range(32 - int(val), 32):
51 bits |= (1 << i)
52
53 return inet_ntoa(pack('>I', bits))
54
55
56 def to_masklen(val):
57 """ converts a netmask to a masklen """
58 if not is_netmask(val):
59 raise ValueError('invalid value for netmask: %s' % val)
60
61 bits = list()
62 for x in val.split('.'):
63 octet = bin(int(x)).count('1')
64 bits.append(octet)
65
66 return sum(bits)
67
68
69 def to_subnet(addr, mask, dotted_notation=False):
70 """ converts an addr / mask pair to a subnet in cidr notation """
71 try:
72 if not is_masklen(mask):
73 raise ValueError
74 cidr = int(mask)
75 mask = to_netmask(mask)
76 except ValueError:
77 cidr = to_masklen(mask)
78
79 addr = addr.split('.')
80 mask = mask.split('.')
81
82 network = list()
83 for s_addr, s_mask in zip(addr, mask):
84 network.append(str(int(s_addr) & int(s_mask)))
85
86 if dotted_notation:
87 return '%s %s' % ('.'.join(network), to_netmask(cidr))
88 return '%s/%s' % ('.'.join(network), cidr)
89
90
91 def to_ipv6_subnet(addr):
92 """ IPv6 addresses are eight groupings. The first four groupings (64 bits) comprise the subnet address. """
93
94 # https://tools.ietf.org/rfc/rfc2374.txt
95
96 # Split by :: to identify omitted zeros
97 ipv6_prefix = addr.split('::')[0]
98
99 # Get the first four groups, or as many as are found + ::
100 found_groups = []
101 for group in ipv6_prefix.split(':'):
102 found_groups.append(group)
103 if len(found_groups) == 4:
104 break
105 if len(found_groups) < 4:
106 found_groups.append('::')
107
108 # Concatenate network address parts
109 network_addr = ''
110 for group in found_groups:
111 if group != '::':
112 network_addr += str(group)
113 network_addr += str(':')
114
115 # Ensure network address ends with ::
116 if not network_addr.endswith('::'):
117 network_addr += str(':')
118 return network_addr
119
120
121 def to_ipv6_network(addr):
122 """ IPv6 addresses are eight groupings. The first three groupings (48 bits) comprise the network address. """
123
124 # Split by :: to identify omitted zeros
125 ipv6_prefix = addr.split('::')[0]
126
127 # Get the first three groups, or as many as are found + ::
128 found_groups = []
129 for group in ipv6_prefix.split(':'):
130 found_groups.append(group)
131 if len(found_groups) == 3:
132 break
133 if len(found_groups) < 3:
134 found_groups.append('::')
135
136 # Concatenate network address parts
137 network_addr = ''
138 for group in found_groups:
139 if group != '::':
140 network_addr += str(group)
141 network_addr += str(':')
142
143 # Ensure network address ends with ::
144 if not network_addr.endswith('::'):
145 network_addr += str(':')
146 return network_addr
147
148
149 def to_bits(val):
150 """ converts a netmask to bits """
151 bits = ''
152 for octet in val.split('.'):
153 bits += bin(int(octet))[2:].zfill(8)
154 return bits
155
156
157 def is_mac(mac_address, *, strict=False):
158 """
159 Validate MAC address for given string
160 Args:
161 mac_address: string to validate as MAC address
162 strict: when True, anchor the match with ``\\Z`` so a trailing newline is
163 rejected. Defaults to False, which anchors with ``$`` and preserves the
164 historical behavior where a value with a trailing newline is accepted
165 (in Python a regex ``$`` also matches just before a final ``\\n``).
166
167 Returns: (Boolean) True if string is valid MAC address, otherwise False
168 """
169 anchor = '\\Z' if strict else '$'
170 mac_addr_regex = re.compile('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}' + anchor)
171 return bool(mac_addr_regex.match(mac_address.lower()))