Skip to main content

stem/
events.rs

1use std::collections::{HashMap, VecDeque};
2use std::time::SystemTime;
3
4use chrono::NaiveDateTime;
5
6use crate::address::{is_valid_ipv4_address, is_valid_ipv6_address, parse_port};
7use crate::descriptor::hidden_service::HiddenServiceDescriptor;
8use crate::descriptor::router_status::RouterStatusEntryV3;
9use crate::enumerations::string_enum;
10use crate::enumerations::*;
11use crate::error::{Error, Result};
12use crate::formatting::{parse_iso_timestamp, parse_timestamp};
13use crate::response::{ControlMessage, unescape_bytes};
14use crate::validation::{
15    is_valid_circuit_id, is_valid_connection_id, is_valid_fingerprint, is_valid_nickname,
16    is_valid_stream_id,
17};
18use crate::version::Requirement;
19
20string_enum!(EventType {
21    AddrMap = "ADDRMAP",
22    AuthDirNewDescs = "AUTHDIR_NEWDESCS",
23    BuildTimeoutSet = "BUILDTIMEOUT_SET",
24    Bw = "BW",
25    CellStats = "CELL_STATS",
26    Circ = "CIRC",
27    CircBw = "CIRC_BW",
28    CircMinor = "CIRC_MINOR",
29    ConfChanged = "CONF_CHANGED",
30    ConnBw = "CONN_BW",
31    ClientsSeen = "CLIENTS_SEEN",
32    Debug = "DEBUG",
33    DescChanged = "DESCCHANGED",
34    Err = "ERR",
35    Guard = "GUARD",
36    HsDesc = "HS_DESC",
37    HsDescContent = "HS_DESC_CONTENT",
38    Info = "INFO",
39    NetworkLiveness = "NETWORK_LIVENESS",
40    NewConsensus = "NEWCONSENSUS",
41    NewDesc = "NEWDESC",
42    Notice = "NOTICE",
43    Ns = "NS",
44    OrConn = "ORCONN",
45    PtLog = "PT_LOG",
46    PtStatus = "PT_STATUS",
47    Signal = "SIGNAL",
48    StatusClient = "STATUS_CLIENT",
49    StatusGeneral = "STATUS_GENERAL",
50    StatusServer = "STATUS_SERVER",
51    Stream = "STREAM",
52    StreamBw = "STREAM_BW",
53    TbEmpty = "TB_EMPTY",
54    TransportLaunched = "TRANSPORT_LAUNCHED",
55    Warn = "WARN",
56    MalformedEvents = "MALFORMED_EVENTS",
57});
58
59impl EventType {
60    pub fn is_sendable(&self) -> bool {
61        let text = self.as_str();
62        *self != EventType::MalformedEvents
63            && !text.is_empty()
64            && text
65                .bytes()
66                .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
67    }
68
69    pub fn version_added(&self) -> Option<Requirement> {
70        Some(match self {
71            Self::AuthDirNewDescs => Requirement::EventAuthdirNewdescs,
72            Self::BuildTimeoutSet => Requirement::EventBuildtimeoutSet,
73            Self::CellStats => Requirement::EventCellStats,
74            Self::CircBw => Requirement::EventCircBw,
75            Self::CircMinor => Requirement::EventCircMinor,
76            Self::ClientsSeen => Requirement::EventClientsSeen,
77            Self::ConfChanged => Requirement::EventConfChanged,
78            Self::ConnBw => Requirement::EventConnBw,
79            Self::DescChanged => Requirement::EventDescChanged,
80            Self::Guard => Requirement::EventGuard,
81            Self::HsDesc => Requirement::EventHsDesc,
82            Self::HsDescContent => Requirement::EventHsDescContent,
83            Self::NetworkLiveness => Requirement::EventNetworkLiveness,
84            Self::NewConsensus => Requirement::EventNewConsensus,
85            Self::Ns => Requirement::EventNs,
86            Self::Signal => Requirement::EventSignal,
87            Self::StatusClient | Self::StatusGeneral | Self::StatusServer => {
88                Requirement::EventStatus
89            }
90            Self::StreamBw => Requirement::EventStreamBw,
91            Self::TbEmpty => Requirement::EventTbEmpty,
92            Self::TransportLaunched => Requirement::EventTransportLaunched,
93            _ => return None,
94        })
95    }
96}
97
98pub type CircuitEntry = (Option<String>, Option<String>);
99
100pub fn parse_circuit_entry(entry: &str) -> Result<CircuitEntry> {
101    let (fingerprint, nickname) =
102        if let Some((fingerprint, nickname)) = entry.split_once('=') {
103            if nickname.contains('=') {
104                return Err(Error::protocol(format!(
105                    "Fingerprint in the circuit path is malformed ({entry})"
106                )));
107            }
108            (Some(fingerprint), Some(nickname))
109        } else if let Some((fingerprint, nickname)) = entry.split_once('~') {
110            if nickname.contains('~') {
111                return Err(Error::protocol(format!(
112                    "Fingerprint in the circuit path is malformed ({entry})"
113                )));
114            }
115            (Some(fingerprint), Some(nickname))
116        } else if entry.starts_with('$') {
117            (Some(entry), None)
118        } else {
119            (None, Some(entry))
120        };
121    if let Some(fingerprint) = fingerprint
122        && !is_valid_fingerprint(fingerprint, true)
123    {
124        return Err(Error::protocol(format!(
125            "Fingerprint in the circuit path is malformed ({fingerprint})"
126        )));
127    }
128    if let Some(nickname) = nickname
129        && !is_valid_nickname(nickname)
130    {
131        return Err(Error::protocol(format!(
132            "Nickname in the circuit path is malformed ({nickname})"
133        )));
134    }
135    Ok((
136        fingerprint.map(|fingerprint| fingerprint[1..].to_string()),
137        nickname.map(str::to_string),
138    ))
139}
140
141pub fn parse_circuit_path(path: &str) -> Result<Vec<CircuitEntry>> {
142    if path.is_empty() {
143        return Ok(Vec::new());
144    }
145    path.split(',')
146        .map(parse_circuit_entry)
147        .collect::<Result<Vec<_>>>()
148        .map_err(|error| Error::protocol(format!("{error}: {path}")))
149}
150
151#[derive(Clone, Copy, PartialEq, Eq)]
152enum Quoting {
153    Plain,
154    Optional,
155}
156
157struct Arguments {
158    text: String,
159    positional: VecDeque<String>,
160    keywords: HashMap<String, String>,
161}
162
163fn is_keyword_character(byte: u8) -> bool {
164    byte.is_ascii_alphanumeric() || byte == b'_'
165}
166
167fn peel_quoted_keyword(content: &str) -> Option<(&str, &str, &str)> {
168    let body = content.strip_suffix('"')?;
169    let bytes = body.as_bytes();
170    let mut search_end = bytes.len();
171    while let Some(position) = body[..search_end].rfind("=\"") {
172        let key_start = bytes[..position]
173            .iter()
174            .rposition(|byte| !is_keyword_character(*byte))
175            .map_or(0, |index| index + 1);
176        let has_space = key_start > 0 && bytes[key_start - 1] == b' ';
177        if key_start < position && has_space {
178            return Some((
179                &body[..key_start - 1],
180                &body[key_start..position],
181                &body[position + 2..],
182            ));
183        }
184        search_end = position;
185    }
186    None
187}
188
189fn peel_plain_keyword(content: &str) -> Option<(&str, &str, &str)> {
190    let space = content.rfind(' ')?;
191    let token = &content[space + 1..];
192    let (key, value) = token.split_once('=')?;
193    let is_key = !key.is_empty() && key.bytes().all(is_keyword_character);
194    is_key.then_some((&content[..space], key, value))
195}
196
197impl Arguments {
198    fn parse(message: &ControlMessage) -> Self {
199        let text = message.to_string();
200        let first_line = text.lines().next().unwrap_or("").to_string();
201        let mut content = first_line.as_str();
202        let mut keywords = HashMap::new();
203        while let Some((rest, key, value)) =
204            peel_quoted_keyword(content).or_else(|| peel_plain_keyword(content))
205        {
206            keywords.insert(key.to_string(), value.to_string());
207            content = rest;
208        }
209        let positional = content
210            .split_whitespace()
211            .skip(1)
212            .map(str::to_string)
213            .collect();
214        Self {
215            text,
216            positional,
217            keywords,
218        }
219    }
220
221    fn take(&mut self, name: &str, quoting: Quoting) -> Result<Option<String>> {
222        let Some(first) = self.positional.pop_front() else {
223            return Ok(None);
224        };
225        let is_quoted = match quoting {
226            Quoting::Plain => false,
227            Quoting::Optional => first.starts_with('"'),
228        };
229        if !is_quoted {
230            return Ok(Some(first));
231        }
232        if !first.starts_with('"') {
233            return Err(self.error(format!(
234                "The {name} value should be quoted, but didn't have a starting quote"
235            )));
236        }
237        let mut pieces = vec![first];
238        loop {
239            let Some(next) = self.positional.pop_front() else {
240                return Err(self.error(format!(
241                    "The {name} value should be quoted, but didn't have an ending quote"
242                )));
243            };
244            let finished = next.ends_with('"');
245            pieces.push(next);
246            if finished {
247                break;
248            }
249        }
250        let joined = pieces.join(" ");
251        Ok(Some(joined[1..joined.len() - 1].to_string()))
252    }
253
254    fn require(&mut self, name: &str, quoting: Quoting) -> Result<String> {
255        self.take(name, quoting)?
256            .ok_or_else(|| self.error(format!("Event is missing its {name}")))
257    }
258
259    fn error(&self, message: impl std::fmt::Display) -> Error {
260        Error::protocol(format!("{message}: {}", self.text))
261    }
262
263    fn keyword(&self, name: &str) -> Option<String> {
264        self.keywords.get(name).cloned()
265    }
266
267    fn number(&self, name: &str, label: &str) -> Result<Option<u64>> {
268        self.keyword(name)
269            .map(|value| self.parse_number(&value, label))
270            .transpose()
271    }
272
273    fn parse_number(&self, value: &str, label: &str) -> Result<u64> {
274        let is_digits =
275            !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit());
276        match is_digits.then(|| value.parse().ok()).flatten() {
277            Some(number) => Ok(number),
278            None => Err(self.error(format!(
279                "{label} should be a positive numeric value, received: {value}"
280            ))),
281        }
282    }
283
284    fn iso_timestamp(&self, value: Option<String>) -> Result<Option<NaiveDateTime>> {
285        value
286            .map(|timestamp| {
287                parse_iso_timestamp(&timestamp).map_err(|error| {
288                    self.error(format!("Unable to parse timestamp ({error})"))
289                })
290            })
291            .transpose()
292    }
293}
294
295fn recognized<T: std::str::FromStr<Err = std::convert::Infallible>>(
296    event_type: &str,
297    attribute: &str,
298    value: &str,
299    is_recognized: impl Fn(&T) -> bool,
300) -> T {
301    let parsed: T = value.parse().unwrap_or_else(|never| match never {});
302    if !is_recognized(&parsed) {
303        log::info!(
304            "{event_type} event had an unrecognized {attribute} ({value}). Maybe a new \
305            addition to the control protocol?"
306        );
307    }
308    parsed
309}
310
311macro_rules! typed {
312    ($event_type:expr, $attribute:expr, $value:expr, $enum:ty) => {
313        recognized::<$enum>($event_type, $attribute, $value, <$enum>::is_recognized)
314    };
315}
316
317macro_rules! typed_option {
318    ($event_type:expr, $attribute:expr, $value:expr, $enum:ty) => {
319        $value
320            .as_deref()
321            .map(|text| typed!($event_type, $attribute, text, $enum))
322    };
323}
324
325#[derive(Debug, Clone, serde::Serialize)]
326pub struct AddrMapEvent {
327    pub hostname: String,
328    pub destination: Option<String>,
329    pub expiry: Option<NaiveDateTime>,
330    pub error: Option<String>,
331    pub utc_expiry: Option<NaiveDateTime>,
332    pub cached: Option<bool>,
333}
334
335#[derive(Debug, Clone, serde::Serialize)]
336pub struct AuthDirNewDescEvent {
337    pub action: String,
338    pub message: String,
339    pub descriptor: String,
340}
341
342#[derive(Debug, Clone, serde::Serialize)]
343pub struct BandwidthEvent {
344    pub read: u64,
345    pub written: u64,
346}
347
348#[derive(Debug, Clone, serde::Serialize)]
349pub struct BuildTimeoutSetEvent {
350    pub set_type: TimeoutSetType,
351    pub total_times: Option<u64>,
352    pub timeout: Option<u64>,
353    pub xm: Option<u64>,
354    pub alpha: Option<f64>,
355    pub quantile: Option<f64>,
356    pub timeout_rate: Option<f64>,
357    pub close_timeout: Option<u64>,
358    pub close_rate: Option<f64>,
359}
360
361#[derive(Debug, Clone, serde::Serialize)]
362pub struct CircuitEvent {
363    pub id: String,
364    pub status: CircStatus,
365    pub path: Vec<CircuitEntry>,
366    pub build_flags: Option<Vec<CircBuildFlag>>,
367    pub purpose: Option<CircPurpose>,
368    pub hs_state: Option<HiddenServiceState>,
369    pub rend_query: Option<String>,
370    pub created: Option<NaiveDateTime>,
371    pub reason: Option<CircClosureReason>,
372    pub remote_reason: Option<CircClosureReason>,
373    pub socks_username: Option<String>,
374    pub socks_password: Option<String>,
375}
376
377#[derive(Debug, Clone, serde::Serialize)]
378pub struct CircMinorEvent {
379    pub id: String,
380    pub event: CircEvent,
381    pub path: Vec<CircuitEntry>,
382    pub build_flags: Option<Vec<CircBuildFlag>>,
383    pub purpose: Option<CircPurpose>,
384    pub hs_state: Option<HiddenServiceState>,
385    pub rend_query: Option<String>,
386    pub created: Option<NaiveDateTime>,
387    pub old_purpose: Option<CircPurpose>,
388    pub old_hs_state: Option<HiddenServiceState>,
389}
390
391#[derive(Debug, Clone, serde::Serialize)]
392pub struct ClientsSeenEvent {
393    pub start_time: Option<NaiveDateTime>,
394    pub locales: Option<HashMap<String, u64>>,
395    pub ip_versions: Option<HashMap<String, u64>>,
396}
397
398#[derive(Debug, Clone, serde::Serialize)]
399pub struct ConfChangedEvent {
400    pub changed: HashMap<String, Vec<String>>,
401    pub unset: Vec<String>,
402    pub config: HashMap<String, Option<String>>,
403}
404
405#[derive(Debug, Clone, serde::Serialize)]
406pub struct GuardEvent {
407    pub guard_type: GuardType,
408    pub endpoint: String,
409    pub endpoint_fingerprint: Option<String>,
410    pub endpoint_nickname: Option<String>,
411    pub status: GuardStatus,
412}
413
414#[derive(Debug, Clone, serde::Serialize)]
415pub struct HsDescEvent {
416    pub action: HsDescAction,
417    pub address: String,
418    pub authentication: HsAuth,
419    pub directory: String,
420    pub directory_fingerprint: Option<String>,
421    pub directory_nickname: Option<String>,
422    pub descriptor_id: Option<String>,
423    pub reason: Option<HsDescReason>,
424    pub replica: Option<u64>,
425    pub index: Option<String>,
426}
427
428#[derive(Debug, Clone, serde::Serialize)]
429pub struct HsDescContentEvent {
430    pub address: Option<String>,
431    pub descriptor_id: String,
432    pub directory: String,
433    pub directory_fingerprint: Option<String>,
434    pub directory_nickname: Option<String>,
435    pub descriptor: Option<HiddenServiceDescriptor>,
436}
437
438#[derive(Debug, Clone, serde::Serialize)]
439pub struct LogEvent {
440    pub runlevel: Runlevel,
441    pub message: String,
442}
443
444#[derive(Debug, Clone, serde::Serialize)]
445pub struct NetworkStatusEvent {
446    pub desc: Vec<RouterStatusEntryV3>,
447}
448
449#[derive(Debug, Clone, serde::Serialize)]
450pub struct NetworkLivenessEvent {
451    pub status: String,
452}
453
454#[derive(Debug, Clone, serde::Serialize)]
455pub struct NewConsensusEvent {
456    pub consensus_content: String,
457}
458
459impl NewConsensusEvent {
460    pub fn entries(&self, validate: bool) -> Result<Vec<RouterStatusEntryV3>> {
461        RouterStatusEntryV3::parse_many(self.consensus_content.as_bytes(), validate)
462    }
463}
464
465#[derive(Debug, Clone, serde::Serialize)]
466pub struct NewDescEvent {
467    pub relays: Vec<CircuitEntry>,
468}
469
470#[derive(Debug, Clone, serde::Serialize)]
471pub struct OrConnEvent {
472    pub endpoint: String,
473    pub endpoint_fingerprint: Option<String>,
474    pub endpoint_nickname: Option<String>,
475    pub endpoint_address: Option<String>,
476    pub endpoint_port: Option<u16>,
477    pub status: OrStatus,
478    pub reason: Option<OrClosureReason>,
479    pub circ_count: Option<u64>,
480    pub id: Option<String>,
481}
482
483#[derive(Debug, Clone, serde::Serialize)]
484pub struct PtLogEvent {
485    pub program: String,
486    pub message: String,
487}
488
489#[derive(Debug, Clone, serde::Serialize)]
490pub struct PtStatusEvent {
491    pub program: String,
492    pub transport: String,
493    pub message: String,
494}
495
496#[derive(Debug, Clone, serde::Serialize)]
497pub struct SignalEvent {
498    pub signal: Signal,
499}
500
501#[derive(Debug, Clone, serde::Serialize)]
502pub struct StatusEvent {
503    pub status_type: StatusType,
504    pub runlevel: Runlevel,
505    pub action: String,
506    pub arguments: HashMap<String, String>,
507}
508
509#[derive(Debug, Clone, serde::Serialize)]
510pub struct StreamEvent {
511    pub id: String,
512    pub status: StreamStatus,
513    pub circ_id: Option<String>,
514    pub target: String,
515    pub target_address: String,
516    pub target_port: u16,
517    pub reason: Option<StreamClosureReason>,
518    pub remote_reason: Option<StreamClosureReason>,
519    pub source: Option<StreamSource>,
520    pub source_addr: Option<String>,
521    pub source_address: Option<String>,
522    pub source_port: Option<u16>,
523    pub purpose: Option<StreamPurpose>,
524    pub socks_username: Option<String>,
525    pub socks_password: Option<String>,
526    pub client_protocol: Option<String>,
527    pub nym_epoch: Option<String>,
528    pub session_group: Option<String>,
529    pub iso_fields: Option<String>,
530}
531
532#[derive(Debug, Clone, serde::Serialize)]
533pub struct StreamBandwidthEvent {
534    pub id: String,
535    pub written: u64,
536    pub read: u64,
537    pub time: Option<NaiveDateTime>,
538}
539
540#[derive(Debug, Clone, serde::Serialize)]
541pub struct TransportLaunchedEvent {
542    pub transport_type: String,
543    pub name: String,
544    pub address: String,
545    pub port: u16,
546}
547
548#[derive(Debug, Clone, serde::Serialize)]
549pub struct ConnectionBandwidthEvent {
550    pub id: String,
551    pub conn_type: ConnectionType,
552    pub read: u64,
553    pub written: u64,
554}
555
556#[derive(Debug, Clone, serde::Serialize)]
557pub struct CircuitBandwidthEvent {
558    pub id: String,
559    pub read: u64,
560    pub written: u64,
561    pub delivered_read: Option<u64>,
562    pub delivered_written: Option<u64>,
563    pub overhead_read: Option<u64>,
564    pub overhead_written: Option<u64>,
565    pub time: Option<NaiveDateTime>,
566}
567
568#[derive(Debug, Clone, serde::Serialize)]
569pub struct CellStatsEvent {
570    pub id: Option<String>,
571    pub inbound_queue: Option<String>,
572    pub inbound_connection: Option<String>,
573    pub inbound_added: Option<HashMap<String, u64>>,
574    pub inbound_removed: Option<HashMap<String, u64>>,
575    pub inbound_time: Option<HashMap<String, u64>>,
576    pub outbound_queue: Option<String>,
577    pub outbound_connection: Option<String>,
578    pub outbound_added: Option<HashMap<String, u64>>,
579    pub outbound_removed: Option<HashMap<String, u64>>,
580    pub outbound_time: Option<HashMap<String, u64>>,
581}
582
583#[derive(Debug, Clone, serde::Serialize)]
584pub struct TokenBucketEmptyEvent {
585    pub bucket: TokenBucket,
586    pub id: Option<String>,
587    pub read: u64,
588    pub written: u64,
589    pub last_refill: u64,
590}
591
592#[derive(Debug, Clone, serde::Serialize)]
593#[serde(untagged)]
594pub enum EventData {
595    AddrMap(AddrMapEvent),
596    AuthDirNewDescs(AuthDirNewDescEvent),
597    Bandwidth(BandwidthEvent),
598    BuildTimeoutSet(BuildTimeoutSetEvent),
599    CellStats(CellStatsEvent),
600    Circuit(CircuitEvent),
601    CircuitBandwidth(CircuitBandwidthEvent),
602    CircMinor(CircMinorEvent),
603    ClientsSeen(ClientsSeenEvent),
604    ConfChanged(ConfChangedEvent),
605    ConnectionBandwidth(ConnectionBandwidthEvent),
606    DescChanged,
607    Guard(GuardEvent),
608    HsDesc(HsDescEvent),
609    HsDescContent(HsDescContentEvent),
610    Log(LogEvent),
611    NetworkLiveness(NetworkLivenessEvent),
612    NetworkStatus(NetworkStatusEvent),
613    NewConsensus(NewConsensusEvent),
614    NewDesc(NewDescEvent),
615    OrConn(OrConnEvent),
616    PtLog(PtLogEvent),
617    PtStatus(PtStatusEvent),
618    Signal(SignalEvent),
619    Status(StatusEvent),
620    Stream(StreamEvent),
621    StreamBandwidth(StreamBandwidthEvent),
622    TokenBucketEmpty(TokenBucketEmptyEvent),
623    TransportLaunched(TransportLaunchedEvent),
624    Unrecognized,
625    Malformed(String),
626}
627
628#[derive(Debug, Clone, serde::Serialize)]
629pub struct Event {
630    pub event_type: String,
631    pub data: EventData,
632    pub positional_args: Vec<String>,
633    pub keyword_args: HashMap<String, String>,
634    #[serde(skip)]
635    pub message: ControlMessage,
636}
637
638impl Event {
639    pub fn arrived_at(&self) -> SystemTime {
640        self.message.arrived_at
641    }
642
643    pub fn is_malformed(&self) -> bool {
644        matches!(self.data, EventData::Malformed(_))
645    }
646
647    pub fn listener_type(&self) -> EventType {
648        match self.is_malformed() {
649            true => EventType::MalformedEvents,
650            false => self.event_type.as_str().into(),
651        }
652    }
653
654    pub fn malformed(message: ControlMessage, reason: String) -> Self {
655        let event_type = message
656            .to_string()
657            .split_whitespace()
658            .next()
659            .unwrap_or_default()
660            .to_string();
661        Self {
662            event_type,
663            data: EventData::Malformed(reason),
664            positional_args: Vec::new(),
665            keyword_args: HashMap::new(),
666            message,
667        }
668    }
669
670    pub fn parse(message: ControlMessage) -> Result<Self> {
671        let text = message.to_string();
672        let Some(event_type) = text.split_whitespace().next().map(str::to_string) else {
673            return Err(Error::protocol(
674                "Received a blank tor event. Events must at the very least have a type.",
675            ));
676        };
677        let mut arguments = Arguments::parse(&message);
678        let positional_args = arguments.positional.iter().cloned().collect();
679        let keyword_args = arguments.keywords.clone();
680        let data = parse_event_data(&event_type, &message, &mut arguments)?;
681        Ok(Self {
682            event_type,
683            data,
684            positional_args,
685            keyword_args,
686            message,
687        })
688    }
689
690    pub fn from_content(content: &str) -> Result<Self> {
691        Self::parse(ControlMessage::parse(content, true)?)
692    }
693}
694
695fn parse_event_data(
696    event_type: &str,
697    message: &ControlMessage,
698    arguments: &mut Arguments,
699) -> Result<EventData> {
700    Ok(match event_type {
701        "ADDRMAP" => EventData::AddrMap(parse_addrmap(arguments)?),
702        "AUTHDIR_NEWDESCS" => {
703            EventData::AuthDirNewDescs(parse_authdir_newdescs(arguments)?)
704        }
705        "BW" => EventData::Bandwidth(parse_bandwidth(arguments)?),
706        "BUILDTIMEOUT_SET" => {
707            EventData::BuildTimeoutSet(parse_buildtimeout_set(arguments)?)
708        }
709        "CELL_STATS" => EventData::CellStats(parse_cell_stats(arguments)?),
710        "CIRC" => EventData::Circuit(parse_circuit(arguments)?),
711        "CIRC_BW" => EventData::CircuitBandwidth(parse_circuit_bandwidth(arguments)?),
712        "CIRC_MINOR" => EventData::CircMinor(parse_circ_minor(arguments)?),
713        "CLIENTS_SEEN" => EventData::ClientsSeen(parse_clients_seen(arguments)?),
714        "CONF_CHANGED" => EventData::ConfChanged(parse_conf_changed(message)),
715        "CONN_BW" => {
716            EventData::ConnectionBandwidth(parse_connection_bandwidth(arguments)?)
717        }
718        "DESCCHANGED" => EventData::DescChanged,
719        "DEBUG" | "INFO" | "NOTICE" | "WARN" | "ERR" => {
720            EventData::Log(parse_log(event_type, message))
721        }
722        "GUARD" => EventData::Guard(parse_guard(arguments)?),
723        "HS_DESC" => EventData::HsDesc(parse_hs_desc(arguments)?),
724        "HS_DESC_CONTENT" => EventData::HsDescContent(parse_hs_desc_content(arguments)?),
725        "NETWORK_LIVENESS" => EventData::NetworkLiveness(NetworkLivenessEvent {
726            status: arguments.require("status", Quoting::Plain)?,
727        }),
728        "NEWCONSENSUS" => EventData::NewConsensus(parse_new_consensus(message)),
729        "NEWDESC" => EventData::NewDesc(parse_new_desc(message)?),
730        "NS" => EventData::NetworkStatus(parse_network_status(message)?),
731        "ORCONN" => EventData::OrConn(parse_or_conn(arguments)?),
732        "PT_LOG" => EventData::PtLog(parse_pt_log(message)?),
733        "PT_STATUS" => EventData::PtStatus(parse_pt_status(message)?),
734        "SIGNAL" => EventData::Signal(SignalEvent {
735            signal: typed!(
736                event_type,
737                "signal",
738                &arguments.require("signal", Quoting::Plain)?,
739                Signal
740            ),
741        }),
742        "STATUS_GENERAL" | "STATUS_CLIENT" | "STATUS_SERVER" => {
743            EventData::Status(parse_status(event_type, arguments)?)
744        }
745        "STREAM" => EventData::Stream(parse_stream(arguments)?),
746        "STREAM_BW" => EventData::StreamBandwidth(parse_stream_bandwidth(arguments)?),
747        "TB_EMPTY" => EventData::TokenBucketEmpty(parse_token_bucket_empty(arguments)?),
748        "TRANSPORT_LAUNCHED" => {
749            EventData::TransportLaunched(parse_transport_launched(arguments)?)
750        }
751        _ => EventData::Unrecognized,
752    })
753}
754
755fn parse_addrmap(arguments: &mut Arguments) -> Result<AddrMapEvent> {
756    let hostname = arguments.require("hostname", Quoting::Plain)?;
757    let destination = arguments.require("destination", Quoting::Plain)?;
758    let expiry = arguments.take("expiry", Quoting::Optional)?;
759    let expiry = match expiry.as_deref() {
760        None | Some("NEVER") => None,
761        Some(value) => Some(
762            parse_timestamp(value)
763                .map_err(|_| arguments.error("Unable to parse date in ADDRMAP event"))?,
764        ),
765    };
766    let utc_expiry = arguments
767        .keyword("EXPIRES")
768        .map(|value| parse_timestamp(&value))
769        .transpose()?;
770    let cached = match arguments.keyword("CACHED").as_deref() {
771        None => None,
772        Some("YES") => Some(true),
773        Some("NO") => Some(false),
774        Some(_) => {
775            return Err(arguments
776                .error("An ADDRMAP event's CACHED mapping can only be 'YES' or 'NO'"));
777        }
778    };
779    Ok(AddrMapEvent {
780        hostname,
781        destination: Some(destination).filter(|value| value != "<error>"),
782        expiry,
783        error: arguments.keyword("error"),
784        utc_expiry,
785        cached,
786    })
787}
788
789fn parse_authdir_newdescs(arguments: &Arguments) -> Result<AuthDirNewDescEvent> {
790    let lines: Vec<&str> = arguments.text.split('\n').collect();
791    if lines.len() < 5 {
792        return Err(Error::protocol(
793            "AUTHDIR_NEWDESCS events must contain lines for at least the type, action, \
794            message, descriptor, and terminating 'OK'",
795        ));
796    }
797    if lines[lines.len() - 1] != "OK" {
798        return Err(Error::protocol("AUTHDIR_NEWDESCS doesn't end with an 'OK'"));
799    }
800    Ok(AuthDirNewDescEvent {
801        action: lines[1].to_string(),
802        message: lines[2].to_string(),
803        descriptor: lines[3..lines.len() - 1].join("\n"),
804    })
805}
806
807fn parse_bandwidth(arguments: &mut Arguments) -> Result<BandwidthEvent> {
808    let read = arguments.take("read", Quoting::Plain)?;
809    let written = arguments.take("written", Quoting::Plain)?;
810    let (Some(read), Some(written)) = (read, written) else {
811        return Err(Error::protocol(
812            "BW event is missing its read or written value",
813        ));
814    };
815    let label = "A BW event's bytes sent and received";
816    Ok(BandwidthEvent {
817        read: arguments.parse_number(&read, label)?,
818        written: arguments.parse_number(&written, label)?,
819    })
820}
821
822fn parse_buildtimeout_set(arguments: &mut Arguments) -> Result<BuildTimeoutSetEvent> {
823    let set_type = arguments.require("set_type", Quoting::Plain)?;
824    let integer = |name: &str, label: &str| -> Result<Option<u64>> {
825        arguments
826            .keyword(name)
827            .map(|value| {
828                value.parse::<u64>().map_err(|_| {
829                    arguments.error(format!(
830                        "The {label} of a BUILDTIMEOUT_SET should be an integer"
831                    ))
832                })
833            })
834            .transpose()
835    };
836    let float = |name: &str, label: &str| -> Result<Option<f64>> {
837        arguments
838            .keyword(name)
839            .map(|value| {
840                value.parse::<f64>().map_err(|_| {
841                    arguments.error(format!(
842                        "The {label} of a BUILDTIMEOUT_SET should be a float"
843                    ))
844                })
845            })
846            .transpose()
847    };
848    Ok(BuildTimeoutSetEvent {
849        total_times: integer("TOTAL_TIMES", "total_times")?,
850        timeout: integer("TIMEOUT_MS", "timeout")?,
851        xm: integer("XM", "xm")?,
852        alpha: float("ALPHA", "alpha")?,
853        quantile: float("CUTOFF_QUANTILE", "quantile")?,
854        timeout_rate: float("TIMEOUT_RATE", "timeout_rate")?,
855        close_timeout: integer("CLOSE_MS", "close_timeout")?,
856        close_rate: float("CLOSE_RATE", "close_rate")?,
857        set_type: typed!("BUILDTIMEOUT_SET", "set_type", &set_type, TimeoutSetType),
858    })
859}
860
861fn parse_build_flags(
862    arguments: &Arguments,
863    event_type: &str,
864) -> Option<Vec<CircBuildFlag>> {
865    arguments.keyword("BUILD_FLAGS").map(|flags| {
866        flags
867            .split(',')
868            .map(|flag| typed!(event_type, "build_flags", flag, CircBuildFlag))
869            .collect()
870    })
871}
872
873fn validated_circuit_id(arguments: &Arguments, id: String) -> Result<String> {
874    match is_valid_circuit_id(&id) {
875        true => Ok(id),
876        false => Err(arguments.error(format!(
877            "Circuit IDs must be one to sixteen alphanumeric characters, got '{id}'"
878        ))),
879    }
880}
881
882fn parse_circuit(arguments: &mut Arguments) -> Result<CircuitEvent> {
883    let id = arguments.require("id", Quoting::Plain)?;
884    let status = arguments.require("status", Quoting::Plain)?;
885    let path = arguments.take("path", Quoting::Plain)?.unwrap_or_default();
886    let created = arguments.iso_timestamp(arguments.keyword("TIME_CREATED"))?;
887    Ok(CircuitEvent {
888        id: validated_circuit_id(arguments, id)?,
889        status: typed!("CIRC", "status", &status, CircStatus),
890        path: parse_circuit_path(&path)?,
891        build_flags: parse_build_flags(arguments, "CIRC"),
892        purpose: typed_option!(
893            "CIRC",
894            "purpose",
895            arguments.keyword("PURPOSE"),
896            CircPurpose
897        ),
898        hs_state: typed_option!(
899            "CIRC",
900            "hs_state",
901            arguments.keyword("HS_STATE"),
902            HiddenServiceState
903        ),
904        rend_query: arguments.keyword("REND_QUERY"),
905        created,
906        reason: typed_option!(
907            "CIRC",
908            "reason",
909            arguments.keyword("REASON"),
910            CircClosureReason
911        ),
912        remote_reason: typed_option!(
913            "CIRC",
914            "remote_reason",
915            arguments.keyword("REMOTE_REASON"),
916            CircClosureReason
917        ),
918        socks_username: arguments.keyword("SOCKS_USERNAME"),
919        socks_password: arguments.keyword("SOCKS_PASSWORD"),
920    })
921}
922
923fn parse_circ_minor(arguments: &mut Arguments) -> Result<CircMinorEvent> {
924    let id = arguments.require("id", Quoting::Plain)?;
925    let event = arguments.require("event", Quoting::Plain)?;
926    let path = arguments.take("path", Quoting::Plain)?.unwrap_or_default();
927    let created = arguments.iso_timestamp(arguments.keyword("TIME_CREATED"))?;
928    Ok(CircMinorEvent {
929        id: validated_circuit_id(arguments, id)?,
930        event: typed!("CIRC_MINOR", "event", &event, CircEvent),
931        path: parse_circuit_path(&path)?,
932        build_flags: parse_build_flags(arguments, "CIRC_MINOR"),
933        purpose: typed_option!(
934            "CIRC_MINOR",
935            "purpose",
936            arguments.keyword("PURPOSE"),
937            CircPurpose
938        ),
939        hs_state: typed_option!(
940            "CIRC_MINOR",
941            "hs_state",
942            arguments.keyword("HS_STATE"),
943            HiddenServiceState
944        ),
945        rend_query: arguments.keyword("REND_QUERY"),
946        created,
947        old_purpose: typed_option!(
948            "CIRC_MINOR",
949            "old_purpose",
950            arguments.keyword("OLD_PURPOSE"),
951            CircPurpose
952        ),
953        old_hs_state: typed_option!(
954            "CIRC_MINOR",
955            "old_hs_state",
956            arguments.keyword("OLD_HS_STATE"),
957            HiddenServiceState
958        ),
959    })
960}
961
962fn parse_count_mapping(
963    arguments: &Arguments,
964    value: &str,
965    kind: &str,
966    require_locale: bool,
967) -> Result<HashMap<String, u64>> {
968    let mut counts = HashMap::new();
969    for entry in value.split(',') {
970        let Some((key, count)) = entry.split_once('=') else {
971            return Err(arguments.error(format!(
972                "The CLIENTS_SEEN's {kind} should be a comma separated listing of \
973                '<key>=<count>' mappings"
974            )));
975        };
976        if require_locale && key.chars().count() != 2 {
977            return Err(arguments.error(format!(
978                "Locales should be a two character code, got '{key}'"
979            )));
980        }
981        let count = arguments.parse_number(count, &format!("{kind} count"))?;
982        if counts.insert(key.to_string(), count).is_some() && require_locale {
983            return Err(arguments
984                .error(format!("CountrySummary had multiple mappings for '{key}'")));
985        }
986    }
987    Ok(counts)
988}
989
990fn parse_clients_seen(arguments: &mut Arguments) -> Result<ClientsSeenEvent> {
991    let start_time = arguments
992        .keyword("TimeStarted")
993        .map(|value| parse_timestamp(&value))
994        .transpose()?;
995    let locales = arguments
996        .keyword("CountrySummary")
997        .map(|value| parse_count_mapping(arguments, &value, "CountrySummary", true))
998        .transpose()?;
999    let ip_versions = arguments
1000        .keyword("IPVersions")
1001        .map(|value| parse_count_mapping(arguments, &value, "IPVersions", false))
1002        .transpose()?;
1003    Ok(ClientsSeenEvent {
1004        start_time,
1005        locales,
1006        ip_versions,
1007    })
1008}
1009
1010fn parse_conf_changed(message: &ControlMessage) -> ConfChangedEvent {
1011    let text = message.to_string();
1012    let lines: Vec<&str> = text.lines().collect();
1013    let body = lines.get(1..lines.len().saturating_sub(1)).unwrap_or(&[]);
1014    let mut event = ConfChangedEvent {
1015        changed: HashMap::new(),
1016        unset: Vec::new(),
1017        config: HashMap::new(),
1018    };
1019    for line in body {
1020        match line.split_once('=') {
1021            Some((key, value)) => {
1022                event
1023                    .changed
1024                    .entry(key.to_string())
1025                    .or_default()
1026                    .push(value.to_string());
1027                event
1028                    .config
1029                    .insert(key.to_string(), Some(value.to_string()));
1030            }
1031            None => {
1032                event.unset.push(line.to_string());
1033                event.config.insert(line.to_string(), None);
1034            }
1035        }
1036    }
1037    event
1038}
1039
1040fn parse_guard(arguments: &mut Arguments) -> Result<GuardEvent> {
1041    let guard_type = arguments.require("guard_type", Quoting::Plain)?;
1042    let endpoint = arguments.require("endpoint", Quoting::Plain)?;
1043    let status = arguments.require("status", Quoting::Plain)?;
1044    let (endpoint_fingerprint, endpoint_nickname) = parse_circuit_entry(&endpoint)
1045        .map_err(|_| arguments.error("GUARD's endpoint doesn't match a ServerSpec"))?;
1046    Ok(GuardEvent {
1047        guard_type: typed!("GUARD", "guard_type", &guard_type, GuardType),
1048        endpoint,
1049        endpoint_fingerprint,
1050        endpoint_nickname,
1051        status: typed!("GUARD", "status", &status, GuardStatus),
1052    })
1053}
1054
1055fn parse_hs_desc(arguments: &mut Arguments) -> Result<HsDescEvent> {
1056    let action = arguments.require("action", Quoting::Plain)?;
1057    let address = arguments.require("address", Quoting::Plain)?;
1058    let authentication = arguments.require("authentication", Quoting::Plain)?;
1059    let directory = arguments.require("directory", Quoting::Plain)?;
1060    let descriptor_id = arguments.take("descriptor_id", Quoting::Plain)?;
1061    let (directory_fingerprint, directory_nickname) = match directory.as_str() {
1062        "UNKNOWN" => (None, None),
1063        _ => parse_circuit_entry(&directory).map_err(|_| {
1064            arguments.error("HS_DESC's directory doesn't match a ServerSpec")
1065        })?,
1066    };
1067    let replica = match arguments.keyword("REPLICA") {
1068        Some(value) => {
1069            Some(arguments.parse_number(&value, "HS_DESC event replica count")?)
1070        }
1071        None => None,
1072    };
1073    Ok(HsDescEvent {
1074        action: typed!("HS_DESC", "action", &action, HsDescAction),
1075        address,
1076        authentication: typed!("HS_DESC", "authentication", &authentication, HsAuth),
1077        directory,
1078        directory_fingerprint,
1079        directory_nickname,
1080        descriptor_id,
1081        reason: typed_option!(
1082            "HS_DESC",
1083            "reason",
1084            arguments.keyword("REASON"),
1085            HsDescReason
1086        ),
1087        replica,
1088        index: arguments.keyword("HSDIR_INDEX"),
1089    })
1090}
1091
1092fn parse_hs_desc_content(arguments: &mut Arguments) -> Result<HsDescContentEvent> {
1093    let address = arguments.require("address", Quoting::Plain)?;
1094    let descriptor_id = arguments.require("descriptor_id", Quoting::Plain)?;
1095    let directory = arguments.require("directory", Quoting::Plain)?;
1096    let (directory_fingerprint, directory_nickname) = parse_circuit_entry(&directory)
1097        .map_err(|_| {
1098            arguments.error("HS_DESC_CONTENT's directory doesn't match a ServerSpec")
1099        })?;
1100    let lines: Vec<&str> = arguments.text.lines().collect();
1101    let content = lines
1102        .get(1..lines.len().saturating_sub(1))
1103        .unwrap_or(&[])
1104        .join("\n");
1105    let descriptor = match content.is_empty() {
1106        true => None,
1107        false => Some(HiddenServiceDescriptor::parse(content.as_bytes(), false)?),
1108    };
1109    Ok(HsDescContentEvent {
1110        address: Some(address).filter(|address| address != "UNKNOWN"),
1111        descriptor_id,
1112        directory,
1113        directory_fingerprint,
1114        directory_nickname,
1115        descriptor,
1116    })
1117}
1118
1119fn parse_log(event_type: &str, message: &ControlMessage) -> LogEvent {
1120    let text = message.to_string();
1121    let mut body = text.get(event_type.len() + 1..).unwrap_or("").to_string();
1122    if let Some(stripped) = body.strip_suffix("\nOK") {
1123        body = stripped.to_string();
1124    }
1125    LogEvent {
1126        runlevel: typed!(event_type, "runlevel", event_type, Runlevel),
1127        message: body,
1128    }
1129}
1130
1131fn body_between(message: &ControlMessage, event_type: &str) -> String {
1132    let text = message.to_string();
1133    let body = text
1134        .strip_prefix(event_type)
1135        .map(|rest| rest.strip_prefix('\n').unwrap_or(rest))
1136        .unwrap_or(&text);
1137    body.strip_suffix("\nOK").unwrap_or(body).to_string()
1138}
1139
1140fn parse_network_status(message: &ControlMessage) -> Result<NetworkStatusEvent> {
1141    let content = body_between(message, "NS");
1142    Ok(NetworkStatusEvent {
1143        desc: RouterStatusEntryV3::parse_many(content.as_bytes(), false)?,
1144    })
1145}
1146
1147fn parse_new_consensus(message: &ControlMessage) -> NewConsensusEvent {
1148    NewConsensusEvent {
1149        consensus_content: body_between(message, "NEWCONSENSUS"),
1150    }
1151}
1152
1153fn parse_new_desc(message: &ControlMessage) -> Result<NewDescEvent> {
1154    let text = message.to_string();
1155    let relays = text
1156        .split_whitespace()
1157        .skip(1)
1158        .map(parse_circuit_entry)
1159        .collect::<Result<Vec<_>>>()?;
1160    Ok(NewDescEvent { relays })
1161}
1162
1163fn parse_endpoint(
1164    arguments: &Arguments,
1165    label: &str,
1166    target: &str,
1167    allow_zero: bool,
1168) -> Result<(String, u16)> {
1169    let Some((address, port)) = target.rsplit_once(':') else {
1170        return Err(arguments.error(format!(
1171            "{label} location must be of the form 'address:port'"
1172        )));
1173    };
1174    let Some(port) = parse_port(port, allow_zero) else {
1175        return Err(arguments.error(format!("{label} location's port is invalid")));
1176    };
1177    Ok((address.to_string(), port))
1178}
1179
1180fn parse_or_conn(arguments: &mut Arguments) -> Result<OrConnEvent> {
1181    let endpoint = arguments.require("endpoint", Quoting::Plain)?;
1182    let status = arguments.require("status", Quoting::Plain)?;
1183    let (mut fingerprint, mut nickname, mut address, mut port) = (None, None, None, None);
1184    match parse_circuit_entry(&endpoint) {
1185        Ok((parsed_fingerprint, parsed_nickname)) => {
1186            fingerprint = parsed_fingerprint;
1187            nickname = parsed_nickname;
1188        }
1189        Err(_) => {
1190            if !endpoint.contains(':') {
1191                return Err(arguments
1192                    .error("ORCONN endpoint is neither a relay nor 'address:port'"));
1193            }
1194            let (parsed_address, parsed_port) =
1195                parse_endpoint(arguments, "ORCONN's endpoint", &endpoint, false)?;
1196            address = Some(parsed_address);
1197            port = Some(parsed_port);
1198        }
1199    }
1200    let circ_count = match arguments.keyword("NCIRCS") {
1201        Some(value) => {
1202            Some(arguments.parse_number(&value, "ORCONN event circuit count")?)
1203        }
1204        None => None,
1205    };
1206    let id = arguments.keyword("ID");
1207    if id.as_deref().is_some_and(|id| !is_valid_connection_id(id)) {
1208        return Err(arguments
1209            .error("Connection IDs must be one to sixteen alphanumeric characters"));
1210    }
1211    Ok(OrConnEvent {
1212        endpoint,
1213        endpoint_fingerprint: fingerprint,
1214        endpoint_nickname: nickname,
1215        endpoint_address: address,
1216        endpoint_port: port,
1217        status: typed!("ORCONN", "status", &status, OrStatus),
1218        reason: typed_option!(
1219            "ORCONN",
1220            "reason",
1221            arguments.keyword("REASON"),
1222            OrClosureReason
1223        ),
1224        circ_count,
1225        id,
1226    })
1227}
1228
1229fn parse_pt_log(message: &ControlMessage) -> Result<PtLogEvent> {
1230    let text = message.to_string();
1231    let rest = text.strip_prefix("PT_LOG").unwrap_or(&text).trim_start();
1232    let Some(rest) = rest.strip_prefix("PT=") else {
1233        return Err(Error::protocol(format!(
1234            "PT_LOG event is missing its PT: {text}"
1235        )));
1236    };
1237    let (program, log_message) = rest.split_once(' ').unwrap_or((rest, ""));
1238    Ok(PtLogEvent {
1239        program: program.to_string(),
1240        message: log_message.to_string(),
1241    })
1242}
1243
1244fn parse_pt_status(message: &ControlMessage) -> Result<PtStatusEvent> {
1245    let text = message.to_string();
1246    let rest = text.strip_prefix("PT_STATUS").unwrap_or(&text).trim_start();
1247    let mut line = crate::response::ControlLine::new(rest);
1248    let missing = || {
1249        Error::protocol(format!(
1250            "PT_STATUS event is missing PT or TRANSPORT: {text}"
1251        ))
1252    };
1253    if !line.is_next_mapping(Some("PT"), false, false) {
1254        return Err(missing());
1255    }
1256    let (_, program) = line.pop_mapping(false, false)?;
1257    if !line.is_next_mapping(Some("TRANSPORT"), false, false) {
1258        return Err(missing());
1259    }
1260    let (_, transport) = line.pop_mapping(false, false)?;
1261    Ok(PtStatusEvent {
1262        program,
1263        transport,
1264        message: line.remainder().to_string(),
1265    })
1266}
1267
1268fn parse_status(event_type: &str, arguments: &mut Arguments) -> Result<StatusEvent> {
1269    let runlevel = arguments.require("runlevel", Quoting::Plain)?;
1270    let action = arguments.require("action", Quoting::Plain)?;
1271    let status_type = match event_type {
1272        "STATUS_GENERAL" => StatusType::General,
1273        "STATUS_CLIENT" => StatusType::Client,
1274        _ => StatusType::Server,
1275    };
1276    Ok(StatusEvent {
1277        status_type,
1278        runlevel: typed!(event_type, "runlevel", &runlevel, Runlevel),
1279        action,
1280        arguments: arguments.keywords.clone(),
1281    })
1282}
1283
1284fn optional_endpoint(
1285    arguments: &Arguments,
1286    label: &str,
1287    value: Option<&str>,
1288) -> Result<(Option<String>, Option<u16>)> {
1289    let Some(value) = value else {
1290        return Ok((None, None));
1291    };
1292    let (address, port) = parse_endpoint(arguments, label, value, true)?;
1293    Ok((Some(address), Some(port)))
1294}
1295
1296fn parse_stream(arguments: &mut Arguments) -> Result<StreamEvent> {
1297    let id = arguments.require("id", Quoting::Plain)?;
1298    let status = arguments.require("status", Quoting::Plain)?;
1299    let circ_id = arguments.take("circ_id", Quoting::Plain)?;
1300    let Some(target) = arguments.take("target", Quoting::Plain)? else {
1301        return Err(arguments.error("STREAM event didn't have a target"));
1302    };
1303    let (target_address, target_port) =
1304        parse_endpoint(arguments, "Target", &target, true)?;
1305    let source_addr = arguments.keyword("SOURCE_ADDR");
1306    let (source_address, source_port) =
1307        optional_endpoint(arguments, "Source", source_addr.as_deref())?;
1308    Ok(StreamEvent {
1309        id,
1310        status: typed!("STREAM", "status", &status, StreamStatus),
1311        circ_id: circ_id.filter(|circ_id| circ_id != "0"),
1312        target,
1313        target_address,
1314        target_port,
1315        reason: typed_option!(
1316            "STREAM",
1317            "reason",
1318            arguments.keyword("REASON"),
1319            StreamClosureReason
1320        ),
1321        remote_reason: typed_option!(
1322            "STREAM",
1323            "remote_reason",
1324            arguments.keyword("REMOTE_REASON"),
1325            StreamClosureReason
1326        ),
1327        source: typed_option!(
1328            "STREAM",
1329            "source",
1330            arguments.keyword("SOURCE"),
1331            StreamSource
1332        ),
1333        source_addr,
1334        source_address,
1335        source_port,
1336        purpose: typed_option!(
1337            "STREAM",
1338            "purpose",
1339            arguments.keyword("PURPOSE"),
1340            StreamPurpose
1341        ),
1342        socks_username: arguments.keyword("SOCKS_USERNAME"),
1343        socks_password: arguments.keyword("SOCKS_PASSWORD"),
1344        client_protocol: arguments.keyword("CLIENT_PROTOCOL"),
1345        nym_epoch: arguments.keyword("NYM_EPOCH"),
1346        session_group: arguments.keyword("SESSION_GROUP"),
1347        iso_fields: arguments.keyword("ISO_FIELDS"),
1348    })
1349}
1350
1351fn parse_stream_bandwidth(arguments: &mut Arguments) -> Result<StreamBandwidthEvent> {
1352    let id = arguments.require("id", Quoting::Plain)?;
1353    if !is_valid_stream_id(&id) {
1354        return Err(arguments.error(format!(
1355            "Stream IDs must be one to sixteen alphanumeric characters, got '{id}'"
1356        )));
1357    }
1358    let written = arguments.require("written", Quoting::Plain)?;
1359    let read = arguments.require("read", Quoting::Plain)?;
1360    let time = arguments.take("time", Quoting::Plain)?;
1361    let label = "A STREAM_BW event's bytes sent and received";
1362    Ok(StreamBandwidthEvent {
1363        id,
1364        written: arguments.parse_number(&written, label)?,
1365        read: arguments.parse_number(&read, label)?,
1366        time: arguments.iso_timestamp(time)?,
1367    })
1368}
1369
1370fn parse_transport_launched(arguments: &mut Arguments) -> Result<TransportLaunchedEvent> {
1371    let transport_type = arguments.require("type", Quoting::Plain)?;
1372    let name = arguments.require("name", Quoting::Plain)?;
1373    let address = arguments.require("address", Quoting::Plain)?;
1374    let port = arguments.require("port", Quoting::Plain)?;
1375    if !matches!(transport_type.as_str(), "server" | "client") {
1376        return Err(
1377            arguments.error("Transport type should either be 'server' or 'client'")
1378        );
1379    }
1380    if !is_valid_ipv4_address(&address) && !is_valid_ipv6_address(&address, false) {
1381        return Err(
1382            arguments.error("Transport address isn't a valid IPv4 or IPv6 address")
1383        );
1384    }
1385    let Some(port) = parse_port(&port, false) else {
1386        return Err(arguments.error("Transport port is invalid"));
1387    };
1388    Ok(TransportLaunchedEvent {
1389        transport_type,
1390        name,
1391        address,
1392        port,
1393    })
1394}
1395
1396fn required_keyword(arguments: &Arguments, name: &str, label: &str) -> Result<String> {
1397    arguments
1398        .keyword(name)
1399        .filter(|value| !value.is_empty())
1400        .ok_or_else(|| Error::protocol(format!("{label} event is missing its {name}")))
1401}
1402
1403fn parse_connection_bandwidth(
1404    arguments: &mut Arguments,
1405) -> Result<ConnectionBandwidthEvent> {
1406    let id = required_keyword(arguments, "ID", "CONN_BW")?;
1407    let conn_type = required_keyword(arguments, "TYPE", "CONN_BW")?;
1408    let read = required_keyword(arguments, "READ", "CONN_BW")?;
1409    let written = required_keyword(arguments, "WRITTEN", "CONN_BW")?;
1410    if !is_valid_connection_id(&id) {
1411        return Err(arguments.error(format!(
1412            "Connection IDs must be one to sixteen alphanumeric characters, got '{id}'"
1413        )));
1414    }
1415    let label = "A CONN_BW event's bytes sent and received";
1416    Ok(ConnectionBandwidthEvent {
1417        id,
1418        conn_type: typed!("CONN_BW", "conn_type", &conn_type, ConnectionType),
1419        read: arguments.parse_number(&read, label)?,
1420        written: arguments.parse_number(&written, label)?,
1421    })
1422}
1423
1424fn parse_circuit_bandwidth(arguments: &mut Arguments) -> Result<CircuitBandwidthEvent> {
1425    let id = required_keyword(arguments, "ID", "CIRC_BW")?;
1426    let read = required_keyword(arguments, "READ", "CIRC_BW")?;
1427    let written = required_keyword(arguments, "WRITTEN", "CIRC_BW")?;
1428    let id = validated_circuit_id(arguments, id)?;
1429    let time = arguments.iso_timestamp(arguments.keyword("TIME"))?;
1430    Ok(CircuitBandwidthEvent {
1431        id,
1432        read: arguments.parse_number(&read, "A CIRC_BW event's bytes received")?,
1433        written: arguments.parse_number(&written, "A CIRC_BW event's bytes sent")?,
1434        delivered_read: arguments.number(
1435            "DELIVERED_READ",
1436            "A CIRC_BW event's delivered bytes received",
1437        )?,
1438        delivered_written: arguments.number(
1439            "DELIVERED_WRITTEN",
1440            "A CIRC_BW event's delivered bytes sent",
1441        )?,
1442        overhead_read: arguments
1443            .number("OVERHEAD_READ", "A CIRC_BW event's overhead bytes received")?,
1444        overhead_written: arguments
1445            .number("OVERHEAD_WRITTEN", "A CIRC_BW event's overhead bytes sent")?,
1446        time,
1447    })
1448}
1449
1450fn parse_cell_type_mapping(
1451    mapping: Option<String>,
1452) -> Result<Option<HashMap<String, u64>>> {
1453    let Some(mapping) = mapping else {
1454        return Ok(None);
1455    };
1456    let mut results = HashMap::new();
1457    for entry in mapping.split(',') {
1458        let Some((key, value)) = entry.rsplit_once(':') else {
1459            return Err(Error::protocol(format!(
1460                "Mappings are expected to be of the form 'key:value', got '{entry}': \
1461                {mapping}"
1462            )));
1463        };
1464        let is_key = !key.is_empty()
1465            && key.bytes().all(|byte| {
1466                byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_'
1467            });
1468        if !is_key {
1469            return Err(Error::protocol(format!(
1470                "Key had invalid characters, got '{key}': {mapping}"
1471            )));
1472        }
1473        let value = value.parse::<u64>().map_err(|_| {
1474            Error::protocol(format!(
1475                "Values should just be integers, got '{value}': {mapping}"
1476            ))
1477        })?;
1478        results.insert(key.to_string(), value);
1479    }
1480    Ok(Some(results))
1481}
1482
1483fn parse_cell_stats(arguments: &mut Arguments) -> Result<CellStatsEvent> {
1484    let circuit_ids = ["ID", "InboundQueue", "OutboundQueue"];
1485    for name in circuit_ids {
1486        if arguments
1487            .keyword(name)
1488            .is_some_and(|value| !is_valid_circuit_id(&value))
1489        {
1490            return Err(arguments.error(format!(
1491                "{name} must be one to sixteen alphanumeric characters"
1492            )));
1493        }
1494    }
1495    for name in ["InboundConn", "OutboundConn"] {
1496        if arguments
1497            .keyword(name)
1498            .is_some_and(|value| !is_valid_connection_id(&value))
1499        {
1500            return Err(arguments.error(format!(
1501                "{name} must be one to sixteen alphanumeric characters"
1502            )));
1503        }
1504    }
1505    Ok(CellStatsEvent {
1506        id: arguments.keyword("ID"),
1507        inbound_queue: arguments.keyword("InboundQueue"),
1508        inbound_connection: arguments.keyword("InboundConn"),
1509        inbound_added: parse_cell_type_mapping(arguments.keyword("InboundAdded"))?,
1510        inbound_removed: parse_cell_type_mapping(arguments.keyword("InboundRemoved"))?,
1511        inbound_time: parse_cell_type_mapping(arguments.keyword("InboundTime"))?,
1512        outbound_queue: arguments.keyword("OutboundQueue"),
1513        outbound_connection: arguments.keyword("OutboundConn"),
1514        outbound_added: parse_cell_type_mapping(arguments.keyword("OutboundAdded"))?,
1515        outbound_removed: parse_cell_type_mapping(arguments.keyword("OutboundRemoved"))?,
1516        outbound_time: parse_cell_type_mapping(arguments.keyword("OutboundTime"))?,
1517    })
1518}
1519
1520fn parse_token_bucket_empty(arguments: &mut Arguments) -> Result<TokenBucketEmptyEvent> {
1521    let bucket = arguments.require("bucket", Quoting::Plain)?;
1522    let id = arguments.keyword("ID");
1523    if id.as_deref().is_some_and(|id| !is_valid_connection_id(id)) {
1524        return Err(arguments
1525            .error("Connection IDs must be one to sixteen alphanumeric characters"));
1526    }
1527    let read = required_keyword(arguments, "READ", "TB_EMPTY")?;
1528    let written = required_keyword(arguments, "WRITTEN", "TB_EMPTY")?;
1529    let last = required_keyword(arguments, "LAST", "TB_EMPTY")?;
1530    Ok(TokenBucketEmptyEvent {
1531        bucket: typed!("TB_EMPTY", "bucket", &bucket, TokenBucket),
1532        id,
1533        read: arguments.parse_number(&read, "A TB_EMPTY's READ value")?,
1534        written: arguments.parse_number(&written, "A TB_EMPTY's WRITTEN value")?,
1535        last_refill: arguments.parse_number(&last, "A TB_EMPTY's LAST value")?,
1536    })
1537}
1538
1539pub fn unescape_event_value(value: &str) -> Result<String> {
1540    Ok(String::from_utf8_lossy(&unescape_bytes(value)?).into_owned())
1541}