Module protocol

Module protocol 

Source
Expand description

Control protocol message parsing for Tor control protocol.

This module provides parsing utilities for control protocol responses, including single-line, multi-line, and data responses. It implements the message format defined in section 2.3 of the Tor control protocol specification.

§Conceptual Role

The protocol module handles the low-level parsing of control protocol messages. It sits between the raw socket communication (crate::socket) and the high-level response types (crate::response).

§Protocol Format

The Tor control protocol uses a text-based format with the following structure:

§Request Format

COMMAND [ARGS]\r\n

§Response Format

Each response line has the format:

STATUS DIVIDER MESSAGE\r\n

Where:

  • STATUS is a 3-digit status code (e.g., 250 for success, 5xx for errors)
  • DIVIDER indicates the line type:
    • (space): Final line of the response
    • -: Continuation line (more lines follow)
    • +: Data line (multi-line data block follows)
  • MESSAGE is the response content

§Status Codes

CodeMeaning
250Success
251Operation unnecessary
5xxError (various types)
650Asynchronous event

§Single-Line Response Example

250 OK

§Multi-Line Response Example

250-version=0.4.7.1
250-config-file=/etc/tor/torrc
250 OK

§Data Response Example

250+info/names=
desc/id/* -- Router descriptors by ID.
desc/name/* -- Router descriptors by nickname.
.
250 OK

§Example

use stem_rs::protocol::{ParsedLine, ControlLine, format_command};

// Parse a response line
let line = ParsedLine::parse("250 OK").unwrap();
assert_eq!(line.status_code, 250);
assert!(line.is_final());

// Parse key=value content
let mut ctrl = ControlLine::new("key1=value1 key2=\"quoted value\"");
let (k, v) = ctrl.pop_mapping(false, false).unwrap();
assert_eq!(k, "key1");
assert_eq!(v, "value1");

// Format a command
let cmd = format_command("GETINFO", &["version"]);
assert_eq!(cmd, "GETINFO version\r\n");

§Thread Safety

ParsedLine is Send and Sync as it contains only owned data. ControlLine is Send but not Sync due to internal mutable state for tracking parse position.

§See Also

Structs§

ControlLine
A parser for space-delimited control protocol response content.
ParsedLine
A parsed line from a Tor control protocol response.

Functions§

format_command
Formats a control protocol command with arguments.
quote_string
Quotes a string for use in control protocol commands.