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/__init__.py ADDED
@@ -0,0 +1,52 @@
1
+ """torwire: Route your Python app's traffic through Tor.
2
+
3
+ No proxychains, no Privoxy, no manual setup.
4
+
5
+ Usage::
6
+
7
+ import torwire
8
+
9
+ with torwire.TorManager() as tor:
10
+ s = tor.requests_session()
11
+ print(s.get("https://api.ipify.org").text)
12
+ tor.new_identity()
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from torwire.config import TorConfig
18
+ from torwire.env import patch_sockets, proxy_env, unpatch_sockets
19
+ from torwire.errors import (
20
+ BinaryNotFoundError,
21
+ BinaryVerificationError,
22
+ BootstrapError,
23
+ BridgeError,
24
+ ControlError,
25
+ DownloadError,
26
+ NewIdentityError,
27
+ NotRunningError,
28
+ TorwireError,
29
+ )
30
+ from torwire.manager import TorManager
31
+ from torwire.pool import TorPool
32
+
33
+ __version__ = "0.1.0"
34
+
35
+ __all__ = [
36
+ "TorManager",
37
+ "TorPool",
38
+ "TorConfig",
39
+ "TorwireError",
40
+ "BinaryNotFoundError",
41
+ "BinaryVerificationError",
42
+ "BootstrapError",
43
+ "BridgeError",
44
+ "ControlError",
45
+ "DownloadError",
46
+ "NewIdentityError",
47
+ "NotRunningError",
48
+ "proxy_env",
49
+ "patch_sockets",
50
+ "unpatch_sockets",
51
+ "__version__",
52
+ ]
torwire/_platform.py ADDED
@@ -0,0 +1,162 @@
1
+ """OS-specific helpers for torwire.
2
+
3
+ Provides platform detection, free-port allocation, and default directory
4
+ resolution that work across Windows, macOS, and Linux.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+ import platform
11
+ import socket
12
+ import sys
13
+ from pathlib import Path
14
+
15
+ import platformdirs
16
+
17
+ logger = logging.getLogger("torwire")
18
+
19
+ # ---------------------------------------------------------------------------
20
+ # Architecture normalisation map
21
+ # ---------------------------------------------------------------------------
22
+ _ARCH_MAP: dict[str, str] = {
23
+ "AMD64": "x86_64",
24
+ "x86_64": "x86_64",
25
+ "arm64": "aarch64",
26
+ "aarch64": "aarch64",
27
+ }
28
+
29
+
30
+ def tor_binary_name() -> str:
31
+ """Return the Tor executable name for the current platform.
32
+
33
+ Returns:
34
+ ``"tor.exe"`` on Windows, ``"tor"`` everywhere else.
35
+ """
36
+ return "tor.exe" if sys.platform == "win32" else "tor"
37
+
38
+
39
+ def subprocess_creation_flags() -> int:
40
+ """Return *creationflags* suitable for :func:`subprocess.Popen`.
41
+
42
+ On Windows the ``CREATE_NO_WINDOW`` flag (``0x08000000``) is returned so
43
+ that spawned Tor processes do not pop up a console window. On all other
44
+ platforms ``0`` is returned.
45
+
46
+ Returns:
47
+ An integer to pass as the ``creationflags`` argument.
48
+ """
49
+ if sys.platform == "win32":
50
+ return 0x08000000 # CREATE_NO_WINDOW
51
+ return 0
52
+
53
+
54
+ def find_free_port(host: str = "127.0.0.1") -> int:
55
+ """Find and return an unused TCP port on *host*.
56
+
57
+ The port is discovered by binding a socket to port ``0`` (which lets the
58
+ OS assign an ephemeral port), reading the assigned number, and immediately
59
+ closing the socket.
60
+
61
+ Args:
62
+ host: The address to bind to. Defaults to ``127.0.0.1``.
63
+
64
+ Returns:
65
+ A free port number.
66
+ """
67
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
68
+ sock.bind((host, 0))
69
+ port: int = sock.getsockname()[1]
70
+ logger.debug("Found free port %d on %s", port, host)
71
+ return port
72
+
73
+
74
+ def default_data_dir() -> Path:
75
+ """Return the default data directory for torwire.
76
+
77
+ Uses :func:`platformdirs.user_data_dir` to resolve the platform-appropriate
78
+ location (e.g. ``~/.local/share/torwire`` on Linux,
79
+ ``~/Library/Application Support/torwire`` on macOS, or
80
+ ``%LOCALAPPDATA%/torwire`` on Windows).
81
+
82
+ Returns:
83
+ A :class:`~pathlib.Path` to the data directory.
84
+ """
85
+ return Path(platformdirs.user_data_dir("torwire"))
86
+
87
+
88
+ def default_cache_dir() -> Path:
89
+ """Return the default cache directory for torwire.
90
+
91
+ Uses :func:`platformdirs.user_cache_dir` to resolve the platform-appropriate
92
+ location (e.g. ``~/.cache/torwire`` on Linux,
93
+ ``~/Library/Caches/torwire`` on macOS, or
94
+ ``%LOCALAPPDATA%/torwire/Cache`` on Windows).
95
+
96
+ Returns:
97
+ A :class:`~pathlib.Path` to the cache directory.
98
+ """
99
+ return Path(platformdirs.user_cache_dir("torwire"))
100
+
101
+
102
+ def detect_platform() -> tuple[str, str]:
103
+ """Detect the current operating system and CPU architecture.
104
+
105
+ The OS name is normalised to one of ``"windows"``, ``"macos"``, or
106
+ ``"linux"``. The architecture string is normalised so that common
107
+ aliases map to canonical values:
108
+
109
+ * ``AMD64`` → ``x86_64``
110
+ * ``arm64`` → ``aarch64``
111
+ * ``x86_64`` → ``x86_64``
112
+ * ``aarch64`` → ``aarch64``
113
+
114
+ Returns:
115
+ A ``(os_name, arch)`` tuple.
116
+
117
+ Raises:
118
+ RuntimeError: If the OS or architecture is not recognised.
119
+ """
120
+ os_name: str
121
+ if sys.platform == "win32":
122
+ os_name = "windows"
123
+ elif sys.platform == "darwin":
124
+ os_name = "macos"
125
+ elif sys.platform.startswith("linux"):
126
+ os_name = "linux"
127
+ else:
128
+ raise RuntimeError(f"Unsupported operating system: {sys.platform}")
129
+
130
+ raw_arch = platform.machine()
131
+ arch = _ARCH_MAP.get(raw_arch)
132
+ if arch is None:
133
+ raise RuntimeError(
134
+ f"Unsupported architecture: {raw_arch!r}. "
135
+ f"Known mappings: {', '.join(sorted(_ARCH_MAP))}"
136
+ )
137
+
138
+ logger.debug("Detected platform: os=%s, arch=%s", os_name, arch)
139
+ return os_name, arch
140
+
141
+
142
+ def is_port_in_use(port: int, host: str = "127.0.0.1") -> bool:
143
+ """Check whether a TCP port is currently in use.
144
+
145
+ Attempts to bind a socket to *host*:*port*. If the bind succeeds the
146
+ port is free and ``False`` is returned; if it fails with
147
+ :data:`~errno.EADDRINUSE` (``OSError``) the port is occupied and
148
+ ``True`` is returned.
149
+
150
+ Args:
151
+ port: The TCP port number to check.
152
+ host: The address to bind to. Defaults to ``127.0.0.1``.
153
+
154
+ Returns:
155
+ ``True`` if the port is already in use, ``False`` otherwise.
156
+ """
157
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
158
+ try:
159
+ sock.bind((host, port))
160
+ except OSError:
161
+ return True
162
+ return False
torwire/binary.py ADDED
@@ -0,0 +1,299 @@
1
+ """Binary discovery, downloading, and verification for the Tor executable."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import logging
8
+ import os
9
+ import re
10
+ import shutil
11
+ import stat
12
+ import subprocess
13
+ import sys
14
+ import tarfile
15
+ import urllib.error
16
+ import urllib.request
17
+ from datetime import datetime, timezone
18
+ from pathlib import Path
19
+
20
+ from torwire._platform import (
21
+ default_cache_dir,
22
+ detect_platform,
23
+ subprocess_creation_flags,
24
+ tor_binary_name,
25
+ )
26
+ from torwire.config import TorConfig
27
+ from torwire.errors import (
28
+ BinaryNotFoundError,
29
+ BinaryVerificationError,
30
+ DownloadError,
31
+ )
32
+
33
+ logger = logging.getLogger("torwire")
34
+
35
+ TOR_VERSION = "14.0.4"
36
+ EXPERT_BUNDLE_BASE_URL = "https://dist.torproject.org/torbrowser"
37
+
38
+ _ARCHIVE_MAP: dict[tuple[str, str], str] = {
39
+ ("windows", "x86_64"): "tor-expert-bundle-windows-x86_64-{ver}.tar.gz",
40
+ ("macos", "x86_64"): "tor-expert-bundle-macos-x86_64-{ver}.tar.gz",
41
+ ("macos", "aarch64"): "tor-expert-bundle-macos-aarch64-{ver}.tar.gz",
42
+ ("linux", "x86_64"): "tor-expert-bundle-linux-x86_64-{ver}.tar.gz",
43
+ ("linux", "aarch64"): "tor-expert-bundle-linux-aarch64-{ver}.tar.gz",
44
+ }
45
+
46
+
47
+ class BinaryManager:
48
+ """Locate, download, and verify the ``tor`` executable.
49
+
50
+ Resolution order:
51
+ 1. ``TorConfig.tor_path`` if explicitly configured.
52
+ 2. ``TORWIRE_TOR_PATH`` environment variable.
53
+ 3. Bundled binary from the ``torwire_bin`` package (if installed).
54
+ 4. Previously downloaded copy in the torwire cache directory.
55
+ 5. System-installed ``tor`` on ``$PATH`` via :func:`shutil.which`.
56
+ 6. Auto-download of the official Tor Expert Bundle (if ``auto_download`` is ``True``).
57
+ """
58
+
59
+ def __init__(self, config: TorConfig | None = None) -> None:
60
+ self._config = config or TorConfig()
61
+
62
+ def ensure(self) -> Path:
63
+ """Find or download the ``tor`` binary and return its path.
64
+
65
+ Raises:
66
+ BinaryNotFoundError: If no binary can be found and auto-download
67
+ is disabled or unsupported on the current platform.
68
+ DownloadError: If downloading the Tor Expert Bundle fails.
69
+ BinaryVerificationError: If downloaded archive verification fails.
70
+ """
71
+ found = self._find_binary()
72
+ if found is not None:
73
+ return found
74
+
75
+ if self._config.auto_download:
76
+ return self._download()
77
+
78
+ raise BinaryNotFoundError()
79
+
80
+ def version(self) -> str | None:
81
+ """Return the installed ``tor`` version string, or ``None`` if unavailable."""
82
+ binary = self._find_binary()
83
+ if binary is None:
84
+ return None
85
+
86
+ try:
87
+ proc = subprocess.run(
88
+ [str(binary), "--version"],
89
+ capture_output=True,
90
+ text=True,
91
+ timeout=10,
92
+ creationflags=subprocess_creation_flags(),
93
+ )
94
+ if proc.returncode != 0:
95
+ return None
96
+ match = re.search(r"Tor version\s+([^\s.]+(?:\.[^\s.]+)*)", proc.stdout)
97
+ if match:
98
+ return match.group(1).rstrip(".")
99
+ return proc.stdout.strip() or None
100
+ except Exception as exc:
101
+ logger.debug("Failed to query tor version: %s", exc)
102
+ return None
103
+
104
+ def clear_cache(self) -> None:
105
+ """Remove all cached Tor downloads from the user cache directory."""
106
+ tor_cache = default_cache_dir() / "tor"
107
+ if tor_cache.exists():
108
+ shutil.rmtree(tor_cache, ignore_errors=True)
109
+ logger.info("Cleared torwire binary cache at %s", tor_cache)
110
+
111
+ def _find_binary(self) -> Path | None:
112
+ """Run resolution steps 1–5 and return a valid executable Path, or None."""
113
+ # 1. Explicit config path
114
+ if self._config.tor_path:
115
+ p = Path(self._config.tor_path).expanduser()
116
+ if p.is_file():
117
+ logger.debug("Using configured tor_path: %s", p)
118
+ return p
119
+ logger.warning("Configured tor_path does not exist: %s", p)
120
+
121
+ # 2. Environment variable
122
+ env_path = os.environ.get("TORWIRE_TOR_PATH")
123
+ if env_path:
124
+ p = Path(env_path).expanduser()
125
+ if p.is_file():
126
+ logger.debug("Using TORWIRE_TOR_PATH: %s", p)
127
+ return p
128
+ logger.warning("TORWIRE_TOR_PATH does not exist: %s", p)
129
+
130
+ # 3. Bundled wheel (torwire-bin)
131
+ try:
132
+ import torwire_bin # type: ignore[import-not-found]
133
+
134
+ bundled = Path(torwire_bin.tor_path())
135
+ if bundled.is_file():
136
+ logger.debug("Using bundled torwire_bin binary: %s", bundled)
137
+ return bundled
138
+ except ImportError:
139
+ pass
140
+ except Exception as exc:
141
+ logger.debug("torwire_bin lookup failed: %s", exc)
142
+
143
+ # 4. Cached download
144
+ cached = self._cached_binary_path()
145
+ if cached is not None and cached.is_file():
146
+ logger.debug("Using cached tor binary: %s", cached)
147
+ return cached
148
+
149
+ # 5. System PATH
150
+ which_path = shutil.which(tor_binary_name())
151
+ if which_path:
152
+ p = Path(which_path)
153
+ logger.debug("Using system tor binary: %s", p)
154
+ return p
155
+
156
+ return None
157
+
158
+ def _platform_cache_dir(self) -> Path | None:
159
+ """Return the cache subdirectory for the current OS/arch, or None."""
160
+ try:
161
+ os_name, arch = detect_platform()
162
+ except RuntimeError:
163
+ return None
164
+ return default_cache_dir() / "tor" / f"{os_name}-{arch}"
165
+
166
+ def _cached_binary_path(self) -> Path | None:
167
+ """Return the expected path of a cached binary if it exists."""
168
+ cache_dir = self._platform_cache_dir()
169
+ if cache_dir is None or not cache_dir.exists():
170
+ return None
171
+
172
+ bin_name = tor_binary_name()
173
+ for candidate in (
174
+ cache_dir / "tor" / bin_name,
175
+ cache_dir / bin_name,
176
+ ):
177
+ if candidate.is_file():
178
+ return candidate
179
+ return None
180
+
181
+ def _get_archive_name(self, version: str = TOR_VERSION) -> str:
182
+ """Return the Tor Expert Bundle archive filename for the current platform."""
183
+ try:
184
+ os_name, arch = detect_platform()
185
+ except RuntimeError as exc:
186
+ raise BinaryNotFoundError(
187
+ f"No official Tor Expert Bundle for this platform ({exc}). "
188
+ "Supply tor_path=, install Tor via your system package manager, "
189
+ "or use TorManager.attach()."
190
+ ) from exc
191
+
192
+ template = _ARCHIVE_MAP.get((os_name, arch))
193
+ if template is None:
194
+ raise BinaryNotFoundError(
195
+ f"No official Tor Expert Bundle for {os_name}/{arch}. "
196
+ "Supply tor_path=, install Tor via your system package manager, "
197
+ "or use TorManager.attach()."
198
+ )
199
+ return template.format(ver=version)
200
+
201
+ def _get_archive_url(self, version: str = TOR_VERSION) -> str:
202
+ """Return the download URL for the Tor Expert Bundle."""
203
+ archive_name = self._get_archive_name(version)
204
+ return f"{EXPERT_BUNDLE_BASE_URL}/{version}/{archive_name}"
205
+
206
+ def _download(self, verify: bool = True) -> Path:
207
+ """Download, verify, and extract the Tor Expert Bundle to the cache dir."""
208
+ archive_name = self._get_archive_name(TOR_VERSION)
209
+ archive_url = self._get_archive_url(TOR_VERSION)
210
+ sums_url = f"{EXPERT_BUNDLE_BASE_URL}/{TOR_VERSION}/sha256sums-signed-build.txt"
211
+
212
+ cache_dir = self._platform_cache_dir()
213
+ if cache_dir is None:
214
+ raise BinaryNotFoundError()
215
+ cache_dir.mkdir(parents=True, exist_ok=True)
216
+ archive_path = cache_dir / archive_name
217
+
218
+ logger.info("Downloading Tor Expert Bundle from %s", archive_url)
219
+ try:
220
+ req = urllib.request.Request(archive_url, headers={"User-Agent": "torwire"})
221
+ with urllib.request.urlopen(req, timeout=120) as resp, open(archive_path, "wb") as out:
222
+ shutil.copyfileobj(resp, out)
223
+ except (urllib.error.URLError, OSError) as exc:
224
+ if archive_path.exists():
225
+ archive_path.unlink(missing_ok=True)
226
+ raise DownloadError(f"Failed to download Tor from {archive_url}: {exc}") from exc
227
+
228
+ if verify:
229
+ expected_hash = self._fetch_expected_sha256(sums_url, archive_name)
230
+ if expected_hash is not None and not self._verify_binary(archive_path, expected_hash):
231
+ archive_path.unlink(missing_ok=True)
232
+ raise BinaryVerificationError(
233
+ f"SHA256 mismatch for {archive_name}. Download may be corrupted or tampered with."
234
+ )
235
+
236
+ try:
237
+ with tarfile.open(archive_path, "r:gz") as tf:
238
+ self._safe_extract_tar(tf, cache_dir)
239
+ except (tarfile.TarError, OSError) as exc:
240
+ raise DownloadError(f"Failed to extract {archive_name}: {exc}") from exc
241
+ finally:
242
+ archive_path.unlink(missing_ok=True)
243
+
244
+ binary = self._cached_binary_path()
245
+ if binary is None or not binary.is_file():
246
+ raise BinaryNotFoundError(
247
+ f"Extracted Tor archive into {cache_dir}, but could not locate {tor_binary_name()}."
248
+ )
249
+
250
+ if sys.platform != "win32":
251
+ current_mode = binary.stat().st_mode
252
+ binary.chmod(current_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
253
+
254
+ meta = {
255
+ "version": TOR_VERSION,
256
+ "archive": archive_name,
257
+ "downloaded_at": datetime.now(timezone.utc).isoformat(),
258
+ }
259
+ (cache_dir / "meta.json").write_text(json.dumps(meta, indent=2), encoding="utf-8")
260
+ logger.info("Tor binary ready at %s", binary)
261
+ return binary
262
+
263
+ def _fetch_expected_sha256(self, sums_url: str, archive_name: str) -> str | None:
264
+ """Fetch SHA256 checksums file and extract the expected digest for *archive_name*."""
265
+ try:
266
+ req = urllib.request.Request(sums_url, headers={"User-Agent": "torwire"})
267
+ with urllib.request.urlopen(req, timeout=30) as resp:
268
+ content = resp.read().decode("utf-8", errors="replace")
269
+ except Exception as exc:
270
+ logger.warning("Could not fetch SHA256 sums from %s: %s", sums_url, exc)
271
+ return None
272
+
273
+ for line in content.splitlines():
274
+ parts = line.strip().split()
275
+ if len(parts) >= 2 and parts[1].lstrip("*").endswith(archive_name):
276
+ return parts[0].lower()
277
+ return None
278
+
279
+ def _verify_binary(self, path: Path, expected_sha256: str | None = None) -> bool:
280
+ """Verify *path* exists, is non-empty, and matches *expected_sha256* if given."""
281
+ if not path.is_file() or path.stat().st_size == 0:
282
+ return False
283
+ if expected_sha256 is None:
284
+ return True
285
+ digest = hashlib.sha256()
286
+ with open(path, "rb") as fh:
287
+ for chunk in iter(lambda: fh.read(65536), b""):
288
+ digest.update(chunk)
289
+ return digest.hexdigest().lower() == expected_sha256.lower()
290
+
291
+ @staticmethod
292
+ def _safe_extract_tar(tf: tarfile.TarFile, dest: Path) -> None:
293
+ """Extract tarfile safely preventing path traversal."""
294
+ dest_resolved = dest.resolve()
295
+ for member in tf.getmembers():
296
+ member_path = (dest / member.name).resolve()
297
+ if not str(member_path).startswith(str(dest_resolved)):
298
+ raise BinaryVerificationError(f"Unsafe path in archive: {member.name}")
299
+ tf.extractall(dest)