Skip to content

Commit

Permalink
broker: Replace regex-parsing logic with urllib.parse.split
Browse files Browse the repository at this point in the history
  • Loading branch information
sjlongland committed Aug 17, 2021
1 parent edc743e commit 71d308a
Showing 1 changed file with 11 additions and 23 deletions.
34 changes: 11 additions & 23 deletions amqtt/broker.py
Expand Up @@ -9,6 +9,7 @@
import websockets
import asyncio
import re
import urllib.parse
from asyncio import CancelledError
from collections import deque

Expand Down Expand Up @@ -127,12 +128,6 @@ class ListenerConfig(object):
"""
Configuration for a given listener.
"""
# Regexes for matching specific IP address/port combos
# The matching of the IP address is approximate, we just want to catch enough
# for `ipaddress` module to do the heavy lifting.
IPV4_RE = re.compile(r"^([\d\.]+):(\d+)$")
IPV6_RE = re.compile(r"^\[([0-9a-f:]+)\]:(\d+)$", re.IGNORECASE)

def __init__(
self,
type: Union[ListenerType, str],
Expand Down Expand Up @@ -163,25 +158,18 @@ def __init__(
# We filter the address string through `ipaddress` to validate it.
if bind:
try:
str_address: Optional[str] = None
str_port: Optional[str] = None
uri = urllib.parse.urlsplit("//%s" % bind)

if uri.port:
self.port = uri.port

match_v6 = self.IPV6_RE.match(bind)
if match_v6:
(str_address, str_port) = match_v6.groups()
self.address = str(ipaddress.IPv6Address(str_address))
if uri.hostname:
# Validate IP address part
self.address = str(ipaddress.ip_address(uri.hostname))
else:
match_v4 = self.IPV4_RE.match(bind)
if match_v4:
(str_address, str_port) = match_v4.groups()
self.address = str(ipaddress.IPv4Address(str_address))
elif bind.startswith(':'):
# Empty address
(_, str_port) = bind.rsplit(':', 1)
else:
str_port = bind

self.port = int(str_port)
# Maybe we were given the port on its own?
self.address = None
self.port = int(uri.hostname)
except ValueError as e:
raise BrokerException(
"Invalid address given in bind value: %r" % (bind,)
Expand Down

0 comments on commit 71d308a

Please sign in to comment.