Skip to main content

ldap_client/client/
search.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3use std::collections::HashSet;
4use std::num::NonZeroU32;
5use std::time::Duration;
6
7use ldap_client_proto::{
8    Control, DerefAliases, Filter, LdapOperation, LdapResult, MessageId, PagedResultsControl,
9    ProtoError, ResultCode, SearchRequest, SearchResultEntry, SearchScope,
10};
11
12use super::session::{Session, TransportError};
13use super::{Client, MAX_SEARCH_ENTRIES, ReferralPolicy, SearchResult};
14use crate::Error;
15
16#[derive(Clone, Debug)]
17enum SearchBase {
18    ClientDefault,
19    Dn(String),
20}
21
22impl SearchBase {
23    /// The existing search methods take an empty base to mean the client's
24    /// default base.
25    fn from_legacy(base: String) -> Self {
26        if base.is_empty() {
27            Self::ClientDefault
28        } else {
29            Self::Dn(base)
30        }
31    }
32}
33
34#[derive(Clone, Debug)]
35pub struct SearchParams {
36    base: SearchBase,
37    scope: SearchScope,
38    filter: Filter,
39    attributes: Vec<String>,
40    deref_aliases: DerefAliases,
41    size_limit: Option<NonZeroU32>,
42    time_limit: Option<Duration>,
43    types_only: bool,
44    controls: Vec<Control>,
45}
46
47impl SearchParams {
48    /// A search under `base`. The empty DN is the root DSE, not the client's
49    /// default base.
50    pub fn new(base: impl Into<String>, scope: SearchScope, filter: Filter) -> Self {
51        Self::with_base(SearchBase::Dn(base.into()), scope, filter)
52    }
53
54    /// A search under the base DN the client was configured with, or under
55    /// the empty DN when it has none.
56    pub fn under_default_base(scope: SearchScope, filter: Filter) -> Self {
57        Self::with_base(SearchBase::ClientDefault, scope, filter)
58    }
59
60    fn with_base(base: SearchBase, scope: SearchScope, filter: Filter) -> Self {
61        Self {
62            base,
63            scope,
64            filter,
65            attributes: Vec::new(),
66            deref_aliases: DerefAliases::NeverDerefAliases,
67            size_limit: None,
68            time_limit: None,
69            types_only: false,
70            controls: Vec::new(),
71        }
72    }
73
74    pub(super) fn from_legacy(
75        base: String,
76        scope: SearchScope,
77        filter: Filter,
78        attributes: Vec<String>,
79    ) -> Self {
80        Self::with_base(SearchBase::from_legacy(base), scope, filter).attributes(attributes)
81    }
82
83    pub fn attributes(mut self, attributes: impl IntoIterator<Item = impl Into<String>>) -> Self {
84        self.attributes = attributes.into_iter().map(Into::into).collect();
85        self
86    }
87
88    pub fn deref_aliases(mut self, deref: DerefAliases) -> Self {
89        self.deref_aliases = deref;
90        self
91    }
92
93    pub fn size_limit(mut self, limit: NonZeroU32) -> Self {
94        self.size_limit = Some(limit);
95        self
96    }
97
98    pub fn time_limit(mut self, limit: Duration) -> Self {
99        self.time_limit = Some(limit);
100        self
101    }
102
103    pub fn types_only(mut self) -> Self {
104        self.types_only = true;
105        self
106    }
107
108    pub fn controls(mut self, controls: Vec<Control>) -> Self {
109        self.controls = controls;
110        self
111    }
112
113    fn request(self, default_base: Option<&str>) -> (SearchRequest, Vec<Control>) {
114        let base_dn = match self.base {
115            SearchBase::Dn(dn) => dn,
116            SearchBase::ClientDefault => default_base.unwrap_or_default().to_owned(),
117        };
118        let request = SearchRequest {
119            base_dn,
120            scope: self.scope,
121            deref_aliases: self.deref_aliases,
122            size_limit: self.size_limit.map_or(0, wire_size_limit),
123            time_limit: self.time_limit.map_or(0, wire_time_limit),
124            types_only: self.types_only,
125            filter: self.filter,
126            attributes: self.attributes,
127        };
128        (request, self.controls)
129    }
130}
131
132/// The wire's limit is an `i32`, and no server can count higher.
133fn wire_size_limit(limit: NonZeroU32) -> i32 {
134    i32::try_from(limit.get()).unwrap_or(i32::MAX)
135}
136
137/// Whole seconds rounded up, so that a sub-second limit does not become the
138/// wire's 0, which means no limit.
139fn wire_time_limit(limit: Duration) -> i32 {
140    let seconds = limit
141        .as_secs()
142        .saturating_add(u64::from(limit.subsec_nanos() > 0));
143    i32::try_from(seconds.max(1)).unwrap_or(i32::MAX)
144}
145
146struct Collected {
147    entries: Vec<SearchResultEntry>,
148    references: Vec<String>,
149    done: LdapResult,
150    controls: Vec<Control>,
151}
152
153async fn collect(session: &mut Session, id: MessageId) -> Result<Collected, TransportError> {
154    let mut entries = Vec::new();
155    let mut references = Vec::new();
156    loop {
157        let message = session.receive(id).await?;
158        match message.operation {
159            LdapOperation::SearchResultEntry(entry) => {
160                if entries.len() >= MAX_SEARCH_ENTRIES {
161                    return Err(TransportError::entry_limit(MAX_SEARCH_ENTRIES));
162                }
163                entries.push(entry);
164            }
165            LdapOperation::SearchResultReference(urls) => references.extend(urls),
166            LdapOperation::SearchResultDone(done) => {
167                return Ok(Collected {
168                    entries,
169                    references,
170                    done,
171                    controls: message.controls,
172                });
173            }
174            _ => {
175                return Err(ProtoError::Protocol(
176                    "unexpected response, expected SearchResult*".into(),
177                )
178                .into());
179            }
180        }
181    }
182}
183
184impl Client {
185    pub async fn search_with(&self, params: SearchParams) -> Result<SearchResult, Error> {
186        let (request, controls) = params.request(self.settings.base_dn.as_deref());
187        let collected = self
188            .with_session(async |session| {
189                let id = session
190                    .send(LdapOperation::SearchRequest(request), controls)
191                    .await?;
192                collect(session, id).await
193            })
194            .await?;
195
196        let Collected {
197            entries,
198            references: mut referrals,
199            done,
200            controls,
201        } = collected;
202        match done.code {
203            ResultCode::Success => {}
204            ResultCode::Referral if self.settings.referral_policy == ReferralPolicy::Ignore => {
205                referrals.extend(done.referral);
206            }
207            _ => return Err(Error::from_failed_result(&done)),
208        }
209        Ok(SearchResult {
210            entries,
211            referrals,
212            controls,
213        })
214    }
215}
216
217#[derive(Debug)]
218enum PageState {
219    Start,
220    Continue(Vec<u8>),
221    Done,
222}
223
224/// Incremental paged search that yields one page of results at a time.
225///
226/// Created via [`Client::search_paged_stream`]. Call [`next_page`](PagedSearch::next_page)
227/// repeatedly to fetch pages. If you stop before exhausting results, call
228/// [`cancel`](PagedSearch::cancel) to release the server-side cookie.
229pub struct PagedSearch<'a> {
230    client: &'a Client,
231    params: SearchParams,
232    page_size: i32,
233    state: PageState,
234    cookies_seen: HashSet<Vec<u8>>,
235}
236
237impl<'a> PagedSearch<'a> {
238    pub(super) fn new(client: &'a Client, params: SearchParams, page_size: i32) -> Self {
239        Self {
240            client,
241            params,
242            page_size,
243            state: PageState::Start,
244            cookies_seen: HashSet::new(),
245        }
246    }
247
248    /// Fetch the next page of results.
249    ///
250    /// Returns `Ok(Some(entries))` for each page, `Ok(None)` when all pages
251    /// have been consumed. After an error the search is over: later calls
252    /// return `Ok(None)`.
253    pub async fn next_page(&mut self) -> Result<Option<Vec<SearchResultEntry>>, Error> {
254        let cookie = match std::mem::replace(&mut self.state, PageState::Done) {
255            PageState::Done => return Ok(None),
256            PageState::Start => Vec::new(),
257            PageState::Continue(cookie) => cookie,
258        };
259
260        let result = self.page(self.page_size, cookie.clone()).await?;
261        self.state = match Control::find::<PagedResultsControl>(&result.controls)? {
262            Some(paged)
263                if !paged.cookie.is_empty() && !self.cookies_seen.insert(paged.cookie.clone()) =>
264            {
265                return Err(Error::Proto(ProtoError::Protocol(
266                    "server repeated a paged results cookie".into(),
267                )));
268            }
269            Some(paged) if !paged.cookie.is_empty() => PageState::Continue(paged.cookie),
270            _ => PageState::Done,
271        };
272        Ok(Some(result.entries))
273    }
274
275    /// Send an abandon request (page size 0) to release the server cookie.
276    ///
277    /// Call this if you stop iterating before all pages are consumed. If you
278    /// don't, the server cookie will eventually time out on its own (~120 s).
279    pub async fn cancel(&mut self) -> Result<(), Error> {
280        if let PageState::Continue(cookie) = std::mem::replace(&mut self.state, PageState::Done) {
281            self.page(0, cookie).await?;
282        }
283        Ok(())
284    }
285
286    /// Returns `true` once all pages have been consumed or `cancel` was called.
287    pub fn is_done(&self) -> bool {
288        matches!(self.state, PageState::Done)
289    }
290
291    async fn page(&self, size: i32, cookie: Vec<u8>) -> Result<SearchResult, Error> {
292        let paged = PagedResultsControl::new(size).with_cookie(cookie);
293        let params = self.params.clone().controls(vec![paged.to_control()]);
294        self.client.search_with(params).await
295    }
296}