-
Notifications
You must be signed in to change notification settings - Fork 0
/
forms.py
161 lines (139 loc) · 5.5 KB
/
forms.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
from __future__ import absolute_import
import socket
from django import forms
from django.utils import simplejson, safestring
class SubnetForm(forms.Form):
"""
The main Django form for the subnet calculator, including the deductive
calculation logic.
"""
address = forms.IPAddressField(required=False)
prefix_6to4 = forms.CharField(required=False, label="6to4 prefix")
prefix_6to4.widget.attrs["readonly"] = "readonly"
hostname = forms.CharField(required=False)
mask = forms.IPAddressField(required=False, label="Subnet (Mask)")
cidr = forms.IntegerField(required=False, label="Subnet (CIDR)")
num_hosts = forms.IntegerField(required=False)
num_hosts.widget.attrs["readonly"] = "readonly"
network = forms.IPAddressField(required=False, label="Subnet ID")
first_host = forms.CharField(required=False)
first_host.widget.attrs["readonly"] = "readonly"
last_host = forms.CharField(required=False)
last_host.widget.attrs["readonly"] = "readonly"
broadcast = forms.CharField(required=False)
broadcast.widget.attrs["readonly"] = "readonly"
exclusive_inputs = [
["mask", "cidr"],
["address", "network", "hostname"],
]
exclusive_inputs_json = safestring.mark_safe(simplejson.dumps(
exclusive_inputs))
def clean(self):
"""
Overridden clean() method which carries out the usual validation and
normalization, but also fills in the gaps in network information based
on the form's data.
"""
self.data = self.get_network_information()
return self.data
@staticmethod
def human_to_int(address):
"""
Take a human-readable IPv4 address in dot notation and convert to an
integer.
"""
parts = address.split(".")
binary_parts = [bin(int(part)).split("b")[-1].rjust(8, "0") for part in
parts]
as_binary = "".join(binary_parts)
return int(as_binary, 2)
@staticmethod
def int_to_human(address):
"""
Take an int representing an IPv4 and convert to the human-readable dot
notation.
Note: although this isn't necesarily to be used as a filter, it follows
the Django convention of returning an empty string on malformed input.
"""
if not isinstance(address, int):
return ""
as_binary = bin(address).split("b")[-1]
as_binary = as_binary.rjust(32, "0")
parts = [as_binary[start:start + 8] for start in range(0, 32, 8)]
return ".".join(str(int(part.ljust(8, "0"), 2)) for part in parts)
@staticmethod
def get_num_hosts(cidr):
"""
Return the number of hosts available to a subnet described in the CIDR
notation (number of contiguous leading bits).
Note: although this isn't necesarily to be used as a filter, it follows
the Django convention of returning an empty string on malformed input.
"""
if not isinstance(cidr, int):
return ""
return 2 ** (32 - cidr) - 2
def get_6to4_prefix(self, address):
if not address:
return ""
parts = (int(part) for part in self.int_to_human(address).split("."))
return "2002:%x%x:%x%x::/48" % tuple(parts)
def get_network_information(self):
"""
Return a dict containing the most comprehensive possible set of
information about a particular network, given the current state of
self.cleaned_data.
"""
address = self.cleaned_data.get("address")
network = self.cleaned_data.get("network")
mask = self.cleaned_data.get("mask")
cidr = self.cleaned_data.get("cidr")
hostname = self.cleaned_data.get("hostname")
if hostname:
try:
address = self.human_to_int(socket.gethostbyname(hostname))
except socket.gaierror:
address = ""
hostname = ""
elif address:
try:
hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(address)
except socket.herror:
hostname = ""
address = self.human_to_int(address)
else:
hostname = ""
prefix_6to4 = self.get_6to4_prefix(address)
if isinstance(cidr, int):
# Force CIDR number to be between 0 and 30, inclusive.
cidr = max(0, cidr)
cidr = min(30, cidr)
mask = int(("1" * cidr).ljust(32, "0"), 2)
elif mask:
mask = self.human_to_int(mask)
cidr = bin(mask).count("1")
num_hosts = self.get_num_hosts(cidr)
if address and isinstance(mask, int):
network = address & mask
elif network:
network = self.human_to_int(network)
if isinstance(network, int):
first_host = network + 1
last_host = network + num_hosts
broadcast = network + num_hosts + 1
else:
network = None
first_host = None
last_host = None
broadcast = None
return ({
"address": self.int_to_human(address),
"prefix_6to4": prefix_6to4,
"broadcast": self.int_to_human(broadcast),
"cidr": cidr,
"first_host": self.int_to_human(first_host),
"hostname": hostname,
"last_host": self.int_to_human(last_host),
"mask": self.int_to_human(mask),
"network": self.int_to_human(network),
"num_hosts": num_hosts,
})