Skip to main content

ldap_client_proto/
controls.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3use ldap_client_ber::tag::{BOOLEAN, Tag};
4use ldap_client_ber::{BerReader, BerWriter};
5
6use crate::ProtoError;
7use crate::result_code::ResultCode;
8
9pub const PAGED_RESULTS_OID: &str = "1.2.840.113556.1.4.319";
10pub const MANAGE_DSA_IT_OID: &str = "2.16.840.1.113730.3.4.2";
11pub const SERVER_SORT_REQUEST_OID: &str = "1.2.840.113556.1.4.473";
12pub const SERVER_SORT_RESPONSE_OID: &str = "1.2.840.113556.1.4.474";
13pub const DOMAIN_SCOPE_OID: &str = "1.2.840.113556.1.4.1339";
14
15// Keep old name for backwards compat
16pub const SERVER_SORT_OID: &str = SERVER_SORT_REQUEST_OID;
17
18pub(crate) const CONTROLS: Tag = Tag::context_constructed(0);
19const ORDERING_RULE: Tag = Tag::context(0);
20const REVERSE_ORDER: Tag = Tag::context(1);
21const ATTRIBUTE_TYPE: Tag = Tag::context(0);
22
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct Control {
25    pub oid: String,
26    pub critical: bool,
27    pub value: Option<Vec<u8>>,
28}
29
30pub trait ControlType {
31    const OID: &'static str;
32}
33
34/// A control the client sends. Criticality belongs to the `Control` that
35/// carries the value, not to the value.
36pub trait RequestControl: ControlType {
37    fn value(&self) -> Option<Vec<u8>>;
38}
39
40pub trait ResponseControl: ControlType + Sized {
41    fn from_value(value: Option<&[u8]>) -> Result<Self, ProtoError>;
42}
43
44impl Control {
45    pub fn new<C: RequestControl>(control: &C, critical: bool) -> Self {
46        Self {
47            oid: C::OID.to_string(),
48            critical,
49            value: control.value(),
50        }
51    }
52
53    pub fn decode<C: ResponseControl>(&self) -> Result<C, ProtoError> {
54        if self.oid != C::OID {
55            return Err(ProtoError::Protocol(format!(
56                "expected control {}, got {}",
57                C::OID,
58                self.oid
59            )));
60        }
61        C::from_value(self.value.as_deref())
62    }
63
64    /// The decoded control with OID `C::OID`, if the server sent one. A
65    /// control that is present and does not decode is an error.
66    pub fn find<C: ResponseControl>(controls: &[Control]) -> Result<Option<C>, ProtoError> {
67        controls
68            .iter()
69            .find(|c| c.oid == C::OID)
70            .map(Control::decode)
71            .transpose()
72    }
73}
74
75/// Simple paged results control (RFC 2696).
76#[derive(Debug, Clone)]
77pub struct PagedResultsControl {
78    pub size: i32,
79    pub cookie: Vec<u8>,
80}
81
82impl PagedResultsControl {
83    pub fn new(size: i32) -> Self {
84        Self {
85            size,
86            cookie: Vec::new(),
87        }
88    }
89
90    pub fn with_cookie(mut self, cookie: Vec<u8>) -> Self {
91        self.cookie = cookie;
92        self
93    }
94
95    pub fn to_control(&self) -> Control {
96        Control::new(self, false)
97    }
98
99    pub fn from_control(control: &Control) -> Result<Self, ProtoError> {
100        control.decode()
101    }
102}
103
104impl ControlType for PagedResultsControl {
105    const OID: &'static str = PAGED_RESULTS_OID;
106}
107
108impl RequestControl for PagedResultsControl {
109    fn value(&self) -> Option<Vec<u8>> {
110        let mut w = BerWriter::new();
111        w.write_sequence(Tag::sequence(), |inner| {
112            inner.write_integer(i64::from(self.size));
113            inner.write_bytes(&self.cookie);
114        });
115        Some(w.into_bytes())
116    }
117}
118
119impl ResponseControl for PagedResultsControl {
120    fn from_value(value: Option<&[u8]>) -> Result<Self, ProtoError> {
121        let value = value
122            .ok_or_else(|| ProtoError::Protocol("paged results control missing value".into()))?;
123        let (size, cookie) = BerReader::new(value).read_sequence(Tag::sequence(), |inner| {
124            Ok((inner.read_integer()?, inner.read_octet_string()?.to_vec()))
125        })?;
126        let size = i32::try_from(size)
127            .map_err(|_| ProtoError::Protocol("paged results size out of range".into()))?;
128        Ok(Self { size, cookie })
129    }
130}
131
132#[derive(Debug, Clone)]
133pub struct ManageDsaItControl {
134    pub critical: bool,
135}
136
137impl ManageDsaItControl {
138    pub fn new(critical: bool) -> Self {
139        Self { critical }
140    }
141
142    pub fn to_control(&self) -> Control {
143        Control::new(self, self.critical)
144    }
145}
146
147impl ControlType for ManageDsaItControl {
148    const OID: &'static str = MANAGE_DSA_IT_OID;
149}
150
151impl RequestControl for ManageDsaItControl {
152    fn value(&self) -> Option<Vec<u8>> {
153        None
154    }
155}
156
157#[derive(Debug, Clone)]
158pub struct DomainScopeControl {
159    pub critical: bool,
160}
161
162impl DomainScopeControl {
163    pub fn new(critical: bool) -> Self {
164        Self { critical }
165    }
166
167    pub fn to_control(&self) -> Control {
168        Control::new(self, self.critical)
169    }
170}
171
172impl ControlType for DomainScopeControl {
173    const OID: &'static str = DOMAIN_SCOPE_OID;
174}
175
176impl RequestControl for DomainScopeControl {
177    fn value(&self) -> Option<Vec<u8>> {
178        None
179    }
180}
181
182/// A single sort key for server-side sort (RFC 2891).
183#[derive(Debug, Clone)]
184pub struct SortKey {
185    pub attribute_type: String,
186    pub ordering_rule: Option<String>,
187    pub reverse_order: bool,
188}
189
190impl SortKey {
191    pub fn new(attribute_type: impl Into<String>) -> Self {
192        Self {
193            attribute_type: attribute_type.into(),
194            ordering_rule: None,
195            reverse_order: false,
196        }
197    }
198
199    pub fn reverse(mut self) -> Self {
200        self.reverse_order = true;
201        self
202    }
203
204    pub fn ordering_rule(mut self, rule: impl Into<String>) -> Self {
205        self.ordering_rule = Some(rule.into());
206        self
207    }
208}
209
210/// Server-side sort request control value (RFC 2891).
211#[derive(Debug, Clone)]
212pub struct SortKeyList {
213    pub keys: Vec<SortKey>,
214}
215
216impl SortKeyList {
217    pub fn new(keys: Vec<SortKey>) -> Self {
218        Self { keys }
219    }
220
221    pub fn to_control(&self, critical: bool) -> Control {
222        Control::new(self, critical)
223    }
224}
225
226impl ControlType for SortKeyList {
227    const OID: &'static str = SERVER_SORT_REQUEST_OID;
228}
229
230impl RequestControl for SortKeyList {
231    fn value(&self) -> Option<Vec<u8>> {
232        let mut w = BerWriter::new();
233        w.write_sequence(Tag::sequence(), |seq| {
234            for key in &self.keys {
235                seq.write_sequence(Tag::sequence(), |inner| {
236                    inner.write_bytes(key.attribute_type.as_bytes());
237                    if let Some(rule) = &key.ordering_rule {
238                        inner.write_octet_string(ORDERING_RULE, rule.as_bytes());
239                    }
240                    if key.reverse_order {
241                        inner.write_octet_string(REVERSE_ORDER, &[0xFF]);
242                    }
243                });
244            }
245        });
246        Some(w.into_bytes())
247    }
248}
249
250/// Server-side sort response control value (RFC 2891).
251#[derive(Debug, Clone)]
252pub struct SortResult {
253    pub result_code: ResultCode,
254    pub attribute_type: Option<String>,
255}
256
257impl SortResult {
258    pub fn from_control(control: &Control) -> Result<Self, ProtoError> {
259        control.decode()
260    }
261}
262
263impl ControlType for SortResult {
264    const OID: &'static str = SERVER_SORT_RESPONSE_OID;
265}
266
267impl ResponseControl for SortResult {
268    fn from_value(value: Option<&[u8]>) -> Result<Self, ProtoError> {
269        let value = value
270            .ok_or_else(|| ProtoError::Protocol("sort response control missing value".into()))?;
271        BerReader::new(value)
272            .read_sequence(Tag::sequence(), |inner| {
273                let result_code = ResultCode::from_i64(inner.read_enumerated()?);
274                let attribute_type = if inner.peek_is(ATTRIBUTE_TYPE) {
275                    let raw = inner.read_implicit(ATTRIBUTE_TYPE)?;
276                    Some(String::from_utf8_lossy(raw).into_owned())
277                } else {
278                    None
279                };
280                Ok(Self {
281                    result_code,
282                    attribute_type,
283                })
284            })
285            .map_err(Into::into)
286    }
287}
288
289pub fn encode_controls(w: &mut BerWriter, controls: &[Control]) {
290    w.write_sequence(CONTROLS, |outer| {
291        for ctrl in controls {
292            outer.write_sequence(Tag::sequence(), |inner| {
293                inner.write_bytes(ctrl.oid.as_bytes());
294                if ctrl.critical {
295                    inner.write_boolean(true);
296                }
297                if let Some(val) = &ctrl.value {
298                    inner.write_bytes(val);
299                }
300            });
301        }
302    });
303}
304
305pub fn decode_controls(r: &mut BerReader<'_>) -> Result<Vec<Control>, ldap_client_ber::BerError> {
306    r.read_sequence_lax(CONTROLS, |outer| {
307        outer.read_each(|outer| {
308            outer.read_sequence(Tag::sequence(), |inner| {
309                let oid = String::from_utf8_lossy(inner.read_octet_string()?).into_owned();
310                let critical = if inner.peek_is(Tag::universal(BOOLEAN)) {
311                    inner.read_boolean()?
312                } else {
313                    false
314                };
315                let value = if inner.is_empty() {
316                    None
317                } else {
318                    Some(inner.read_octet_string()?.to_vec())
319                };
320
321                Ok(Control {
322                    oid,
323                    critical,
324                    value,
325                })
326            })
327        })
328    })
329}