Module socket

Module socket 

Source
Expand description

Control socket communication with Tor’s control interface.

This module provides low-level async socket communication with Tor’s control interface. It handles both TCP and Unix domain socket connections, with proper message framing according to the Tor control protocol specification.

§Conceptual Role

The ControlSocket is the transport layer for the Tor control protocol. It handles:

  • Establishing TCP connections to Tor’s ControlPort (typically port 9051)
  • Establishing Unix domain socket connections to Tor’s ControlSocket
  • Sending formatted control protocol messages with proper CRLF termination
  • Receiving and parsing control protocol responses (single-line, multi-line, and data)
  • Connection lifecycle management and status tracking

Most users should use the high-level Controller API instead of this module directly. This module is primarily useful for:

  • Implementing custom control protocol extensions
  • Low-level debugging of control protocol communication
  • Building alternative high-level abstractions

§Protocol Format

The Tor control protocol uses a text-based format with CRLF line endings:

  • Requests: COMMAND [ARGS]\r\n
  • Single-line responses: STATUS MESSAGE\r\n (space divider)
  • Multi-line responses: STATUS-LINE1\r\n STATUS-LINE2\r\n ... STATUS FINAL\r\n (hyphen divider)
  • Data responses: STATUS+KEYWORD\r\n DATA...\r\n .\r\n (plus divider, dot terminator)

Status codes follow HTTP conventions:

  • 2xx: Success
  • 4xx: Client error (bad request)
  • 5xx: Server error (Tor rejected the command)
  • 6xx: Asynchronous event notification

§Example

use stem_rs::ControlSocket;
use std::net::SocketAddr;

// Connect to Tor's control port
let addr: SocketAddr = "127.0.0.1:9051".parse().unwrap();
let mut socket = ControlSocket::connect_port(addr).await?;

// Query protocol info (no authentication required)
socket.send("PROTOCOLINFO 1").await?;
let response = socket.recv().await?;

if response.is_ok() {
    println!("Protocol info: {}", response.content());
}

§Thread Safety

ControlSocket is Send but not Sync. The socket maintains internal read/write buffers that require exclusive access. For concurrent access from multiple tasks, wrap in Arc<Mutex<ControlSocket>> or use separate connections.

§Platform Support

  • TCP sockets: Supported on all platforms
  • Unix domain sockets: Supported on Unix-like systems only (Linux, macOS, BSD)

On non-Unix platforms, connect_unix returns Error::Socket with ErrorKind::Unsupported.

§See Also

Structs§

ControlMessage
A parsed control protocol response message.
ControlSocket
A connection to Tor’s control interface.