stem 1.2.3

A complete Rust library for Tor control protocol โ€” build privacy-focused applications with type-safe, async-first APIs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
<h1 align="center">stem</h1>

<h3 align="center">A complete Rust library for Tor control protocol</h3>
<p align="center">
  Build privacy-focused applications with type-safe, async-first APIs
</p>

<p align="center">
  <a href="https://crates.io/crates/stem">
    <img src="https://img.shields.io/crates/v/stem?style=for-the-badge&logo=rust&logoColor=white&color=f74c00" alt="Crates.io">
  </a>
  <a href="https://stem.tn3w.dev/docs/">
    <img src="https://img.shields.io/docsrs/stem?style=for-the-badge&logo=docs.rs&logoColor=white" alt="docs.rs">
  </a>
  <a href="https://github.com/tn3w/stem/blob/master/LICENSE">
    <img src="https://img.shields.io/badge/license-Apache--2.0-blue?style=for-the-badge" alt="License">
  </a>
</p>

<p align="center">
  <a href="https://github.com/tn3w/stem/actions">
    <img src="https://img.shields.io/github/actions/workflow/status/tn3w/stem/tests.yml?style=for-the-badge&logo=github&logoColor=white&label=CI" alt="CI">
  </a>
  <a href="https://github.com/tn3w/stem">
    <img src="https://img.shields.io/github/stars/tn3w/stem?style=for-the-badge&logo=github&logoColor=white" alt="Stars">
  </a>
</p>

<p align="center">
  <a href="https://stem.tn3w.dev">๐ŸŒ Website</a> โ€ข
  <a href="https://stem.tn3w.dev/docs/">๐Ÿ“š Documentation</a> โ€ข
  <a href="https://stem.tn3w.dev/tutorials">๐Ÿ“– Tutorials</a> โ€ข
  <a href="#-quick-start">๐Ÿš€ Quick Start</a> โ€ข
  <a href="#-examples">๐Ÿ’ก Examples</a>
</p>

## Overview

