Skip to main content

freeswitch_types/commands/
variables.rs

1//! Channel variable scope and ordered key-value storage for originate commands.
2
3use indexmap::IndexMap;
4use std::fmt;
5use std::str::FromStr;
6
7use super::originate::OriginateError;
8
9/// Scope for channel variables in an originate command.
10///
11/// - `Enterprise` (`<>`) -- applies across all threads (`:_:` separated)
12/// - `Default` (`{}`) -- applies to all channels in this originate
13/// - `Channel` (`[]`) -- applies only to one specific channel
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
16#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
17#[non_exhaustive]
18pub enum VariablesType {
19    /// `<>` scope -- applies across all `:_:` separated threads.
20    Enterprise,
21    /// `{}` scope -- applies to all channels in this originate.
22    Default,
23    /// `[]` scope -- applies to one specific channel.
24    Channel,
25}
26
27impl VariablesType {
28    pub(super) fn delimiters(self) -> (char, char) {
29        match self {
30            Self::Enterprise => ('<', '>'),
31            Self::Default => ('{', '}'),
32            Self::Channel => ('[', ']'),
33        }
34    }
35}
36
37/// Ordered set of channel variables with FreeSWITCH escaping.
38///
39/// Backslashes are doubled, commas are escaped with `\,`, single quotes with
40/// `\'`, and values with spaces are wrapped in single quotes. This form
41/// round-trips through [`FromStr`]; what the switch itself decodes depends on
42/// which command carries the block, and is documented in
43/// `docs/dial-string-format.md`.
44///
45/// # Serde format
46///
47/// [`Default`](VariablesType::Default) scope serializes as a flat JSON map:
48/// `{"key": "value", ...}`. Non-default scopes serialize as
49/// `{"scope": "Enterprise", "vars": {"key": "value"}}`.
50/// Deserialization accepts both formats; a flat map implies `Default` scope.
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct Variables {
53    vars_type: VariablesType,
54    inner: IndexMap<String, String>,
55}
56
57pub(super) fn escape_value(value: &str) -> String {
58    // The backslash goes first, or the ones introduced below get doubled.
59    let escaped = value
60        .replace('\\', "\\\\")
61        .replace('\'', "\\'")
62        .replace(',', "\\,");
63    if escaped.contains(' ') {
64        format!("'{}'", escaped)
65    } else {
66        escaped
67    }
68}
69
70fn unescape_value(value: &str) -> String {
71    let s = value
72        .strip_prefix('\'')
73        .and_then(|s| s.strip_suffix('\''))
74        .unwrap_or(value);
75
76    let mut out = String::with_capacity(s.len());
77    let mut chars = s.chars();
78    while let Some(c) = chars.next() {
79        if c != '\\' {
80            out.push(c);
81            continue;
82        }
83        match chars.next() {
84            Some(next) => out.push(next),
85            // Hand-written input can end in a backslash that escapes nothing.
86            None => out.push('\\'),
87        }
88    }
89    out
90}
91
92impl Variables {
93    /// Create an empty variable set with the given scope.
94    pub fn new(vars_type: VariablesType) -> Self {
95        Self {
96            vars_type,
97            inner: IndexMap::new(),
98        }
99    }
100
101    /// Create from an existing set of key-value pairs.
102    pub fn with_vars(
103        vars_type: VariablesType,
104        vars: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
105    ) -> Self {
106        Self {
107            vars_type,
108            inner: vars
109                .into_iter()
110                .map(|(k, v)| (k.into(), v.into()))
111                .collect(),
112        }
113    }
114
115    /// Insert or overwrite a variable.
116    pub fn insert(&mut self, key: impl Into<String>, value: impl Into<String>) {
117        self.inner
118            .insert(key.into(), value.into());
119    }
120
121    /// Remove a variable by name, returning its value if it existed.
122    pub fn remove(&mut self, key: &str) -> Option<String> {
123        self.inner
124            .shift_remove(key)
125    }
126
127    /// Look up a variable by name.
128    pub fn get(&self, key: &str) -> Option<&str> {
129        self.inner
130            .get(key)
131            .map(|s| s.as_str())
132    }
133
134    /// Whether the set contains no variables.
135    pub fn is_empty(&self) -> bool {
136        self.inner
137            .is_empty()
138    }
139
140    /// Number of variables.
141    pub fn len(&self) -> usize {
142        self.inner
143            .len()
144    }
145
146    /// Variable scope (Enterprise, Default, or Channel).
147    pub fn scope(&self) -> VariablesType {
148        self.vars_type
149    }
150
151    /// Change the variable scope.
152    pub fn set_scope(&mut self, scope: VariablesType) {
153        self.vars_type = scope;
154    }
155
156    /// Iterate over key-value pairs in insertion order.
157    pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
158        self.inner
159            .iter()
160            .map(|(k, v)| (k.as_str(), v.as_str()))
161    }
162
163    /// Mutable iterator over key-value pairs in insertion order.
164    pub fn iter_mut(&mut self) -> impl Iterator<Item = (&str, &mut String)> {
165        self.inner
166            .iter_mut()
167            .map(|(k, v)| (k.as_str(), v))
168    }
169
170    /// Mutable iterator over values in insertion order.
171    pub fn values_mut(&mut self) -> impl Iterator<Item = &mut String> {
172        self.inner
173            .values_mut()
174    }
175}
176
177#[cfg(feature = "serde")]
178impl serde::Serialize for Variables {
179    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
180        if self.vars_type == VariablesType::Default {
181            self.inner
182                .serialize(serializer)
183        } else {
184            use serde::ser::SerializeStruct;
185            let mut s = serializer.serialize_struct("Variables", 2)?;
186            s.serialize_field("scope", &self.vars_type)?;
187            s.serialize_field("vars", &self.inner)?;
188            s.end()
189        }
190    }
191}
192
193#[cfg(feature = "serde")]
194impl<'de> serde::Deserialize<'de> for Variables {
195    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
196        #[derive(serde::Deserialize)]
197        #[serde(untagged)]
198        enum VariablesRepr {
199            Scoped {
200                scope: VariablesType,
201                vars: IndexMap<String, String>,
202            },
203            Flat(IndexMap<String, String>),
204        }
205
206        match VariablesRepr::deserialize(deserializer)? {
207            VariablesRepr::Scoped { scope, vars } => Ok(Self {
208                vars_type: scope,
209                inner: vars,
210            }),
211            VariablesRepr::Flat(map) => Ok(Self {
212                vars_type: VariablesType::Default,
213                inner: map,
214            }),
215        }
216    }
217}
218
219impl fmt::Display for Variables {
220    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
221        let (open, close) = self
222            .vars_type
223            .delimiters();
224        f.write_fmt(format_args!("{}", open))?;
225        for (i, (key, value)) in self
226            .inner
227            .iter()
228            .enumerate()
229        {
230            if i > 0 {
231                f.write_str(",")?;
232            }
233            write!(f, "{}={}", key, escape_value(value))?;
234        }
235        f.write_fmt(format_args!("{}", close))
236    }
237}
238
239impl FromStr for Variables {
240    type Err = OriginateError;
241
242    fn from_str(s: &str) -> Result<Self, Self::Err> {
243        let s = s.trim();
244        if s.len() < 2 {
245            return Err(OriginateError::ParseError(
246                "variable block too short".into(),
247            ));
248        }
249
250        let (vars_type, inner_str) = match (s.as_bytes()[0], s.as_bytes()[s.len() - 1]) {
251            (b'{', b'}') => (VariablesType::Default, &s[1..s.len() - 1]),
252            (b'<', b'>') => (VariablesType::Enterprise, &s[1..s.len() - 1]),
253            (b'[', b']') => (VariablesType::Channel, &s[1..s.len() - 1]),
254            _ => {
255                return Err(OriginateError::ParseError(format!(
256                    "unknown variable delimiters: {}",
257                    s
258                )));
259            }
260        };
261
262        let mut inner = IndexMap::new();
263        if !inner_str.is_empty() {
264            if let Some(rest) = inner_str.strip_prefix("^^") {
265                let sep = rest
266                    .chars()
267                    .next()
268                    .ok_or_else(|| {
269                        OriginateError::ParseError("^^ without separator character".into())
270                    })?;
271                let (_, close) = vars_type.delimiters();
272                if sep == close || sep == '=' {
273                    return Err(OriginateError::ParseError(format!(
274                        "invalid ^^ separator: '{sep}'"
275                    )));
276                }
277                let var_str = &rest[sep.len_utf8()..];
278                if !var_str.is_empty() {
279                    for part in var_str.split(sep) {
280                        let (key, value) = part
281                            .split_once('=')
282                            .ok_or_else(|| {
283                                OriginateError::ParseError(format!("missing = in variable: {part}"))
284                            })?;
285                        inner.insert(key.to_string(), value.to_string());
286                    }
287                }
288            } else {
289                for part in split_unescaped_commas(inner_str) {
290                    let (key, value) = part
291                        .split_once('=')
292                        .ok_or_else(|| {
293                            OriginateError::ParseError(format!("missing = in variable: {part}"))
294                        })?;
295                    inner.insert(key.to_string(), unescape_value(value));
296                }
297            }
298        }
299
300        Ok(Self { vars_type, inner })
301    }
302}
303
304/// Split on commas that are not escaped by a backslash.
305///
306/// A comma preceded by an odd number of backslashes is escaped (e.g. `\,`).
307/// A comma preceded by an even number of backslashes is a real split point
308/// (e.g. `\\,` means escaped backslash followed by comma delimiter).
309pub(super) fn split_unescaped_commas(s: &str) -> Vec<&str> {
310    let mut parts = Vec::new();
311    let mut start = 0;
312    let bytes = s.as_bytes();
313
314    for i in 0..bytes.len() {
315        if bytes[i] == b',' {
316            let mut backslashes = 0;
317            let mut j = i;
318            while j > 0 && bytes[j - 1] == b'\\' {
319                backslashes += 1;
320                j -= 1;
321            }
322            if backslashes % 2 == 0 {
323                parts.push(&s[start..i]);
324                start = i + 1;
325            }
326        }
327    }
328    parts.push(&s[start..]);
329    parts
330}
331
332#[cfg(test)]
333mod tests {
334    use super::*;
335
336    /// `split_unescaped_commas` reads a comma behind an even number of
337    /// backslashes as a real separator, so a value ending in a backslash has to
338    /// be written with its own backslash escaped or the writer contradicts the
339    /// reader and the block no longer parses.
340    #[test]
341    fn value_with_backslash_round_trips() {
342        for value in [r"a\,b", r"C:\path", r"trailing\", r"\\", r"a\nb"] {
343            let mut vars = Variables::new(VariablesType::Default);
344            vars.insert("k", value);
345            vars.insert("after", "sentinel");
346            let rendered = vars.to_string();
347
348            let back: Variables = rendered
349                .parse()
350                .unwrap_or_else(|e| {
351                    panic!("{value:?} rendered {rendered} and failed to parse: {e}")
352                });
353            assert_eq!(back.get("k"), Some(value), "rendered {rendered}");
354            assert_eq!(
355                back.get("after"),
356                Some("sentinel"),
357                "value {value:?} ate the next variable: {rendered}"
358            );
359        }
360    }
361
362    #[test]
363    fn variables_standard_chars() {
364        let mut vars = Variables::new(VariablesType::Default);
365        vars.insert("test_key", "this_value");
366        let result = vars.to_string();
367        assert!(result.contains("test_key"));
368        assert!(result.contains("this_value"));
369    }
370
371    #[test]
372    fn variables_comma_escaped() {
373        let mut vars = Variables::new(VariablesType::Default);
374        vars.insert("test_key", "this,is,a,value");
375        let result = vars.to_string();
376        assert!(result.contains("\\,"));
377    }
378
379    #[test]
380    fn variables_spaces_quoted() {
381        let mut vars = Variables::new(VariablesType::Default);
382        vars.insert("test_key", "this is a value");
383        let result = vars.to_string();
384        assert_eq!(
385            result
386                .matches('\'')
387                .count(),
388            2
389        );
390    }
391
392    #[test]
393    fn variables_single_quote_escaped() {
394        let mut vars = Variables::new(VariablesType::Default);
395        vars.insert("test_key", "let's_this_be_a_value");
396        let result = vars.to_string();
397        assert!(result.contains("\\'"));
398    }
399
400    #[test]
401    fn variables_enterprise_delimiters() {
402        let mut vars = Variables::new(VariablesType::Enterprise);
403        vars.insert("k", "v");
404        let result = vars.to_string();
405        assert!(result.starts_with('<'));
406        assert!(result.ends_with('>'));
407    }
408
409    #[test]
410    fn variables_channel_delimiters() {
411        let mut vars = Variables::new(VariablesType::Channel);
412        vars.insert("k", "v");
413        let result = vars.to_string();
414        assert!(result.starts_with('['));
415        assert!(result.ends_with(']'));
416    }
417
418    #[test]
419    fn variables_default_delimiters() {
420        let mut vars = Variables::new(VariablesType::Default);
421        vars.insert("k", "v");
422        let result = vars.to_string();
423        assert!(result.starts_with('{'));
424        assert!(result.ends_with('}'));
425    }
426
427    #[test]
428    fn variables_parse_round_trip() {
429        let mut vars = Variables::new(VariablesType::Default);
430        vars.insert("origination_caller_id_number", "9005551212");
431        vars.insert("sip_h_Call-Info", "<url>;meta=123,<uri>");
432        let s = vars.to_string();
433        let parsed: Variables = s
434            .parse()
435            .unwrap();
436        assert_eq!(
437            parsed.get("origination_caller_id_number"),
438            Some("9005551212")
439        );
440        assert_eq!(parsed.get("sip_h_Call-Info"), Some("<url>;meta=123,<uri>"));
441    }
442
443    #[test]
444    fn split_unescaped_commas_basic() {
445        assert_eq!(split_unescaped_commas("a,b,c"), vec!["a", "b", "c"]);
446    }
447
448    #[test]
449    fn split_unescaped_commas_escaped() {
450        assert_eq!(split_unescaped_commas(r"a\,b,c"), vec![r"a\,b", "c"]);
451    }
452
453    #[test]
454    fn split_unescaped_commas_double_backslash() {
455        // \\, = escaped backslash + comma delimiter
456        assert_eq!(split_unescaped_commas(r"a\\,b"), vec![r"a\\", "b"]);
457    }
458
459    #[test]
460    fn split_unescaped_commas_triple_backslash() {
461        // \\\, = escaped backslash + escaped comma (no split)
462        assert_eq!(split_unescaped_commas(r"a\\\,b"), vec![r"a\\\,b"]);
463    }
464
465    #[test]
466    fn variables_caret_caret_separator() {
467        let vars: Variables =
468            "[^^:sip_invite_domain=pbx.example.com:presence_id=1211@pbx.example.com]"
469                .parse()
470                .unwrap();
471        assert_eq!(vars.scope(), VariablesType::Channel);
472        assert_eq!(vars.get("sip_invite_domain"), Some("pbx.example.com"));
473        assert_eq!(vars.get("presence_id"), Some("1211@pbx.example.com"));
474    }
475
476    #[test]
477    fn variables_caret_caret_display_uses_canonical_comma() {
478        let vars: Variables = "[^^:a=1:b=2]"
479            .parse()
480            .unwrap();
481        assert_eq!(vars.to_string(), "[a=1,b=2]");
482    }
483
484    #[test]
485    fn variables_caret_caret_default_scope() {
486        let vars: Variables = "{^^|x=1|y=2}"
487            .parse()
488            .unwrap();
489        assert_eq!(vars.scope(), VariablesType::Default);
490        assert_eq!(vars.get("x"), Some("1"));
491        assert_eq!(vars.get("y"), Some("2"));
492    }
493
494    #[test]
495    fn variables_caret_caret_enterprise_scope() {
496        let vars: Variables = "<^^;a=1;b=2>"
497            .parse()
498            .unwrap();
499        assert_eq!(vars.scope(), VariablesType::Enterprise);
500        assert_eq!(vars.get("a"), Some("1"));
501    }
502
503    #[test]
504    fn variables_caret_caret_no_unescape() {
505        let vars: Variables = r"[^^:key=val\,ue:other=x]"
506            .parse()
507            .unwrap();
508        assert_eq!(vars.get("key"), Some(r"val\,ue"));
509    }
510
511    #[test]
512    fn variables_caret_caret_values_with_commas() {
513        let vars: Variables = "[^^|sip_h_X-Call-Info=<urn:foo>;purpose=bar,<urn:baz>|other=val]"
514            .parse()
515            .unwrap();
516        assert_eq!(
517            vars.get("sip_h_X-Call-Info"),
518            Some("<urn:foo>;purpose=bar,<urn:baz>")
519        );
520        assert_eq!(vars.get("other"), Some("val"));
521    }
522
523    #[test]
524    fn variables_caret_caret_empty_vars() {
525        let vars: Variables = "[^^:]"
526            .parse()
527            .unwrap();
528        assert!(vars.is_empty());
529        assert_eq!(vars.scope(), VariablesType::Channel);
530    }
531
532    #[test]
533    fn variables_caret_caret_missing_separator() {
534        assert!("[^^]"
535            .parse::<Variables>()
536            .is_err());
537    }
538
539    #[test]
540    fn variables_caret_caret_closing_bracket_as_sep() {
541        assert!("[^^]]"
542            .parse::<Variables>()
543            .is_err());
544    }
545
546    #[test]
547    fn variables_caret_caret_equals_as_sep() {
548        assert!("[^^=a=1]"
549            .parse::<Variables>()
550            .is_err());
551    }
552
553    #[test]
554    fn variables_from_str_empty_block() {
555        let result = "{}".parse::<Variables>();
556        assert!(
557            result.is_ok(),
558            "empty variable block should parse successfully"
559        );
560        let vars = result.unwrap();
561        assert!(
562            vars.is_empty(),
563            "parsed empty block should have no variables"
564        );
565    }
566
567    #[test]
568    fn variables_from_str_empty_channel_block() {
569        let result = "[]".parse::<Variables>();
570        assert!(result.is_ok());
571        let vars = result.unwrap();
572        assert!(vars.is_empty());
573        assert_eq!(vars.scope(), VariablesType::Channel);
574    }
575
576    #[test]
577    fn variables_from_str_empty_enterprise_block() {
578        let result = "<>".parse::<Variables>();
579        assert!(result.is_ok());
580        let vars = result.unwrap();
581        assert!(vars.is_empty());
582        assert_eq!(vars.scope(), VariablesType::Enterprise);
583    }
584
585    #[test]
586    fn serde_variables_type() {
587        let json = serde_json::to_string(&VariablesType::Enterprise).unwrap();
588        assert_eq!(json, "\"enterprise\"");
589        let parsed: VariablesType = serde_json::from_str(&json).unwrap();
590        assert_eq!(parsed, VariablesType::Enterprise);
591    }
592
593    #[test]
594    fn serde_variables_flat_default() {
595        let mut vars = Variables::new(VariablesType::Default);
596        vars.insert("key1", "val1");
597        vars.insert("key2", "val2");
598        let json = serde_json::to_string(&vars).unwrap();
599        let parsed: Variables = serde_json::from_str(&json).unwrap();
600        assert_eq!(parsed.scope(), VariablesType::Default);
601        assert_eq!(parsed.get("key1"), Some("val1"));
602        assert_eq!(parsed.get("key2"), Some("val2"));
603    }
604
605    #[test]
606    fn serde_variables_scoped_enterprise() {
607        let mut vars = Variables::new(VariablesType::Enterprise);
608        vars.insert("key1", "val1");
609        let json = serde_json::to_string(&vars).unwrap();
610        assert!(json.contains("\"enterprise\""));
611        let parsed: Variables = serde_json::from_str(&json).unwrap();
612        assert_eq!(parsed.scope(), VariablesType::Enterprise);
613        assert_eq!(parsed.get("key1"), Some("val1"));
614    }
615
616    #[test]
617    fn serde_variables_flat_map_deserializes_as_default() {
618        let json = r#"{"key1":"val1","key2":"val2"}"#;
619        let vars: Variables = serde_json::from_str(json).unwrap();
620        assert_eq!(vars.scope(), VariablesType::Default);
621        assert_eq!(vars.get("key1"), Some("val1"));
622        assert_eq!(vars.get("key2"), Some("val2"));
623    }
624
625    #[test]
626    fn serde_variables_scoped_deserializes() {
627        let json = r#"{"scope":"channel","vars":{"k":"v"}}"#;
628        let vars: Variables = serde_json::from_str(json).unwrap();
629        assert_eq!(vars.scope(), VariablesType::Channel);
630        assert_eq!(vars.get("k"), Some("v"));
631    }
632}