commit a6c5a063d1f963a53e012b4c31478f90dea0d795 Author: Damian Johnson atagar@torproject.org Date: Fri Aug 17 10:24:16 2012 -0700
Better validation of controller's from_port() function
I scratched my head due to an awefully misleading stacktrace when I passed a port value into the method's argument slot. Validating the inputs to avoid having this cause confusion in the future.
Before:
Traceback (most recent call last): File "<stdin>", line 1, in <module> File "test/prompt.py", line 67, in controller controller = stem.control.Controller.from_port(CONTROL_PORT) File "stem/control.py", line 457, in from_port control_port = stem.socket.ControlPort(control_addr, control_port) File "stem/socket.py", line 287, in __init__ if connect: self.connect() File "stem/socket.py", line 171, in connect self._socket = self._make_socket() File "stem/socket.py", line 311, in _make_socket control_socket.connect((self._control_addr, str(self._control_port))) File "/usr/lib/python2.7/socket.py", line 224, in meth return getattr(self._sock,name)(*args) TypeError: coercing to Unicode: need string or buffer, int found
After:
Traceback (most recent call last): File "<stdin>", line 1, in <module> File "test/prompt.py", line 67, in controller controller = stem.control.Controller.from_port(CONTROL_PORT) File "stem/control.py", line 459, in from_port raise ValueError("Invalid ip address: %s" % control_addr) ValueError: Invalid ip address: 2779 --- stem/control.py | 6 ++++++ stem/util/connection.py | 2 ++ 2 files changed, 8 insertions(+), 0 deletions(-)
diff --git a/stem/control.py b/stem/control.py index aca6f41..dd5f812 100644 --- a/stem/control.py +++ b/stem/control.py @@ -48,6 +48,7 @@ import threading import stem.response import stem.socket import stem.version +import stem.util.connection import stem.util.log as log
# state changes a control socket can have @@ -454,6 +455,11 @@ class Controller(BaseController): :raises: :class:`stem.socket.SocketError` if we're unable to establish a connection """
+ if not stem.util.connection.is_valid_ip_address(control_addr): + raise ValueError("Invalid IP address: %s" % control_addr) + elif not stem.util.connection.is_valid_port(control_port): + raise ValueError("Invalid port: %s" % control_port) + control_port = stem.socket.ControlPort(control_addr, control_port) return Controller(control_port)
diff --git a/stem/util/connection.py b/stem/util/connection.py index eda3569..02201bb 100644 --- a/stem/util/connection.py +++ b/stem/util/connection.py @@ -39,6 +39,8 @@ def is_valid_ip_address(address): :returns: True if input is a valid IPv4 address, False otherwise """
+ if not isinstance(address, str): return False + # checks if theres four period separated values if address.count(".") != 3: return False
tor-commits@lists.torproject.org