**stem** is a Rust implementation of [Stem](https://stem.torproject.org/), the Python library for interacting with Tor's control protocol. It provides idiomatic, type-safe Rust APIs while maintaining complete functional parity with Python Stem.

Whether you're building privacy tools, monitoring Tor relays, managing circuits, or creating onion services โ€” stem gives you the building blocks you need with the safety guarantees Rust provides.

```rust
use stem::{Controller, Error};

#[tokio::main]
async fn main() -> Result<(), Error> {
    // Connect to Tor's control port
    let mut ctrl = Controller::from_port("127.0.0.1:9051".parse()?).await?;

    // Authenticate (auto-detects method)
    ctrl.authenticate(None).await?;

    // Query Tor version
    let version = ctrl.get_version().await?;
    println!("Connected to Tor {}", version);

    Ok(())
}
```

## โœจ Features

<table>
<tr>
<td width="50%">

### ๐Ÿ”Œ Control Socket

Connect to Tor via TCP or Unix domain sockets with full async I/O powered by Tokio.

- TCP port connections (`127.0.0.1:9051`)
- Unix domain sockets (`/var/run/tor/control`)
- Non-blocking async operations
- Automatic reconnection handling

</td>
<td width="50%">

### ๐Ÿ” Authentication

All authentication methods with automatic detection and secure credential handling.

- **SAFECOOKIE** โ€” Challenge-response (recommended)
- **COOKIE** โ€” File-based authentication
- **PASSWORD** โ€” HashedControlPassword
- **NONE** โ€” Open control port

</td>
</tr>
<tr>
<td width="50%">

### ๐ŸŽ›๏ธ Controller API

High-level interface for complete Tor interaction.

- Query configuration and status
- Send signals (NEWNYM, RELOAD, etc.)
- Create, extend, and close circuits
- Attach and manage streams
- Create ephemeral hidden services
- Map addresses for custom routing

</td>
<td width="50%">

### ๐Ÿ“„ Descriptor Parsing

Complete parsing for all Tor descriptor types.

- **Server Descriptors** โ€” Full relay metadata
- **Microdescriptors** โ€” Compact client-side info
- **Consensus Documents** โ€” Network status
- **Extra-Info** โ€” Bandwidth statistics
- **Hidden Service** โ€” v2 and v3 descriptors
- **Bandwidth Files** โ€” Authority measurements

</td>
</tr>
<tr>
<td width="50%">

### ๐Ÿ“ก Event Handling

Subscribe to real-time Tor events with strongly-typed event structs.

- Bandwidth monitoring (`BW`, `CIRC_BW`)
- Circuit lifecycle (`CIRC`, `CIRC_MINOR`)
- Stream tracking (`STREAM`, `STREAM_BW`)
- Log messages (`DEBUG` โ†’ `ERR`)
- Status updates (`STATUS_*`)
- Hidden service events (`HS_DESC`)

</td>
<td width="50%">

### ๐Ÿšช Exit Policy

Parse and evaluate relay exit policies.

- Full exit policy parsing
- IPv4 and IPv6 support
- CIDR notation for address ranges
- Port range evaluation
- Policy summarization

</td>
</tr>
</table>

## ๐Ÿš€ Quick Start

Add stem to your `Cargo.toml`:

```toml
[dependencies]
stem = "1.2"
tokio = { version = "1", features = ["full"] }
```

Or install via cargo:

```bash
cargo add stem tokio --features tokio/full
```

### Enable Tor's Control Port

Add to your `torrc`:

```
ControlPort 9051
CookieAuthentication 1
```

Or for password authentication:

```
ControlPort 9051
HashedControlPassword 16:872860B76453A77D60CA2BB8C1A7042072093276A3D701AD684053EC4C
```

Generate a hashed password:

```bash
tor --hash-password "your-password"
```

## ๐ŸŽ›๏ธ Feature Flags

stem uses feature flags to allow you to compile only what you need, reducing compile time and binary size.

### Default Features

By default, all features are enabled:

```toml
[dependencies]
stem = "1.2"  # Includes all features
```

### Minimal Build

For a minimal build with just the core functionality:

```toml
[dependencies]
stem = { version = "1.2", default-features = false }
```

This includes: socket communication, authentication, protocol parsing, utilities, and version handling.

### Available Features

| Feature | Description | Dependencies |
|---------|-------------|--------------|
| `full` | All features (default) | All features below |
| `controller` | High-level Controller API | `events` |
| `descriptors` | Tor descriptor parsing | `client`, `exit-policy` |
| `events` | Event subscription and handling | None |
| `exit-policy` | Exit policy parsing and evaluation | None |
| `client` | ORPort relay communication | None |
| `interpreter` | Interactive Tor control interpreter | `controller`, `events` |
| `compression` | Gzip decompression for descriptors | None |

### Custom Feature Combinations

**Controller only** (no descriptor parsing):
```toml
[dependencies]
stem = { version = "1.2", default-features = false, features = ["controller"] }
```

**Descriptors only** (offline analysis):
```toml
[dependencies]
stem = { version = "1.2", default-features = false, features = ["descriptors"] }
```

**Controller + Descriptors** (most common):
```toml
[dependencies]
stem = { version = "1.2", default-features = false, features = ["controller", "descriptors"] }
```

### Compile Time Improvements

Approximate compile time reductions with feature flags:

- **Minimal build**: ~40% faster (excludes descriptors, controller, events)
- **Controller-only**: ~30% faster (excludes descriptor parsing)
- **Descriptors-only**: ~20% faster (excludes controller, events)

Binary size reductions follow similar patterns.

## ๐Ÿ’ก Examples

### Connect and Authenticate

```rust
use stem::{Controller, Error};

#[tokio::main]
async fn main() -> Result<(), Error> {
    // Connect via TCP
    let mut ctrl = Controller::from_port("127.0.0.1:9051".parse()?).await?;

    // Or via Unix socket
    // let mut ctrl = Controller::from_socket_file(Path::new("/var/run/tor/control")).await?;

    // Auto-detect authentication method
    ctrl.authenticate(None).await?;

    // Or use password
    // ctrl.authenticate(Some("my_password")).await?;

    println!("Connected!");
    Ok(())
}
```

### Query Information

```rust
// Get Tor version
let version = ctrl.get_version().await?;
println!("Tor {}", version);

// Get process ID
let pid = ctrl.get_pid().await?;
println!("PID: {}", pid);

// Query arbitrary info
let traffic_read = ctrl.get_info("traffic/read").await?;
let traffic_written = ctrl.get_info("traffic/written").await?;
println!("Traffic: {} read, {} written", traffic_read, traffic_written);

// Get configuration
let socks_ports = ctrl.get_conf("SocksPort").await?;
for port in socks_ports {
    println!("SOCKS port: {}", port);
}
```

### Circuit Management

```rust
use stem::CircStatus;

// List all circuits
let circuits = ctrl.get_circuits().await?;
for circuit in circuits {
    if circuit.status == CircStatus::Built {
        println!("Circuit {} ({} hops):", circuit.id, circuit.path.len());
        for relay in &circuit.path {
            println!("  โ†’ {} ({:?})", relay.fingerprint, relay.nickname);
        }
    }
}

// Create a new circuit
let circuit_id = ctrl.new_circuit(None).await?;
println!("Created circuit: {}", circuit_id);

// Close a circuit
ctrl.close_circuit(circuit_id).await?;
```

### Stream Management

```rust
use stem::StreamStatus;

// List all streams
let streams = ctrl.get_streams().await?;
for stream in streams {
    println!("Stream {} โ†’ {}:{} ({:?})",
        stream.id,
        stream.target_host,
        stream.target_port,
        stream.status
    );
}
```

### Event Subscription

```rust
use stem::EventType;

// Subscribe to events
ctrl.set_events(&[
    EventType::Bw,      // Bandwidth
    EventType::Circ,    // Circuits
    EventType::Stream,  // Streams
    EventType::Notice,  // Log messages
]).await?;

// Process events
loop {
    let event = ctrl.recv_event().await?;
    match event {
        ParsedEvent::Bandwidth(bw) => {
            println!("BW: {} read, {} written", bw.read, bw.written);
        }
        ParsedEvent::Circuit(circ) => {
            println!("Circuit {}: {:?}", circ.id, circ.status);
        }
        ParsedEvent::Log(log) => {
            println!("[{}] {}", log.runlevel, log.message);
        }
        _ => {}
    }
}
```

### Send Signals

```rust
use stem::Signal;

// Request new identity (new circuits)
ctrl.signal(Signal::Newnym).await?;

// Clear DNS cache
ctrl.signal(Signal::ClearDnsCache).await?;

// Reload configuration
ctrl.signal(Signal::Reload).await?;

// Graceful shutdown
ctrl.signal(Signal::Shutdown).await?;
```

### Hidden Services

```rust
// Create ephemeral hidden service (v3 onion)
let response = ctrl.create_ephemeral_hidden_service(
    &[(80, "127.0.0.1:8080")],  // Map port 80 to local 8080
    "NEW",                       // Generate new key
    "ED25519-V3",                // Use v3 onion (recommended)
    &[],                         // No special flags
).await?;

println!("Hidden service: {}.onion", response.service_id);
println!("Private key: {:?}", response.private_key);

// Remove hidden service
ctrl.remove_ephemeral_hidden_service(&response.service_id).await?;
```

### Descriptor Parsing

```rust
use stem::descriptor::{
    ServerDescriptor, Microdescriptor, NetworkStatusDocument,
    Descriptor, DigestHash, DigestEncoding,
    download_consensus, download_server_descriptors,
};

// Download and parse consensus
let consensus = download_consensus(None).await?;
println!("Valid until: {}", consensus.valid_until);
println!("Relays: {}", consensus.routers.len());

// Parse server descriptor
let content = std::fs::read_to_string("cached-descriptors")?;
let descriptor = ServerDescriptor::parse(&content)?;
println!("Relay: {} ({})", descriptor.nickname, descriptor.fingerprint);
println!("Bandwidth: {} avg, {} burst",
    descriptor.bandwidth_avg, descriptor.bandwidth_burst);

// Compute digest
let digest = descriptor.digest(DigestHash::Sha1, DigestEncoding::Hex)?;
println!("Digest: {}", digest);
```

### Exit Policy Evaluation

```rust
use stem::exit_policy::ExitPolicy;
use std::net::IpAddr;

let policy = ExitPolicy::parse("accept *:80, accept *:443, reject *:*")?;

// Check if traffic is allowed
let addr: IpAddr = "93.184.216.34".parse()?;
if policy.can_exit_to(addr, 443) {
    println!("HTTPS traffic allowed");
}

// Get policy summary
println!("Policy: {}", policy.summary());
```

### Version Comparison

```rust
use stem::Version;

let version = ctrl.get_version().await?;

// Compare versions
let min_version = Version::parse("0.4.0.0")?;
if version >= min_version {
    println!("Tor {} supports required features", version);
}
```

## ๐Ÿ“ฆ Module Reference

| Module                                                   | Description                                                       |
| -------------------------------------------------------- | ----------------------------------------------------------------- |
| [`controller`]https://stem.tn3w.dev/docs/controller/   | High-level Tor control interface                                  |
| [`socket`]https://stem.tn3w.dev/docs/socket/           | Low-level control socket communication                            |
| [`auth`]https://stem.tn3w.dev/docs/auth/               | Authentication methods and protocol info                          |
| [`descriptor`]https://stem.tn3w.dev/docs/descriptor/   | Tor descriptor parsing (server, micro, consensus, hidden service) |
| [`events`]https://stem.tn3w.dev/docs/events/           | Event types and real-time handling                                |
| [`exit_policy`]https://stem.tn3w.dev/docs/exit_policy/ | Exit policy parsing and evaluation                                |
| [`version`]https://stem.tn3w.dev/docs/version/         | Version parsing and comparison                                    |
| [`client`]https://stem.tn3w.dev/docs/client/           | Direct ORPort relay communication                                 |
| [`interpreter`]https://stem.tn3w.dev/docs/interpreter/ | Interactive Tor control interpreter                               |
| [`util`]https://stem.tn3w.dev/docs/util/               | Validation utilities (fingerprints, nicknames, etc.)              |

## ๐Ÿ”’ Security

stem is designed with security as a priority:

- **100% Safe Rust** โ€” No `unsafe` code
- **Constant-time comparison** โ€” For authentication tokens and cookies
- **Memory clearing** โ€” Sensitive data cleared after use
- **Input validation** โ€” Prevents protocol injection attacks
- **Signature verification** โ€” Optional cryptographic validation for descriptors

## โšก Performance

- **Async-first** โ€” Built on Tokio for high-performance async I/O
- **Zero-copy parsing** โ€” Efficient descriptor parsing where possible
- **Event streaming** โ€” Non-blocking real-time event handling
- **Connection pooling** โ€” Efficient socket management

## ๐Ÿ› ๏ธ Requirements

- **Rust** 1.70+
- **Tokio** runtime
- **Tor** instance with control port enabled

## ๐Ÿงช Testing

```bash
# Run unit tests
cargo test

# Run with integration tests (requires running Tor)
cargo test --features integration

# Run extensive tests
cargo test --features extensive
```

## ๐Ÿ“Š Comparison with Python Stem

stem maintains functional parity with Python Stem while providing Rust's safety guarantees:

| Feature                | Python Stem | stem |
| ---------------------- | ----------- | ------- |
| Control Protocol       | โœ…          | โœ…      |
| All Auth Methods       | โœ…          | โœ…      |
| Descriptor Parsing     | โœ…          | โœ…      |
| Event Handling         | โœ…          | โœ…      |
| Exit Policy            | โœ…          | โœ…      |
| Hidden Services        | โœ…          | โœ…      |
| Type Safety            | โŒ          | โœ…      |
| Memory Safety          | โŒ          | โœ…      |
| Async/Await            | โŒ          | โœ…      |
| Zero-cost Abstractions | โŒ          | โœ…      |

## ๐Ÿ“„ License

Copyright 2026 stem contributors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

## ๐Ÿค Contributing

Contributions are welcome! Please feel free to submit issues and pull requests.

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## ๐Ÿ”— Links

<p align="center">
  <a href="https://stem.tn3w.dev">Website</a> โ€ข
  <a href="https://stem.tn3w.dev/docs/">Documentation</a> โ€ข
  <a href="https://stem.tn3w.dev/tutorials">Tutorials</a> โ€ข
  <a href="https://crates.io/crates/stem">crates.io</a> โ€ข
  <a href="https://github.com/tn3w/stem">GitHub</a> โ€ข
  <a href="https://stem.torproject.org/">Python Stem</a>
</p>

<p align="center">
  <sub>Built with ๐Ÿฆ€ by the stem contributors</sub>
</p>