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/cli.py ADDED
@@ -0,0 +1,199 @@
1
+ """Command-line interface for torwire."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import logging
7
+ import shutil
8
+ import signal
9
+ import sys
10
+ import threading
11
+
12
+
13
+ def main(argv: list[str] | None = None) -> int:
14
+ """Entry point for the ``torwire`` CLI command."""
15
+ parser = argparse.ArgumentParser(
16
+ prog="torwire",
17
+ description="Route traffic through Tor. No manual setup needed.",
18
+ )
19
+ parser.add_argument("-v", "--verbose", action="store_true", help="Enable debug logging")
20
+ subparsers = parser.add_subparsers(dest="command", help="Available commands")
21
+
22
+ # start
23
+ start_parser = subparsers.add_parser("start", help="Start Tor proxy (runs until Ctrl+C)")
24
+ start_parser.add_argument("--socks", type=int, default=0, help="SOCKS port (0=auto)")
25
+ start_parser.add_argument("--http", type=int, default=0, help="HTTP proxy port (0=auto)")
26
+ start_parser.add_argument("--country", type=str, default=None, help="Exit countries (comma-separated)")
27
+ start_parser.add_argument("--bridges", type=str, default=None, help="Bridge lines (comma-separated)")
28
+ start_parser.add_argument("--profile", choices=["default", "low_end"], default="default")
29
+ start_parser.add_argument("--persist", action="store_true", help="Persist data for faster restarts")
30
+ start_parser.add_argument("--tor-path", type=str, default=None, help="Path to tor binary")
31
+
32
+ # ip
33
+ subparsers.add_parser("ip", help="Print current exit IP")
34
+
35
+ # newnym
36
+ subparsers.add_parser("newnym", help="Request new Tor identity")
37
+
38
+ # download
39
+ subparsers.add_parser("download", help="Pre-download the Tor binary")
40
+
41
+ # doctor
42
+ subparsers.add_parser("doctor", help="Run environment diagnostics")
43
+
44
+ args = parser.parse_args(argv)
45
+
46
+ if args.verbose:
47
+ logging.basicConfig(
48
+ level=logging.DEBUG,
49
+ format="%(asctime)s %(name)s %(levelname)s %(message)s",
50
+ )
51
+ else:
52
+ logging.basicConfig(level=logging.INFO, format="%(message)s")
53
+
54
+ if args.command is None:
55
+ parser.print_help()
56
+ return 0
57
+
58
+ try:
59
+ if args.command == "start":
60
+ return _cmd_start(args)
61
+ if args.command == "ip":
62
+ return _cmd_ip(args)
63
+ if args.command == "newnym":
64
+ return _cmd_newnym(args)
65
+ if args.command == "download":
66
+ return _cmd_download(args)
67
+ if args.command == "doctor":
68
+ return _cmd_doctor(args)
69
+ except KeyboardInterrupt:
70
+ print("\nInterrupted.")
71
+ return 130
72
+ except Exception as exc:
73
+ print(f"Error: {exc}", file=sys.stderr)
74
+ return 1
75
+
76
+ return 0
77
+
78
+
79
+ def _cmd_start(args: argparse.Namespace) -> int:
80
+ from torwire.config import TorConfig
81
+ from torwire.manager import TorManager
82
+
83
+ countries = args.country.split(",") if args.country else None
84
+ bridges = args.bridges.split(",") if args.bridges else None
85
+
86
+ config = TorConfig(
87
+ socks_port=args.socks,
88
+ http_port=args.http,
89
+ exit_countries=countries,
90
+ bridges=bridges,
91
+ profile=args.profile,
92
+ persist_data=args.persist,
93
+ tor_path=args.tor_path,
94
+ )
95
+
96
+ with TorManager(config) as tor:
97
+ print(f"SOCKS proxy: {tor.socks_url}")
98
+ if tor.http_url:
99
+ print(f"HTTP proxy: {tor.http_url}")
100
+ try:
101
+ print(f"Exit IP: {tor.current_ip()}")
102
+ except Exception:
103
+ print("Exit IP: (could not determine)")
104
+ print("\nPress Ctrl+C to stop.")
105
+
106
+ stop_event = threading.Event()
107
+
108
+ def _handle_signal(_sig: int, _frame: object) -> None:
109
+ stop_event.set()
110
+
111
+ signal.signal(signal.SIGINT, _handle_signal)
112
+ signal.signal(signal.SIGTERM, _handle_signal)
113
+ stop_event.wait()
114
+
115
+ return 0
116
+
117
+
118
+ def _cmd_ip(_args: argparse.Namespace) -> int:
119
+ from torwire.checks import get_exit_ip
120
+
121
+ try:
122
+ print(get_exit_ip("socks5h://127.0.0.1:9050"))
123
+ except Exception:
124
+ ip = get_exit_ip()
125
+ print(f"{ip} (direct, not through Tor)")
126
+ return 0
127
+
128
+
129
+ def _cmd_newnym(_args: argparse.Namespace) -> int:
130
+ from torwire.controller import TorController
131
+
132
+ ctrl = TorController(9051, "")
133
+ try:
134
+ ctrl.connect()
135
+ ctrl.new_identity()
136
+ print("New identity requested.")
137
+ except Exception as exc:
138
+ print(f"Failed: {exc}", file=sys.stderr)
139
+ print("Make sure Tor is running with a control port.", file=sys.stderr)
140
+ return 1
141
+ finally:
142
+ ctrl.close()
143
+ return 0
144
+
145
+
146
+ def _cmd_download(_args: argparse.Namespace) -> int:
147
+ from torwire.binary import BinaryManager
148
+
149
+ print("Ensuring Tor binary...")
150
+ path = BinaryManager().ensure()
151
+ print(f"Tor binary ready at: {path}")
152
+ return 0
153
+
154
+
155
+ def _cmd_doctor(_args: argparse.Namespace) -> int:
156
+ from torwire._platform import default_cache_dir, detect_platform, tor_binary_name
157
+ from torwire.binary import BinaryManager
158
+
159
+ os_name, arch = detect_platform()
160
+ print(f"Platform: {os_name} {arch}")
161
+ print(f"Python: {sys.version.splitlines()[0]}")
162
+ print(f"Cache dir: {default_cache_dir()}")
163
+
164
+ system_tor = shutil.which(tor_binary_name())
165
+ print(f"System tor: {system_tor or 'not found'}")
166
+
167
+ try:
168
+ import torwire_bin # type: ignore[import-not-found]
169
+
170
+ print(f"Bundled tor: {torwire_bin.tor_path()}")
171
+ except ImportError:
172
+ print("Bundled tor: not installed (pip install torwire[bundled])")
173
+
174
+ try:
175
+ cached = BinaryManager()._find_binary()
176
+ print(f"Resolved tor: {cached or 'not found'}")
177
+ except Exception:
178
+ print("Resolved tor: not found")
179
+
180
+ try:
181
+ import stem
182
+
183
+ print(f"stem: {stem.__version__}")
184
+ except ImportError:
185
+ print("stem: NOT INSTALLED (required!)")
186
+
187
+ for name in ("requests", "httpx", "aiohttp", "aiohttp_socks"):
188
+ try:
189
+ mod = __import__(name)
190
+ ver = getattr(mod, "__version__", "installed")
191
+ print(f"{name:14s} {ver}")
192
+ except ImportError:
193
+ print(f"{name:14s} not installed")
194
+
195
+ return 0
196
+
197
+
198
+ if __name__ == "__main__":
199
+ sys.exit(main())
File without changes
@@ -0,0 +1,49 @@
1
+ """Factory for creating ``aiohttp.ClientSession`` instances routed through Tor."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import secrets
7
+ from typing import TYPE_CHECKING, Any
8
+ from urllib.parse import urlparse, urlunparse
9
+
10
+ if TYPE_CHECKING:
11
+ import aiohttp
12
+
13
+ logger = logging.getLogger("torwire")
14
+
15
+ DEFAULT_USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; rv:128.0) Gecko/20100101 Firefox/128.0"
16
+
17
+
18
+ def create_session(
19
+ socks_url: str,
20
+ isolated: bool = False,
21
+ user_agent: str | None = DEFAULT_USER_AGENT,
22
+ **kwargs: Any,
23
+ ) -> "aiohttp.ClientSession":
24
+ """Create an :class:`aiohttp.ClientSession` configured to use Tor's SOCKS5 proxy."""
25
+ try:
26
+ import aiohttp as _aiohttp
27
+ from aiohttp_socks import ProxyConnector # type: ignore[import-untyped]
28
+ except ImportError as exc:
29
+ raise ImportError(
30
+ "aiohttp and aiohttp-socks are required. "
31
+ "Install with: pip install torwire[aiohttp]"
32
+ ) from exc
33
+
34
+ proxy_url = socks_url
35
+ if isolated:
36
+ parsed = urlparse(socks_url)
37
+ host = parsed.hostname or "127.0.0.1"
38
+ port = parsed.port
39
+ user = secrets.token_hex(8)
40
+ password = secrets.token_hex(8)
41
+ netloc = f"{user}:{password}@{host}" if port is None else f"{user}:{password}@{host}:{port}"
42
+ proxy_url = urlunparse(parsed._replace(netloc=netloc))
43
+
44
+ connector = ProxyConnector.from_url(proxy_url, rdns=True)
45
+ headers = dict(kwargs.pop("headers", {}))
46
+ if user_agent:
47
+ headers.setdefault("User-Agent", user_agent)
48
+
49
+ return _aiohttp.ClientSession(connector=connector, headers=headers, **kwargs)
@@ -0,0 +1,72 @@
1
+ """Factories for creating ``httpx`` sync and async clients routed through Tor."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import secrets
7
+ from typing import TYPE_CHECKING, Any
8
+ from urllib.parse import urlparse, urlunparse
9
+
10
+ if TYPE_CHECKING:
11
+ import httpx
12
+
13
+ logger = logging.getLogger("torwire")
14
+
15
+ DEFAULT_USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; rv:128.0) Gecko/20100101 Firefox/128.0"
16
+
17
+
18
+ def _maybe_isolate(socks_url: str, isolated: bool) -> str:
19
+ """Return *socks_url* with random SOCKS credentials if *isolated* is True."""
20
+ if not isolated:
21
+ return socks_url
22
+ parsed = urlparse(socks_url)
23
+ host = parsed.hostname or "127.0.0.1"
24
+ port = parsed.port
25
+ user = secrets.token_hex(8)
26
+ password = secrets.token_hex(8)
27
+ netloc = f"{user}:{password}@{host}" if port is None else f"{user}:{password}@{host}:{port}"
28
+ return urlunparse(parsed._replace(netloc=netloc))
29
+
30
+
31
+ def create_client(
32
+ socks_url: str,
33
+ isolated: bool = False,
34
+ user_agent: str | None = DEFAULT_USER_AGENT,
35
+ **kwargs: Any,
36
+ ) -> "httpx.Client":
37
+ """Create an :class:`httpx.Client` configured to use Tor's SOCKS5 proxy."""
38
+ try:
39
+ import httpx as _httpx
40
+ except ImportError as exc:
41
+ raise ImportError(
42
+ "httpx is required. Install with: pip install torwire[httpx]"
43
+ ) from exc
44
+
45
+ proxy_url = _maybe_isolate(socks_url, isolated)
46
+ headers = dict(kwargs.pop("headers", {}))
47
+ if user_agent:
48
+ headers.setdefault("User-Agent", user_agent)
49
+
50
+ return _httpx.Client(proxy=proxy_url, headers=headers, **kwargs)
51
+
52
+
53
+ def create_async_client(
54
+ socks_url: str,
55
+ isolated: bool = False,
56
+ user_agent: str | None = DEFAULT_USER_AGENT,
57
+ **kwargs: Any,
58
+ ) -> "httpx.AsyncClient":
59
+ """Create an :class:`httpx.AsyncClient` configured to use Tor's SOCKS5 proxy."""
60
+ try:
61
+ import httpx as _httpx
62
+ except ImportError as exc:
63
+ raise ImportError(
64
+ "httpx is required. Install with: pip install torwire[httpx]"
65
+ ) from exc
66
+
67
+ proxy_url = _maybe_isolate(socks_url, isolated)
68
+ headers = dict(kwargs.pop("headers", {}))
69
+ if user_agent:
70
+ headers.setdefault("User-Agent", user_agent)
71
+
72
+ return _httpx.AsyncClient(proxy=proxy_url, headers=headers, **kwargs)
@@ -0,0 +1,69 @@
1
+ """Factory for creating ``requests.Session`` instances routed through Tor."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import secrets
7
+ from typing import TYPE_CHECKING
8
+ from urllib.parse import urlparse, urlunparse
9
+
10
+ if TYPE_CHECKING:
11
+ import requests
12
+
13
+ logger = logging.getLogger("torwire")
14
+
15
+ DEFAULT_USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; rv:128.0) Gecko/20100101 Firefox/128.0"
16
+
17
+
18
+ def _inject_credentials(url: str, user: str, password: str) -> str:
19
+ """Embed SOCKS5 username/password credentials into *url* for stream isolation."""
20
+ parsed = urlparse(url)
21
+ host = parsed.hostname or "127.0.0.1"
22
+ port = parsed.port
23
+ netloc = f"{user}:{password}@{host}" if port is None else f"{user}:{password}@{host}:{port}"
24
+ return urlunparse(parsed._replace(netloc=netloc))
25
+
26
+
27
+ def create_session(
28
+ socks_url: str,
29
+ isolated: bool = False,
30
+ user_agent: str | None = DEFAULT_USER_AGENT,
31
+ ) -> "requests.Session":
32
+ """Create a :class:`requests.Session` configured to use Tor's SOCKS5 proxy.
33
+
34
+ Args:
35
+ socks_url: Tor SOCKS5 proxy URL (e.g. ``"socks5h://127.0.0.1:9050"``).
36
+ isolated: If ``True``, generate random SOCKS credentials so Tor assigns
37
+ this session its own circuit.
38
+ user_agent: Optional ``User-Agent`` header. Pass ``None`` to omit.
39
+
40
+ Returns:
41
+ Configured :class:`requests.Session`.
42
+
43
+ Raises:
44
+ ImportError: If ``requests`` (or ``requests[socks]``) is not installed.
45
+ """
46
+ try:
47
+ import requests as _requests
48
+ except ImportError as exc:
49
+ raise ImportError(
50
+ "requests is required. Install with: pip install torwire[requests]"
51
+ ) from exc
52
+
53
+ proxy_url = socks_url
54
+ if isolated:
55
+ proxy_url = _inject_credentials(
56
+ socks_url,
57
+ secrets.token_hex(8),
58
+ secrets.token_hex(8),
59
+ )
60
+
61
+ session = _requests.Session()
62
+ session.proxies = {
63
+ "http": proxy_url,
64
+ "https": proxy_url,
65
+ }
66
+ if user_agent:
67
+ session.headers["User-Agent"] = user_agent
68
+
69
+ return session
torwire/config.py ADDED
@@ -0,0 +1,154 @@
1
+ """Configuration dataclass for torwire."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from dataclasses import dataclass, field
7
+
8
+ logger = logging.getLogger("torwire")
9
+
10
+ LOW_END_TORRC: dict[str, str] = {
11
+ "MaxMemInQueues": "256 MB",
12
+ "ConnectionPadding": "0",
13
+ "ReducedConnectionPadding": "1",
14
+ "DormantClientTimeout": "600",
15
+ }
16
+ """Torrc overrides suitable for memory-constrained environments."""
17
+
18
+
19
+ @dataclass
20
+ class TorConfig:
21
+ """Holds all torwire settings with safe, privacy-preserving defaults.
22
+
23
+ Every field has a sensible default so that ``TorConfig()`` is a valid,
24
+ ready-to-use configuration. Ports default to ``0`` which means
25
+ *pick a free port at launch time* via ``socket.bind(("127.0.0.1", 0))``.
26
+
27
+ Attributes:
28
+ tor_path: Explicit path to a ``tor`` binary. When *None* the
29
+ library searches ``$PATH`` and, if *auto_download* is enabled,
30
+ downloads a copy automatically.
31
+ auto_download: Whether to download a Tor binary when none is
32
+ found locally.
33
+ socks_port: SOCKS5 port to listen on. ``0`` means *pick a free
34
+ port*.
35
+ control_port: Tor control-protocol port. ``0`` means *pick a
36
+ free port*.
37
+ http_port: Optional HTTP CONNECT proxy port. ``None`` disables
38
+ the HTTP proxy.
39
+ control_password: Password for the Tor control port. When
40
+ *None* a random password is generated at launch time.
41
+ data_dir: Tor ``DataDirectory``. ``None`` means use a
42
+ platform-appropriate temporary directory.
43
+ persist_data: If *True* the data directory is kept between runs,
44
+ allowing guard-node state to persist.
45
+ exit_countries: ISO-3166 country codes to restrict exit nodes to
46
+ (e.g. ``["{us}", "{de}"]``).
47
+ strict_exit: If *True*, set ``StrictNodes 1`` so Tor never uses
48
+ exits outside *exit_countries*.
49
+ bridges: Bridge lines to use for censorship circumvention.
50
+ extra_torrc: Arbitrary extra torrc key/value pairs merged last
51
+ (highest priority).
52
+ profile: Configuration profile name. ``"low_end"`` applies
53
+ memory-saving torrc tweaks from :data:`LOW_END_TORRC`.
54
+ bootstrap_timeout: Seconds to wait for Tor to bootstrap.
55
+ ``None`` selects a sensible default based on the profile.
56
+ watchdog: Whether to monitor the Tor process and restart it on
57
+ unexpected exit.
58
+ max_restarts: Maximum automatic restarts before giving up.
59
+ newnym_wait: Whether :meth:`TorProcess.new_identity` should
60
+ block until Tor signals that the new circuit is ready.
61
+ isolate_by_default: If *True* each SOCKS connection uses
62
+ stream isolation (``IsolateSOCKSAuth``).
63
+ log_level: Tor log severity forwarded to *stderr*
64
+ (``debug``, ``info``, ``notice``, ``warn``, ``err``).
65
+ """
66
+
67
+ tor_path: str | None = None
68
+ auto_download: bool = True
69
+ socks_port: int = 0
70
+ control_port: int = 0
71
+ http_port: int | None = None
72
+ control_password: str | None = None
73
+ data_dir: str | None = None
74
+ persist_data: bool = False
75
+ exit_countries: list[str] | None = None
76
+ strict_exit: bool = False
77
+ bridges: list[str] | None = None
78
+ extra_torrc: dict[str, str] = field(default_factory=dict)
79
+ profile: str = "default"
80
+ bootstrap_timeout: float | None = None
81
+ watchdog: bool = True
82
+ max_restarts: int = 5
83
+ newnym_wait: bool = True
84
+ isolate_by_default: bool = False
85
+ log_level: str = "notice"
86
+
87
+ # --------------------------------------------------------------------- #
88
+ # Public helpers
89
+ # --------------------------------------------------------------------- #
90
+
91
+ def effective_torrc(self) -> dict[str, str]:
92
+ """Build the full torrc dictionary ready to be written to disk.
93
+
94
+ Layering order (last wins):
95
+
96
+ 1. Hard-coded base settings (``ClientOnly``, ``SafeSocks``, …).
97
+ 2. Profile-specific overrides (e.g. :data:`LOW_END_TORRC`).
98
+ 3. Exit-country and bridge directives derived from instance fields.
99
+ 4. :attr:`extra_torrc` — always applied last so the caller can
100
+ override anything.
101
+
102
+ Returns:
103
+ A ``dict[str, str]`` mapping torrc keys to their values.
104
+ """
105
+ # 1. Base settings — secure defaults for a client-only instance.
106
+ torrc: dict[str, str] = {
107
+ "ClientOnly": "1",
108
+ "AvoidDiskWrites": "1",
109
+ "SafeSocks": "1",
110
+ "Log": f"{self.log_level} stderr",
111
+ }
112
+
113
+ # 2. Profile overrides.
114
+ if self.profile == "low_end":
115
+ torrc.update(LOW_END_TORRC)
116
+
117
+ # 3a. Exit-country restrictions.
118
+ if self.exit_countries:
119
+ torrc["ExitNodes"] = ",".join(self.exit_countries)
120
+ if self.strict_exit:
121
+ torrc["StrictNodes"] = "1"
122
+
123
+ # 3b. Bridge configuration.
124
+ if self.bridges:
125
+ torrc["UseBridges"] = "1"
126
+ for idx, bridge in enumerate(self.bridges):
127
+ # Tor accepts multiple Bridge lines; we key them uniquely so
128
+ # the dict can be serialised to a torrc file with one line per
129
+ # entry later. The writer is responsible for stripping the
130
+ # numeric suffix and emitting bare ``Bridge`` directives.
131
+ torrc[f"Bridge{idx}"] = bridge
132
+
133
+ # 4. Caller-supplied overrides always win.
134
+ torrc.update(self.extra_torrc)
135
+
136
+ return torrc
137
+
138
+ def effective_bootstrap_timeout(self) -> float:
139
+ """Return the bootstrap timeout in seconds.
140
+
141
+ If :attr:`bootstrap_timeout` was set explicitly that value is
142
+ returned unchanged. Otherwise a profile-aware default is used:
143
+
144
+ * ``"low_end"`` → ``120.0`` seconds (slower hardware / network).
145
+ * everything else → ``90.0`` seconds.
146
+
147
+ Returns:
148
+ Timeout in seconds as a *float*.
149
+ """
150
+ if self.bootstrap_timeout is not None:
151
+ return self.bootstrap_timeout
152
+ if self.profile == "low_end":
153
+ return 120.0
154
+ return 90.0