stem_rs/events.rs
1//! Event types and handling for Tor control protocol async notifications.
2//!
3//! This module provides comprehensive event types for all Tor control protocol
4//! asynchronous events, as described in section 4.1 of the
5//! [control-spec](https://spec.torproject.org/control-spec/replies.html#asynchronous-events).
6//!
7//! # Overview
8//!
9//! Tor emits asynchronous events to notify controllers about state changes,
10//! bandwidth usage, circuit activity, and other important occurrences. Events
11//! are received after subscribing via the `SETEVENTS` command through the
12//! [`Controller`](crate::Controller).
13//!
14//! # Event Categories
15//!
16//! Events are organized into several categories:
17//!
18//! - **Bandwidth Events**: [`BandwidthEvent`], [`CircuitBandwidthEvent`],
19//! [`ConnectionBandwidthEvent`] - Track data transfer rates
20//! - **Circuit Events**: [`CircuitEvent`] - Monitor circuit lifecycle
21//! - **Stream Events**: [`StreamEvent`] - Track stream connections
22//! - **Connection Events**: [`OrConnEvent`] - Monitor OR connections
23//! - **Log Events**: [`LogEvent`] - Receive Tor log messages
24//! - **Status Events**: [`StatusEvent`] - Bootstrap progress and status changes
25//! - **Guard Events**: [`GuardEvent`] - Guard relay changes
26//! - **Hidden Service Events**: [`HsDescEvent`] - Hidden service descriptor activity
27//! - **Configuration Events**: [`ConfChangedEvent`] - Configuration changes
28//! - **Network Events**: [`NetworkLivenessEvent`] - Network connectivity status
29//!
30//! # Event Subscription
31//!
32//! To receive events, subscribe using the controller's `set_events` method:
33//!
34//! ```rust,no_run
35//! use stem_rs::{controller::Controller, EventType};
36//!
37//! # async fn example() -> Result<(), stem_rs::Error> {
38//! let mut controller = Controller::from_port("127.0.0.1:9051".parse()?).await?;
39//! controller.authenticate(None).await?;
40//!
41//! // Subscribe to bandwidth and circuit events
42//! controller.set_events(&[EventType::Bw, EventType::Circ]).await?;
43//!
44//! // Events will now be delivered asynchronously
45//! # Ok(())
46//! # }
47//! ```
48//!
49//! # Event Parsing
50//!
51//! Raw event data from Tor is parsed into strongly-typed event structs using
52//! [`ParsedEvent::parse`]. Each event type provides access to its specific
53//! fields while also preserving the raw content for debugging.
54//!
55//! # Thread Safety
56//!
57//! All event types implement [`Send`] and [`Sync`], allowing them to be safely
58//! shared across threads. The [`Event`] trait requires these bounds.
59//!
60//! # See Also
61//!
62//! - [`crate::controller`] - High-level controller API for event subscription
63//! - [`crate::protocol`] - Low-level protocol message handling
64
65use std::collections::HashMap;
66use std::time::Instant;
67
68use chrono::{DateTime, Local, Utc};
69
70use crate::controller::{CircuitId, StreamId};
71use crate::protocol::ControlLine;
72use crate::{
73 CircBuildFlag, CircClosureReason, CircPurpose, CircStatus, ConnectionType, Error, EventType,
74 GuardStatus, GuardType, HiddenServiceState, HsAuth, HsDescAction, HsDescReason,
75 OrClosureReason, OrStatus, Runlevel, Signal, StatusType, StreamClosureReason, StreamPurpose,
76 StreamSource, StreamStatus, TimeoutSetType,
77};
78
79/// Trait implemented by all Tor control protocol events.
80///
81/// This trait provides a common interface for accessing event metadata
82/// regardless of the specific event type. All event types must be thread-safe
83/// (`Send + Sync`) to support concurrent event handling.
84///
85/// # Implementors
86///
87/// All event structs in this module implement this trait:
88/// - [`BandwidthEvent`], [`LogEvent`], [`CircuitEvent`], [`StreamEvent`]
89/// - [`OrConnEvent`], [`AddrMapEvent`], [`BuildTimeoutSetEvent`]
90/// - [`GuardEvent`], [`NewDescEvent`], [`SignalEvent`], [`StatusEvent`]
91/// - [`ConfChangedEvent`], [`NetworkLivenessEvent`], [`CircuitBandwidthEvent`]
92/// - [`ConnectionBandwidthEvent`], [`HsDescEvent`]
93///
94/// # Example
95///
96/// ```rust,ignore
97/// fn handle_event(event: &dyn Event) {
98/// println!("Received {:?} event at {:?}", event.event_type(), event.arrived_at());
99/// println!("Raw content: {}", event.raw_content());
100/// }
101/// ```
102pub trait Event: Send + Sync {
103 /// Returns the type of this event.
104 ///
105 /// This corresponds to the event keyword used in `SETEVENTS` commands.
106 fn event_type(&self) -> EventType;
107
108 /// Returns the raw, unparsed content of the event.
109 ///
110 /// Useful for debugging or when additional parsing is needed beyond
111 /// what the typed event provides.
112 fn raw_content(&self) -> &str;
113
114 /// Returns the instant when this event was received.
115 ///
116 /// This is the local time when the event was parsed, not when Tor
117 /// generated it. Useful for measuring event latency or ordering events.
118 fn arrived_at(&self) -> Instant;
119}
120
121/// Event emitted every second with the bytes sent and received by Tor.
122///
123/// The BW event is one of the most commonly used events for monitoring
124/// Tor's bandwidth usage. It provides a snapshot of data transfer rates
125/// over the last second.
126///
127/// # Event Format
128///
129/// The raw event format is: `BW <bytes_read> <bytes_written>`
130///
131/// # Use Cases
132///
133/// - Monitoring bandwidth consumption
134/// - Building bandwidth graphs
135/// - Detecting network activity
136/// - Rate limiting applications
137///
138/// # Example
139///
140/// ```rust,ignore
141/// use stem_rs::events::BandwidthEvent;
142///
143/// fn handle_bandwidth(event: &BandwidthEvent) {
144/// let read_kbps = event.read as f64 / 1024.0;
145/// let written_kbps = event.written as f64 / 1024.0;
146/// println!("Bandwidth: {:.2} KB/s read, {:.2} KB/s written", read_kbps, written_kbps);
147/// }
148/// ```
149///
150/// # See Also
151///
152/// - [`CircuitBandwidthEvent`] - Per-circuit bandwidth tracking
153/// - [`ConnectionBandwidthEvent`] - Per-connection bandwidth tracking
154#[derive(Debug, Clone)]
155pub struct BandwidthEvent {
156 /// Bytes received by Tor in the last second.
157 pub read: u64,
158 /// Bytes sent by Tor in the last second.
159 pub written: u64,
160 raw_content: String,
161 arrived_at: Instant,
162}
163
164impl Event for BandwidthEvent {
165 fn event_type(&self) -> EventType {
166 EventType::Bw
167 }
168 fn raw_content(&self) -> &str {
169 &self.raw_content
170 }
171 fn arrived_at(&self) -> Instant {
172 self.arrived_at
173 }
174}
175
176impl BandwidthEvent {
177 /// Parses a bandwidth event from raw control protocol content.
178 ///
179 /// # Arguments
180 ///
181 /// * `content` - The event content after the event type, e.g., "15 25"
182 ///
183 /// # Errors
184 ///
185 /// Returns [`Error::Protocol`] if:
186 /// - The content is missing required values
187 /// - The read or written values are not valid integers
188 ///
189 /// # Example
190 ///
191 /// ```rust,ignore
192 /// let event = BandwidthEvent::parse("1024 2048")?;
193 /// assert_eq!(event.read, 1024);
194 /// assert_eq!(event.written, 2048);
195 /// ```
196 pub fn parse(content: &str) -> Result<Self, Error> {
197 let mut line = ControlLine::new(content);
198 let read_str = line.pop(false, false)?;
199 let written_str = line.pop(false, false)?;
200
201 let read: u64 = read_str.parse().map_err(|_| {
202 Error::Protocol(format!("invalid read value in BW event: {}", read_str))
203 })?;
204 let written: u64 = written_str.parse().map_err(|_| {
205 Error::Protocol(format!(
206 "invalid written value in BW event: {}",
207 written_str
208 ))
209 })?;
210
211 Ok(Self {
212 read,
213 written,
214 raw_content: content.to_string(),
215 arrived_at: Instant::now(),
216 })
217 }
218}
219
220/// Tor logging event for receiving log messages from the Tor process.
221///
222/// These are the most visible kind of event since, by default, Tor logs
223/// at the NOTICE [`Runlevel`] to stdout. Log events allow controllers to
224/// receive and process Tor's log output programmatically.
225///
226/// # Runlevels
227///
228/// Log events are categorized by severity:
229/// - [`Runlevel::Debug`] - Verbose debugging information
230/// - [`Runlevel::Info`] - Informational messages
231/// - [`Runlevel::Notice`] - Normal operational messages (default)
232/// - [`Runlevel::Warn`] - Warning conditions
233/// - [`Runlevel::Err`] - Error conditions
234///
235/// # Event Types
236///
237/// Each runlevel corresponds to a separate event type:
238/// - `DEBUG`, `INFO`, `NOTICE`, `WARN`, `ERR`
239///
240/// # Example
241///
242/// ```rust,ignore
243/// use stem_rs::{EventType, Runlevel};
244/// use stem_rs::events::LogEvent;
245///
246/// fn handle_log(event: &LogEvent) {
247/// match event.runlevel {
248/// Runlevel::Err | Runlevel::Warn => {
249/// eprintln!("[{}] {}", event.runlevel, event.message);
250/// }
251/// _ => {
252/// println!("[{}] {}", event.runlevel, event.message);
253/// }
254/// }
255/// }
256/// ```
257///
258/// # See Also
259///
260/// - [`Runlevel`](crate::Runlevel) - Log severity levels
261/// - [`StatusEvent`] - Structured status messages
262#[derive(Debug, Clone)]
263pub struct LogEvent {
264 /// Severity level of the log message.
265 pub runlevel: Runlevel,
266 /// The log message content.
267 pub message: String,
268 raw_content: String,
269 arrived_at: Instant,
270}
271
272impl Event for LogEvent {
273 fn event_type(&self) -> EventType {
274 match self.runlevel {
275 Runlevel::Debug => EventType::Debug,
276 Runlevel::Info => EventType::Info,
277 Runlevel::Notice => EventType::Notice,
278 Runlevel::Warn => EventType::Warn,
279 Runlevel::Err => EventType::Err,
280 }
281 }
282 fn raw_content(&self) -> &str {
283 &self.raw_content
284 }
285 fn arrived_at(&self) -> Instant {
286 self.arrived_at
287 }
288}
289
290impl LogEvent {
291 /// Parses a log event from raw control protocol content.
292 ///
293 /// # Arguments
294 ///
295 /// * `runlevel` - The severity level of the log message
296 /// * `message` - The log message content
297 ///
298 /// # Errors
299 ///
300 /// This method currently does not return errors but returns `Result`
301 /// for API consistency with other event parsers.
302 pub fn parse(runlevel: Runlevel, message: &str) -> Result<Self, Error> {
303 Ok(Self {
304 runlevel,
305 message: message.to_string(),
306 raw_content: message.to_string(),
307 arrived_at: Instant::now(),
308 })
309 }
310}
311
312/// Event indicating that a circuit's status has changed.
313///
314/// Circuit events are fundamental to understanding Tor's operation. They
315/// track the lifecycle of circuits from creation through closure, including
316/// the relays involved and the purpose of each circuit.
317///
318/// # Circuit Lifecycle
319///
320/// Circuits progress through these states:
321/// 1. [`CircStatus::Launched`] - Circuit creation initiated
322/// 2. [`CircStatus::Extended`] - Circuit extended to additional hops
323/// 3. [`CircStatus::Built`] - Circuit fully constructed and ready
324/// 4. [`CircStatus::Failed`] or [`CircStatus::Closed`] - Circuit terminated
325///
326/// # Path Information
327///
328/// The `path` field contains the relays in the circuit as `(fingerprint, nickname)`
329/// tuples. The fingerprint is always present; the nickname may be `None` if
330/// the `VERBOSE_NAMES` feature isn't enabled (on by default since Tor 0.2.2.1).
331///
332/// # Hidden Service Circuits
333///
334/// For hidden service circuits, additional fields provide context:
335/// - `hs_state` - Current state in the hidden service protocol
336/// - `rend_query` - The rendezvous point address
337/// - `purpose` - Indicates the circuit's role (intro, rend, etc.)
338///
339/// # Example
340///
341/// ```rust,ignore
342/// use stem_rs::events::CircuitEvent;
343/// use stem_rs::CircStatus;
344///
345/// fn handle_circuit(event: &CircuitEvent) {
346/// match event.status {
347/// CircStatus::Built => {
348/// println!("Circuit {} built with {} hops", event.id, event.path.len());
349/// for (fingerprint, nickname) in &event.path {
350/// println!(" - {} ({:?})", fingerprint, nickname);
351/// }
352/// }
353/// CircStatus::Failed => {
354/// println!("Circuit {} failed: {:?}", event.id, event.reason);
355/// }
356/// _ => {}
357/// }
358/// }
359/// ```
360///
361/// # See Also
362///
363/// - [`CircStatus`](crate::CircStatus) - Circuit status values
364/// - [`CircPurpose`](crate::CircPurpose) - Circuit purpose types
365/// - [`CircClosureReason`](crate::CircClosureReason) - Closure reasons
366#[derive(Debug, Clone)]
367pub struct CircuitEvent {
368 /// Unique identifier for this circuit.
369 pub id: CircuitId,
370 /// Current status of the circuit.
371 pub status: CircStatus,
372 /// Relays in the circuit path as `(fingerprint, nickname)` tuples.
373 pub path: Vec<(String, Option<String>)>,
374 /// Flags governing how the circuit was built.
375 pub build_flags: Option<Vec<CircBuildFlag>>,
376 /// Purpose that the circuit is intended for.
377 pub purpose: Option<CircPurpose>,
378 /// Hidden service state if this is an HS circuit.
379 pub hs_state: Option<HiddenServiceState>,
380 /// Rendezvous query if this is a hidden service circuit.
381 pub rend_query: Option<String>,
382 /// Time when the circuit was created or cannibalized.
383 pub created: Option<DateTime<Utc>>,
384 /// Reason for circuit closure (local).
385 pub reason: Option<CircClosureReason>,
386 /// Reason for circuit closure (from remote side).
387 pub remote_reason: Option<CircClosureReason>,
388 /// SOCKS username for stream isolation.
389 pub socks_username: Option<String>,
390 /// SOCKS password for stream isolation.
391 pub socks_password: Option<String>,
392 raw_content: String,
393 arrived_at: Instant,
394}
395
396impl Event for CircuitEvent {
397 fn event_type(&self) -> EventType {
398 EventType::Circ
399 }
400 fn raw_content(&self) -> &str {
401 &self.raw_content
402 }
403 fn arrived_at(&self) -> Instant {
404 self.arrived_at
405 }
406}
407
408impl CircuitEvent {
409 /// Parses a circuit event from raw control protocol content.
410 ///
411 /// # Arguments
412 ///
413 /// * `content` - The event content after the event type
414 ///
415 /// # Event Format
416 ///
417 /// ```text
418 /// CircuitID CircStatus [Path] [BUILD_FLAGS=...] [PURPOSE=...] [HS_STATE=...]
419 /// [REND_QUERY=...] [TIME_CREATED=...] [REASON=...] [REMOTE_REASON=...]
420 /// [SOCKS_USERNAME="..."] [SOCKS_PASSWORD="..."]
421 /// ```
422 ///
423 /// # Errors
424 ///
425 /// Returns [`Error::Protocol`] if:
426 /// - The circuit ID or status is missing
427 /// - The status is not a recognized value
428 pub fn parse(content: &str) -> Result<Self, Error> {
429 let mut line = ControlLine::new(content);
430 let id_str = line.pop(false, false)?;
431 let status_str = line.pop(false, false)?;
432 let status = parse_circ_status(&status_str)?;
433
434 let mut path = Vec::new();
435 let mut build_flags = None;
436 let mut purpose = None;
437 let mut hs_state = None;
438 let mut rend_query = None;
439 let mut created = None;
440 let mut reason = None;
441 let mut remote_reason = None;
442 let mut socks_username = None;
443 let mut socks_password = None;
444
445 while !line.is_empty() {
446 if line.is_next_mapping(Some("BUILD_FLAGS"), false) {
447 let (_, flags_str) = line.pop_mapping(false, false)?;
448 build_flags = Some(parse_build_flags(&flags_str));
449 } else if line.is_next_mapping(Some("PURPOSE"), false) {
450 let (_, p) = line.pop_mapping(false, false)?;
451 purpose = parse_circ_purpose(&p).ok();
452 } else if line.is_next_mapping(Some("HS_STATE"), false) {
453 let (_, s) = line.pop_mapping(false, false)?;
454 hs_state = parse_hs_state(&s).ok();
455 } else if line.is_next_mapping(Some("REND_QUERY"), false) {
456 let (_, q) = line.pop_mapping(false, false)?;
457 rend_query = Some(q);
458 } else if line.is_next_mapping(Some("TIME_CREATED"), false) {
459 let (_, t) = line.pop_mapping(false, false)?;
460 created = parse_iso_timestamp(&t).ok();
461 } else if line.is_next_mapping(Some("REASON"), false) {
462 let (_, r) = line.pop_mapping(false, false)?;
463 reason = parse_circ_closure_reason(&r).ok();
464 } else if line.is_next_mapping(Some("REMOTE_REASON"), false) {
465 let (_, r) = line.pop_mapping(false, false)?;
466 remote_reason = parse_circ_closure_reason(&r).ok();
467 } else if line.is_next_mapping(Some("SOCKS_USERNAME"), true) {
468 let (_, u) = line.pop_mapping(true, true)?;
469 socks_username = Some(u);
470 } else if line.is_next_mapping(Some("SOCKS_PASSWORD"), true) {
471 let (_, p) = line.pop_mapping(true, true)?;
472 socks_password = Some(p);
473 } else {
474 let token = line.pop(false, false)?;
475 if token.starts_with('$') || token.contains('~') || token.contains(',') {
476 path = parse_circuit_path(&token);
477 }
478 }
479 }
480
481 Ok(Self {
482 id: CircuitId::new(id_str),
483 status,
484 path,
485 build_flags,
486 purpose,
487 hs_state,
488 rend_query,
489 created,
490 reason,
491 remote_reason,
492 socks_username,
493 socks_password,
494 raw_content: content.to_string(),
495 arrived_at: Instant::now(),
496 })
497 }
498}
499
500/// Event indicating that a stream's status has changed.
501///
502/// Stream events track the lifecycle of TCP connections made through Tor.
503/// Each stream is associated with a circuit and connects to a specific
504/// target host and port.
505///
506/// # Stream Lifecycle
507///
508/// Streams progress through these states:
509/// 1. [`StreamStatus::New`] - New stream request received
510/// 2. [`StreamStatus::SentConnect`] - CONNECT sent to exit relay
511/// 3. [`StreamStatus::Remap`] - Address remapped (e.g., DNS resolution)
512/// 4. [`StreamStatus::Succeeded`] - Connection established
513/// 5. [`StreamStatus::Closed`] or [`StreamStatus::Failed`] - Stream terminated
514///
515/// # Circuit Association
516///
517/// The `circuit_id` field indicates which circuit carries this stream.
518/// A value of `None` (circuit ID "0") means the stream is not yet
519/// attached to a circuit.
520///
521/// # Example
522///
523/// ```rust,ignore
524/// use stem_rs::events::StreamEvent;
525/// use stem_rs::StreamStatus;
526///
527/// fn handle_stream(event: &StreamEvent) {
528/// match event.status {
529/// StreamStatus::New => {
530/// println!("New stream {} to {}:{}",
531/// event.id, event.target_host, event.target_port);
532/// }
533/// StreamStatus::Succeeded => {
534/// println!("Stream {} connected via circuit {:?}",
535/// event.id, event.circuit_id);
536/// }
537/// StreamStatus::Closed | StreamStatus::Failed => {
538/// println!("Stream {} ended: {:?}", event.id, event.reason);
539/// }
540/// _ => {}
541/// }
542/// }
543/// ```
544///
545/// # See Also
546///
547/// - [`StreamStatus`](crate::StreamStatus) - Stream status values
548/// - [`StreamPurpose`](crate::StreamPurpose) - Stream purpose types
549/// - [`StreamClosureReason`](crate::StreamClosureReason) - Closure reasons
550#[derive(Debug, Clone)]
551pub struct StreamEvent {
552 /// Unique identifier for this stream.
553 pub id: StreamId,
554 /// Current status of the stream.
555 pub status: StreamStatus,
556 /// Circuit carrying this stream, or `None` if unattached.
557 pub circuit_id: Option<CircuitId>,
558 /// Target hostname or IP address.
559 pub target_host: String,
560 /// Target port number.
561 pub target_port: u16,
562 /// Reason for stream closure (local).
563 pub reason: Option<StreamClosureReason>,
564 /// Reason for stream closure (from remote side).
565 pub remote_reason: Option<StreamClosureReason>,
566 /// Source of address resolution (cache or exit).
567 pub source: Option<StreamSource>,
568 /// Source address of the client connection.
569 pub source_addr: Option<String>,
570 /// Purpose of this stream.
571 pub purpose: Option<StreamPurpose>,
572 raw_content: String,
573 arrived_at: Instant,
574}
575
576impl Event for StreamEvent {
577 fn event_type(&self) -> EventType {
578 EventType::Stream
579 }
580 fn raw_content(&self) -> &str {
581 &self.raw_content
582 }
583 fn arrived_at(&self) -> Instant {
584 self.arrived_at
585 }
586}
587
588impl StreamEvent {
589 /// Parses a stream event from raw control protocol content.
590 ///
591 /// # Arguments
592 ///
593 /// * `content` - The event content after the event type
594 ///
595 /// # Event Format
596 ///
597 /// ```text
598 /// StreamID StreamStatus CircuitID Target [REASON=...] [REMOTE_REASON=...]
599 /// [SOURCE=...] [SOURCE_ADDR=...] [PURPOSE=...]
600 /// ```
601 ///
602 /// # Errors
603 ///
604 /// Returns [`Error::Protocol`] if:
605 /// - Required fields are missing
606 /// - The status is not a recognized value
607 /// - The target format is invalid
608 pub fn parse(content: &str) -> Result<Self, Error> {
609 let mut line = ControlLine::new(content);
610 let id_str = line.pop(false, false)?;
611 let status_str = line.pop(false, false)?;
612 let circuit_id_str = line.pop(false, false)?;
613 let target = line.pop(false, false)?;
614
615 let status = parse_stream_status(&status_str)?;
616 let circuit_id = if circuit_id_str == "0" {
617 None
618 } else {
619 Some(CircuitId::new(circuit_id_str))
620 };
621 let (target_host, target_port) = parse_target(&target)?;
622
623 let mut reason = None;
624 let mut remote_reason = None;
625 let mut source = None;
626 let mut source_addr = None;
627 let mut purpose = None;
628
629 while !line.is_empty() {
630 if line.is_next_mapping(Some("REASON"), false) {
631 let (_, r) = line.pop_mapping(false, false)?;
632 reason = parse_stream_closure_reason(&r).ok();
633 } else if line.is_next_mapping(Some("REMOTE_REASON"), false) {
634 let (_, r) = line.pop_mapping(false, false)?;
635 remote_reason = parse_stream_closure_reason(&r).ok();
636 } else if line.is_next_mapping(Some("SOURCE"), false) {
637 let (_, s) = line.pop_mapping(false, false)?;
638 source = parse_stream_source(&s).ok();
639 } else if line.is_next_mapping(Some("SOURCE_ADDR"), false) {
640 let (_, a) = line.pop_mapping(false, false)?;
641 source_addr = Some(a);
642 } else if line.is_next_mapping(Some("PURPOSE"), false) {
643 let (_, p) = line.pop_mapping(false, false)?;
644 purpose = parse_stream_purpose(&p).ok();
645 } else {
646 let _ = line.pop(false, false)?;
647 }
648 }
649
650 Ok(Self {
651 id: StreamId::new(id_str),
652 status,
653 circuit_id,
654 target_host,
655 target_port,
656 reason,
657 remote_reason,
658 source,
659 source_addr,
660 purpose,
661 raw_content: content.to_string(),
662 arrived_at: Instant::now(),
663 })
664 }
665}
666
667/// Event indicating that an OR (Onion Router) connection status has changed.
668///
669/// OR connection events track the status of connections between Tor relays.
670/// These are the TLS connections that carry circuit traffic between nodes
671/// in the Tor network.
672///
673/// # Connection Lifecycle
674///
675/// OR connections progress through these states:
676/// 1. [`OrStatus::New`] - Connection initiated
677/// 2. [`OrStatus::Launched`] - Connection attempt in progress
678/// 3. [`OrStatus::Connected`] - TLS handshake completed
679/// 4. [`OrStatus::Failed`] or [`OrStatus::Closed`] - Connection terminated
680///
681/// # Example
682///
683/// ```rust,ignore
684/// use stem_rs::events::OrConnEvent;
685/// use stem_rs::OrStatus;
686///
687/// fn handle_orconn(event: &OrConnEvent) {
688/// match event.status {
689/// OrStatus::Connected => {
690/// println!("Connected to relay: {}", event.target);
691/// }
692/// OrStatus::Failed | OrStatus::Closed => {
693/// println!("Connection to {} ended: {:?}", event.target, event.reason);
694/// }
695/// _ => {}
696/// }
697/// }
698/// ```
699///
700/// # See Also
701///
702/// - [`OrStatus`](crate::OrStatus) - OR connection status values
703/// - [`OrClosureReason`](crate::OrClosureReason) - Closure reasons
704#[derive(Debug, Clone)]
705pub struct OrConnEvent {
706 /// Connection identifier (may be `None` for older Tor versions).
707 pub id: Option<String>,
708 /// Current status of the OR connection.
709 pub status: OrStatus,
710 /// Target relay address (IP:port or fingerprint).
711 pub target: String,
712 /// Reason for connection closure.
713 pub reason: Option<OrClosureReason>,
714 /// Number of circuits using this connection.
715 pub num_circuits: Option<u32>,
716 raw_content: String,
717 arrived_at: Instant,
718}
719
720impl Event for OrConnEvent {
721 fn event_type(&self) -> EventType {
722 EventType::OrConn
723 }
724 fn raw_content(&self) -> &str {
725 &self.raw_content
726 }
727 fn arrived_at(&self) -> Instant {
728 self.arrived_at
729 }
730}
731
732impl OrConnEvent {
733 /// Parses an OR connection event from raw control protocol content.
734 ///
735 /// # Arguments
736 ///
737 /// * `content` - The event content after the event type
738 ///
739 /// # Event Format
740 ///
741 /// ```text
742 /// Target Status [REASON=...] [NCIRCS=...] [ID=...]
743 /// ```
744 ///
745 /// # Errors
746 ///
747 /// Returns [`Error::Protocol`] if:
748 /// - Required fields are missing
749 /// - The status is not a recognized value
750 pub fn parse(content: &str) -> Result<Self, Error> {
751 let mut line = ControlLine::new(content);
752 let target = line.pop(false, false)?;
753 let status_str = line.pop(false, false)?;
754 let status = parse_or_status(&status_str)?;
755
756 let mut id = None;
757 let mut reason = None;
758 let mut num_circuits = None;
759
760 while !line.is_empty() {
761 if line.is_next_mapping(Some("REASON"), false) {
762 let (_, r) = line.pop_mapping(false, false)?;
763 reason = parse_or_closure_reason(&r).ok();
764 } else if line.is_next_mapping(Some("NCIRCS"), false) {
765 let (_, n) = line.pop_mapping(false, false)?;
766 num_circuits = n.parse().ok();
767 } else if line.is_next_mapping(Some("ID"), false) {
768 let (_, i) = line.pop_mapping(false, false)?;
769 id = Some(i);
770 } else {
771 let _ = line.pop(false, false)?;
772 }
773 }
774
775 Ok(Self {
776 id,
777 status,
778 target,
779 reason,
780 num_circuits,
781 raw_content: content.to_string(),
782 arrived_at: Instant::now(),
783 })
784 }
785}
786
787/// Event indicating a new address mapping has been created.
788///
789/// Address map events are emitted when Tor creates a mapping between
790/// a hostname and its resolved address. This can occur due to DNS
791/// resolution, `MAPADDRESS` commands, or `TrackHostExits` configuration.
792///
793/// # Expiration
794///
795/// Address mappings have an expiration time after which they are no longer
796/// valid. The `expiry` field contains the local time, while `utc_expiry`
797/// contains the UTC time (if available).
798///
799/// # Caching
800///
801/// The `cached` field indicates whether the mapping will be kept until
802/// expiration (`true`) or may be evicted earlier (`false`).
803///
804/// # Error Mappings
805///
806/// When DNS resolution fails, `destination` will be `None` and the `error`
807/// field will contain the error code.
808///
809/// # Example
810///
811/// ```rust,ignore
812/// use stem_rs::events::AddrMapEvent;
813///
814/// fn handle_addrmap(event: &AddrMapEvent) {
815/// match &event.destination {
816/// Some(dest) => {
817/// println!("{} -> {} (expires: {:?})",
818/// event.hostname, dest, event.expiry);
819/// }
820/// None => {
821/// println!("Resolution failed for {}: {:?}",
822/// event.hostname, event.error);
823/// }
824/// }
825/// }
826/// ```
827#[derive(Debug, Clone)]
828pub struct AddrMapEvent {
829 /// The hostname being resolved.
830 pub hostname: String,
831 /// The resolved address, or `None` if resolution failed.
832 pub destination: Option<String>,
833 /// Expiration time in local time.
834 pub expiry: Option<DateTime<Local>>,
835 /// Error code if resolution failed.
836 pub error: Option<String>,
837 /// Expiration time in UTC.
838 pub utc_expiry: Option<DateTime<Utc>>,
839 /// Whether the mapping is cached until expiration.
840 pub cached: Option<bool>,
841 raw_content: String,
842 arrived_at: Instant,
843}
844
845impl Event for AddrMapEvent {
846 fn event_type(&self) -> EventType {
847 EventType::AddrMap
848 }
849 fn raw_content(&self) -> &str {
850 &self.raw_content
851 }
852 fn arrived_at(&self) -> Instant {
853 self.arrived_at
854 }
855}
856
857impl AddrMapEvent {
858 /// Parses an address map event from raw control protocol content.
859 ///
860 /// # Arguments
861 ///
862 /// * `content` - The event content after the event type
863 ///
864 /// # Event Format
865 ///
866 /// ```text
867 /// Hostname Destination Expiry [error=...] [EXPIRES="..."] [CACHED=YES|NO]
868 /// ```
869 ///
870 /// # Errors
871 ///
872 /// Returns [`Error::Protocol`] if required fields are missing.
873 pub fn parse(content: &str) -> Result<Self, Error> {
874 let mut line = ControlLine::new(content);
875 let hostname = line.pop(false, false)?;
876 let dest_str = line.pop(false, false)?;
877 let destination = if dest_str == "<error>" {
878 None
879 } else {
880 Some(dest_str)
881 };
882
883 let expiry_str = if line.is_next_quoted() {
884 Some(line.pop(true, false)?)
885 } else {
886 let token = line.pop(false, false)?;
887 if token == "NEVER" {
888 None
889 } else {
890 Some(token)
891 }
892 };
893
894 let expiry = expiry_str.and_then(|s| parse_local_timestamp(&s).ok());
895
896 let mut error = None;
897 let mut utc_expiry = None;
898 let mut cached = None;
899
900 while !line.is_empty() {
901 if line.is_next_mapping(Some("error"), false) {
902 let (_, e) = line.pop_mapping(false, false)?;
903 error = Some(e);
904 } else if line.is_next_mapping(Some("EXPIRES"), true) {
905 let (_, e) = line.pop_mapping(true, false)?;
906 utc_expiry = parse_utc_timestamp(&e).ok();
907 } else if line.is_next_mapping(Some("CACHED"), true) {
908 let (_, c) = line.pop_mapping(true, false)?;
909 cached = match c.as_str() {
910 "YES" => Some(true),
911 "NO" => Some(false),
912 _ => None,
913 };
914 } else {
915 let _ = line.pop(false, false)?;
916 }
917 }
918
919 Ok(Self {
920 hostname,
921 destination,
922 expiry,
923 error,
924 utc_expiry,
925 cached,
926 raw_content: content.to_string(),
927 arrived_at: Instant::now(),
928 })
929 }
930}
931
932/// Event indicating that the circuit build timeout has changed.
933///
934/// Tor dynamically adjusts its circuit build timeout based on observed
935/// circuit construction times. This event is emitted when the timeout
936/// value changes, providing insight into network performance.
937///
938/// # Timeout Calculation
939///
940/// Tor uses a Pareto distribution to model circuit build times:
941/// - `xm` - The Pareto Xm parameter (minimum value)
942/// - `alpha` - The Pareto alpha parameter (shape)
943/// - `quantile` - The CDF cutoff quantile
944///
945/// # Set Types
946///
947/// The `set_type` indicates why the timeout changed:
948/// - [`TimeoutSetType::Computed`] - Calculated from observed times
949/// - [`TimeoutSetType::Reset`] - Reset to default values
950/// - [`TimeoutSetType::Suspended`] - Timeout learning suspended
951/// - [`TimeoutSetType::Discard`] - Discarding learned values
952/// - [`TimeoutSetType::Resume`] - Resuming timeout learning
953///
954/// # Example
955///
956/// ```rust,ignore
957/// use stem_rs::events::BuildTimeoutSetEvent;
958///
959/// fn handle_timeout(event: &BuildTimeoutSetEvent) {
960/// if let Some(timeout) = event.timeout {
961/// println!("Circuit timeout set to {}ms ({:?})", timeout, event.set_type);
962/// }
963/// if let Some(rate) = event.timeout_rate {
964/// println!("Timeout rate: {:.2}%", rate * 100.0);
965/// }
966/// }
967/// ```
968///
969/// # See Also
970///
971/// - [`TimeoutSetType`](crate::TimeoutSetType) - Timeout change reasons
972#[derive(Debug, Clone)]
973pub struct BuildTimeoutSetEvent {
974 /// Type of timeout change.
975 pub set_type: TimeoutSetType,
976 /// Number of circuit build times used to calculate timeout.
977 pub total_times: Option<u32>,
978 /// Circuit build timeout in milliseconds.
979 pub timeout: Option<u32>,
980 /// Pareto Xm parameter in milliseconds.
981 pub xm: Option<u32>,
982 /// Pareto alpha parameter.
983 pub alpha: Option<f64>,
984 /// CDF quantile cutoff point.
985 pub quantile: Option<f64>,
986 /// Ratio of circuits that timed out.
987 pub timeout_rate: Option<f64>,
988 /// Duration to keep measurement circuits in milliseconds.
989 pub close_timeout: Option<u32>,
990 /// Ratio of measurement circuits that were closed.
991 pub close_rate: Option<f64>,
992 raw_content: String,
993 arrived_at: Instant,
994}
995
996impl Event for BuildTimeoutSetEvent {
997 fn event_type(&self) -> EventType {
998 EventType::BuildTimeoutSet
999 }
1000 fn raw_content(&self) -> &str {
1001 &self.raw_content
1002 }
1003 fn arrived_at(&self) -> Instant {
1004 self.arrived_at
1005 }
1006}
1007
1008impl BuildTimeoutSetEvent {
1009 /// Parses a build timeout set event from raw control protocol content.
1010 ///
1011 /// # Arguments
1012 ///
1013 /// * `content` - The event content after the event type
1014 ///
1015 /// # Event Format
1016 ///
1017 /// ```text
1018 /// SetType [TOTAL_TIMES=...] [TIMEOUT_MS=...] [XM=...] [ALPHA=...]
1019 /// [CUTOFF_QUANTILE=...] [TIMEOUT_RATE=...] [CLOSE_MS=...] [CLOSE_RATE=...]
1020 /// ```
1021 ///
1022 /// # Errors
1023 ///
1024 /// Returns [`Error::Protocol`] if:
1025 /// - The set type is missing or unrecognized
1026 /// - Numeric values cannot be parsed
1027 pub fn parse(content: &str) -> Result<Self, Error> {
1028 let mut line = ControlLine::new(content);
1029 let set_type_str = line.pop(false, false)?;
1030 let set_type = parse_timeout_set_type(&set_type_str)?;
1031
1032 let mut total_times = None;
1033 let mut timeout = None;
1034 let mut xm = None;
1035 let mut alpha = None;
1036 let mut quantile = None;
1037 let mut timeout_rate = None;
1038 let mut close_timeout = None;
1039 let mut close_rate = None;
1040
1041 while !line.is_empty() {
1042 if line.is_next_mapping(Some("TOTAL_TIMES"), false) {
1043 let (_, v) = line.pop_mapping(false, false)?;
1044 total_times = Some(
1045 v.parse()
1046 .map_err(|_| Error::Protocol(format!("invalid TOTAL_TIMES: {}", v)))?,
1047 );
1048 } else if line.is_next_mapping(Some("TIMEOUT_MS"), false) {
1049 let (_, v) = line.pop_mapping(false, false)?;
1050 timeout = Some(
1051 v.parse()
1052 .map_err(|_| Error::Protocol(format!("invalid TIMEOUT_MS: {}", v)))?,
1053 );
1054 } else if line.is_next_mapping(Some("XM"), false) {
1055 let (_, v) = line.pop_mapping(false, false)?;
1056 xm = Some(
1057 v.parse()
1058 .map_err(|_| Error::Protocol(format!("invalid XM: {}", v)))?,
1059 );
1060 } else if line.is_next_mapping(Some("ALPHA"), false) {
1061 let (_, v) = line.pop_mapping(false, false)?;
1062 alpha = Some(
1063 v.parse()
1064 .map_err(|_| Error::Protocol(format!("invalid ALPHA: {}", v)))?,
1065 );
1066 } else if line.is_next_mapping(Some("CUTOFF_QUANTILE"), false) {
1067 let (_, v) = line.pop_mapping(false, false)?;
1068 quantile = Some(
1069 v.parse()
1070 .map_err(|_| Error::Protocol(format!("invalid CUTOFF_QUANTILE: {}", v)))?,
1071 );
1072 } else if line.is_next_mapping(Some("TIMEOUT_RATE"), false) {
1073 let (_, v) = line.pop_mapping(false, false)?;
1074 timeout_rate = Some(
1075 v.parse()
1076 .map_err(|_| Error::Protocol(format!("invalid TIMEOUT_RATE: {}", v)))?,
1077 );
1078 } else if line.is_next_mapping(Some("CLOSE_MS"), false) {
1079 let (_, v) = line.pop_mapping(false, false)?;
1080 close_timeout = Some(
1081 v.parse()
1082 .map_err(|_| Error::Protocol(format!("invalid CLOSE_MS: {}", v)))?,
1083 );
1084 } else if line.is_next_mapping(Some("CLOSE_RATE"), false) {
1085 let (_, v) = line.pop_mapping(false, false)?;
1086 close_rate = Some(
1087 v.parse()
1088 .map_err(|_| Error::Protocol(format!("invalid CLOSE_RATE: {}", v)))?,
1089 );
1090 } else {
1091 let _ = line.pop(false, false)?;
1092 }
1093 }
1094
1095 Ok(Self {
1096 set_type,
1097 total_times,
1098 timeout,
1099 xm,
1100 alpha,
1101 quantile,
1102 timeout_rate,
1103 close_timeout,
1104 close_rate,
1105 raw_content: content.to_string(),
1106 arrived_at: Instant::now(),
1107 })
1108 }
1109}
1110
1111/// Event indicating that guard relay status has changed.
1112///
1113/// Guard events track changes to the entry guards that Tor uses for the
1114/// first hop of circuits. Entry guards are a security feature that limits
1115/// the set of relays that can observe your traffic entering the Tor network.
1116///
1117/// # Guard Types
1118///
1119/// Currently, only [`GuardType::Entry`] is used, representing entry guards.
1120///
1121/// # Guard Status
1122///
1123/// Guards can have these statuses:
1124/// - [`GuardStatus::New`] - Newly selected as a guard
1125/// - [`GuardStatus::Up`] - Guard is reachable
1126/// - [`GuardStatus::Down`] - Guard is unreachable
1127/// - [`GuardStatus::Good`] - Guard confirmed as good
1128/// - [`GuardStatus::Bad`] - Guard marked as bad
1129/// - [`GuardStatus::Dropped`] - Guard removed from list
1130///
1131/// # Example
1132///
1133/// ```rust,ignore
1134/// use stem_rs::events::GuardEvent;
1135/// use stem_rs::GuardStatus;
1136///
1137/// fn handle_guard(event: &GuardEvent) {
1138/// match event.status {
1139/// GuardStatus::New => {
1140/// println!("New guard: {} ({:?})",
1141/// event.endpoint_fingerprint, event.endpoint_nickname);
1142/// }
1143/// GuardStatus::Down => {
1144/// println!("Guard {} is down", event.endpoint_fingerprint);
1145/// }
1146/// GuardStatus::Dropped => {
1147/// println!("Guard {} dropped", event.endpoint_fingerprint);
1148/// }
1149/// _ => {}
1150/// }
1151/// }
1152/// ```
1153///
1154/// # See Also
1155///
1156/// - [`GuardType`](crate::GuardType) - Guard type values
1157/// - [`GuardStatus`](crate::GuardStatus) - Guard status values
1158#[derive(Debug, Clone)]
1159pub struct GuardEvent {
1160 /// Type of guard (currently only Entry).
1161 pub guard_type: GuardType,
1162 /// Full endpoint string (fingerprint with optional nickname).
1163 pub endpoint: String,
1164 /// Relay fingerprint (40 hex characters).
1165 pub endpoint_fingerprint: String,
1166 /// Relay nickname if available.
1167 pub endpoint_nickname: Option<String>,
1168 /// Current status of the guard.
1169 pub status: GuardStatus,
1170 raw_content: String,
1171 arrived_at: Instant,
1172}
1173
1174impl Event for GuardEvent {
1175 fn event_type(&self) -> EventType {
1176 EventType::Guard
1177 }
1178 fn raw_content(&self) -> &str {
1179 &self.raw_content
1180 }
1181 fn arrived_at(&self) -> Instant {
1182 self.arrived_at
1183 }
1184}
1185
1186impl GuardEvent {
1187 /// Parses a guard event from raw control protocol content.
1188 ///
1189 /// # Arguments
1190 ///
1191 /// * `content` - The event content after the event type
1192 ///
1193 /// # Event Format
1194 ///
1195 /// ```text
1196 /// GuardType Endpoint Status
1197 /// ```
1198 ///
1199 /// Where Endpoint is either a fingerprint or `fingerprint=nickname`.
1200 ///
1201 /// # Errors
1202 ///
1203 /// Returns [`Error::Protocol`] if:
1204 /// - Required fields are missing
1205 /// - The guard type or status is unrecognized
1206 pub fn parse(content: &str) -> Result<Self, Error> {
1207 let mut line = ControlLine::new(content);
1208 let guard_type_str = line.pop(false, false)?;
1209 let endpoint = line.pop(false, false)?;
1210 let status_str = line.pop(false, false)?;
1211
1212 let guard_type = parse_guard_type(&guard_type_str)?;
1213 let status = parse_guard_status(&status_str)?;
1214 let (fingerprint, nickname) = parse_relay_endpoint(&endpoint);
1215
1216 Ok(Self {
1217 guard_type,
1218 endpoint,
1219 endpoint_fingerprint: fingerprint,
1220 endpoint_nickname: nickname,
1221 status,
1222 raw_content: content.to_string(),
1223 arrived_at: Instant::now(),
1224 })
1225 }
1226}
1227
1228/// Event indicating that new relay descriptors are available.
1229///
1230/// This event is emitted when Tor receives new server descriptors for
1231/// relays in the network. It provides a list of relays whose descriptors
1232/// have been updated.
1233///
1234/// # Relay Identification
1235///
1236/// Each relay is identified by its fingerprint and optionally its nickname.
1237/// The `relays` field contains `(fingerprint, nickname)` tuples.
1238///
1239/// # Example
1240///
1241/// ```rust,ignore
1242/// use stem_rs::events::NewDescEvent;
1243///
1244/// fn handle_newdesc(event: &NewDescEvent) {
1245/// println!("Received {} new descriptors:", event.relays.len());
1246/// for (fingerprint, nickname) in &event.relays {
1247/// match nickname {
1248/// Some(nick) => println!(" {} ({})", fingerprint, nick),
1249/// None => println!(" {}", fingerprint),
1250/// }
1251/// }
1252/// }
1253/// ```
1254#[derive(Debug, Clone)]
1255pub struct NewDescEvent {
1256 /// List of relays with new descriptors as `(fingerprint, nickname)` tuples.
1257 pub relays: Vec<(String, Option<String>)>,
1258 raw_content: String,
1259 arrived_at: Instant,
1260}
1261
1262impl Event for NewDescEvent {
1263 fn event_type(&self) -> EventType {
1264 EventType::NewDesc
1265 }
1266 fn raw_content(&self) -> &str {
1267 &self.raw_content
1268 }
1269 fn arrived_at(&self) -> Instant {
1270 self.arrived_at
1271 }
1272}
1273
1274impl NewDescEvent {
1275 /// Parses a new descriptor event from raw control protocol content.
1276 ///
1277 /// # Arguments
1278 ///
1279 /// * `content` - The event content after the event type
1280 ///
1281 /// # Event Format
1282 ///
1283 /// ```text
1284 /// Relay1 [Relay2 ...]
1285 /// ```
1286 ///
1287 /// Where each relay is either a fingerprint or `fingerprint=nickname`.
1288 ///
1289 /// # Errors
1290 ///
1291 /// This method currently does not return errors but returns `Result`
1292 /// for API consistency.
1293 pub fn parse(content: &str) -> Result<Self, Error> {
1294 let mut relays = Vec::new();
1295 for token in content.split_whitespace() {
1296 let (fingerprint, nickname) = parse_relay_endpoint(token);
1297 relays.push((fingerprint, nickname));
1298 }
1299 Ok(Self {
1300 relays,
1301 raw_content: content.to_string(),
1302 arrived_at: Instant::now(),
1303 })
1304 }
1305}
1306
1307/// Event indicating that Tor received a signal.
1308///
1309/// This event is emitted when Tor receives a signal, either from the
1310/// operating system or via the control protocol's `SIGNAL` command.
1311///
1312/// # Signals
1313///
1314/// Common signals include:
1315/// - [`Signal::Newnym`] - Request new circuits
1316/// - [`Signal::Reload`] - Reload configuration
1317/// - [`Signal::Shutdown`] - Graceful shutdown
1318/// - [`Signal::Halt`] - Immediate shutdown
1319///
1320/// # Example
1321///
1322/// ```rust,ignore
1323/// use stem_rs::events::SignalEvent;
1324/// use stem_rs::Signal;
1325///
1326/// fn handle_signal(event: &SignalEvent) {
1327/// match event.signal {
1328/// Signal::Newnym => println!("New identity requested"),
1329/// Signal::Shutdown => println!("Tor is shutting down"),
1330/// _ => println!("Received signal: {:?}", event.signal),
1331/// }
1332/// }
1333/// ```
1334///
1335/// # See Also
1336///
1337/// - [`Signal`](crate::Signal) - Signal types
1338#[derive(Debug, Clone)]
1339pub struct SignalEvent {
1340 /// The signal that was received.
1341 pub signal: Signal,
1342 raw_content: String,
1343 arrived_at: Instant,
1344}
1345
1346impl Event for SignalEvent {
1347 fn event_type(&self) -> EventType {
1348 EventType::Signal
1349 }
1350 fn raw_content(&self) -> &str {
1351 &self.raw_content
1352 }
1353 fn arrived_at(&self) -> Instant {
1354 self.arrived_at
1355 }
1356}
1357
1358impl SignalEvent {
1359 /// Parses a signal event from raw control protocol content.
1360 ///
1361 /// # Arguments
1362 ///
1363 /// * `content` - The event content after the event type
1364 ///
1365 /// # Errors
1366 ///
1367 /// Returns [`Error::Protocol`] if the signal is unrecognized.
1368 pub fn parse(content: &str) -> Result<Self, Error> {
1369 let signal = parse_signal(content.trim())?;
1370 Ok(Self {
1371 signal,
1372 raw_content: content.to_string(),
1373 arrived_at: Instant::now(),
1374 })
1375 }
1376}
1377
1378/// Event providing status information about Tor's operation.
1379///
1380/// Status events provide structured information about Tor's operational
1381/// state, including bootstrap progress, circuit establishment, and
1382/// various warnings or errors.
1383///
1384/// # Status Types
1385///
1386/// Events are categorized by type:
1387/// - [`StatusType::General`] - General status (e.g., consensus arrived)
1388/// - [`StatusType::Client`] - Client-specific status (e.g., bootstrap progress)
1389/// - [`StatusType::Server`] - Server-specific status (e.g., reachability checks)
1390///
1391/// # Bootstrap Progress
1392///
1393/// The most common use of status events is tracking bootstrap progress.
1394/// Look for `action == "BOOTSTRAP"` and check the `PROGRESS` argument.
1395///
1396/// # Example
1397///
1398/// ```rust,ignore
1399/// use stem_rs::events::StatusEvent;
1400/// use stem_rs::StatusType;
1401///
1402/// fn handle_status(event: &StatusEvent) {
1403/// if event.action == "BOOTSTRAP" {
1404/// if let Some(progress) = event.arguments.get("PROGRESS") {
1405/// println!("Bootstrap progress: {}%", progress);
1406/// }
1407/// if let Some(summary) = event.arguments.get("SUMMARY") {
1408/// println!("Status: {}", summary);
1409/// }
1410/// }
1411/// }
1412/// ```
1413///
1414/// # See Also
1415///
1416/// - [`StatusType`](crate::StatusType) - Status event types
1417/// - [`Runlevel`](crate::Runlevel) - Severity levels
1418#[derive(Debug, Clone)]
1419pub struct StatusEvent {
1420 /// Type of status event (General, Client, or Server).
1421 pub status_type: StatusType,
1422 /// Severity level of the status message.
1423 pub runlevel: Runlevel,
1424 /// Action or event name (e.g., "BOOTSTRAP", "CIRCUIT_ESTABLISHED").
1425 pub action: String,
1426 /// Key-value arguments providing additional details.
1427 pub arguments: HashMap<String, String>,
1428 raw_content: String,
1429 arrived_at: Instant,
1430}
1431
1432impl Event for StatusEvent {
1433 fn event_type(&self) -> EventType {
1434 EventType::Status
1435 }
1436 fn raw_content(&self) -> &str {
1437 &self.raw_content
1438 }
1439 fn arrived_at(&self) -> Instant {
1440 self.arrived_at
1441 }
1442}
1443
1444impl StatusEvent {
1445 /// Parses a status event from raw control protocol content.
1446 ///
1447 /// # Arguments
1448 ///
1449 /// * `status_type` - The type of status event
1450 /// * `content` - The event content after the event type
1451 ///
1452 /// # Event Format
1453 ///
1454 /// ```text
1455 /// Runlevel Action [Key=Value ...]
1456 /// ```
1457 ///
1458 /// # Errors
1459 ///
1460 /// Returns [`Error::Protocol`] if:
1461 /// - Required fields are missing
1462 /// - The runlevel is unrecognized
1463 pub fn parse(status_type: StatusType, content: &str) -> Result<Self, Error> {
1464 let mut line = ControlLine::new(content);
1465 let runlevel_str = line.pop(false, false)?;
1466 let action = line.pop(false, false)?;
1467 let runlevel = parse_runlevel(&runlevel_str)?;
1468
1469 let mut arguments = HashMap::new();
1470 while !line.is_empty() {
1471 if line.peek_key().is_some() {
1472 let quoted = line.is_next_mapping(None, true);
1473 let (k, v) = line.pop_mapping(quoted, quoted)?;
1474 arguments.insert(k, v);
1475 } else {
1476 let _ = line.pop(false, false)?;
1477 }
1478 }
1479
1480 Ok(Self {
1481 status_type,
1482 runlevel,
1483 action,
1484 arguments,
1485 raw_content: content.to_string(),
1486 arrived_at: Instant::now(),
1487 })
1488 }
1489}
1490
1491/// Event indicating that Tor's configuration has changed.
1492///
1493/// This event is emitted when configuration options are modified, either
1494/// through `SETCONF` commands or by reloading the configuration file.
1495///
1496/// # Changed vs Unset
1497///
1498/// - `changed` - Options that were set to new values
1499/// - `unset` - Options that were reset to defaults
1500///
1501/// Options can have multiple values (e.g., `ExitPolicy`), so `changed`
1502/// maps option names to a list of values.
1503///
1504/// # Example
1505///
1506/// ```rust,ignore
1507/// use stem_rs::events::ConfChangedEvent;
1508///
1509/// fn handle_conf_changed(event: &ConfChangedEvent) {
1510/// for (option, values) in &event.changed {
1511/// println!("Changed: {} = {:?}", option, values);
1512/// }
1513/// for option in &event.unset {
1514/// println!("Unset: {}", option);
1515/// }
1516/// }
1517/// ```
1518#[derive(Debug, Clone)]
1519pub struct ConfChangedEvent {
1520 /// Options that were changed, mapped to their new values.
1521 pub changed: HashMap<String, Vec<String>>,
1522 /// Options that were unset (reset to defaults).
1523 pub unset: Vec<String>,
1524 raw_content: String,
1525 arrived_at: Instant,
1526}
1527
1528impl Event for ConfChangedEvent {
1529 fn event_type(&self) -> EventType {
1530 EventType::ConfChanged
1531 }
1532 fn raw_content(&self) -> &str {
1533 &self.raw_content
1534 }
1535 fn arrived_at(&self) -> Instant {
1536 self.arrived_at
1537 }
1538}
1539
1540impl ConfChangedEvent {
1541 /// Parses a configuration changed event from multi-line content.
1542 ///
1543 /// # Arguments
1544 ///
1545 /// * `lines` - The event content lines (excluding header/footer)
1546 ///
1547 /// # Event Format
1548 ///
1549 /// Each line is either:
1550 /// - `Key=Value` - Option set to a value
1551 /// - `Key` - Option unset
1552 ///
1553 /// # Errors
1554 ///
1555 /// This method currently does not return errors but returns `Result`
1556 /// for API consistency.
1557 pub fn parse(lines: &[String]) -> Result<Self, Error> {
1558 let mut changed: HashMap<String, Vec<String>> = HashMap::new();
1559 let mut unset = Vec::new();
1560
1561 for line in lines {
1562 if let Some(eq_pos) = line.find('=') {
1563 let key = line[..eq_pos].to_string();
1564 let value = line[eq_pos + 1..].to_string();
1565 changed.entry(key).or_default().push(value);
1566 } else if !line.is_empty() {
1567 unset.push(line.clone());
1568 }
1569 }
1570
1571 Ok(Self {
1572 changed,
1573 unset,
1574 raw_content: lines.join("\n"),
1575 arrived_at: Instant::now(),
1576 })
1577 }
1578}
1579
1580/// Event indicating network connectivity status.
1581///
1582/// This event is emitted when Tor's view of network liveness changes.
1583/// It indicates whether Tor believes the network is reachable.
1584///
1585/// # Status Values
1586///
1587/// - `"UP"` - Network is reachable
1588/// - `"DOWN"` - Network is unreachable
1589///
1590/// # Example
1591///
1592/// ```rust,ignore
1593/// use stem_rs::events::NetworkLivenessEvent;
1594///
1595/// fn handle_liveness(event: &NetworkLivenessEvent) {
1596/// match event.status.as_str() {
1597/// "UP" => println!("Network is up"),
1598/// "DOWN" => println!("Network is down"),
1599/// _ => println!("Unknown network status: {}", event.status),
1600/// }
1601/// }
1602/// ```
1603#[derive(Debug, Clone)]
1604pub struct NetworkLivenessEvent {
1605 /// Network status ("UP" or "DOWN").
1606 pub status: String,
1607 raw_content: String,
1608 arrived_at: Instant,
1609}
1610
1611impl Event for NetworkLivenessEvent {
1612 fn event_type(&self) -> EventType {
1613 EventType::NetworkLiveness
1614 }
1615 fn raw_content(&self) -> &str {
1616 &self.raw_content
1617 }
1618 fn arrived_at(&self) -> Instant {
1619 self.arrived_at
1620 }
1621}
1622
1623impl NetworkLivenessEvent {
1624 /// Parses a network liveness event from raw control protocol content.
1625 ///
1626 /// # Arguments
1627 ///
1628 /// * `content` - The event content after the event type
1629 ///
1630 /// # Errors
1631 ///
1632 /// This method currently does not return errors but returns `Result`
1633 /// for API consistency.
1634 pub fn parse(content: &str) -> Result<Self, Error> {
1635 let status = content.split_whitespace().next().unwrap_or("").to_string();
1636 Ok(Self {
1637 status,
1638 raw_content: content.to_string(),
1639 arrived_at: Instant::now(),
1640 })
1641 }
1642}
1643
1644/// Event providing bandwidth information for a specific circuit.
1645///
1646/// Unlike [`BandwidthEvent`] which provides aggregate bandwidth, this event
1647/// tracks bandwidth usage per circuit. This is useful for monitoring
1648/// individual connections or identifying high-bandwidth circuits.
1649///
1650/// # Example
1651///
1652/// ```rust,ignore
1653/// use stem_rs::events::CircuitBandwidthEvent;
1654///
1655/// fn handle_circ_bw(event: &CircuitBandwidthEvent) {
1656/// println!("Circuit {} bandwidth: {} read, {} written",
1657/// event.id, event.read, event.written);
1658/// if let Some(time) = &event.time {
1659/// println!(" at {}", time);
1660/// }
1661/// }
1662/// ```
1663///
1664/// # See Also
1665///
1666/// - [`BandwidthEvent`] - Aggregate bandwidth
1667/// - [`ConnectionBandwidthEvent`] - Per-connection bandwidth
1668#[derive(Debug, Clone)]
1669pub struct CircuitBandwidthEvent {
1670 /// Circuit identifier.
1671 pub id: CircuitId,
1672 /// Bytes read on this circuit.
1673 pub read: u64,
1674 /// Bytes written on this circuit.
1675 pub written: u64,
1676 /// Timestamp of the measurement (if available).
1677 pub time: Option<DateTime<Utc>>,
1678 raw_content: String,
1679 arrived_at: Instant,
1680}
1681
1682impl Event for CircuitBandwidthEvent {
1683 fn event_type(&self) -> EventType {
1684 EventType::CircBw
1685 }
1686 fn raw_content(&self) -> &str {
1687 &self.raw_content
1688 }
1689 fn arrived_at(&self) -> Instant {
1690 self.arrived_at
1691 }
1692}
1693
1694impl CircuitBandwidthEvent {
1695 /// Parses a circuit bandwidth event from raw control protocol content.
1696 ///
1697 /// # Arguments
1698 ///
1699 /// * `content` - The event content after the event type
1700 ///
1701 /// # Event Format
1702 ///
1703 /// ```text
1704 /// ID=CircuitID READ=bytes WRITTEN=bytes [TIME=timestamp]
1705 /// ```
1706 ///
1707 /// # Errors
1708 ///
1709 /// Returns [`Error::Protocol`] if:
1710 /// - Required fields (ID, READ, WRITTEN) are missing
1711 /// - Numeric values cannot be parsed
1712 pub fn parse(content: &str) -> Result<Self, Error> {
1713 let mut line = ControlLine::new(content);
1714 let mut id = None;
1715 let mut read = None;
1716 let mut written = None;
1717 let mut time = None;
1718
1719 while !line.is_empty() {
1720 if line.is_next_mapping(Some("ID"), false) {
1721 let (_, v) = line.pop_mapping(false, false)?;
1722 id = Some(CircuitId::new(v));
1723 } else if line.is_next_mapping(Some("READ"), false) {
1724 let (_, v) = line.pop_mapping(false, false)?;
1725 read = Some(
1726 v.parse()
1727 .map_err(|_| Error::Protocol(format!("invalid READ value: {}", v)))?,
1728 );
1729 } else if line.is_next_mapping(Some("WRITTEN"), false) {
1730 let (_, v) = line.pop_mapping(false, false)?;
1731 written = Some(
1732 v.parse()
1733 .map_err(|_| Error::Protocol(format!("invalid WRITTEN value: {}", v)))?,
1734 );
1735 } else if line.is_next_mapping(Some("TIME"), false) {
1736 let (_, v) = line.pop_mapping(false, false)?;
1737 time = parse_iso_timestamp(&v).ok();
1738 } else {
1739 let _ = line.pop(false, false)?;
1740 }
1741 }
1742
1743 Ok(Self {
1744 id: id.ok_or_else(|| Error::Protocol("missing ID in CIRC_BW".to_string()))?,
1745 read: read.ok_or_else(|| Error::Protocol("missing READ in CIRC_BW".to_string()))?,
1746 written: written
1747 .ok_or_else(|| Error::Protocol("missing WRITTEN in CIRC_BW".to_string()))?,
1748 time,
1749 raw_content: content.to_string(),
1750 arrived_at: Instant::now(),
1751 })
1752 }
1753}
1754
1755/// Event providing bandwidth information for a specific connection.
1756///
1757/// This event tracks bandwidth usage per connection, categorized by
1758/// connection type (OR, Dir, Exit). Useful for detailed bandwidth
1759/// analysis and monitoring.
1760///
1761/// # Connection Types
1762///
1763/// - [`ConnectionType::Or`] - Onion Router connections (relay-to-relay)
1764/// - [`ConnectionType::Dir`] - Directory connections
1765/// - [`ConnectionType::Exit`] - Exit connections to the internet
1766///
1767/// # Example
1768///
1769/// ```rust,ignore
1770/// use stem_rs::events::ConnectionBandwidthEvent;
1771/// use stem_rs::ConnectionType;
1772///
1773/// fn handle_conn_bw(event: &ConnectionBandwidthEvent) {
1774/// let type_str = match event.conn_type {
1775/// ConnectionType::Or => "OR",
1776/// ConnectionType::Dir => "Dir",
1777/// ConnectionType::Exit => "Exit",
1778/// };
1779/// println!("{} connection {}: {} read, {} written",
1780/// type_str, event.id, event.read, event.written);
1781/// }
1782/// ```
1783///
1784/// # See Also
1785///
1786/// - [`BandwidthEvent`] - Aggregate bandwidth
1787/// - [`CircuitBandwidthEvent`] - Per-circuit bandwidth
1788/// - [`ConnectionType`](crate::ConnectionType) - Connection types
1789#[derive(Debug, Clone)]
1790pub struct ConnectionBandwidthEvent {
1791 /// Connection identifier.
1792 pub id: String,
1793 /// Type of connection.
1794 pub conn_type: ConnectionType,
1795 /// Bytes read on this connection.
1796 pub read: u64,
1797 /// Bytes written on this connection.
1798 pub written: u64,
1799 raw_content: String,
1800 arrived_at: Instant,
1801}
1802
1803impl Event for ConnectionBandwidthEvent {
1804 fn event_type(&self) -> EventType {
1805 EventType::ConnBw
1806 }
1807 fn raw_content(&self) -> &str {
1808 &self.raw_content
1809 }
1810 fn arrived_at(&self) -> Instant {
1811 self.arrived_at
1812 }
1813}
1814
1815impl ConnectionBandwidthEvent {
1816 /// Parses a connection bandwidth event from raw control protocol content.
1817 ///
1818 /// # Arguments
1819 ///
1820 /// * `content` - The event content after the event type
1821 ///
1822 /// # Event Format
1823 ///
1824 /// ```text
1825 /// ID=ConnID TYPE=ConnType READ=bytes WRITTEN=bytes
1826 /// ```
1827 ///
1828 /// # Errors
1829 ///
1830 /// Returns [`Error::Protocol`] if:
1831 /// - Required fields (ID, TYPE, READ, WRITTEN) are missing
1832 /// - The connection type is unrecognized
1833 /// - Numeric values cannot be parsed
1834 pub fn parse(content: &str) -> Result<Self, Error> {
1835 let mut line = ControlLine::new(content);
1836 let mut id = None;
1837 let mut conn_type = None;
1838 let mut read = None;
1839 let mut written = None;
1840
1841 while !line.is_empty() {
1842 if line.is_next_mapping(Some("ID"), false) {
1843 let (_, v) = line.pop_mapping(false, false)?;
1844 id = Some(v);
1845 } else if line.is_next_mapping(Some("TYPE"), false) {
1846 let (_, v) = line.pop_mapping(false, false)?;
1847 conn_type = Some(parse_connection_type(&v)?);
1848 } else if line.is_next_mapping(Some("READ"), false) {
1849 let (_, v) = line.pop_mapping(false, false)?;
1850 read = Some(
1851 v.parse()
1852 .map_err(|_| Error::Protocol(format!("invalid READ value: {}", v)))?,
1853 );
1854 } else if line.is_next_mapping(Some("WRITTEN"), false) {
1855 let (_, v) = line.pop_mapping(false, false)?;
1856 written = Some(
1857 v.parse()
1858 .map_err(|_| Error::Protocol(format!("invalid WRITTEN value: {}", v)))?,
1859 );
1860 } else {
1861 let _ = line.pop(false, false)?;
1862 }
1863 }
1864
1865 Ok(Self {
1866 id: id.ok_or_else(|| Error::Protocol("missing ID in CONN_BW".to_string()))?,
1867 conn_type: conn_type
1868 .ok_or_else(|| Error::Protocol("missing TYPE in CONN_BW".to_string()))?,
1869 read: read.ok_or_else(|| Error::Protocol("missing READ in CONN_BW".to_string()))?,
1870 written: written
1871 .ok_or_else(|| Error::Protocol("missing WRITTEN in CONN_BW".to_string()))?,
1872 raw_content: content.to_string(),
1873 arrived_at: Instant::now(),
1874 })
1875 }
1876}
1877
1878/// Event triggered when fetching or uploading hidden service descriptors.
1879///
1880/// This event tracks the lifecycle of hidden service descriptor operations,
1881/// including requests, uploads, and failures. It's essential for monitoring
1882/// hidden service connectivity.
1883///
1884/// # Actions
1885///
1886/// The `action` field indicates the operation:
1887/// - [`HsDescAction::Requested`] - Descriptor fetch requested
1888/// - [`HsDescAction::Received`] - Descriptor successfully received
1889/// - [`HsDescAction::Uploaded`] - Descriptor successfully uploaded
1890/// - [`HsDescAction::Failed`] - Operation failed (check `reason`)
1891/// - [`HsDescAction::Created`] - New descriptor created
1892/// - [`HsDescAction::Ignore`] - Descriptor ignored
1893///
1894/// # Directory Information
1895///
1896/// The `directory` field contains the HSDir relay handling the request.
1897/// The fingerprint and nickname are extracted into separate fields for
1898/// convenience.
1899///
1900/// # Example
1901///
1902/// ```rust,ignore
1903/// use stem_rs::events::HsDescEvent;
1904/// use stem_rs::HsDescAction;
1905///
1906/// fn handle_hsdesc(event: &HsDescEvent) {
1907/// match event.action {
1908/// HsDescAction::Received => {
1909/// println!("Got descriptor for {} from {:?}",
1910/// event.address, event.directory_nickname);
1911/// }
1912/// HsDescAction::Failed => {
1913/// println!("Failed to get descriptor for {}: {:?}",
1914/// event.address, event.reason);
1915/// }
1916/// _ => {}
1917/// }
1918/// }
1919/// ```
1920///
1921/// # See Also
1922///
1923/// - [`HsDescAction`](crate::HsDescAction) - Descriptor actions
1924/// - [`HsDescReason`](crate::HsDescReason) - Failure reasons
1925/// - [`HsAuth`](crate::HsAuth) - Authentication types
1926#[derive(Debug, Clone)]
1927pub struct HsDescEvent {
1928 /// Action being performed on the descriptor.
1929 pub action: HsDescAction,
1930 /// Hidden service address (onion address).
1931 pub address: String,
1932 /// Authentication type for the hidden service.
1933 pub authentication: Option<HsAuth>,
1934 /// Full directory relay string.
1935 pub directory: Option<String>,
1936 /// Directory relay fingerprint.
1937 pub directory_fingerprint: Option<String>,
1938 /// Directory relay nickname.
1939 pub directory_nickname: Option<String>,
1940 /// Descriptor identifier.
1941 pub descriptor_id: Option<String>,
1942 /// Reason for failure (if action is Failed).
1943 pub reason: Option<HsDescReason>,
1944 raw_content: String,
1945 arrived_at: Instant,
1946}
1947
1948impl Event for HsDescEvent {
1949 fn event_type(&self) -> EventType {
1950 EventType::HsDesc
1951 }
1952 fn raw_content(&self) -> &str {
1953 &self.raw_content
1954 }
1955 fn arrived_at(&self) -> Instant {
1956 self.arrived_at
1957 }
1958}
1959
1960impl HsDescEvent {
1961 /// Parses a hidden service descriptor event from raw control protocol content.
1962 ///
1963 /// # Arguments
1964 ///
1965 /// * `content` - The event content after the event type
1966 ///
1967 /// # Event Format
1968 ///
1969 /// ```text
1970 /// Action Address AuthType [Directory] [DescriptorID] [REASON=...]
1971 /// ```
1972 ///
1973 /// # Errors
1974 ///
1975 /// Returns [`Error::Protocol`] if:
1976 /// - Required fields are missing
1977 /// - The action is unrecognized
1978 pub fn parse(content: &str) -> Result<Self, Error> {
1979 let mut line = ControlLine::new(content);
1980 let action_str = line.pop(false, false)?;
1981 let address = line.pop(false, false)?;
1982 let auth_str = line.pop(false, false)?;
1983
1984 let action = parse_hs_desc_action(&action_str)?;
1985 let authentication = parse_hs_auth(&auth_str).ok();
1986
1987 let mut directory = None;
1988 let mut directory_fingerprint = None;
1989 let mut directory_nickname = None;
1990 let mut descriptor_id = None;
1991 let mut reason = None;
1992
1993 if !line.is_empty() {
1994 let dir_token = line.pop(false, false)?;
1995 if dir_token != "UNKNOWN" {
1996 directory = Some(dir_token.clone());
1997 let (fp, nick) = parse_relay_endpoint(&dir_token);
1998 directory_fingerprint = Some(fp);
1999 directory_nickname = nick;
2000 }
2001 }
2002
2003 if !line.is_empty() && line.peek_key().is_none_or(|k| k != "REASON") {
2004 descriptor_id = Some(line.pop(false, false)?);
2005 }
2006
2007 while !line.is_empty() {
2008 if line.is_next_mapping(Some("REASON"), false) {
2009 let (_, r) = line.pop_mapping(false, false)?;
2010 reason = parse_hs_desc_reason(&r).ok();
2011 } else {
2012 let _ = line.pop(false, false)?;
2013 }
2014 }
2015
2016 Ok(Self {
2017 action,
2018 address,
2019 authentication,
2020 directory,
2021 directory_fingerprint,
2022 directory_nickname,
2023 descriptor_id,
2024 reason,
2025 raw_content: content.to_string(),
2026 arrived_at: Instant::now(),
2027 })
2028 }
2029}
2030
2031/// Parses a circuit status string into a [`CircStatus`] enum variant.
2032///
2033/// Converts a case-insensitive string representation of a circuit status
2034/// from the Tor control protocol into the corresponding enum variant.
2035///
2036/// # Arguments
2037///
2038/// * `s` - The circuit status string to parse (e.g., "LAUNCHED", "BUILT")
2039///
2040/// # Returns
2041///
2042/// * `Ok(CircStatus)` - The parsed circuit status variant
2043/// * `Err(Error::Protocol)` - If the string doesn't match any known status
2044///
2045/// # Supported Values
2046///
2047/// - `LAUNCHED` - Circuit construction has begun
2048/// - `BUILT` - Circuit is fully constructed and ready for use
2049/// - `GUARD_WAIT` - Waiting for guard node selection
2050/// - `EXTENDED` - Circuit has been extended by one hop
2051/// - `FAILED` - Circuit construction failed
2052/// - `CLOSED` - Circuit has been closed
2053fn parse_circ_status(s: &str) -> Result<CircStatus, Error> {
2054 match s.to_uppercase().as_str() {
2055 "LAUNCHED" => Ok(CircStatus::Launched),
2056 "BUILT" => Ok(CircStatus::Built),
2057 "GUARD_WAIT" => Ok(CircStatus::GuardWait),
2058 "EXTENDED" => Ok(CircStatus::Extended),
2059 "FAILED" => Ok(CircStatus::Failed),
2060 "CLOSED" => Ok(CircStatus::Closed),
2061 _ => Err(Error::Protocol(format!("unknown circuit status: {}", s))),
2062 }
2063}
2064
2065/// Parses a stream status string into a [`StreamStatus`] enum variant.
2066///
2067/// Converts a case-insensitive string representation of a stream status
2068/// from the Tor control protocol into the corresponding enum variant.
2069///
2070/// # Arguments
2071///
2072/// * `s` - The stream status string to parse (e.g., "NEW", "SUCCEEDED")
2073///
2074/// # Returns
2075///
2076/// * `Ok(StreamStatus)` - The parsed stream status variant
2077/// * `Err(Error::Protocol)` - If the string doesn't match any known status
2078///
2079/// # Supported Values
2080///
2081/// - `NEW` - New stream awaiting connection
2082/// - `NEWRESOLVE` - New stream awaiting DNS resolution
2083/// - `REMAP` - Address has been remapped
2084/// - `SENTCONNECT` - Connect request sent to exit
2085/// - `SENTRESOLVE` - Resolve request sent to exit
2086/// - `SUCCEEDED` - Stream connection succeeded
2087/// - `FAILED` - Stream connection failed
2088/// - `DETACHED` - Stream detached from circuit
2089/// - `CONTROLLER_WAIT` - Waiting for controller attachment
2090/// - `CLOSED` - Stream has been closed
2091fn parse_stream_status(s: &str) -> Result<StreamStatus, Error> {
2092 match s.to_uppercase().as_str() {
2093 "NEW" => Ok(StreamStatus::New),
2094 "NEWRESOLVE" => Ok(StreamStatus::NewResolve),
2095 "REMAP" => Ok(StreamStatus::Remap),
2096 "SENTCONNECT" => Ok(StreamStatus::SentConnect),
2097 "SENTRESOLVE" => Ok(StreamStatus::SentResolve),
2098 "SUCCEEDED" => Ok(StreamStatus::Succeeded),
2099 "FAILED" => Ok(StreamStatus::Failed),
2100 "DETACHED" => Ok(StreamStatus::Detached),
2101 "CONTROLLER_WAIT" => Ok(StreamStatus::ControllerWait),
2102 "CLOSED" => Ok(StreamStatus::Closed),
2103 _ => Err(Error::Protocol(format!("unknown stream status: {}", s))),
2104 }
2105}
2106
2107/// Parses an OR (Onion Router) connection status string into an [`OrStatus`] enum variant.
2108///
2109/// Converts a case-insensitive string representation of an OR connection status
2110/// from the Tor control protocol into the corresponding enum variant.
2111///
2112/// # Arguments
2113///
2114/// * `s` - The OR status string to parse (e.g., "NEW", "CONNECTED")
2115///
2116/// # Returns
2117///
2118/// * `Ok(OrStatus)` - The parsed OR connection status variant
2119/// * `Err(Error::Protocol)` - If the string doesn't match any known status
2120///
2121/// # Supported Values
2122///
2123/// - `NEW` - New OR connection initiated
2124/// - `LAUNCHED` - Connection attempt launched
2125/// - `CONNECTED` - Successfully connected to OR
2126/// - `FAILED` - Connection attempt failed
2127/// - `CLOSED` - Connection has been closed
2128fn parse_or_status(s: &str) -> Result<OrStatus, Error> {
2129 match s.to_uppercase().as_str() {
2130 "NEW" => Ok(OrStatus::New),
2131 "LAUNCHED" => Ok(OrStatus::Launched),
2132 "CONNECTED" => Ok(OrStatus::Connected),
2133 "FAILED" => Ok(OrStatus::Failed),
2134 "CLOSED" => Ok(OrStatus::Closed),
2135 _ => Err(Error::Protocol(format!("unknown OR status: {}", s))),
2136 }
2137}
2138
2139/// Parses a guard type string into a [`GuardType`] enum variant.
2140///
2141/// Converts a case-insensitive string representation of a guard node type
2142/// from the Tor control protocol into the corresponding enum variant.
2143///
2144/// # Arguments
2145///
2146/// * `s` - The guard type string to parse (currently only "ENTRY")
2147///
2148/// # Returns
2149///
2150/// * `Ok(GuardType)` - The parsed guard type variant
2151/// * `Err(Error::Protocol)` - If the string doesn't match any known type
2152///
2153/// # Supported Values
2154///
2155/// - `ENTRY` - Entry guard node
2156fn parse_guard_type(s: &str) -> Result<GuardType, Error> {
2157 match s.to_uppercase().as_str() {
2158 "ENTRY" => Ok(GuardType::Entry),
2159 _ => Err(Error::Protocol(format!("unknown guard type: {}", s))),
2160 }
2161}
2162
2163/// Parses a guard status string into a [`GuardStatus`] enum variant.
2164///
2165/// Converts a case-insensitive string representation of a guard node status
2166/// from the Tor control protocol into the corresponding enum variant.
2167///
2168/// # Arguments
2169///
2170/// * `s` - The guard status string to parse (e.g., "NEW", "UP", "DOWN")
2171///
2172/// # Returns
2173///
2174/// * `Ok(GuardStatus)` - The parsed guard status variant
2175/// * `Err(Error::Protocol)` - If the string doesn't match any known status
2176///
2177/// # Supported Values
2178///
2179/// - `NEW` - Guard node newly selected
2180/// - `DROPPED` - Guard node dropped from selection
2181/// - `UP` - Guard node is reachable
2182/// - `DOWN` - Guard node is unreachable
2183/// - `BAD` - Guard node marked as bad
2184/// - `GOOD` - Guard node marked as good
2185fn parse_guard_status(s: &str) -> Result<GuardStatus, Error> {
2186 match s.to_uppercase().as_str() {
2187 "NEW" => Ok(GuardStatus::New),
2188 "DROPPED" => Ok(GuardStatus::Dropped),
2189 "UP" => Ok(GuardStatus::Up),
2190 "DOWN" => Ok(GuardStatus::Down),
2191 "BAD" => Ok(GuardStatus::Bad),
2192 "GOOD" => Ok(GuardStatus::Good),
2193 _ => Err(Error::Protocol(format!("unknown guard status: {}", s))),
2194 }
2195}
2196
2197/// Parses a timeout set type string into a [`TimeoutSetType`] enum variant.
2198///
2199/// Converts a case-insensitive string representation of a circuit build
2200/// timeout set type from the Tor control protocol into the corresponding enum variant.
2201///
2202/// # Arguments
2203///
2204/// * `s` - The timeout set type string to parse (e.g., "COMPUTED", "RESET")
2205///
2206/// # Returns
2207///
2208/// * `Ok(TimeoutSetType)` - The parsed timeout set type variant
2209/// * `Err(Error::Protocol)` - If the string doesn't match any known type
2210///
2211/// # Supported Values
2212///
2213/// - `COMPUTED` - Timeout computed from circuit build times
2214/// - `RESET` - Timeout values have been reset
2215/// - `SUSPENDED` - Timeout learning suspended
2216/// - `DISCARD` - Timeout values discarded
2217/// - `RESUME` - Timeout learning resumed
2218fn parse_timeout_set_type(s: &str) -> Result<TimeoutSetType, Error> {
2219 match s.to_uppercase().as_str() {
2220 "COMPUTED" => Ok(TimeoutSetType::Computed),
2221 "RESET" => Ok(TimeoutSetType::Reset),
2222 "SUSPENDED" => Ok(TimeoutSetType::Suspended),
2223 "DISCARD" => Ok(TimeoutSetType::Discard),
2224 "RESUME" => Ok(TimeoutSetType::Resume),
2225 _ => Err(Error::Protocol(format!("unknown timeout set type: {}", s))),
2226 }
2227}
2228
2229/// Parses a log runlevel string into a [`Runlevel`] enum variant.
2230///
2231/// Converts a case-insensitive string representation of a Tor log severity
2232/// level from the Tor control protocol into the corresponding enum variant.
2233///
2234/// # Arguments
2235///
2236/// * `s` - The runlevel string to parse (e.g., "DEBUG", "INFO", "WARN")
2237///
2238/// # Returns
2239///
2240/// * `Ok(Runlevel)` - The parsed runlevel variant
2241/// * `Err(Error::Protocol)` - If the string doesn't match any known level
2242///
2243/// # Supported Values
2244///
2245/// - `DEBUG` - Debug-level messages (most verbose)
2246/// - `INFO` - Informational messages
2247/// - `NOTICE` - Normal operational messages
2248/// - `WARN` - Warning messages
2249/// - `ERR` - Error messages (most severe)
2250fn parse_runlevel(s: &str) -> Result<Runlevel, Error> {
2251 match s.to_uppercase().as_str() {
2252 "DEBUG" => Ok(Runlevel::Debug),
2253 "INFO" => Ok(Runlevel::Info),
2254 "NOTICE" => Ok(Runlevel::Notice),
2255 "WARN" => Ok(Runlevel::Warn),
2256 "ERR" => Ok(Runlevel::Err),
2257 _ => Err(Error::Protocol(format!("unknown runlevel: {}", s))),
2258 }
2259}
2260
2261/// Parses a signal string into a [`Signal`] enum variant.
2262///
2263/// Converts a case-insensitive string representation of a Tor signal
2264/// from the Tor control protocol into the corresponding enum variant.
2265/// Supports both signal names and their Unix signal equivalents.
2266///
2267/// # Arguments
2268///
2269/// * `s` - The signal string to parse (e.g., "RELOAD", "HUP", "NEWNYM")
2270///
2271/// # Returns
2272///
2273/// * `Ok(Signal)` - The parsed signal variant
2274/// * `Err(Error::Protocol)` - If the string doesn't match any known signal
2275///
2276/// # Supported Values
2277///
2278/// - `RELOAD` or `HUP` - Reload configuration
2279/// - `SHUTDOWN` or `INT` - Controlled shutdown
2280/// - `DUMP` or `USR1` - Dump statistics
2281/// - `DEBUG` or `USR2` - Switch to debug logging
2282/// - `HALT` or `TERM` - Immediate shutdown
2283/// - `NEWNYM` - Request new circuits
2284/// - `CLEARDNSCACHE` - Clear DNS cache
2285/// - `HEARTBEAT` - Trigger heartbeat log
2286/// - `ACTIVE` - Wake from dormant mode
2287/// - `DORMANT` - Enter dormant mode
2288fn parse_signal(s: &str) -> Result<Signal, Error> {
2289 match s.to_uppercase().as_str() {
2290 "RELOAD" | "HUP" => Ok(Signal::Reload),
2291 "SHUTDOWN" | "INT" => Ok(Signal::Shutdown),
2292 "DUMP" | "USR1" => Ok(Signal::Dump),
2293 "DEBUG" | "USR2" => Ok(Signal::Debug),
2294 "HALT" | "TERM" => Ok(Signal::Halt),
2295 "NEWNYM" => Ok(Signal::Newnym),
2296 "CLEARDNSCACHE" => Ok(Signal::ClearDnsCache),
2297 "HEARTBEAT" => Ok(Signal::Heartbeat),
2298 "ACTIVE" => Ok(Signal::Active),
2299 "DORMANT" => Ok(Signal::Dormant),
2300 _ => Err(Error::Protocol(format!("unknown signal: {}", s))),
2301 }
2302}
2303
2304/// Parses a connection type string into a [`ConnectionType`] enum variant.
2305///
2306/// Converts a case-insensitive string representation of a Tor connection type
2307/// from the Tor control protocol into the corresponding enum variant.
2308///
2309/// # Arguments
2310///
2311/// * `s` - The connection type string to parse (e.g., "OR", "DIR", "EXIT")
2312///
2313/// # Returns
2314///
2315/// * `Ok(ConnectionType)` - The parsed connection type variant
2316/// * `Err(Error::Protocol)` - If the string doesn't match any known type
2317///
2318/// # Supported Values
2319///
2320/// - `OR` - Onion Router connection (relay-to-relay)
2321/// - `DIR` - Directory connection
2322/// - `EXIT` - Exit connection to destination
2323fn parse_connection_type(s: &str) -> Result<ConnectionType, Error> {
2324 match s.to_uppercase().as_str() {
2325 "OR" => Ok(ConnectionType::Or),
2326 "DIR" => Ok(ConnectionType::Dir),
2327 "EXIT" => Ok(ConnectionType::Exit),
2328 _ => Err(Error::Protocol(format!("unknown connection type: {}", s))),
2329 }
2330}
2331
2332/// Parses a hidden service descriptor action string into an [`HsDescAction`] enum variant.
2333///
2334/// Converts a case-insensitive string representation of a hidden service
2335/// descriptor action from the Tor control protocol into the corresponding enum variant.
2336///
2337/// # Arguments
2338///
2339/// * `s` - The HS_DESC action string to parse (e.g., "REQUESTED", "RECEIVED")
2340///
2341/// # Returns
2342///
2343/// * `Ok(HsDescAction)` - The parsed action variant
2344/// * `Err(Error::Protocol)` - If the string doesn't match any known action
2345///
2346/// # Supported Values
2347///
2348/// - `REQUESTED` - Descriptor fetch requested
2349/// - `UPLOAD` - Descriptor upload initiated
2350/// - `RECEIVED` - Descriptor successfully received
2351/// - `UPLOADED` - Descriptor successfully uploaded
2352/// - `IGNORE` - Descriptor ignored
2353/// - `FAILED` - Descriptor operation failed
2354/// - `CREATED` - Descriptor created locally
2355fn parse_hs_desc_action(s: &str) -> Result<HsDescAction, Error> {
2356 match s.to_uppercase().as_str() {
2357 "REQUESTED" => Ok(HsDescAction::Requested),
2358 "UPLOAD" => Ok(HsDescAction::Upload),
2359 "RECEIVED" => Ok(HsDescAction::Received),
2360 "UPLOADED" => Ok(HsDescAction::Uploaded),
2361 "IGNORE" => Ok(HsDescAction::Ignore),
2362 "FAILED" => Ok(HsDescAction::Failed),
2363 "CREATED" => Ok(HsDescAction::Created),
2364 _ => Err(Error::Protocol(format!("unknown HS_DESC action: {}", s))),
2365 }
2366}
2367
2368/// Parses a hidden service authentication type string into an [`HsAuth`] enum variant.
2369///
2370/// Converts a case-insensitive string representation of a hidden service
2371/// authentication type from the Tor control protocol into the corresponding enum variant.
2372///
2373/// # Arguments
2374///
2375/// * `s` - The HS auth type string to parse (e.g., "NO_AUTH", "BASIC_AUTH")
2376///
2377/// # Returns
2378///
2379/// * `Ok(HsAuth)` - The parsed authentication type variant
2380/// * `Err(Error::Protocol)` - If the string doesn't match any known type
2381///
2382/// # Supported Values
2383///
2384/// - `NO_AUTH` - No authentication required
2385/// - `BASIC_AUTH` - Basic authentication
2386/// - `STEALTH_AUTH` - Stealth authentication (more private)
2387/// - `UNKNOWN` - Unknown authentication type
2388fn parse_hs_auth(s: &str) -> Result<HsAuth, Error> {
2389 match s.to_uppercase().as_str() {
2390 "NO_AUTH" => Ok(HsAuth::NoAuth),
2391 "BASIC_AUTH" => Ok(HsAuth::BasicAuth),
2392 "STEALTH_AUTH" => Ok(HsAuth::StealthAuth),
2393 "UNKNOWN" => Ok(HsAuth::Unknown),
2394 _ => Err(Error::Protocol(format!("unknown HS auth type: {}", s))),
2395 }
2396}
2397
2398/// Parses a hidden service descriptor failure reason string into an [`HsDescReason`] enum variant.
2399///
2400/// Converts a case-insensitive string representation of a hidden service
2401/// descriptor failure reason from the Tor control protocol into the corresponding enum variant.
2402///
2403/// # Arguments
2404///
2405/// * `s` - The HS_DESC reason string to parse (e.g., "NOT_FOUND", "BAD_DESC")
2406///
2407/// # Returns
2408///
2409/// * `Ok(HsDescReason)` - The parsed reason variant
2410/// * `Err(Error::Protocol)` - If the string doesn't match any known reason
2411///
2412/// # Supported Values
2413///
2414/// - `BAD_DESC` - Descriptor was malformed or invalid
2415/// - `QUERY_REJECTED` - Query was rejected by HSDir
2416/// - `UPLOAD_REJECTED` - Upload was rejected by HSDir
2417/// - `NOT_FOUND` - Descriptor not found
2418/// - `QUERY_NO_HSDIR` - No HSDir available for query
2419/// - `QUERY_RATE_LIMITED` - Query rate limited
2420/// - `UNEXPECTED` - Unexpected error occurred
2421fn parse_hs_desc_reason(s: &str) -> Result<HsDescReason, Error> {
2422 match s.to_uppercase().as_str() {
2423 "BAD_DESC" => Ok(HsDescReason::BadDesc),
2424 "QUERY_REJECTED" => Ok(HsDescReason::QueryRejected),
2425 "UPLOAD_REJECTED" => Ok(HsDescReason::UploadRejected),
2426 "NOT_FOUND" => Ok(HsDescReason::NotFound),
2427 "QUERY_NO_HSDIR" => Ok(HsDescReason::QueryNoHsDir),
2428 "QUERY_RATE_LIMITED" => Ok(HsDescReason::QueryRateLimited),
2429 "UNEXPECTED" => Ok(HsDescReason::Unexpected),
2430 _ => Err(Error::Protocol(format!("unknown HS_DESC reason: {}", s))),
2431 }
2432}
2433
2434/// Parses a circuit purpose string into a [`CircPurpose`] enum variant.
2435///
2436/// Converts a case-insensitive string representation of a circuit purpose
2437/// from the Tor control protocol into the corresponding enum variant.
2438///
2439/// # Arguments
2440///
2441/// * `s` - The circuit purpose string to parse (e.g., "GENERAL", "HS_CLIENT_REND")
2442///
2443/// # Returns
2444///
2445/// * `Ok(CircPurpose)` - The parsed circuit purpose variant
2446/// * `Err(Error::Protocol)` - If the string doesn't match any known purpose
2447///
2448/// # Supported Values
2449///
2450/// - `GENERAL` - General-purpose circuit for user traffic
2451/// - `HS_CLIENT_INTRO` - Hidden service client introduction circuit
2452/// - `HS_CLIENT_REND` - Hidden service client rendezvous circuit
2453/// - `HS_SERVICE_INTRO` - Hidden service introduction point circuit
2454/// - `HS_SERVICE_REND` - Hidden service rendezvous circuit
2455/// - `TESTING` - Circuit for testing purposes
2456/// - `CONTROLLER` - Circuit created by controller
2457/// - `MEASURE_TIMEOUT` - Circuit for measuring build timeouts
2458/// - `HS_VANGUARDS` - Vanguard circuit for hidden services
2459/// - `PATH_BIAS_TESTING` - Circuit for path bias testing
2460/// - `CIRCUIT_PADDING` - Circuit for padding purposes
2461fn parse_circ_purpose(s: &str) -> Result<CircPurpose, Error> {
2462 match s.to_uppercase().as_str() {
2463 "GENERAL" => Ok(CircPurpose::General),
2464 "HS_CLIENT_INTRO" => Ok(CircPurpose::HsClientIntro),
2465 "HS_CLIENT_REND" => Ok(CircPurpose::HsClientRend),
2466 "HS_SERVICE_INTRO" => Ok(CircPurpose::HsServiceIntro),
2467 "HS_SERVICE_REND" => Ok(CircPurpose::HsServiceRend),
2468 "TESTING" => Ok(CircPurpose::Testing),
2469 "CONTROLLER" => Ok(CircPurpose::Controller),
2470 "MEASURE_TIMEOUT" => Ok(CircPurpose::MeasureTimeout),
2471 "HS_VANGUARDS" => Ok(CircPurpose::HsVanguards),
2472 "PATH_BIAS_TESTING" => Ok(CircPurpose::PathBiasTesting),
2473 "CIRCUIT_PADDING" => Ok(CircPurpose::CircuitPadding),
2474 _ => Err(Error::Protocol(format!("unknown circuit purpose: {}", s))),
2475 }
2476}
2477
2478/// Parses a hidden service state string into a [`HiddenServiceState`] enum variant.
2479///
2480/// Converts a case-insensitive string representation of a hidden service
2481/// circuit state from the Tor control protocol into the corresponding enum variant.
2482///
2483/// # Arguments
2484///
2485/// * `s` - The HS state string to parse (e.g., "HSCI_CONNECTING", "HSCR_JOINED")
2486///
2487/// # Returns
2488///
2489/// * `Ok(HiddenServiceState)` - The parsed hidden service state variant
2490/// * `Err(Error::Protocol)` - If the string doesn't match any known state
2491///
2492/// # Supported Values
2493///
2494/// Client Introduction (HSCI):
2495/// - `HSCI_CONNECTING` - Connecting to introduction point
2496/// - `HSCI_INTRO_SENT` - Introduction sent to service
2497/// - `HSCI_DONE` - Introduction complete
2498///
2499/// Client Rendezvous (HSCR):
2500/// - `HSCR_CONNECTING` - Connecting to rendezvous point
2501/// - `HSCR_ESTABLISHED_IDLE` - Rendezvous established, idle
2502/// - `HSCR_ESTABLISHED_WAITING` - Rendezvous established, waiting
2503/// - `HSCR_JOINED` - Rendezvous joined with service
2504///
2505/// Service Introduction (HSSI):
2506/// - `HSSI_CONNECTING` - Service connecting to intro point
2507/// - `HSSI_ESTABLISHED` - Service intro point established
2508///
2509/// Service Rendezvous (HSSR):
2510/// - `HSSR_CONNECTING` - Service connecting to rendezvous
2511/// - `HSSR_JOINED` - Service joined rendezvous
2512fn parse_hs_state(s: &str) -> Result<HiddenServiceState, Error> {
2513 match s.to_uppercase().as_str() {
2514 "HSCI_CONNECTING" => Ok(HiddenServiceState::HsciConnecting),
2515 "HSCI_INTRO_SENT" => Ok(HiddenServiceState::HsciIntroSent),
2516 "HSCI_DONE" => Ok(HiddenServiceState::HsciDone),
2517 "HSCR_CONNECTING" => Ok(HiddenServiceState::HscrConnecting),
2518 "HSCR_ESTABLISHED_IDLE" => Ok(HiddenServiceState::HscrEstablishedIdle),
2519 "HSCR_ESTABLISHED_WAITING" => Ok(HiddenServiceState::HscrEstablishedWaiting),
2520 "HSCR_JOINED" => Ok(HiddenServiceState::HscrJoined),
2521 "HSSI_CONNECTING" => Ok(HiddenServiceState::HssiConnecting),
2522 "HSSI_ESTABLISHED" => Ok(HiddenServiceState::HssiEstablished),
2523 "HSSR_CONNECTING" => Ok(HiddenServiceState::HssrConnecting),
2524 "HSSR_JOINED" => Ok(HiddenServiceState::HssrJoined),
2525 _ => Err(Error::Protocol(format!("unknown HS state: {}", s))),
2526 }
2527}
2528
2529/// Parses a circuit closure reason string into a [`CircClosureReason`] enum variant.
2530///
2531/// Converts a case-insensitive string representation of a circuit closure reason
2532/// from the Tor control protocol into the corresponding enum variant.
2533///
2534/// # Arguments
2535///
2536/// * `s` - The circuit closure reason string to parse (e.g., "FINISHED", "TIMEOUT")
2537///
2538/// # Returns
2539///
2540/// * `Ok(CircClosureReason)` - The parsed closure reason variant
2541/// * `Err(Error::Protocol)` - If the string doesn't match any known reason
2542///
2543/// # Supported Values
2544///
2545/// - `NONE` - No reason given
2546/// - `TORPROTOCOL` - Tor protocol violation
2547/// - `INTERNAL` - Internal error
2548/// - `REQUESTED` - Closure requested by client
2549/// - `HIBERNATING` - Relay is hibernating
2550/// - `RESOURCELIMIT` - Resource limit reached
2551/// - `CONNECTFAILED` - Connection to relay failed
2552/// - `OR_IDENTITY` - OR identity mismatch
2553/// - `OR_CONN_CLOSED` - OR connection closed
2554/// - `FINISHED` - Circuit finished normally
2555/// - `TIMEOUT` - Circuit timed out
2556/// - `DESTROYED` - Circuit was destroyed
2557/// - `NOPATH` - No path available
2558/// - `NOSUCHSERVICE` - Hidden service not found
2559/// - `MEASUREMENT_EXPIRED` - Measurement circuit expired
2560/// - `IP_NOW_REDUNDANT` - Introduction point now redundant
2561fn parse_circ_closure_reason(s: &str) -> Result<CircClosureReason, Error> {
2562 match s.to_uppercase().as_str() {
2563 "NONE" => Ok(CircClosureReason::None),
2564 "TORPROTOCOL" => Ok(CircClosureReason::TorProtocol),
2565 "INTERNAL" => Ok(CircClosureReason::Internal),
2566 "REQUESTED" => Ok(CircClosureReason::Requested),
2567 "HIBERNATING" => Ok(CircClosureReason::Hibernating),
2568 "RESOURCELIMIT" => Ok(CircClosureReason::ResourceLimit),
2569 "CONNECTFAILED" => Ok(CircClosureReason::ConnectFailed),
2570 "OR_IDENTITY" => Ok(CircClosureReason::OrIdentity),
2571 "OR_CONN_CLOSED" => Ok(CircClosureReason::OrConnClosed),
2572 "FINISHED" => Ok(CircClosureReason::Finished),
2573 "TIMEOUT" => Ok(CircClosureReason::Timeout),
2574 "DESTROYED" => Ok(CircClosureReason::Destroyed),
2575 "NOPATH" => Ok(CircClosureReason::NoPath),
2576 "NOSUCHSERVICE" => Ok(CircClosureReason::NoSuchService),
2577 "MEASUREMENT_EXPIRED" => Ok(CircClosureReason::MeasurementExpired),
2578 "IP_NOW_REDUNDANT" => Ok(CircClosureReason::IpNowRedundant),
2579 _ => Err(Error::Protocol(format!(
2580 "unknown circuit closure reason: {}",
2581 s
2582 ))),
2583 }
2584}
2585
2586/// Parses a stream closure reason string into a [`StreamClosureReason`] enum variant.
2587///
2588/// Converts a case-insensitive string representation of a stream closure reason
2589/// from the Tor control protocol into the corresponding enum variant.
2590///
2591/// # Arguments
2592///
2593/// * `s` - The stream closure reason string to parse (e.g., "DONE", "TIMEOUT")
2594///
2595/// # Returns
2596///
2597/// * `Ok(StreamClosureReason)` - The parsed closure reason variant
2598/// * `Err(Error::Protocol)` - If the string doesn't match any known reason
2599///
2600/// # Supported Values
2601///
2602/// - `MISC` - Miscellaneous error
2603/// - `RESOLVEFAILED` - DNS resolution failed
2604/// - `CONNECTREFUSED` - Connection refused by destination
2605/// - `EXITPOLICY` - Exit policy rejected connection
2606/// - `DESTROY` - Circuit was destroyed
2607/// - `DONE` - Stream completed normally
2608/// - `TIMEOUT` - Stream timed out
2609/// - `NOROUTE` - No route to destination
2610/// - `HIBERNATING` - Relay is hibernating
2611/// - `INTERNAL` - Internal error
2612/// - `RESOURCELIMIT` - Resource limit reached
2613/// - `CONNRESET` - Connection reset
2614/// - `TORPROTOCOL` - Tor protocol violation
2615/// - `NOTDIRECTORY` - Not a directory server
2616/// - `END` - Stream ended
2617/// - `PRIVATE_ADDR` - Private address rejected
2618fn parse_stream_closure_reason(s: &str) -> Result<StreamClosureReason, Error> {
2619 match s.to_uppercase().as_str() {
2620 "MISC" => Ok(StreamClosureReason::Misc),
2621 "RESOLVEFAILED" => Ok(StreamClosureReason::ResolveFailed),
2622 "CONNECTREFUSED" => Ok(StreamClosureReason::ConnectRefused),
2623 "EXITPOLICY" => Ok(StreamClosureReason::ExitPolicy),
2624 "DESTROY" => Ok(StreamClosureReason::Destroy),
2625 "DONE" => Ok(StreamClosureReason::Done),
2626 "TIMEOUT" => Ok(StreamClosureReason::Timeout),
2627 "NOROUTE" => Ok(StreamClosureReason::NoRoute),
2628 "HIBERNATING" => Ok(StreamClosureReason::Hibernating),
2629 "INTERNAL" => Ok(StreamClosureReason::Internal),
2630 "RESOURCELIMIT" => Ok(StreamClosureReason::ResourceLimit),
2631 "CONNRESET" => Ok(StreamClosureReason::ConnReset),
2632 "TORPROTOCOL" => Ok(StreamClosureReason::TorProtocol),
2633 "NOTDIRECTORY" => Ok(StreamClosureReason::NotDirectory),
2634 "END" => Ok(StreamClosureReason::End),
2635 "PRIVATE_ADDR" => Ok(StreamClosureReason::PrivateAddr),
2636 _ => Err(Error::Protocol(format!(
2637 "unknown stream closure reason: {}",
2638 s
2639 ))),
2640 }
2641}
2642
2643/// Parses a stream source string into a [`StreamSource`] enum variant.
2644///
2645/// Converts a case-insensitive string representation of a stream source
2646/// from the Tor control protocol into the corresponding enum variant.
2647///
2648/// # Arguments
2649///
2650/// * `s` - The stream source string to parse (e.g., "CACHE", "EXIT")
2651///
2652/// # Returns
2653///
2654/// * `Ok(StreamSource)` - The parsed stream source variant
2655/// * `Err(Error::Protocol)` - If the string doesn't match any known source
2656///
2657/// # Supported Values
2658///
2659/// - `CACHE` - Data from cache
2660/// - `EXIT` - Data from exit node
2661fn parse_stream_source(s: &str) -> Result<StreamSource, Error> {
2662 match s.to_uppercase().as_str() {
2663 "CACHE" => Ok(StreamSource::Cache),
2664 "EXIT" => Ok(StreamSource::Exit),
2665 _ => Err(Error::Protocol(format!("unknown stream source: {}", s))),
2666 }
2667}
2668
2669/// Parses a stream purpose string into a [`StreamPurpose`] enum variant.
2670///
2671/// Converts a case-insensitive string representation of a stream purpose
2672/// from the Tor control protocol into the corresponding enum variant.
2673///
2674/// # Arguments
2675///
2676/// * `s` - The stream purpose string to parse (e.g., "USER", "DIR_FETCH")
2677///
2678/// # Returns
2679///
2680/// * `Ok(StreamPurpose)` - The parsed stream purpose variant
2681/// * `Err(Error::Protocol)` - If the string doesn't match any known purpose
2682///
2683/// # Supported Values
2684///
2685/// - `DIR_FETCH` - Directory fetch operation
2686/// - `DIR_UPLOAD` - Directory upload operation
2687/// - `DNS_REQUEST` - DNS resolution request
2688/// - `DIRPORT_TEST` - Directory port testing
2689/// - `USER` - User-initiated stream
2690fn parse_stream_purpose(s: &str) -> Result<StreamPurpose, Error> {
2691 match s.to_uppercase().as_str() {
2692 "DIR_FETCH" => Ok(StreamPurpose::DirFetch),
2693 "DIR_UPLOAD" => Ok(StreamPurpose::DirUpload),
2694 "DNS_REQUEST" => Ok(StreamPurpose::DnsRequest),
2695 "DIRPORT_TEST" => Ok(StreamPurpose::DirportTest),
2696 "USER" => Ok(StreamPurpose::User),
2697 _ => Err(Error::Protocol(format!("unknown stream purpose: {}", s))),
2698 }
2699}
2700
2701/// Parses an OR connection closure reason string into an [`OrClosureReason`] enum variant.
2702///
2703/// Converts a case-insensitive string representation of an OR connection
2704/// closure reason from the Tor control protocol into the corresponding enum variant.
2705///
2706/// # Arguments
2707///
2708/// * `s` - The OR closure reason string to parse (e.g., "DONE", "TIMEOUT")
2709///
2710/// # Returns
2711///
2712/// * `Ok(OrClosureReason)` - The parsed closure reason variant
2713/// * `Err(Error::Protocol)` - If the string doesn't match any known reason
2714///
2715/// # Supported Values
2716///
2717/// - `DONE` - Connection completed normally
2718/// - `CONNECTREFUSED` - Connection refused
2719/// - `IDENTITY` - Identity verification failed
2720/// - `CONNECTRESET` - Connection reset
2721/// - `TIMEOUT` - Connection timed out
2722/// - `NOROUTE` - No route to relay
2723/// - `IOERROR` - I/O error occurred
2724/// - `RESOURCELIMIT` - Resource limit reached
2725/// - `MISC` - Miscellaneous error
2726/// - `PT_MISSING` - Pluggable transport missing
2727fn parse_or_closure_reason(s: &str) -> Result<OrClosureReason, Error> {
2728 match s.to_uppercase().as_str() {
2729 "DONE" => Ok(OrClosureReason::Done),
2730 "CONNECTREFUSED" => Ok(OrClosureReason::ConnectRefused),
2731 "IDENTITY" => Ok(OrClosureReason::Identity),
2732 "CONNECTRESET" => Ok(OrClosureReason::ConnectReset),
2733 "TIMEOUT" => Ok(OrClosureReason::Timeout),
2734 "NOROUTE" => Ok(OrClosureReason::NoRoute),
2735 "IOERROR" => Ok(OrClosureReason::IoError),
2736 "RESOURCELIMIT" => Ok(OrClosureReason::ResourceLimit),
2737 "MISC" => Ok(OrClosureReason::Misc),
2738 "PT_MISSING" => Ok(OrClosureReason::PtMissing),
2739 _ => Err(Error::Protocol(format!("unknown OR closure reason: {}", s))),
2740 }
2741}
2742
2743/// Parses a comma-separated string of circuit build flags into a vector of [`CircBuildFlag`].
2744///
2745/// Converts a comma-separated string of circuit build flags from the Tor
2746/// control protocol into a vector of enum variants. Unknown flags are silently ignored.
2747///
2748/// # Arguments
2749///
2750/// * `s` - The comma-separated build flags string (e.g., "ONEHOP_TUNNEL,IS_INTERNAL")
2751///
2752/// # Returns
2753///
2754/// A vector of recognized [`CircBuildFlag`] variants. Unknown flags are filtered out.
2755///
2756/// # Supported Values
2757///
2758/// - `ONEHOP_TUNNEL` - Single-hop circuit (for directory connections)
2759/// - `IS_INTERNAL` - Internal circuit (not for user traffic)
2760/// - `NEED_CAPACITY` - Circuit needs high-capacity relays
2761/// - `NEED_UPTIME` - Circuit needs high-uptime relays
2762fn parse_build_flags(s: &str) -> Vec<CircBuildFlag> {
2763 s.split(',')
2764 .filter_map(|f| match f.to_uppercase().as_str() {
2765 "ONEHOP_TUNNEL" => Some(CircBuildFlag::OneHopTunnel),
2766 "IS_INTERNAL" => Some(CircBuildFlag::IsInternal),
2767 "NEED_CAPACITY" => Some(CircBuildFlag::NeedCapacity),
2768 "NEED_UPTIME" => Some(CircBuildFlag::NeedUptime),
2769 _ => None,
2770 })
2771 .collect()
2772}
2773
2774/// Parses a circuit path string into a vector of relay fingerprint and nickname pairs.
2775///
2776/// Converts a comma-separated circuit path string from the Tor control protocol
2777/// into a vector of tuples containing relay fingerprints and optional nicknames.
2778///
2779/// # Arguments
2780///
2781/// * `s` - The circuit path string (e.g., "$FP1~nick1,$FP2=nick2,$FP3")
2782///
2783/// # Returns
2784///
2785/// A vector of tuples where each tuple contains:
2786/// - The relay fingerprint (with leading `$` stripped)
2787/// - An optional nickname (if present after `~` or `=`)
2788///
2789/// # Format
2790///
2791/// Each relay in the path can be specified as:
2792/// - `$FINGERPRINT~nickname` - Fingerprint with nickname (tilde separator)
2793/// - `$FINGERPRINT=nickname` - Fingerprint with nickname (equals separator)
2794/// - `$FINGERPRINT` - Fingerprint only
2795/// - `FINGERPRINT` - Fingerprint without `$` prefix
2796fn parse_circuit_path(s: &str) -> Vec<(String, Option<String>)> {
2797 s.split(',')
2798 .map(|relay| {
2799 let relay = relay.trim_start_matches('$');
2800 if let Some((fp, nick)) = relay.split_once('~') {
2801 (fp.to_string(), Some(nick.to_string()))
2802 } else if let Some((fp, nick)) = relay.split_once('=') {
2803 (fp.to_string(), Some(nick.to_string()))
2804 } else {
2805 (relay.to_string(), None)
2806 }
2807 })
2808 .collect()
2809}
2810
2811/// Parses a relay endpoint string into a fingerprint and optional nickname.
2812///
2813/// Converts a relay endpoint string from the Tor control protocol into a tuple
2814/// containing the relay fingerprint and optional nickname.
2815///
2816/// # Arguments
2817///
2818/// * `s` - The relay endpoint string (e.g., "$FP~nickname" or "$FP=nickname")
2819///
2820/// # Returns
2821///
2822/// A tuple containing:
2823/// - The relay fingerprint (with leading `$` stripped)
2824/// - An optional nickname (if present after `~` or `=`)
2825///
2826/// # Format
2827///
2828/// The relay can be specified as:
2829/// - `$FINGERPRINT~nickname` - Fingerprint with nickname (tilde separator)
2830/// - `$FINGERPRINT=nickname` - Fingerprint with nickname (equals separator)
2831/// - `$FINGERPRINT` - Fingerprint only
2832/// - `FINGERPRINT` - Fingerprint without `$` prefix
2833fn parse_relay_endpoint(s: &str) -> (String, Option<String>) {
2834 let s = s.trim_start_matches('$');
2835 if let Some((fp, nick)) = s.split_once('~') {
2836 (fp.to_string(), Some(nick.to_string()))
2837 } else if let Some((fp, nick)) = s.split_once('=') {
2838 (fp.to_string(), Some(nick.to_string()))
2839 } else {
2840 (s.to_string(), None)
2841 }
2842}
2843
2844/// Parses a target address string into a host and port tuple.
2845///
2846/// Converts a target address string (host:port format) from the Tor control
2847/// protocol into a tuple containing the host and port number.
2848///
2849/// # Arguments
2850///
2851/// * `target` - The target address string (e.g., "example.com:80" or "[::1]:443")
2852///
2853/// # Returns
2854///
2855/// * `Ok((host, port))` - The parsed host string and port number
2856/// * `Err(Error::Protocol)` - If the port cannot be parsed as a valid u16
2857///
2858/// # Format
2859///
2860/// Supports both IPv4 and IPv6 addresses:
2861/// - `hostname:port` - Standard hostname with port
2862/// - `ip:port` - IPv4 address with port
2863/// - `[ipv6]:port` - IPv6 address with port (brackets preserved in host)
2864///
2865/// If no port is specified, returns port 0.
2866fn parse_target(target: &str) -> Result<(String, u16), Error> {
2867 if let Some(colon_pos) = target.rfind(':') {
2868 let host = target[..colon_pos].to_string();
2869 let port_str = &target[colon_pos + 1..];
2870 let port: u16 = port_str
2871 .parse()
2872 .map_err(|_| Error::Protocol(format!("invalid port: {}", port_str)))?;
2873 Ok((host, port))
2874 } else {
2875 Ok((target.to_string(), 0))
2876 }
2877}
2878
2879/// Parses an ISO 8601 timestamp string into a UTC [`DateTime`].
2880///
2881/// Converts a timestamp string in ISO 8601 format from the Tor control
2882/// protocol into a [`DateTime<Utc>`] value.
2883///
2884/// # Arguments
2885///
2886/// * `s` - The timestamp string (e.g., "2024-01-15 12:30:45" or "2024-01-15T12:30:45.123")
2887///
2888/// # Returns
2889///
2890/// * `Ok(DateTime<Utc>)` - The parsed UTC datetime
2891/// * `Err(Error::Protocol)` - If the timestamp format is invalid
2892///
2893/// # Supported Formats
2894///
2895/// - `YYYY-MM-DD HH:MM:SS` - Standard format
2896/// - `YYYY-MM-DDTHH:MM:SS` - ISO 8601 with T separator
2897/// - `YYYY-MM-DD HH:MM:SS.fff` - With fractional seconds
2898/// - `YYYY-MM-DDTHH:MM:SS.fff` - ISO 8601 with fractional seconds
2899fn parse_iso_timestamp(s: &str) -> Result<DateTime<Utc>, Error> {
2900 let s = s.replace('T', " ");
2901 let formats = ["%Y-%m-%d %H:%M:%S%.f", "%Y-%m-%d %H:%M:%S"];
2902 for fmt in &formats {
2903 if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(&s, fmt) {
2904 return Ok(DateTime::from_naive_utc_and_offset(dt, Utc));
2905 }
2906 }
2907 Err(Error::Protocol(format!("invalid timestamp: {}", s)))
2908}
2909
2910/// Parses a local timestamp string into a local [`DateTime`].
2911///
2912/// Converts a timestamp string from the Tor control protocol into a
2913/// [`DateTime<Local>`] value using the system's local timezone offset.
2914///
2915/// # Arguments
2916///
2917/// * `s` - The timestamp string (e.g., "2024-01-15 12:30:45")
2918///
2919/// # Returns
2920///
2921/// * `Ok(DateTime<Local>)` - The parsed local datetime
2922/// * `Err(Error::Protocol)` - If the timestamp format is invalid
2923///
2924/// # Supported Formats
2925///
2926/// - `YYYY-MM-DD HH:MM:SS` - Standard format
2927/// - `YYYY-MM-DD HH:MM:SS.fff` - With fractional seconds
2928///
2929/// # Note
2930///
2931/// The timestamp is interpreted as being in the local timezone at the
2932/// time of parsing. The current local timezone offset is applied.
2933fn parse_local_timestamp(s: &str) -> Result<DateTime<Local>, Error> {
2934 let formats = ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M:%S%.f"];
2935 for fmt in &formats {
2936 if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(s, fmt) {
2937 return Ok(DateTime::from_naive_utc_and_offset(
2938 dt,
2939 *Local::now().offset(),
2940 ));
2941 }
2942 }
2943 Err(Error::Protocol(format!("invalid local timestamp: {}", s)))
2944}
2945
2946/// Parses a UTC timestamp string into a UTC [`DateTime`].
2947///
2948/// This is an alias for [`parse_iso_timestamp`] that explicitly indicates
2949/// the timestamp should be interpreted as UTC.
2950///
2951/// # Arguments
2952///
2953/// * `s` - The timestamp string in ISO 8601 format
2954///
2955/// # Returns
2956///
2957/// * `Ok(DateTime<Utc>)` - The parsed UTC datetime
2958/// * `Err(Error::Protocol)` - If the timestamp format is invalid
2959///
2960/// # See Also
2961///
2962/// - [`parse_iso_timestamp`] - The underlying implementation
2963fn parse_utc_timestamp(s: &str) -> Result<DateTime<Utc>, Error> {
2964 parse_iso_timestamp(s)
2965}
2966
2967/// Enumeration of all parsed event types.
2968///
2969/// This enum provides a unified way to handle different event types
2970/// through pattern matching. Use [`ParsedEvent::parse`] to convert
2971/// raw event data into the appropriate variant.
2972///
2973/// # Parsing Events
2974///
2975/// Events are parsed from raw control protocol messages:
2976///
2977/// ```rust,ignore
2978/// use stem_rs::events::ParsedEvent;
2979///
2980/// let event = ParsedEvent::parse("BW", "1024 2048", None)?;
2981/// match event {
2982/// ParsedEvent::Bandwidth(bw) => {
2983/// println!("Read: {}, Written: {}", bw.read, bw.written);
2984/// }
2985/// _ => {}
2986/// }
2987/// ```
2988///
2989/// # Unknown Events
2990///
2991/// Events that don't match a known type are captured as
2992/// [`ParsedEvent::Unknown`], preserving the raw content for
2993/// debugging or custom handling.
2994///
2995/// # Display
2996///
2997/// All variants implement [`Display`](std::fmt::Display) to reconstruct
2998/// a human-readable representation of the event.
2999#[derive(Debug, Clone)]
3000pub enum ParsedEvent {
3001 /// Aggregate bandwidth event (BW).
3002 Bandwidth(BandwidthEvent),
3003 /// Log message event (DEBUG, INFO, NOTICE, WARN, ERR).
3004 Log(LogEvent),
3005 /// Circuit status change event (CIRC).
3006 Circuit(CircuitEvent),
3007 /// Stream status change event (STREAM).
3008 Stream(StreamEvent),
3009 /// OR connection status change event (ORCONN).
3010 OrConn(OrConnEvent),
3011 /// Address mapping event (ADDRMAP).
3012 AddrMap(AddrMapEvent),
3013 /// Circuit build timeout change event (BUILDTIMEOUT_SET).
3014 BuildTimeoutSet(BuildTimeoutSetEvent),
3015 /// Guard relay status change event (GUARD).
3016 Guard(GuardEvent),
3017 /// New descriptor available event (NEWDESC).
3018 NewDesc(NewDescEvent),
3019 /// Signal received event (SIGNAL).
3020 Signal(SignalEvent),
3021 /// Status event (STATUS_GENERAL, STATUS_CLIENT, STATUS_SERVER).
3022 Status(StatusEvent),
3023 /// Configuration changed event (CONF_CHANGED).
3024 ConfChanged(ConfChangedEvent),
3025 /// Network liveness event (NETWORK_LIVENESS).
3026 NetworkLiveness(NetworkLivenessEvent),
3027 /// Per-circuit bandwidth event (CIRC_BW).
3028 CircuitBandwidth(CircuitBandwidthEvent),
3029 /// Per-connection bandwidth event (CONN_BW).
3030 ConnectionBandwidth(ConnectionBandwidthEvent),
3031 /// Hidden service descriptor event (HS_DESC).
3032 HsDesc(HsDescEvent),
3033 /// Unknown or unrecognized event type.
3034 Unknown {
3035 /// The event type string.
3036 event_type: String,
3037 /// The raw event content.
3038 content: String,
3039 },
3040}
3041
3042impl ParsedEvent {
3043 /// Parses raw event data into a typed event.
3044 ///
3045 /// # Arguments
3046 ///
3047 /// * `event_type` - The event type keyword (e.g., "BW", "CIRC")
3048 /// * `content` - The event content after the type
3049 /// * `lines` - Optional multi-line content for events like CONF_CHANGED
3050 ///
3051 /// # Supported Event Types
3052 ///
3053 /// - `BW` - Bandwidth events
3054 /// - `DEBUG`, `INFO`, `NOTICE`, `WARN`, `ERR` - Log events
3055 /// - `CIRC` - Circuit events
3056 /// - `STREAM` - Stream events
3057 /// - `ORCONN` - OR connection events
3058 /// - `ADDRMAP` - Address map events
3059 /// - `BUILDTIMEOUT_SET` - Build timeout events
3060 /// - `GUARD` - Guard events
3061 /// - `NEWDESC` - New descriptor events
3062 /// - `SIGNAL` - Signal events
3063 /// - `STATUS_GENERAL`, `STATUS_CLIENT`, `STATUS_SERVER` - Status events
3064 /// - `CONF_CHANGED` - Configuration change events
3065 /// - `NETWORK_LIVENESS` - Network liveness events
3066 /// - `CIRC_BW` - Circuit bandwidth events
3067 /// - `CONN_BW` - Connection bandwidth events
3068 /// - `HS_DESC` - Hidden service descriptor events
3069 ///
3070 /// # Errors
3071 ///
3072 /// Returns [`Error::Protocol`] if the event content is malformed.
3073 /// Unknown event types are returned as [`ParsedEvent::Unknown`]
3074 /// rather than causing an error.
3075 ///
3076 /// # Example
3077 ///
3078 /// ```rust,ignore
3079 /// use stem_rs::events::ParsedEvent;
3080 ///
3081 /// // Parse a bandwidth event
3082 /// let event = ParsedEvent::parse("BW", "100 200", None)?;
3083 ///
3084 /// // Parse a circuit event
3085 /// let event = ParsedEvent::parse("CIRC", "1 BUILT $ABC...=relay", None)?;
3086 ///
3087 /// // Unknown events are captured, not rejected
3088 /// let event = ParsedEvent::parse("FUTURE_EVENT", "data", None)?;
3089 /// assert!(matches!(event, ParsedEvent::Unknown { .. }));
3090 /// ```
3091 pub fn parse(event_type: &str, content: &str, lines: Option<&[String]>) -> Result<Self, Error> {
3092 match event_type.to_uppercase().as_str() {
3093 "BW" => Ok(ParsedEvent::Bandwidth(BandwidthEvent::parse(content)?)),
3094 "DEBUG" => Ok(ParsedEvent::Log(LogEvent::parse(Runlevel::Debug, content)?)),
3095 "INFO" => Ok(ParsedEvent::Log(LogEvent::parse(Runlevel::Info, content)?)),
3096 "NOTICE" => Ok(ParsedEvent::Log(LogEvent::parse(
3097 Runlevel::Notice,
3098 content,
3099 )?)),
3100 "WARN" => Ok(ParsedEvent::Log(LogEvent::parse(Runlevel::Warn, content)?)),
3101 "ERR" => Ok(ParsedEvent::Log(LogEvent::parse(Runlevel::Err, content)?)),
3102 "CIRC" => Ok(ParsedEvent::Circuit(CircuitEvent::parse(content)?)),
3103 "STREAM" => Ok(ParsedEvent::Stream(StreamEvent::parse(content)?)),
3104 "ORCONN" => Ok(ParsedEvent::OrConn(OrConnEvent::parse(content)?)),
3105 "ADDRMAP" => Ok(ParsedEvent::AddrMap(AddrMapEvent::parse(content)?)),
3106 "BUILDTIMEOUT_SET" => Ok(ParsedEvent::BuildTimeoutSet(BuildTimeoutSetEvent::parse(
3107 content,
3108 )?)),
3109 "GUARD" => Ok(ParsedEvent::Guard(GuardEvent::parse(content)?)),
3110 "NEWDESC" => Ok(ParsedEvent::NewDesc(NewDescEvent::parse(content)?)),
3111 "SIGNAL" => Ok(ParsedEvent::Signal(SignalEvent::parse(content)?)),
3112 "STATUS_GENERAL" => Ok(ParsedEvent::Status(StatusEvent::parse(
3113 StatusType::General,
3114 content,
3115 )?)),
3116 "STATUS_CLIENT" => Ok(ParsedEvent::Status(StatusEvent::parse(
3117 StatusType::Client,
3118 content,
3119 )?)),
3120 "STATUS_SERVER" => Ok(ParsedEvent::Status(StatusEvent::parse(
3121 StatusType::Server,
3122 content,
3123 )?)),
3124 "CONF_CHANGED" => {
3125 let lines = lines.unwrap_or(&[]);
3126 Ok(ParsedEvent::ConfChanged(ConfChangedEvent::parse(lines)?))
3127 }
3128 "NETWORK_LIVENESS" => Ok(ParsedEvent::NetworkLiveness(NetworkLivenessEvent::parse(
3129 content,
3130 )?)),
3131 "CIRC_BW" => Ok(ParsedEvent::CircuitBandwidth(CircuitBandwidthEvent::parse(
3132 content,
3133 )?)),
3134 "CONN_BW" => Ok(ParsedEvent::ConnectionBandwidth(
3135 ConnectionBandwidthEvent::parse(content)?,
3136 )),
3137 "HS_DESC" => Ok(ParsedEvent::HsDesc(HsDescEvent::parse(content)?)),
3138 _ => Ok(ParsedEvent::Unknown {
3139 event_type: event_type.to_string(),
3140 content: content.to_string(),
3141 }),
3142 }
3143 }
3144
3145 /// Returns the event type string for this event.
3146 ///
3147 /// This returns the canonical event type keyword as used in
3148 /// `SETEVENTS` commands and event responses.
3149 ///
3150 /// # Example
3151 ///
3152 /// ```rust,ignore
3153 /// let event = ParsedEvent::parse("BW", "100 200", None)?;
3154 /// assert_eq!(event.event_type(), "BW");
3155 /// ```
3156 pub fn event_type(&self) -> &str {
3157 match self {
3158 ParsedEvent::Bandwidth(_) => "BW",
3159 ParsedEvent::Log(e) => match e.runlevel {
3160 Runlevel::Debug => "DEBUG",
3161 Runlevel::Info => "INFO",
3162 Runlevel::Notice => "NOTICE",
3163 Runlevel::Warn => "WARN",
3164 Runlevel::Err => "ERR",
3165 },
3166 ParsedEvent::Circuit(_) => "CIRC",
3167 ParsedEvent::Stream(_) => "STREAM",
3168 ParsedEvent::OrConn(_) => "ORCONN",
3169 ParsedEvent::AddrMap(_) => "ADDRMAP",
3170 ParsedEvent::BuildTimeoutSet(_) => "BUILDTIMEOUT_SET",
3171 ParsedEvent::Guard(_) => "GUARD",
3172 ParsedEvent::NewDesc(_) => "NEWDESC",
3173 ParsedEvent::Signal(_) => "SIGNAL",
3174 ParsedEvent::Status(e) => match e.status_type {
3175 StatusType::General => "STATUS_GENERAL",
3176 StatusType::Client => "STATUS_CLIENT",
3177 StatusType::Server => "STATUS_SERVER",
3178 },
3179 ParsedEvent::ConfChanged(_) => "CONF_CHANGED",
3180 ParsedEvent::NetworkLiveness(_) => "NETWORK_LIVENESS",
3181 ParsedEvent::CircuitBandwidth(_) => "CIRC_BW",
3182 ParsedEvent::ConnectionBandwidth(_) => "CONN_BW",
3183 ParsedEvent::HsDesc(_) => "HS_DESC",
3184 ParsedEvent::Unknown { event_type, .. } => event_type,
3185 }
3186 }
3187}
3188
3189impl std::fmt::Display for ParsedEvent {
3190 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3191 match self {
3192 ParsedEvent::Bandwidth(e) => write!(f, "650 BW {} {}", e.read, e.written),
3193 ParsedEvent::Log(e) => write!(f, "650 {} {}", e.runlevel, e.message),
3194 ParsedEvent::Circuit(e) => write!(f, "650 CIRC {} {}", e.id, e.status),
3195 ParsedEvent::Stream(e) => write!(f, "650 STREAM {} {}", e.id, e.status),
3196 ParsedEvent::OrConn(e) => write!(f, "650 ORCONN {} {}", e.target, e.status),
3197 ParsedEvent::AddrMap(e) => {
3198 write!(
3199 f,
3200 "650 ADDRMAP {} {}",
3201 e.hostname,
3202 e.destination.as_deref().unwrap_or("<error>")
3203 )
3204 }
3205 ParsedEvent::BuildTimeoutSet(e) => write!(f, "650 BUILDTIMEOUT_SET {:?}", e.set_type),
3206 ParsedEvent::Guard(e) => {
3207 write!(f, "650 GUARD {} {} {}", e.guard_type, e.endpoint, e.status)
3208 }
3209 ParsedEvent::NewDesc(e) => {
3210 let relays: Vec<String> = e
3211 .relays
3212 .iter()
3213 .map(|(fp, nick)| match nick {
3214 Some(n) => format!("{}~{}", fp, n),
3215 None => fp.clone(),
3216 })
3217 .collect();
3218 write!(f, "650 NEWDESC {}", relays.join(" "))
3219 }
3220 ParsedEvent::Signal(e) => write!(f, "650 SIGNAL {}", e.signal),
3221 ParsedEvent::Status(e) => write!(
3222 f,
3223 "650 STATUS_{} {} {}",
3224 e.status_type, e.runlevel, e.action
3225 ),
3226 ParsedEvent::ConfChanged(e) => {
3227 let changes: Vec<String> = e
3228 .changed
3229 .iter()
3230 .map(|(k, v)| format!("{}={}", k, v.join(",")))
3231 .collect();
3232 write!(f, "650 CONF_CHANGED {}", changes.join(" "))
3233 }
3234 ParsedEvent::NetworkLiveness(e) => write!(f, "650 NETWORK_LIVENESS {}", e.status),
3235 ParsedEvent::CircuitBandwidth(e) => {
3236 write!(f, "650 CIRC_BW {} {} {}", e.id, e.read, e.written)
3237 }
3238 ParsedEvent::ConnectionBandwidth(e) => write!(
3239 f,
3240 "650 CONN_BW {} {} {} {}",
3241 e.id, e.conn_type, e.read, e.written
3242 ),
3243 ParsedEvent::HsDesc(e) => write!(f, "650 HS_DESC {} {}", e.action, e.address),
3244 ParsedEvent::Unknown {
3245 event_type,
3246 content,
3247 } => write!(f, "650 {} {}", event_type, content),
3248 }
3249 }
3250}
3251
3252#[cfg(test)]
3253mod tests {
3254 use super::*;
3255 use chrono::{Datelike, Timelike};
3256
3257 #[test]
3258 fn test_bandwidth_event() {
3259 let event = BandwidthEvent::parse("15 25").unwrap();
3260 assert_eq!(event.read, 15);
3261 assert_eq!(event.written, 25);
3262 }
3263
3264 #[test]
3265 fn test_bandwidth_event_zero() {
3266 let event = BandwidthEvent::parse("0 0").unwrap();
3267 assert_eq!(event.read, 0);
3268 assert_eq!(event.written, 0);
3269 }
3270
3271 #[test]
3272 fn test_bandwidth_event_invalid_missing_values() {
3273 assert!(BandwidthEvent::parse("").is_err());
3274 assert!(BandwidthEvent::parse("15").is_err());
3275 }
3276
3277 #[test]
3278 fn test_bandwidth_event_invalid_non_numeric() {
3279 assert!(BandwidthEvent::parse("x 25").is_err());
3280 assert!(BandwidthEvent::parse("15 y").is_err());
3281 }
3282
3283 #[test]
3284 fn test_log_event() {
3285 let event = LogEvent::parse(Runlevel::Debug, "test message").unwrap();
3286 assert_eq!(event.runlevel, Runlevel::Debug);
3287 assert_eq!(event.message, "test message");
3288 }
3289
3290 #[test]
3291 fn test_log_event_debug() {
3292 let event = LogEvent::parse(
3293 Runlevel::Debug,
3294 "connection_edge_process_relay_cell(): Got an extended cell! Yay.",
3295 )
3296 .unwrap();
3297 assert_eq!(event.runlevel, Runlevel::Debug);
3298 assert_eq!(
3299 event.message,
3300 "connection_edge_process_relay_cell(): Got an extended cell! Yay."
3301 );
3302 }
3303
3304 #[test]
3305 fn test_log_event_info() {
3306 let event = LogEvent::parse(
3307 Runlevel::Info,
3308 "circuit_finish_handshake(): Finished building circuit hop:",
3309 )
3310 .unwrap();
3311 assert_eq!(event.runlevel, Runlevel::Info);
3312 }
3313
3314 #[test]
3315 fn test_log_event_warn() {
3316 let event = LogEvent::parse(Runlevel::Warn, "a multi-line\nwarning message").unwrap();
3317 assert_eq!(event.runlevel, Runlevel::Warn);
3318 assert_eq!(event.message, "a multi-line\nwarning message");
3319 }
3320
3321 #[test]
3322 fn test_circuit_event_launched() {
3323 let content = "7 LAUNCHED BUILD_FLAGS=NEED_CAPACITY PURPOSE=GENERAL TIME_CREATED=2012-11-08T16:48:38.417238";
3324 let event = CircuitEvent::parse(content).unwrap();
3325 assert_eq!(event.id.0, "7");
3326 assert_eq!(event.status, CircStatus::Launched);
3327 assert!(event.path.is_empty());
3328 assert_eq!(event.build_flags, Some(vec![CircBuildFlag::NeedCapacity]));
3329 assert_eq!(event.purpose, Some(CircPurpose::General));
3330 assert!(event.created.is_some());
3331 assert_eq!(event.reason, None);
3332 assert_eq!(event.remote_reason, None);
3333 assert_eq!(event.socks_username, None);
3334 assert_eq!(event.socks_password, None);
3335 }
3336
3337 #[test]
3338 fn test_circuit_event_extended() {
3339 let content = "7 EXTENDED $999A226EBED397F331B612FE1E4CFAE5C1F201BA=piyaz BUILD_FLAGS=NEED_CAPACITY PURPOSE=GENERAL";
3340 let event = CircuitEvent::parse(content).unwrap();
3341 assert_eq!(event.id.0, "7");
3342 assert_eq!(event.status, CircStatus::Extended);
3343 assert_eq!(event.path.len(), 1);
3344 assert_eq!(event.path[0].0, "999A226EBED397F331B612FE1E4CFAE5C1F201BA");
3345 assert_eq!(event.path[0].1, Some("piyaz".to_string()));
3346 }
3347
3348 #[test]
3349 fn test_circuit_event_failed() {
3350 let content = "5 FAILED $E57A476CD4DFBD99B4EE52A100A58610AD6E80B9=ergebnisoffen BUILD_FLAGS=NEED_CAPACITY PURPOSE=GENERAL REASON=DESTROYED REMOTE_REASON=OR_CONN_CLOSED";
3351 let event = CircuitEvent::parse(content).unwrap();
3352 assert_eq!(event.id.0, "5");
3353 assert_eq!(event.status, CircStatus::Failed);
3354 assert_eq!(event.reason, Some(CircClosureReason::Destroyed));
3355 assert_eq!(event.remote_reason, Some(CircClosureReason::OrConnClosed));
3356 }
3357
3358 #[test]
3359 fn test_circuit_event_with_credentials() {
3360 let content = r#"7 LAUNCHED SOCKS_USERNAME="It's a me, Mario!" SOCKS_PASSWORD="your princess is in another castle""#;
3361 let event = CircuitEvent::parse(content).unwrap();
3362 assert_eq!(event.id.0, "7");
3363 assert_eq!(event.status, CircStatus::Launched);
3364 assert_eq!(event.socks_username, Some("It's a me, Mario!".to_string()));
3365 assert_eq!(
3366 event.socks_password,
3367 Some("your princess is in another castle".to_string())
3368 );
3369 }
3370
3371 #[test]
3372 fn test_circuit_event_launched_old_format() {
3373 let content = "4 LAUNCHED";
3374 let event = CircuitEvent::parse(content).unwrap();
3375 assert_eq!(event.id.0, "4");
3376 assert_eq!(event.status, CircStatus::Launched);
3377 assert!(event.path.is_empty());
3378 assert_eq!(event.build_flags, None);
3379 assert_eq!(event.purpose, None);
3380 }
3381
3382 #[test]
3383 fn test_circuit_event_extended_old_format() {
3384 let content = "$E57A476CD4DFBD99B4EE52A100A58610AD6E80B9,hamburgerphone";
3385 let event = CircuitEvent::parse(&format!("1 EXTENDED {}", content)).unwrap();
3386 assert_eq!(event.id.0, "1");
3387 assert_eq!(event.status, CircStatus::Extended);
3388 }
3389
3390 #[test]
3391 fn test_circuit_event_built_old_format() {
3392 let content =
3393 "1 BUILT $E57A476CD4DFBD99B4EE52A100A58610AD6E80B9,hamburgerphone,PrivacyRepublic14";
3394 let event = CircuitEvent::parse(content).unwrap();
3395 assert_eq!(event.id.0, "1");
3396 assert_eq!(event.status, CircStatus::Built);
3397 }
3398
3399 #[test]
3400 fn test_stream_event_new() {
3401 let content = "18 NEW 0 encrypted.google.com:443 SOURCE_ADDR=127.0.0.1:47849 PURPOSE=USER";
3402 let event = StreamEvent::parse(content).unwrap();
3403 assert_eq!(event.id.0, "18");
3404 assert_eq!(event.status, StreamStatus::New);
3405 assert_eq!(event.circuit_id, None);
3406 assert_eq!(event.target_host, "encrypted.google.com");
3407 assert_eq!(event.target_port, 443);
3408 assert_eq!(event.source_addr, Some("127.0.0.1:47849".to_string()));
3409 assert_eq!(event.purpose, Some(StreamPurpose::User));
3410 }
3411
3412 #[test]
3413 fn test_stream_event_sentconnect() {
3414 let content = "18 SENTCONNECT 26 encrypted.google.com:443";
3415 let event = StreamEvent::parse(content).unwrap();
3416 assert_eq!(event.id.0, "18");
3417 assert_eq!(event.status, StreamStatus::SentConnect);
3418 assert_eq!(event.circuit_id, Some(CircuitId::new("26")));
3419 assert_eq!(event.target_host, "encrypted.google.com");
3420 assert_eq!(event.target_port, 443);
3421 assert_eq!(event.source_addr, None);
3422 assert_eq!(event.purpose, None);
3423 }
3424
3425 #[test]
3426 fn test_stream_event_remap() {
3427 let content = "18 REMAP 26 74.125.227.129:443 SOURCE=EXIT";
3428 let event = StreamEvent::parse(content).unwrap();
3429 assert_eq!(event.id.0, "18");
3430 assert_eq!(event.status, StreamStatus::Remap);
3431 assert_eq!(event.circuit_id, Some(CircuitId::new("26")));
3432 assert_eq!(event.target_host, "74.125.227.129");
3433 assert_eq!(event.target_port, 443);
3434 assert_eq!(event.source, Some(StreamSource::Exit));
3435 }
3436
3437 #[test]
3438 fn test_stream_event_succeeded() {
3439 let content = "18 SUCCEEDED 26 74.125.227.129:443";
3440 let event = StreamEvent::parse(content).unwrap();
3441 assert_eq!(event.id.0, "18");
3442 assert_eq!(event.status, StreamStatus::Succeeded);
3443 assert_eq!(event.circuit_id, Some(CircuitId::new("26")));
3444 assert_eq!(event.target_host, "74.125.227.129");
3445 assert_eq!(event.target_port, 443);
3446 }
3447
3448 #[test]
3449 fn test_stream_event_closed() {
3450 let content = "21 CLOSED 26 74.125.227.129:443 REASON=CONNRESET";
3451 let event = StreamEvent::parse(content).unwrap();
3452 assert_eq!(event.status, StreamStatus::Closed);
3453 assert_eq!(event.reason, Some(StreamClosureReason::ConnReset));
3454 }
3455
3456 #[test]
3457 fn test_stream_event_closed_done() {
3458 let content = "25 CLOSED 26 199.7.52.72:80 REASON=DONE";
3459 let event = StreamEvent::parse(content).unwrap();
3460 assert_eq!(event.id.0, "25");
3461 assert_eq!(event.status, StreamStatus::Closed);
3462 assert_eq!(event.reason, Some(StreamClosureReason::Done));
3463 }
3464
3465 #[test]
3466 fn test_stream_event_dir_fetch() {
3467 let content = "14 NEW 0 176.28.51.238.$649F2D0ACF418F7CFC6539AB2257EB2D5297BAFA.exit:443 SOURCE_ADDR=(Tor_internal):0 PURPOSE=DIR_FETCH";
3468 let event = StreamEvent::parse(content).unwrap();
3469 assert_eq!(event.id.0, "14");
3470 assert_eq!(event.status, StreamStatus::New);
3471 assert_eq!(event.circuit_id, None);
3472 assert_eq!(
3473 event.target_host,
3474 "176.28.51.238.$649F2D0ACF418F7CFC6539AB2257EB2D5297BAFA.exit"
3475 );
3476 assert_eq!(event.target_port, 443);
3477 assert_eq!(event.source_addr, Some("(Tor_internal):0".to_string()));
3478 assert_eq!(event.purpose, Some(StreamPurpose::DirFetch));
3479 }
3480
3481 #[test]
3482 fn test_stream_event_dns_request() {
3483 let content = "1113 NEW 0 www.google.com:0 SOURCE_ADDR=127.0.0.1:15297 PURPOSE=DNS_REQUEST";
3484 let event = StreamEvent::parse(content).unwrap();
3485 assert_eq!(event.id.0, "1113");
3486 assert_eq!(event.status, StreamStatus::New);
3487 assert_eq!(event.target_host, "www.google.com");
3488 assert_eq!(event.target_port, 0);
3489 assert_eq!(event.purpose, Some(StreamPurpose::DnsRequest));
3490 }
3491
3492 #[test]
3493 fn test_orconn_event_closed() {
3494 let content = "$A1130635A0CDA6F60C276FBF6994EFBD4ECADAB1~tama CLOSED REASON=DONE";
3495 let event = OrConnEvent::parse(content).unwrap();
3496 assert_eq!(
3497 event.target,
3498 "$A1130635A0CDA6F60C276FBF6994EFBD4ECADAB1~tama"
3499 );
3500 assert_eq!(event.status, OrStatus::Closed);
3501 assert_eq!(event.reason, Some(OrClosureReason::Done));
3502 assert_eq!(event.num_circuits, None);
3503 assert_eq!(event.id, None);
3504 }
3505
3506 #[test]
3507 fn test_orconn_event_connected() {
3508 let content = "127.0.0.1:9000 CONNECTED NCIRCS=20 ID=18";
3509 let event = OrConnEvent::parse(content).unwrap();
3510 assert_eq!(event.target, "127.0.0.1:9000");
3511 assert_eq!(event.status, OrStatus::Connected);
3512 assert_eq!(event.num_circuits, Some(20));
3513 assert_eq!(event.id, Some("18".to_string()));
3514 assert_eq!(event.reason, None);
3515 }
3516
3517 #[test]
3518 fn test_orconn_event_launched() {
3519 let content = "$7ED90E2833EE38A75795BA9237B0A4560E51E1A0=GreenDragon LAUNCHED";
3520 let event = OrConnEvent::parse(content).unwrap();
3521 assert_eq!(
3522 event.target,
3523 "$7ED90E2833EE38A75795BA9237B0A4560E51E1A0=GreenDragon"
3524 );
3525 assert_eq!(event.status, OrStatus::Launched);
3526 assert_eq!(event.reason, None);
3527 assert_eq!(event.num_circuits, None);
3528 }
3529
3530 #[test]
3531 fn test_addrmap_event() {
3532 let content =
3533 r#"www.atagar.com 75.119.206.243 "2012-11-19 00:50:13" EXPIRES="2012-11-19 08:50:13""#;
3534 let event = AddrMapEvent::parse(content).unwrap();
3535 assert_eq!(event.hostname, "www.atagar.com");
3536 assert_eq!(event.destination, Some("75.119.206.243".to_string()));
3537 assert!(event.expiry.is_some());
3538 assert_eq!(event.error, None);
3539 assert!(event.utc_expiry.is_some());
3540 }
3541
3542 #[test]
3543 fn test_addrmap_event_no_expiration() {
3544 let content = "www.atagar.com 75.119.206.243 NEVER";
3545 let event = AddrMapEvent::parse(content).unwrap();
3546 assert_eq!(event.hostname, "www.atagar.com");
3547 assert_eq!(event.destination, Some("75.119.206.243".to_string()));
3548 assert_eq!(event.expiry, None);
3549 assert_eq!(event.utc_expiry, None);
3550 }
3551
3552 #[test]
3553 fn test_addrmap_event_error() {
3554 let content = r#"www.atagar.com <error> "2012-11-19 00:50:13" error=yes EXPIRES="2012-11-19 08:50:13""#;
3555 let event = AddrMapEvent::parse(content).unwrap();
3556 assert_eq!(event.hostname, "www.atagar.com");
3557 assert_eq!(event.destination, None);
3558 assert_eq!(event.error, Some("yes".to_string()));
3559 }
3560
3561 #[test]
3562 fn test_addrmap_event_cached_yes() {
3563 let content = r#"example.com 192.0.43.10 "2013-04-03 22:31:22" EXPIRES="2013-04-03 20:31:22" CACHED="YES""#;
3564 let event = AddrMapEvent::parse(content).unwrap();
3565 assert_eq!(event.hostname, "example.com");
3566 assert_eq!(event.cached, Some(true));
3567 }
3568
3569 #[test]
3570 fn test_addrmap_event_cached_no() {
3571 let content = r#"example.com 192.0.43.10 "2013-04-03 22:29:11" EXPIRES="2013-04-03 20:29:11" CACHED="NO""#;
3572 let event = AddrMapEvent::parse(content).unwrap();
3573 assert_eq!(event.hostname, "example.com");
3574 assert_eq!(event.cached, Some(false));
3575 }
3576
3577 #[test]
3578 fn test_build_timeout_set_event() {
3579 let content = "COMPUTED TOTAL_TIMES=124 TIMEOUT_MS=9019 XM=1375 ALPHA=0.855662 CUTOFF_QUANTILE=0.800000 TIMEOUT_RATE=0.137097 CLOSE_MS=21850 CLOSE_RATE=0.072581";
3580 let event = BuildTimeoutSetEvent::parse(content).unwrap();
3581 assert_eq!(event.set_type, TimeoutSetType::Computed);
3582 assert_eq!(event.total_times, Some(124));
3583 assert_eq!(event.timeout, Some(9019));
3584 assert_eq!(event.xm, Some(1375));
3585 assert!((event.alpha.unwrap() - 0.855662).abs() < 0.0001);
3586 assert!((event.quantile.unwrap() - 0.8).abs() < 0.0001);
3587 assert!((event.timeout_rate.unwrap() - 0.137097).abs() < 0.0001);
3588 assert_eq!(event.close_timeout, Some(21850));
3589 assert!((event.close_rate.unwrap() - 0.072581).abs() < 0.0001);
3590 }
3591
3592 #[test]
3593 fn test_build_timeout_set_event_invalid_total_times() {
3594 let content = "COMPUTED TOTAL_TIMES=one_twenty_four TIMEOUT_MS=9019";
3595 assert!(BuildTimeoutSetEvent::parse(content).is_err());
3596 }
3597
3598 #[test]
3599 fn test_build_timeout_set_event_invalid_quantile() {
3600 let content = "COMPUTED TOTAL_TIMES=124 CUTOFF_QUANTILE=zero_point_eight";
3601 assert!(BuildTimeoutSetEvent::parse(content).is_err());
3602 }
3603
3604 #[test]
3605 fn test_guard_event_new() {
3606 let content = "ENTRY $36B5DBA788246E8369DBAF58577C6BC044A9A374 NEW";
3607 let event = GuardEvent::parse(content).unwrap();
3608 assert_eq!(event.guard_type, GuardType::Entry);
3609 assert_eq!(event.endpoint, "$36B5DBA788246E8369DBAF58577C6BC044A9A374");
3610 assert_eq!(
3611 event.endpoint_fingerprint,
3612 "36B5DBA788246E8369DBAF58577C6BC044A9A374"
3613 );
3614 assert_eq!(event.endpoint_nickname, None);
3615 assert_eq!(event.status, GuardStatus::New);
3616 }
3617
3618 #[test]
3619 fn test_guard_event_good() {
3620 let content = "ENTRY $5D0034A368E0ABAF663D21847E1C9B6CFA09752A GOOD";
3621 let event = GuardEvent::parse(content).unwrap();
3622 assert_eq!(event.guard_type, GuardType::Entry);
3623 assert_eq!(
3624 event.endpoint_fingerprint,
3625 "5D0034A368E0ABAF663D21847E1C9B6CFA09752A"
3626 );
3627 assert_eq!(event.endpoint_nickname, None);
3628 assert_eq!(event.status, GuardStatus::Good);
3629 }
3630
3631 #[test]
3632 fn test_guard_event_bad() {
3633 let content = "ENTRY $5D0034A368E0ABAF663D21847E1C9B6CFA09752A=caerSidi BAD";
3634 let event = GuardEvent::parse(content).unwrap();
3635 assert_eq!(
3636 event.endpoint_fingerprint,
3637 "5D0034A368E0ABAF663D21847E1C9B6CFA09752A"
3638 );
3639 assert_eq!(event.endpoint_nickname, Some("caerSidi".to_string()));
3640 assert_eq!(event.status, GuardStatus::Bad);
3641 }
3642
3643 #[test]
3644 fn test_newdesc_event_single() {
3645 let content = "$B3FA3110CC6F42443F039220C134CBD2FC4F0493=Sakura";
3646 let event = NewDescEvent::parse(content).unwrap();
3647 assert_eq!(event.relays.len(), 1);
3648 assert_eq!(
3649 event.relays[0].0,
3650 "B3FA3110CC6F42443F039220C134CBD2FC4F0493"
3651 );
3652 assert_eq!(event.relays[0].1, Some("Sakura".to_string()));
3653 }
3654
3655 #[test]
3656 fn test_newdesc_event_multiple() {
3657 let content = "$BE938957B2CA5F804B3AFC2C1EE6673170CDBBF8=Moonshine $B4BE08B22D4D2923EDC3970FD1B93D0448C6D8FF~Unnamed";
3658 let event = NewDescEvent::parse(content).unwrap();
3659 assert_eq!(event.relays.len(), 2);
3660 assert_eq!(
3661 event.relays[0].0,
3662 "BE938957B2CA5F804B3AFC2C1EE6673170CDBBF8"
3663 );
3664 assert_eq!(event.relays[0].1, Some("Moonshine".to_string()));
3665 assert_eq!(
3666 event.relays[1].0,
3667 "B4BE08B22D4D2923EDC3970FD1B93D0448C6D8FF"
3668 );
3669 assert_eq!(event.relays[1].1, Some("Unnamed".to_string()));
3670 }
3671
3672 #[test]
3673 fn test_signal_event() {
3674 let event = SignalEvent::parse("DEBUG").unwrap();
3675 assert_eq!(event.signal, Signal::Debug);
3676
3677 let event = SignalEvent::parse("DUMP").unwrap();
3678 assert_eq!(event.signal, Signal::Dump);
3679 }
3680
3681 #[test]
3682 fn test_signal_event_all_signals() {
3683 assert_eq!(SignalEvent::parse("RELOAD").unwrap().signal, Signal::Reload);
3684 assert_eq!(SignalEvent::parse("HUP").unwrap().signal, Signal::Reload);
3685 assert_eq!(
3686 SignalEvent::parse("SHUTDOWN").unwrap().signal,
3687 Signal::Shutdown
3688 );
3689 assert_eq!(SignalEvent::parse("INT").unwrap().signal, Signal::Shutdown);
3690 assert_eq!(SignalEvent::parse("DUMP").unwrap().signal, Signal::Dump);
3691 assert_eq!(SignalEvent::parse("USR1").unwrap().signal, Signal::Dump);
3692 assert_eq!(SignalEvent::parse("DEBUG").unwrap().signal, Signal::Debug);
3693 assert_eq!(SignalEvent::parse("USR2").unwrap().signal, Signal::Debug);
3694 assert_eq!(SignalEvent::parse("HALT").unwrap().signal, Signal::Halt);
3695 assert_eq!(SignalEvent::parse("TERM").unwrap().signal, Signal::Halt);
3696 assert_eq!(SignalEvent::parse("NEWNYM").unwrap().signal, Signal::Newnym);
3697 assert_eq!(
3698 SignalEvent::parse("CLEARDNSCACHE").unwrap().signal,
3699 Signal::ClearDnsCache
3700 );
3701 assert_eq!(
3702 SignalEvent::parse("HEARTBEAT").unwrap().signal,
3703 Signal::Heartbeat
3704 );
3705 assert_eq!(SignalEvent::parse("ACTIVE").unwrap().signal, Signal::Active);
3706 assert_eq!(
3707 SignalEvent::parse("DORMANT").unwrap().signal,
3708 Signal::Dormant
3709 );
3710 }
3711
3712 #[test]
3713 fn test_status_event() {
3714 let content = "NOTICE CONSENSUS_ARRIVED";
3715 let event = StatusEvent::parse(StatusType::General, content).unwrap();
3716 assert_eq!(event.status_type, StatusType::General);
3717 assert_eq!(event.runlevel, Runlevel::Notice);
3718 assert_eq!(event.action, "CONSENSUS_ARRIVED");
3719 }
3720
3721 #[test]
3722 fn test_status_event_enough_dir_info() {
3723 let content = "NOTICE ENOUGH_DIR_INFO";
3724 let event = StatusEvent::parse(StatusType::Client, content).unwrap();
3725 assert_eq!(event.status_type, StatusType::Client);
3726 assert_eq!(event.runlevel, Runlevel::Notice);
3727 assert_eq!(event.action, "ENOUGH_DIR_INFO");
3728 }
3729
3730 #[test]
3731 fn test_status_event_circuit_established() {
3732 let content = "NOTICE CIRCUIT_ESTABLISHED";
3733 let event = StatusEvent::parse(StatusType::Client, content).unwrap();
3734 assert_eq!(event.status_type, StatusType::Client);
3735 assert_eq!(event.runlevel, Runlevel::Notice);
3736 assert_eq!(event.action, "CIRCUIT_ESTABLISHED");
3737 }
3738
3739 #[test]
3740 fn test_status_event_with_args() {
3741 let content = "NOTICE BOOTSTRAP PROGRESS=53 TAG=loading_descriptors SUMMARY=\"Loading relay descriptors\"";
3742 let event = StatusEvent::parse(StatusType::Client, content).unwrap();
3743 assert_eq!(event.status_type, StatusType::Client);
3744 assert_eq!(event.action, "BOOTSTRAP");
3745 assert_eq!(event.arguments.get("PROGRESS"), Some(&"53".to_string()));
3746 assert_eq!(
3747 event.arguments.get("TAG"),
3748 Some(&"loading_descriptors".to_string())
3749 );
3750 assert_eq!(
3751 event.arguments.get("SUMMARY"),
3752 Some(&"Loading relay descriptors".to_string())
3753 );
3754 }
3755
3756 #[test]
3757 fn test_status_event_bootstrap_stuck() {
3758 let content = "WARN BOOTSTRAP PROGRESS=80 TAG=conn_or SUMMARY=\"Connecting to the Tor network\" WARNING=\"Network is unreachable\" REASON=NOROUTE COUNT=5 RECOMMENDATION=warn";
3759 let event = StatusEvent::parse(StatusType::Client, content).unwrap();
3760 assert_eq!(event.status_type, StatusType::Client);
3761 assert_eq!(event.runlevel, Runlevel::Warn);
3762 assert_eq!(event.action, "BOOTSTRAP");
3763 assert_eq!(event.arguments.get("PROGRESS"), Some(&"80".to_string()));
3764 assert_eq!(event.arguments.get("TAG"), Some(&"conn_or".to_string()));
3765 assert_eq!(
3766 event.arguments.get("WARNING"),
3767 Some(&"Network is unreachable".to_string())
3768 );
3769 assert_eq!(event.arguments.get("REASON"), Some(&"NOROUTE".to_string()));
3770 assert_eq!(event.arguments.get("COUNT"), Some(&"5".to_string()));
3771 assert_eq!(
3772 event.arguments.get("RECOMMENDATION"),
3773 Some(&"warn".to_string())
3774 );
3775 }
3776
3777 #[test]
3778 fn test_status_event_bootstrap_done() {
3779 let content = "NOTICE BOOTSTRAP PROGRESS=100 TAG=done SUMMARY=\"Done\"";
3780 let event = StatusEvent::parse(StatusType::Client, content).unwrap();
3781 assert_eq!(event.arguments.get("PROGRESS"), Some(&"100".to_string()));
3782 assert_eq!(event.arguments.get("TAG"), Some(&"done".to_string()));
3783 assert_eq!(event.arguments.get("SUMMARY"), Some(&"Done".to_string()));
3784 }
3785
3786 #[test]
3787 fn test_status_event_server_check_reachability() {
3788 let content = "NOTICE CHECKING_REACHABILITY ORADDRESS=71.35.143.230:9050";
3789 let event = StatusEvent::parse(StatusType::Server, content).unwrap();
3790 assert_eq!(event.status_type, StatusType::Server);
3791 assert_eq!(event.runlevel, Runlevel::Notice);
3792 assert_eq!(event.action, "CHECKING_REACHABILITY");
3793 assert_eq!(
3794 event.arguments.get("ORADDRESS"),
3795 Some(&"71.35.143.230:9050".to_string())
3796 );
3797 }
3798
3799 #[test]
3800 fn test_status_event_dns_timeout() {
3801 let content =
3802 "NOTICE NAMESERVER_STATUS NS=205.171.3.25 STATUS=DOWN ERR=\"request timed out.\"";
3803 let event = StatusEvent::parse(StatusType::Server, content).unwrap();
3804 assert_eq!(event.action, "NAMESERVER_STATUS");
3805 assert_eq!(event.arguments.get("NS"), Some(&"205.171.3.25".to_string()));
3806 assert_eq!(event.arguments.get("STATUS"), Some(&"DOWN".to_string()));
3807 assert_eq!(
3808 event.arguments.get("ERR"),
3809 Some(&"request timed out.".to_string())
3810 );
3811 }
3812
3813 #[test]
3814 fn test_status_event_dns_down() {
3815 let content = "WARN NAMESERVER_ALL_DOWN";
3816 let event = StatusEvent::parse(StatusType::Server, content).unwrap();
3817 assert_eq!(event.status_type, StatusType::Server);
3818 assert_eq!(event.runlevel, Runlevel::Warn);
3819 assert_eq!(event.action, "NAMESERVER_ALL_DOWN");
3820 }
3821
3822 #[test]
3823 fn test_status_event_dns_up() {
3824 let content = "NOTICE NAMESERVER_STATUS NS=205.171.3.25 STATUS=UP";
3825 let event = StatusEvent::parse(StatusType::Server, content).unwrap();
3826 assert_eq!(event.action, "NAMESERVER_STATUS");
3827 assert_eq!(event.arguments.get("STATUS"), Some(&"UP".to_string()));
3828 }
3829
3830 #[test]
3831 fn test_conf_changed_event() {
3832 let lines = vec![
3833 "ExitNodes=caerSidi".to_string(),
3834 "ExitPolicy".to_string(),
3835 "MaxCircuitDirtiness=20".to_string(),
3836 ];
3837 let event = ConfChangedEvent::parse(&lines).unwrap();
3838 assert_eq!(
3839 event.changed.get("ExitNodes"),
3840 Some(&vec!["caerSidi".to_string()])
3841 );
3842 assert_eq!(
3843 event.changed.get("MaxCircuitDirtiness"),
3844 Some(&vec!["20".to_string()])
3845 );
3846 assert_eq!(event.unset, vec!["ExitPolicy".to_string()]);
3847 }
3848
3849 #[test]
3850 fn test_conf_changed_event_multiple_values() {
3851 let lines = vec![
3852 "ExitPolicy=accept 34.3.4.5".to_string(),
3853 "ExitPolicy=accept 3.4.53.3".to_string(),
3854 "MaxCircuitDirtiness=20".to_string(),
3855 ];
3856 let event = ConfChangedEvent::parse(&lines).unwrap();
3857 assert_eq!(
3858 event.changed.get("ExitPolicy"),
3859 Some(&vec![
3860 "accept 34.3.4.5".to_string(),
3861 "accept 3.4.53.3".to_string()
3862 ])
3863 );
3864 assert_eq!(
3865 event.changed.get("MaxCircuitDirtiness"),
3866 Some(&vec!["20".to_string()])
3867 );
3868 assert!(event.unset.is_empty());
3869 }
3870
3871 #[test]
3872 fn test_network_liveness_event() {
3873 let event = NetworkLivenessEvent::parse("UP").unwrap();
3874 assert_eq!(event.status, "UP");
3875
3876 let event = NetworkLivenessEvent::parse("DOWN").unwrap();
3877 assert_eq!(event.status, "DOWN");
3878 }
3879
3880 #[test]
3881 fn test_network_liveness_event_other_status() {
3882 let event = NetworkLivenessEvent::parse("OTHER_STATUS key=value").unwrap();
3883 assert_eq!(event.status, "OTHER_STATUS");
3884 }
3885
3886 #[test]
3887 fn test_circuit_bandwidth_event() {
3888 let content = "ID=11 READ=272 WRITTEN=817";
3889 let event = CircuitBandwidthEvent::parse(content).unwrap();
3890 assert_eq!(event.id.0, "11");
3891 assert_eq!(event.read, 272);
3892 assert_eq!(event.written, 817);
3893 assert_eq!(event.time, None);
3894 }
3895
3896 #[test]
3897 fn test_circuit_bandwidth_event_with_time() {
3898 let content = "ID=11 READ=272 WRITTEN=817 TIME=2012-12-06T13:51:11.433755";
3899 let event = CircuitBandwidthEvent::parse(content).unwrap();
3900 assert_eq!(event.id.0, "11");
3901 assert!(event.time.is_some());
3902 }
3903
3904 #[test]
3905 fn test_circuit_bandwidth_event_invalid_written() {
3906 let content = "ID=11 READ=272 WRITTEN=817.7";
3907 assert!(CircuitBandwidthEvent::parse(content).is_err());
3908 }
3909
3910 #[test]
3911 fn test_circuit_bandwidth_event_missing_id() {
3912 let content = "READ=272 WRITTEN=817";
3913 assert!(CircuitBandwidthEvent::parse(content).is_err());
3914 }
3915
3916 #[test]
3917 fn test_connection_bandwidth_event() {
3918 let content = "ID=11 TYPE=DIR READ=272 WRITTEN=817";
3919 let event = ConnectionBandwidthEvent::parse(content).unwrap();
3920 assert_eq!(event.id, "11");
3921 assert_eq!(event.conn_type, ConnectionType::Dir);
3922 assert_eq!(event.read, 272);
3923 assert_eq!(event.written, 817);
3924 }
3925
3926 #[test]
3927 fn test_connection_bandwidth_event_invalid_written() {
3928 let content = "ID=11 TYPE=DIR READ=272 WRITTEN=817.7";
3929 assert!(ConnectionBandwidthEvent::parse(content).is_err());
3930 }
3931
3932 #[test]
3933 fn test_connection_bandwidth_event_missing_id() {
3934 let content = "TYPE=DIR READ=272 WRITTEN=817";
3935 assert!(ConnectionBandwidthEvent::parse(content).is_err());
3936 }
3937
3938 #[test]
3939 fn test_hs_desc_event() {
3940 let content = "REQUESTED ajhb7kljbiru65qo NO_AUTH $67B2BDA4264D8A189D9270E28B1D30A262838243=europa1 b3oeducbhjmbqmgw2i3jtz4fekkrinwj";
3941 let event = HsDescEvent::parse(content).unwrap();
3942 assert_eq!(event.action, HsDescAction::Requested);
3943 assert_eq!(event.address, "ajhb7kljbiru65qo");
3944 assert_eq!(event.authentication, Some(HsAuth::NoAuth));
3945 assert_eq!(
3946 event.directory,
3947 Some("$67B2BDA4264D8A189D9270E28B1D30A262838243=europa1".to_string())
3948 );
3949 assert_eq!(
3950 event.directory_fingerprint,
3951 Some("67B2BDA4264D8A189D9270E28B1D30A262838243".to_string())
3952 );
3953 assert_eq!(event.directory_nickname, Some("europa1".to_string()));
3954 assert_eq!(
3955 event.descriptor_id,
3956 Some("b3oeducbhjmbqmgw2i3jtz4fekkrinwj".to_string())
3957 );
3958 assert_eq!(event.reason, None);
3959 }
3960
3961 #[test]
3962 fn test_hs_desc_event_no_desc_id() {
3963 let content =
3964 "REQUESTED ajhb7kljbiru65qo NO_AUTH $67B2BDA4264D8A189D9270E28B1D30A262838243";
3965 let event = HsDescEvent::parse(content).unwrap();
3966 assert_eq!(
3967 event.directory,
3968 Some("$67B2BDA4264D8A189D9270E28B1D30A262838243".to_string())
3969 );
3970 assert_eq!(
3971 event.directory_fingerprint,
3972 Some("67B2BDA4264D8A189D9270E28B1D30A262838243".to_string())
3973 );
3974 assert_eq!(event.directory_nickname, None);
3975 assert_eq!(event.descriptor_id, None);
3976 assert_eq!(event.reason, None);
3977 }
3978
3979 #[test]
3980 fn test_hs_desc_event_not_found() {
3981 let content = "REQUESTED ajhb7kljbiru65qo NO_AUTH UNKNOWN";
3982 let event = HsDescEvent::parse(content).unwrap();
3983 assert_eq!(event.directory, None);
3984 assert_eq!(event.directory_fingerprint, None);
3985 assert_eq!(event.directory_nickname, None);
3986 assert_eq!(event.descriptor_id, None);
3987 assert_eq!(event.reason, None);
3988 }
3989
3990 #[test]
3991 fn test_hs_desc_event_failed() {
3992 let content = "FAILED ajhb7kljbiru65qo NO_AUTH $67B2BDA4264D8A189D9270E28B1D30A262838243 b3oeducbhjmbqmgw2i3jtz4fekkrinwj REASON=NOT_FOUND";
3993 let event = HsDescEvent::parse(content).unwrap();
3994 assert_eq!(event.action, HsDescAction::Failed);
3995 assert_eq!(event.address, "ajhb7kljbiru65qo");
3996 assert_eq!(event.authentication, Some(HsAuth::NoAuth));
3997 assert_eq!(
3998 event.directory,
3999 Some("$67B2BDA4264D8A189D9270E28B1D30A262838243".to_string())
4000 );
4001 assert_eq!(
4002 event.directory_fingerprint,
4003 Some("67B2BDA4264D8A189D9270E28B1D30A262838243".to_string())
4004 );
4005 assert_eq!(event.directory_nickname, None);
4006 assert_eq!(
4007 event.descriptor_id,
4008 Some("b3oeducbhjmbqmgw2i3jtz4fekkrinwj".to_string())
4009 );
4010 assert_eq!(event.reason, Some(HsDescReason::NotFound));
4011 }
4012
4013 #[test]
4014 fn test_parsed_event_dispatch() {
4015 let event = ParsedEvent::parse("BW", "100 200", None).unwrap();
4016 match event {
4017 ParsedEvent::Bandwidth(bw) => {
4018 assert_eq!(bw.read, 100);
4019 assert_eq!(bw.written, 200);
4020 }
4021 _ => panic!("expected bandwidth event"),
4022 }
4023
4024 let event = ParsedEvent::parse("CIRC", "1 BUILT", None).unwrap();
4025 match event {
4026 ParsedEvent::Circuit(circ) => {
4027 assert_eq!(circ.id.0, "1");
4028 assert_eq!(circ.status, CircStatus::Built);
4029 }
4030 _ => panic!("expected circuit event"),
4031 }
4032 }
4033
4034 #[test]
4035 fn test_parsed_event_log_events() {
4036 let event = ParsedEvent::parse("DEBUG", "test debug message", None).unwrap();
4037 match event {
4038 ParsedEvent::Log(log) => {
4039 assert_eq!(log.runlevel, Runlevel::Debug);
4040 assert_eq!(log.message, "test debug message");
4041 }
4042 _ => panic!("expected log event"),
4043 }
4044
4045 let event = ParsedEvent::parse("INFO", "test info message", None).unwrap();
4046 match event {
4047 ParsedEvent::Log(log) => {
4048 assert_eq!(log.runlevel, Runlevel::Info);
4049 }
4050 _ => panic!("expected log event"),
4051 }
4052
4053 let event = ParsedEvent::parse("NOTICE", "test notice message", None).unwrap();
4054 match event {
4055 ParsedEvent::Log(log) => {
4056 assert_eq!(log.runlevel, Runlevel::Notice);
4057 }
4058 _ => panic!("expected log event"),
4059 }
4060
4061 let event = ParsedEvent::parse("WARN", "test warn message", None).unwrap();
4062 match event {
4063 ParsedEvent::Log(log) => {
4064 assert_eq!(log.runlevel, Runlevel::Warn);
4065 }
4066 _ => panic!("expected log event"),
4067 }
4068
4069 let event = ParsedEvent::parse("ERR", "test error message", None).unwrap();
4070 match event {
4071 ParsedEvent::Log(log) => {
4072 assert_eq!(log.runlevel, Runlevel::Err);
4073 }
4074 _ => panic!("expected log event"),
4075 }
4076 }
4077
4078 #[test]
4079 fn test_parsed_event_status_events() {
4080 let event = ParsedEvent::parse("STATUS_GENERAL", "NOTICE CONSENSUS_ARRIVED", None).unwrap();
4081 match event {
4082 ParsedEvent::Status(status) => {
4083 assert_eq!(status.status_type, StatusType::General);
4084 assert_eq!(status.action, "CONSENSUS_ARRIVED");
4085 }
4086 _ => panic!("expected status event"),
4087 }
4088
4089 let event = ParsedEvent::parse("STATUS_CLIENT", "NOTICE ENOUGH_DIR_INFO", None).unwrap();
4090 match event {
4091 ParsedEvent::Status(status) => {
4092 assert_eq!(status.status_type, StatusType::Client);
4093 }
4094 _ => panic!("expected status event"),
4095 }
4096
4097 let event = ParsedEvent::parse(
4098 "STATUS_SERVER",
4099 "NOTICE CHECKING_REACHABILITY ORADDRESS=127.0.0.1:9050",
4100 None,
4101 )
4102 .unwrap();
4103 match event {
4104 ParsedEvent::Status(status) => {
4105 assert_eq!(status.status_type, StatusType::Server);
4106 }
4107 _ => panic!("expected status event"),
4108 }
4109 }
4110
4111 #[test]
4112 fn test_parsed_event_unknown() {
4113 let event = ParsedEvent::parse("UNKNOWN_EVENT", "some content", None).unwrap();
4114 match event {
4115 ParsedEvent::Unknown {
4116 event_type,
4117 content,
4118 } => {
4119 assert_eq!(event_type, "UNKNOWN_EVENT");
4120 assert_eq!(content, "some content");
4121 }
4122 _ => panic!("expected unknown event"),
4123 }
4124 }
4125
4126 #[test]
4127 fn test_parse_circuit_path() {
4128 let path = parse_circuit_path("$999A226EBED397F331B612FE1E4CFAE5C1F201BA=piyaz");
4129 assert_eq!(path.len(), 1);
4130 assert_eq!(path[0].0, "999A226EBED397F331B612FE1E4CFAE5C1F201BA");
4131 assert_eq!(path[0].1, Some("piyaz".to_string()));
4132
4133 let path = parse_circuit_path(
4134 "$E57A476CD4DFBD99B4EE52A100A58610AD6E80B9,hamburgerphone,PrivacyRepublic14",
4135 );
4136 assert_eq!(path.len(), 3);
4137 }
4138
4139 #[test]
4140 fn test_parse_relay_endpoint() {
4141 let (fp, nick) = parse_relay_endpoint("$36B5DBA788246E8369DBAF58577C6BC044A9A374");
4142 assert_eq!(fp, "36B5DBA788246E8369DBAF58577C6BC044A9A374");
4143 assert_eq!(nick, None);
4144
4145 let (fp, nick) = parse_relay_endpoint("$5D0034A368E0ABAF663D21847E1C9B6CFA09752A=caerSidi");
4146 assert_eq!(fp, "5D0034A368E0ABAF663D21847E1C9B6CFA09752A");
4147 assert_eq!(nick, Some("caerSidi".to_string()));
4148
4149 let (fp, nick) = parse_relay_endpoint("$B4BE08B22D4D2923EDC3970FD1B93D0448C6D8FF~Unnamed");
4150 assert_eq!(fp, "B4BE08B22D4D2923EDC3970FD1B93D0448C6D8FF");
4151 assert_eq!(nick, Some("Unnamed".to_string()));
4152 }
4153
4154 #[test]
4155 fn test_parse_target() {
4156 let (host, port) = parse_target("encrypted.google.com:443").unwrap();
4157 assert_eq!(host, "encrypted.google.com");
4158 assert_eq!(port, 443);
4159
4160 let (host, port) = parse_target("74.125.227.129:443").unwrap();
4161 assert_eq!(host, "74.125.227.129");
4162 assert_eq!(port, 443);
4163
4164 let (host, port) = parse_target("www.google.com:0").unwrap();
4165 assert_eq!(host, "www.google.com");
4166 assert_eq!(port, 0);
4167 }
4168
4169 #[test]
4170 fn test_parse_iso_timestamp() {
4171 let dt = parse_iso_timestamp("2012-11-08T16:48:38.417238").unwrap();
4172 assert_eq!(dt.year(), 2012);
4173 assert_eq!(dt.month(), 11);
4174 assert_eq!(dt.day(), 8);
4175 assert_eq!(dt.hour(), 16);
4176 assert_eq!(dt.minute(), 48);
4177 assert_eq!(dt.second(), 38);
4178
4179 let dt = parse_iso_timestamp("2012-12-06T13:51:11.433755").unwrap();
4180 assert_eq!(dt.year(), 2012);
4181 assert_eq!(dt.month(), 12);
4182 assert_eq!(dt.day(), 6);
4183 }
4184
4185 #[test]
4186 fn test_parse_build_flags() {
4187 let flags = parse_build_flags("NEED_CAPACITY");
4188 assert_eq!(flags, vec![CircBuildFlag::NeedCapacity]);
4189
4190 let flags = parse_build_flags("IS_INTERNAL,NEED_CAPACITY");
4191 assert_eq!(
4192 flags,
4193 vec![CircBuildFlag::IsInternal, CircBuildFlag::NeedCapacity]
4194 );
4195
4196 let flags = parse_build_flags("ONEHOP_TUNNEL,IS_INTERNAL,NEED_CAPACITY,NEED_UPTIME");
4197 assert_eq!(
4198 flags,
4199 vec![
4200 CircBuildFlag::OneHopTunnel,
4201 CircBuildFlag::IsInternal,
4202 CircBuildFlag::NeedCapacity,
4203 CircBuildFlag::NeedUptime
4204 ]
4205 );
4206 }
4207}