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/manager.py ADDED
@@ -0,0 +1,370 @@
1
+ """Main public entry point: TorManager."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from contextlib import contextmanager
7
+ from typing import Any, Generator
8
+
9
+ from torwire import checks
10
+ from torwire.binary import BinaryManager
11
+ from torwire.bridge import HttpBridge
12
+ from torwire.config import TorConfig
13
+ from torwire.controller import TorController
14
+ from torwire.env import proxy_env as _proxy_env
15
+ from torwire.errors import NotRunningError
16
+ from torwire.process import TorProcess, _Watchdog
17
+ from torwire.rotation import RotationPolicy, _RotationTimer
18
+
19
+ logger = logging.getLogger("torwire")
20
+
21
+
22
+ class TorManager:
23
+ """Manage a Tor process, control port, HTTP bridge, and client sessions.
24
+
25
+ Usage::
26
+
27
+ with TorManager() as tor:
28
+ s = tor.requests_session()
29
+ print(s.get("https://api.ipify.org").text)
30
+ tor.new_identity()
31
+ """
32
+
33
+ def __init__(self, config: TorConfig | None = None, **overrides: Any) -> None:
34
+ cfg = config or TorConfig()
35
+ for key, value in overrides.items():
36
+ if hasattr(cfg, key):
37
+ setattr(cfg, key, value)
38
+ else:
39
+ raise ValueError(f"Unknown config key: {key!r}")
40
+
41
+ self._config = cfg
42
+ self._process: TorProcess | None = None
43
+ self._controller: TorController | None = None
44
+ self._bridge: HttpBridge | None = None
45
+ self._watchdog: _Watchdog | None = None
46
+ self._rotation_timer: _RotationTimer | None = None
47
+ self._running = False
48
+ self._attached_socks_port: int | None = None
49
+ self._tracked_sessions: list[Any] = []
50
+
51
+ # ------------------------------------------------------------------ #
52
+ # Lifecycle
53
+ # ------------------------------------------------------------------ #
54
+
55
+ def start(self) -> TorManager:
56
+ """Start Tor, connect the control port, and optionally start the HTTP bridge."""
57
+ if self._running:
58
+ return self
59
+
60
+ logger.info("Starting torwire...")
61
+
62
+ binary_mgr = BinaryManager(self._config)
63
+ tor_path = binary_mgr.ensure()
64
+ logger.info("Using tor binary: %s", tor_path)
65
+
66
+ self._process = TorProcess(self._config, tor_path)
67
+ self._process.start(on_progress=self._on_bootstrap_progress)
68
+ logger.info(
69
+ "Tor started on SOCKS port %d, control port %d",
70
+ self._process.socks_port,
71
+ self._process.control_port,
72
+ )
73
+
74
+ self._controller = TorController(
75
+ self._process.control_port,
76
+ self._process.control_password,
77
+ )
78
+ self._controller.connect()
79
+ logger.info("Connected to Tor control port")
80
+
81
+ if self._config.http_port is not None:
82
+ self._bridge = HttpBridge(
83
+ socks_host="127.0.0.1",
84
+ socks_port=self._process.socks_port,
85
+ listen_host="127.0.0.1",
86
+ listen_port=self._config.http_port,
87
+ )
88
+ self._bridge.start()
89
+ logger.info("HTTP bridge started on port %d", self._bridge.port)
90
+
91
+ if self._config.watchdog:
92
+ self._watchdog = _Watchdog(
93
+ self._process,
94
+ max_restarts=self._config.max_restarts,
95
+ on_restart=self._on_tor_restart,
96
+ )
97
+ self._watchdog.start()
98
+
99
+ self._running = True
100
+ logger.info("torwire is ready")
101
+ return self
102
+
103
+ def stop(self) -> None:
104
+ """Stop all components and clean up resources."""
105
+ if not self._running:
106
+ return
107
+
108
+ logger.info("Stopping torwire...")
109
+ self._running = False
110
+
111
+ self.stop_auto_rotate()
112
+
113
+ for session in self._tracked_sessions:
114
+ try:
115
+ if hasattr(session, "close"):
116
+ session.close()
117
+ except Exception:
118
+ pass
119
+ self._tracked_sessions.clear()
120
+
121
+ if self._watchdog is not None:
122
+ self._watchdog.stop()
123
+ self._watchdog = None
124
+
125
+ if self._bridge is not None:
126
+ self._bridge.stop()
127
+ self._bridge = None
128
+
129
+ if self._controller is not None:
130
+ self._controller.close()
131
+ self._controller = None
132
+
133
+ if self._process is not None:
134
+ self._process.stop()
135
+ self._process = None
136
+
137
+ logger.info("torwire stopped")
138
+
139
+ def __enter__(self) -> TorManager:
140
+ return self.start()
141
+
142
+ def __exit__(self, *exc: Any) -> None:
143
+ self.stop()
144
+
145
+ async def __aenter__(self) -> TorManager:
146
+ return self.start()
147
+
148
+ async def __aexit__(self, *exc: Any) -> None:
149
+ self.stop()
150
+
151
+ @property
152
+ def running(self) -> bool:
153
+ """Return ``True`` if the manager is currently running."""
154
+ return self._running
155
+
156
+ @classmethod
157
+ def attach(
158
+ cls,
159
+ socks_port: int = 9050,
160
+ control_port: int = 9051,
161
+ password: str = "",
162
+ http_port: int | None = None,
163
+ ) -> TorManager:
164
+ """Attach to an already-running Tor instance (e.g. system Tor or Tor Browser)."""
165
+ instance = cls(
166
+ TorConfig(
167
+ socks_port=socks_port,
168
+ control_port=control_port,
169
+ control_password=password,
170
+ http_port=http_port,
171
+ watchdog=False,
172
+ )
173
+ )
174
+ instance._attached_socks_port = socks_port
175
+ instance._controller = TorController(control_port, password)
176
+ instance._controller.connect()
177
+
178
+ if http_port is not None:
179
+ instance._bridge = HttpBridge(
180
+ socks_host="127.0.0.1",
181
+ socks_port=socks_port,
182
+ listen_host="127.0.0.1",
183
+ listen_port=http_port,
184
+ )
185
+ instance._bridge.start()
186
+
187
+ instance._running = True
188
+ return instance
189
+
190
+ # ------------------------------------------------------------------ #
191
+ # Endpoints
192
+ # ------------------------------------------------------------------ #
193
+
194
+ def _require_running(self) -> None:
195
+ if not self._running:
196
+ raise NotRunningError("TorManager is not running. Call start() first.")
197
+
198
+ @property
199
+ def socks_port(self) -> int:
200
+ """Return the active SOCKS5 port."""
201
+ self._require_running()
202
+ if self._process is not None:
203
+ return self._process.socks_port
204
+ return self._attached_socks_port or 9050
205
+
206
+ @property
207
+ def socks_url(self) -> str:
208
+ """Return the ``socks5h://`` proxy URL (remote DNS resolution)."""
209
+ return f"socks5h://127.0.0.1:{self.socks_port}"
210
+
211
+ @property
212
+ def http_url(self) -> str | None:
213
+ """Return the HTTP bridge URL, or ``None`` if the bridge is disabled."""
214
+ if self._bridge is not None and self._bridge.running:
215
+ return self._bridge.url
216
+ return None
217
+
218
+ @property
219
+ def proxies(self) -> dict[str, str]:
220
+ """Return a proxy mapping suitable for ``requests``."""
221
+ url = self.socks_url
222
+ return {"http": url, "https": url}
223
+
224
+ # ------------------------------------------------------------------ #
225
+ # IP Control & Rotation
226
+ # ------------------------------------------------------------------ #
227
+
228
+ def new_identity(self, wait: bool = True) -> str:
229
+ """Request a new Tor identity (NEWNYM) and return the new exit IP."""
230
+ self._require_running()
231
+ if self._controller is None:
232
+ raise NotRunningError("No controller connection.")
233
+
234
+ self._controller.new_identity(wait=wait)
235
+
236
+ for session in self._tracked_sessions:
237
+ try:
238
+ if hasattr(session, "close"):
239
+ session.close()
240
+ except Exception:
241
+ pass
242
+ self._tracked_sessions.clear()
243
+
244
+ try:
245
+ return self.current_ip()
246
+ except Exception:
247
+ return ""
248
+
249
+ def current_ip(self) -> str:
250
+ """Query and return the current Tor exit IP address."""
251
+ self._require_running()
252
+ proxy = self.http_url or self.socks_url
253
+ return checks.get_exit_ip(proxy)
254
+
255
+ def set_exit_countries(self, codes: list[str], strict: bool = False) -> None:
256
+ """Set preferred exit node countries (e.g. ``["us", "de"]``)."""
257
+ self._require_running()
258
+ if self._controller is None:
259
+ raise NotRunningError("No controller connection.")
260
+ self._controller.set_exit_countries(codes, strict=strict)
261
+
262
+ def auto_rotate(self, policy: RotationPolicy) -> None:
263
+ """Start automatic IP rotation using *policy*."""
264
+ self._require_running()
265
+ self.stop_auto_rotate()
266
+ self._rotation_timer = _RotationTimer(
267
+ policy=policy,
268
+ rotate_fn=lambda: self.new_identity(wait=self._config.newnym_wait),
269
+ )
270
+ self._rotation_timer.start()
271
+
272
+ def stop_auto_rotate(self) -> None:
273
+ """Stop automatic IP rotation if active."""
274
+ if self._rotation_timer is not None:
275
+ self._rotation_timer.stop()
276
+ self._rotation_timer = None
277
+
278
+ # ------------------------------------------------------------------ #
279
+ # Client Factories
280
+ # ------------------------------------------------------------------ #
281
+
282
+ def requests_session(self, isolated: bool = False) -> Any:
283
+ """Create a :class:`requests.Session` routed through Tor."""
284
+ self._require_running()
285
+ from torwire.clients.requests_ import create_session
286
+
287
+ use_isolated = isolated or self._config.isolate_by_default
288
+ session = create_session(self.socks_url, isolated=use_isolated)
289
+ self._tracked_sessions.append(session)
290
+ return session
291
+
292
+ def httpx_client(self, isolated: bool = False, **kwargs: Any) -> Any:
293
+ """Create an :class:`httpx.Client` routed through Tor."""
294
+ self._require_running()
295
+ from torwire.clients.httpx_ import create_client
296
+
297
+ use_isolated = isolated or self._config.isolate_by_default
298
+ return create_client(self.socks_url, isolated=use_isolated, **kwargs)
299
+
300
+ def httpx_async_client(self, isolated: bool = False, **kwargs: Any) -> Any:
301
+ """Create an :class:`httpx.AsyncClient` routed through Tor."""
302
+ self._require_running()
303
+ from torwire.clients.httpx_ import create_async_client
304
+
305
+ use_isolated = isolated or self._config.isolate_by_default
306
+ return create_async_client(self.socks_url, isolated=use_isolated, **kwargs)
307
+
308
+ def aiohttp_session(self, isolated: bool = False, **kwargs: Any) -> Any:
309
+ """Create an :class:`aiohttp.ClientSession` routed through Tor."""
310
+ self._require_running()
311
+ from torwire.clients.aiohttp_ import create_session
312
+
313
+ use_isolated = isolated or self._config.isolate_by_default
314
+ return create_session(self.socks_url, isolated=use_isolated, **kwargs)
315
+
316
+ # ------------------------------------------------------------------ #
317
+ # Environment Integration
318
+ # ------------------------------------------------------------------ #
319
+
320
+ @contextmanager
321
+ def proxy_env(self) -> Generator[None, None, None]:
322
+ """Temporarily set ``HTTP_PROXY``, ``HTTPS_PROXY``, and ``ALL_PROXY``."""
323
+ self._require_running()
324
+ http = self.http_url
325
+ socks = self.socks_url
326
+ with _proxy_env(
327
+ http_proxy=http or socks,
328
+ https_proxy=http or socks,
329
+ all_proxy=socks,
330
+ ):
331
+ yield
332
+
333
+ # ------------------------------------------------------------------ #
334
+ # Diagnostics
335
+ # ------------------------------------------------------------------ #
336
+
337
+ def health(self) -> checks.HealthReport:
338
+ """Return a :class:`~torwire.checks.HealthReport` for this instance."""
339
+ process_alive = self._process.is_alive if self._process else self._running
340
+ control_alive = self._controller.is_alive() if self._controller else False
341
+ proxy = (self.http_url or self.socks_url) if self._running else None
342
+ return checks.health_check(
343
+ process_alive=process_alive,
344
+ control_alive=control_alive,
345
+ proxy_url=proxy,
346
+ )
347
+
348
+ def leak_check(self) -> checks.LeakReport:
349
+ """Run an IP/DNS leak check and return a :class:`~torwire.checks.LeakReport`."""
350
+ self._require_running()
351
+ return checks.leak_check(self.http_url or self.socks_url)
352
+
353
+ # ------------------------------------------------------------------ #
354
+ # Callbacks
355
+ # ------------------------------------------------------------------ #
356
+
357
+ def _on_bootstrap_progress(self, percent: int, message: str) -> None:
358
+ logger.info("Tor bootstrap: %d%% - %s", percent, message)
359
+
360
+ def _on_tor_restart(self) -> None:
361
+ logger.warning("Tor process restarted by watchdog; reconnecting controller...")
362
+ if self._process is None:
363
+ return
364
+ if self._controller is not None:
365
+ self._controller.close()
366
+ self._controller = TorController(
367
+ self._process.control_port,
368
+ self._process.control_password,
369
+ )
370
+ self._controller.connect()
torwire/pool.py ADDED
@@ -0,0 +1,125 @@
1
+ """Manage multiple independent Tor instances via TorPool."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import threading
7
+ from typing import Any, Iterator
8
+
9
+ from torwire.config import TorConfig
10
+ from torwire.errors import TorwireError
11
+ from torwire.manager import TorManager
12
+
13
+ logger = logging.getLogger("torwire")
14
+
15
+
16
+ class TorPool:
17
+ """Run and round-robin across *size* independent :class:`TorManager` instances.
18
+
19
+ For most workloads, a single :class:`TorManager` with ``isolated=True``
20
+ sessions is lighter and faster. Use ``TorPool`` when you need higher
21
+ parallel throughput or truly isolated Tor processes.
22
+ """
23
+
24
+ def __init__(
25
+ self,
26
+ size: int = 3,
27
+ config: TorConfig | None = None,
28
+ **overrides: Any,
29
+ ) -> None:
30
+ if size < 1:
31
+ raise ValueError("Pool size must be at least 1.")
32
+ self._size = size
33
+ self._base_config = config or TorConfig()
34
+ self._overrides = overrides
35
+ self._instances: list[TorManager] = []
36
+ self._index = 0
37
+ self._lock = threading.Lock()
38
+
39
+ def start(self) -> TorPool:
40
+ """Start all Tor instances in the pool."""
41
+ if self._instances:
42
+ return self
43
+ logger.info("Starting TorPool with %d instances...", self._size)
44
+ for i in range(self._size):
45
+ cfg = TorConfig(
46
+ tor_path=self._base_config.tor_path,
47
+ auto_download=self._base_config.auto_download,
48
+ socks_port=0,
49
+ control_port=0,
50
+ http_port=self._base_config.http_port,
51
+ control_password=None,
52
+ data_dir=None,
53
+ persist_data=self._base_config.persist_data,
54
+ exit_countries=self._base_config.exit_countries,
55
+ strict_exit=self._base_config.strict_exit,
56
+ bridges=self._base_config.bridges,
57
+ extra_torrc=dict(self._base_config.extra_torrc),
58
+ profile=self._base_config.profile,
59
+ bootstrap_timeout=self._base_config.bootstrap_timeout,
60
+ watchdog=self._base_config.watchdog,
61
+ max_restarts=self._base_config.max_restarts,
62
+ newnym_wait=self._base_config.newnym_wait,
63
+ isolate_by_default=self._base_config.isolate_by_default,
64
+ log_level=self._base_config.log_level,
65
+ )
66
+ manager = TorManager(cfg, **self._overrides)
67
+ manager.start()
68
+ self._instances.append(manager)
69
+ logger.info("Pool instance %d/%d started", i + 1, self._size)
70
+ return self
71
+
72
+ def stop(self) -> None:
73
+ """Stop all Tor instances in the pool."""
74
+ for inst in self._instances:
75
+ try:
76
+ inst.stop()
77
+ except Exception as exc:
78
+ logger.error("Error stopping pool instance: %s", exc)
79
+ self._instances.clear()
80
+ self._index = 0
81
+
82
+ def __enter__(self) -> TorPool:
83
+ return self.start()
84
+
85
+ def __exit__(self, *exc: Any) -> None:
86
+ self.stop()
87
+
88
+ @property
89
+ def size(self) -> int:
90
+ """Return the number of running instances (or configured size if stopped)."""
91
+ return len(self._instances) if self._instances else self._size
92
+
93
+ def next(self) -> TorManager:
94
+ """Return the next :class:`TorManager` instance in round-robin order."""
95
+ if not self._instances:
96
+ raise TorwireError("TorPool is not started. Call start() first.")
97
+ with self._lock:
98
+ inst = self._instances[self._index % len(self._instances)]
99
+ self._index += 1
100
+ return inst
101
+
102
+ def next_proxy(self) -> str:
103
+ """Return the next ``socks5h://`` proxy URL in round-robin order."""
104
+ return self.next().socks_url
105
+
106
+ def all_proxies(self) -> list[str]:
107
+ """Return a list of all active ``socks5h://`` proxy URLs."""
108
+ return [inst.socks_url for inst in self._instances]
109
+
110
+ def rotate_all(self) -> None:
111
+ """Trigger ``new_identity(wait=False)`` on every instance in the pool."""
112
+ for inst in self._instances:
113
+ try:
114
+ inst.new_identity(wait=False)
115
+ except Exception as exc:
116
+ logger.warning("Failed to rotate pool instance: %s", exc)
117
+
118
+ def __getitem__(self, index: int) -> TorManager:
119
+ return self._instances[index]
120
+
121
+ def __len__(self) -> int:
122
+ return len(self._instances)
123
+
124
+ def __iter__(self) -> Iterator[TorManager]:
125
+ return iter(self._instances)