torwire 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
torwire/controller.py ADDED
@@ -0,0 +1,189 @@
1
+ """Tor control-port wrapper built on stem."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import time
7
+ from dataclasses import dataclass
8
+
9
+ import stem
10
+ import stem.control
11
+
12
+ from torwire.errors import ControlError, NewIdentityError, NotRunningError
13
+
14
+ logger = logging.getLogger("torwire")
15
+
16
+ _MIN_NEWNYM_INTERVAL = 10.0
17
+
18
+
19
+ @dataclass
20
+ class CircuitInfo:
21
+ """Information about an active Tor circuit."""
22
+
23
+ id: str
24
+ status: str
25
+ path: list[str]
26
+ build_time: float | None = None
27
+
28
+
29
+ class TorController:
30
+ """Wraps :class:`stem.control.Controller` for identity rotation and introspection."""
31
+
32
+ def __init__(
33
+ self,
34
+ control_port: int,
35
+ password: str = "",
36
+ host: str = "127.0.0.1",
37
+ ) -> None:
38
+ self._host = host
39
+ self._port = control_port
40
+ self._password = password
41
+ self._controller: stem.control.Controller | None = None
42
+ self._last_newnym: float = 0.0
43
+
44
+ def connect(self) -> None:
45
+ """Connect and authenticate to the Tor control port.
46
+
47
+ Raises:
48
+ ControlError: If connection or authentication fails.
49
+ """
50
+ try:
51
+ ctrl = stem.control.Controller.from_port(
52
+ address=self._host,
53
+ port=self._port,
54
+ )
55
+ if self._password:
56
+ ctrl.authenticate(password=self._password)
57
+ else:
58
+ ctrl.authenticate()
59
+ self._controller = ctrl
60
+ except Exception as exc:
61
+ raise ControlError(
62
+ f"Failed to connect to Tor control port {self._host}:{self._port}: {exc}"
63
+ ) from exc
64
+
65
+ def close(self) -> None:
66
+ """Close the control-port connection."""
67
+ if self._controller is not None:
68
+ try:
69
+ self._controller.close()
70
+ except Exception:
71
+ pass
72
+ self._controller = None
73
+
74
+ @property
75
+ def connected(self) -> bool:
76
+ """Return ``True`` if connected and the control socket is alive."""
77
+ return self._controller is not None and self._controller.is_alive()
78
+
79
+ def _require_connected(self) -> stem.control.Controller:
80
+ if self._controller is None or not self._controller.is_alive():
81
+ raise NotRunningError("Not connected to Tor control port.")
82
+ return self._controller
83
+
84
+ def new_identity(self, wait: bool = True, timeout: float = 30.0) -> None:
85
+ """Send ``NEWNYM`` to Tor to request fresh circuits.
86
+
87
+ Enforces Tor's 10-second rate limit between ``NEWNYM`` signals.
88
+
89
+ Args:
90
+ wait: If ``True``, pause briefly after signalling so new circuits
91
+ can be established.
92
+ timeout: Maximum seconds to wait (capped against rate-limit delay).
93
+
94
+ Raises:
95
+ NewIdentityError: If sending the ``NEWNYM`` signal fails.
96
+ NotRunningError: If the controller is not connected.
97
+ """
98
+ ctrl = self._require_connected()
99
+
100
+ elapsed = time.monotonic() - self._last_newnym
101
+ if self._last_newnym > 0 and elapsed < _MIN_NEWNYM_INTERVAL:
102
+ remaining = _MIN_NEWNYM_INTERVAL - elapsed
103
+ if wait:
104
+ sleep_time = min(remaining, timeout)
105
+ logger.debug("Rate-limiting NEWNYM; sleeping %.2fs", sleep_time)
106
+ time.sleep(sleep_time)
107
+
108
+ try:
109
+ ctrl.signal(stem.Signal.NEWNYM)
110
+ self._last_newnym = time.monotonic()
111
+ except stem.ControllerError as exc:
112
+ raise NewIdentityError(f"NEWNYM signal failed: {exc}") from exc
113
+
114
+ if wait:
115
+ time.sleep(min(1.5, timeout))
116
+
117
+ def circuits(self) -> list[CircuitInfo]:
118
+ """Return a list of current Tor circuits."""
119
+ ctrl = self._require_connected()
120
+ result: list[CircuitInfo] = []
121
+ try:
122
+ for circ in ctrl.get_circuits():
123
+ result.append(
124
+ CircuitInfo(
125
+ id=str(circ.id),
126
+ status=str(circ.status),
127
+ path=[entry[0] for entry in circ.path],
128
+ build_time=None,
129
+ )
130
+ )
131
+ except stem.ControllerError as exc:
132
+ raise ControlError(f"Failed to list circuits: {exc}") from exc
133
+ return result
134
+
135
+ def set_exit_countries(self, codes: list[str], strict: bool = False) -> None:
136
+ """Configure preferred exit node countries at runtime.
137
+
138
+ Args:
139
+ codes: List of ISO-3166 alpha-2 country codes (e.g. ``["us", "de"]``).
140
+ strict: If ``True``, set ``StrictNodes 1``.
141
+ """
142
+ ctrl = self._require_connected()
143
+ try:
144
+ formatted = ",".join(
145
+ c if (c.startswith("{") and c.endswith("}")) else f"{{{c}}}"
146
+ for c in codes
147
+ )
148
+ ctrl.set_conf("ExitNodes", formatted)
149
+ ctrl.set_conf("StrictNodes", "1" if strict else "0")
150
+ except stem.ControllerError as exc:
151
+ raise ControlError(f"Failed to set exit countries: {exc}") from exc
152
+
153
+ def close_circuits(self) -> None:
154
+ """Close all currently open Tor circuits."""
155
+ ctrl = self._require_connected()
156
+ try:
157
+ for circ in ctrl.get_circuits():
158
+ try:
159
+ ctrl.close_circuit(circ.id)
160
+ except stem.ControllerError:
161
+ pass
162
+ except stem.ControllerError as exc:
163
+ raise ControlError(f"Failed to close circuits: {exc}") from exc
164
+
165
+ def is_alive(self) -> bool:
166
+ """Return ``True`` if the control connection responds to ``GETINFO version``."""
167
+ try:
168
+ ctrl = self._require_connected()
169
+ ctrl.get_version()
170
+ return True
171
+ except Exception:
172
+ return False
173
+
174
+ def get_config(self, key: str) -> str | None:
175
+ """Read a single Tor configuration value."""
176
+ ctrl = self._require_connected()
177
+ try:
178
+ value: str | None = ctrl.get_conf(key)
179
+ return value
180
+ except Exception:
181
+ return None
182
+
183
+ def set_config(self, key: str, value: str) -> None:
184
+ """Set a Tor configuration value at runtime."""
185
+ ctrl = self._require_connected()
186
+ try:
187
+ ctrl.set_conf(key, value)
188
+ except stem.ControllerError as exc:
189
+ raise ControlError(f"Failed to set {key}={value}: {exc}") from exc
torwire/env.py ADDED
@@ -0,0 +1,101 @@
1
+ """Proxy environment variable context manager and optional socket patching."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import logging
7
+ import os
8
+ import socket
9
+ from typing import Any, Generator
10
+
11
+ logger = logging.getLogger("torwire")
12
+
13
+ _original_socket: Any = None
14
+
15
+
16
+ @contextlib.contextmanager
17
+ def proxy_env(
18
+ http_proxy: str | None = None,
19
+ https_proxy: str | None = None,
20
+ socks_proxy: str | None = None,
21
+ all_proxy: str | None = None,
22
+ ) -> Generator[None, None, None]:
23
+ """Context manager that temporarily sets proxy environment variables.
24
+
25
+ Sets ``HTTP_PROXY``, ``HTTPS_PROXY``, ``ALL_PROXY`` (and their lowercase
26
+ counterparts) for the duration of the ``with`` block, then restores the
27
+ original environment state on exit.
28
+ """
29
+ env_vars: dict[str, str] = {}
30
+ if http_proxy:
31
+ env_vars["HTTP_PROXY"] = http_proxy
32
+ env_vars["http_proxy"] = http_proxy
33
+ if https_proxy:
34
+ env_vars["HTTPS_PROXY"] = https_proxy
35
+ env_vars["https_proxy"] = https_proxy
36
+ if socks_proxy:
37
+ env_vars["ALL_PROXY"] = socks_proxy
38
+ env_vars["all_proxy"] = socks_proxy
39
+ if all_proxy:
40
+ env_vars["ALL_PROXY"] = all_proxy
41
+ env_vars["all_proxy"] = all_proxy
42
+
43
+ saved: dict[str, str | None] = {}
44
+ for key, value in env_vars.items():
45
+ saved[key] = os.environ.get(key)
46
+ os.environ[key] = value
47
+
48
+ try:
49
+ yield
50
+ finally:
51
+ for key, original in saved.items():
52
+ if original is None:
53
+ os.environ.pop(key, None)
54
+ else:
55
+ os.environ[key] = original
56
+
57
+
58
+ def patch_sockets(socks_host: str = "127.0.0.1", socks_port: int = 9050) -> None:
59
+ """Monkey-patch :mod:`socket` to route all TCP connections through SOCKS5.
60
+
61
+ .. warning::
62
+ Opt-in and discouraged for general use. Patching ``socket.socket``
63
+ affects all TCP connections in the process (including localhost) and
64
+ is not thread-safe. ``socket.getaddrinfo`` still resolves DNS locally
65
+ unless handled separately, which can cause DNS leaks.
66
+
67
+ Requires ``PySocks`` (``pip install pysocks``).
68
+ """
69
+ global _original_socket
70
+ try:
71
+ import socks # type: ignore[import-untyped]
72
+ except ImportError as exc:
73
+ raise ImportError(
74
+ "PySocks is required for socket patching. Install it with: pip install pysocks"
75
+ ) from exc
76
+
77
+ if _original_socket is None:
78
+ _original_socket = socket.socket
79
+
80
+ socks.set_default_proxy(socks.SOCKS5, socks_host, socks_port, rdns=True)
81
+ socket.socket = socks.socksocket # type: ignore[misc]
82
+ logger.warning(
83
+ "Global socket.socket patched to SOCKS5 (%s:%d). "
84
+ "Note: socket.getaddrinfo may still resolve DNS locally.",
85
+ socks_host,
86
+ socks_port,
87
+ )
88
+
89
+
90
+ def unpatch_sockets() -> None:
91
+ """Restore the original ``socket.socket`` class after :func:`patch_sockets`."""
92
+ global _original_socket
93
+ if _original_socket is not None:
94
+ socket.socket = _original_socket
95
+ _original_socket = None
96
+ try:
97
+ import socks # type: ignore[import-untyped]
98
+
99
+ socks.set_default_proxy()
100
+ except ImportError:
101
+ pass
torwire/errors.py ADDED
@@ -0,0 +1,198 @@
1
+ """Exception hierarchy for the torwire library."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class TorwireError(Exception):
7
+ """Base exception for all torwire errors.
8
+
9
+ All exceptions raised by torwire inherit from this class, so you can
10
+ catch ``TorwireError`` to handle any torwire-specific failure in a
11
+ single except block.
12
+ """
13
+
14
+ def __init__(self, message: str = "A torwire error occurred.") -> None:
15
+ super().__init__(message)
16
+
17
+
18
+ class BinaryNotFoundError(TorwireError):
19
+ """The Tor binary could not be located on this system.
20
+
21
+ This is raised when torwire cannot find a usable ``tor`` executable via
22
+ the configured *tor_path*, the system PATH, or the managed binary cache.
23
+
24
+ To fix this you can:
25
+ * Pass an explicit ``tor_path="/path/to/tor"`` when creating a TorManager.
26
+ * Install Tor through your system package manager.
27
+ * Use ``TorManager.attach()`` to connect to an already-running Tor instance.
28
+ """
29
+
30
+ def __init__(
31
+ self,
32
+ message: str = (
33
+ "Tor binary not found. Supply tor_path=, install Tor, "
34
+ "or use TorManager.attach()."
35
+ ),
36
+ ) -> None:
37
+ super().__init__(message)
38
+
39
+
40
+ class BinaryVerificationError(TorwireError):
41
+ """Hash or signature verification of a Tor binary failed.
42
+
43
+ The downloaded or supplied Tor binary did not match the expected
44
+ cryptographic hash or signature. This may indicate a corrupted
45
+ download, a tampered binary, or a mismatch between the expected and
46
+ actual binary versions.
47
+
48
+ To fix this you can:
49
+ * Re-download the binary (delete the cached copy and retry).
50
+ * Verify that your network connection is not being intercepted.
51
+ * Supply a known-good binary via ``tor_path=``.
52
+ """
53
+
54
+ def __init__(
55
+ self,
56
+ message: str = (
57
+ "Tor binary verification failed. The file hash or signature "
58
+ "does not match the expected value."
59
+ ),
60
+ ) -> None:
61
+ super().__init__(message)
62
+
63
+
64
+ class DownloadError(TorwireError):
65
+ """Failed to download the Tor binary from the configured source.
66
+
67
+ The download may have failed due to network issues, DNS resolution
68
+ problems, or the remote server being unreachable.
69
+
70
+ To fix this you can:
71
+ * Check your network connection and try again.
72
+ * Supply a pre-downloaded binary via ``tor_path=``.
73
+ * If behind a firewall, configure bridges or a proxy.
74
+ """
75
+
76
+ def __init__(
77
+ self,
78
+ message: str = (
79
+ "Failed to download Tor binary. Check network or use "
80
+ "tor_path= instead."
81
+ ),
82
+ ) -> None:
83
+ super().__init__(message)
84
+
85
+
86
+ class BootstrapError(TorwireError):
87
+ """Tor failed to complete its bootstrap (circuit-building) phase in time.
88
+
89
+ Bootstrap is the process by which Tor connects to the network, fetches
90
+ a consensus, and builds circuits. This error means that process did
91
+ not finish before the configured timeout expired.
92
+
93
+ To fix this you can:
94
+ * Verify your internet connection is working.
95
+ * Supply bridge addresses via ``bridges=[...]`` if Tor is blocked.
96
+ * Increase the ``timeout`` parameter to allow more time.
97
+ """
98
+
99
+ def __init__(
100
+ self,
101
+ message: str = (
102
+ "Tor bootstrap timed out. Check network, try bridges=[], "
103
+ "or increase timeout."
104
+ ),
105
+ ) -> None:
106
+ super().__init__(message)
107
+
108
+
109
+ class ControlError(TorwireError):
110
+ """Communication with the Tor control port failed.
111
+
112
+ This is raised when torwire is unable to authenticate with, send
113
+ commands to, or receive responses from the Tor control port. Common
114
+ causes include the Tor process crashing, the control port being
115
+ closed, or an authentication mismatch.
116
+
117
+ To fix this you can:
118
+ * Ensure the Tor process is still running.
119
+ * Check that the control port password matches.
120
+ * Restart the TorManager to spawn a fresh Tor process.
121
+ """
122
+
123
+ def __init__(
124
+ self,
125
+ message: str = (
126
+ "Control port communication failed. The Tor process may have "
127
+ "exited or the control connection was lost."
128
+ ),
129
+ ) -> None:
130
+ super().__init__(message)
131
+
132
+
133
+ class NewIdentityError(TorwireError):
134
+ """Failed to switch to a new Tor identity (NEWNYM).
135
+
136
+ A NEWNYM signal asks Tor to build new circuits so that subsequent
137
+ connections appear to come from a different IP address. This error
138
+ means the signal could not be sent or Tor rejected it.
139
+
140
+ To fix this you can:
141
+ * Wait at least 10 seconds between NEWNYM requests (Tor rate-limits them).
142
+ * Ensure the Tor process is still running and the control port is reachable.
143
+ """
144
+
145
+ def __init__(
146
+ self,
147
+ message: str = (
148
+ "Failed to obtain a new Tor identity. Ensure Tor is running "
149
+ "and wait at least 10 seconds between NEWNYM requests."
150
+ ),
151
+ ) -> None:
152
+ super().__init__(message)
153
+
154
+
155
+ class BridgeError(TorwireError):
156
+ """An error occurred while configuring or connecting through Tor bridges.
157
+
158
+ Bridges are unlisted Tor relays used to circumvent censorship. This
159
+ error indicates that the supplied bridge lines are malformed, the
160
+ bridge is unreachable, or a pluggable transport failed to start.
161
+
162
+ To fix this you can:
163
+ * Verify that the bridge lines are correctly formatted.
164
+ * Try different bridge addresses (obtain them from https://bridges.torproject.org).
165
+ * Ensure required pluggable transports (e.g. obfs4proxy) are installed.
166
+ """
167
+
168
+ def __init__(
169
+ self,
170
+ message: str = (
171
+ "Bridge configuration or connection failed. Verify bridge lines "
172
+ "and ensure any required pluggable transports are installed."
173
+ ),
174
+ ) -> None:
175
+ super().__init__(message)
176
+
177
+
178
+ class NotRunningError(TorwireError):
179
+ """An operation was attempted on a TorManager that is not running.
180
+
181
+ The TorManager must be started (and Tor must be bootstrapped) before
182
+ you can request proxies, rotate identities, or perform other
183
+ operations that require a live Tor process.
184
+
185
+ To fix this you can:
186
+ * Call ``await manager.start()`` or use the async context manager
187
+ before performing operations.
188
+ * Check ``manager.is_running`` to verify state before calling methods.
189
+ """
190
+
191
+ def __init__(
192
+ self,
193
+ message: str = (
194
+ "TorManager is not running. Call start() or use the async "
195
+ "context manager before performing this operation."
196
+ ),
197
+ ) -> None:
198
+ super().__init__(message)