✨ New util API command: address

Allows to test a provided or the client's address whether it is a LAN
address, and if so returns the subnet address in CIDR notation.
This commit is contained in:
Gina Häußge committed 2020-11-16 17:55:49 +01:00
1 parent c44e90302d
commit 89f3edcb27
4 files changed
+206 -59

No files matched your search

+34
View File
@@ -398,6 +398,7 @@ def utilTest():
"url": ["url"],
"server": ["host", "port"],
"resolution": ["name"],
"address": [],
}
command, data, response = get_json_command_from_request(request, valid_commands)
@@ -412,6 +413,8 @@ def utilTest():
return _test_server(data)
elif command == "resolution":
return _test_resolution(data)
elif command == "address":
return _test_address(data)
def _test_path(data):
@@ -743,3 +746,34 @@ def _test_resolution(data):
result = {"name": name, "result": resolvable}
return jsonify(**result)
def _test_address(data):
import netaddr
from octoprint.util.net import get_lan_ranges, sanitize_address
remote_addr = data.get("address")
if not remote_addr:
remote_addr = get_remote_address(request)
remote_addr = sanitize_address(remote_addr)
ip = netaddr.IPAddress(remote_addr)
lan_subnets = get_lan_ranges()
detected_subnet = None
for subnet in lan_subnets:
if ip in subnet:
detected_subnet = subnet
break
result = {
"is_lan_address": detected_subnet is not None,
"address": remote_addr,
}
if detected_subnet is not None:
result["subnet"] = str(detected_subnet)
return jsonify(**result)
@@ -64,6 +64,15 @@
return this.test("resolution", data, opts);
};
OctoPrintUtilClient.prototype.testAddress = function (address, additional, opts) {
additional = additional || {};
var data = $.extend({}, additional);
data.address = address;
return this.test("address", data, opts);
};
OctoPrintClient.registerComponent("util", OctoPrintUtilClient);
return OctoPrintUtilClient;
});
+73 -57
View File
@@ -53,71 +53,81 @@ else:
HAS_V6 = False
def get_lan_ranges(additional_private=None):
logger = logging.getLogger(__name__)
if additional_private is None or not isinstance(additional_private, (list, tuple)):
additional_private = []
subnets = list(netaddr.ip.IPV4_PRIVATE) + [
netaddr.ip.IPV4_LOOPBACK,
netaddr.ip.IPV4_LINK_LOCAL,
]
if HAS_V6:
subnets += list(netaddr.ip.IPV6_PRIVATE) + [
netaddr.IPNetwork(netaddr.ip.IPV6_LOOPBACK),
netaddr.ip.IPV6_LINK_LOCAL,
]
for additional in additional_private:
try:
subnets.append(netaddr.IPNetwork(additional))
except Exception:
if logger.isEnabledFor(logging.DEBUG):
logger.exception(
"Error while trying to add additional private network to local subnets: {}".format(
additional
)
)
def to_ipnetwork(address):
prefix = address["netmask"]
if "/" in prefix:
# v6 notation in netifaces output, e.g. "ffff:ffff:ffff:ffff::/64"
_, prefix = prefix.split("/")
addr = strip_interface_tag(address["addr"])
return netaddr.IPNetwork("{}/{}".format(addr, prefix))
for interface in netifaces.interfaces():
addrs = netifaces.ifaddresses(interface)
for v4 in addrs.get(socket.AF_INET, ()):
try:
subnets.append(to_ipnetwork(v4))
except Exception:
if logger.isEnabledFor(logging.DEBUG):
logger.exception(
"Error while trying to add v4 network to local subnets: {!r}".format(
v4
)
)
if HAS_V6:
for v6 in addrs.get(socket.AF_INET6, ()):
try:
subnets.append(to_ipnetwork(v6))
except Exception:
if logger.isEnabledFor(logging.DEBUG):
logger.exception(
"Error while trying to add v6 network to local subnets: {!r}".format(
v6
)
)
return subnets
def is_lan_address(address, additional_private=None):
if not address:
# no address is LAN address
return True
try:
address = unmap_v4_as_v6(address)
address = strip_interface_tag(address)
address = sanitize_address(address)
ip = netaddr.IPAddress(address)
if ip.is_private() or ip.is_loopback():
return True
subnets = get_lan_ranges(additional_private=additional_private)
if additional_private is None or not isinstance(
additional_private, (list, tuple)
):
additional_private = []
subnets = netaddr.IPSet()
for additional in additional_private:
try:
subnets.add(netaddr.IPNetwork(additional))
except Exception:
if logging.getLogger(__name__).isEnabledFor(logging.DEBUG):
logging.getLogger(__name__).exception(
"Error while trying to add additional private network to local subnets: {}".format(
additional
)
)
def to_ipnetwork(address):
prefix = address["netmask"]
if "/" in prefix:
# v6 notation in netifaces output, e.g. "ffff:ffff:ffff:ffff::/64"
_, prefix = prefix.split("/")
addr = strip_interface_tag(address["addr"])
return netaddr.IPNetwork("{}/{}".format(addr, prefix))
for interface in netifaces.interfaces():
addrs = netifaces.ifaddresses(interface)
for v4 in addrs.get(socket.AF_INET, ()):
try:
subnets.add(to_ipnetwork(v4))
except Exception:
if logging.getLogger(__name__).isEnabledFor(logging.DEBUG):
logging.getLogger(__name__).exception(
"Error while trying to add v4 network to local subnets: {!r}".format(
v4
)
)
if HAS_V6:
for v6 in addrs.get(socket.AF_INET6, ()):
try:
subnets.add(to_ipnetwork(v6))
except Exception:
if logging.getLogger(__name__).isEnabledFor(logging.DEBUG):
logging.getLogger(__name__).exception(
"Error while trying to add v6 network to local subnets: {!r}".format(
v6
)
)
if ip in subnets:
if any(map(lambda subnet: ip in subnet, subnets)):
return True
return False
@@ -132,6 +142,12 @@ def is_lan_address(address, additional_private=None):
return True
def sanitize_address(address):
address = unmap_v4_as_v6(address)
address = strip_interface_tag(address)
return address
def strip_interface_tag(address):
if "%" in address:
# interface comment, e.g. "fe80::457f:bbee:d579:1063%wlan0"