1use std::fmt;
4
5use ldap_client_ber::reader::decode_i64_bytes;
6use ldap_client_ber::tag::Tag;
7use ldap_client_ber::{BerError, BerReader, BerWriter};
8use zeroize::Zeroizing;
9
10use crate::ProtoError;
11use crate::controls::{CONTROLS, Control, decode_controls, encode_controls};
12use crate::filter::Filter;
13use crate::result_code::ResultCode;
14use crate::syntax::to_utf8;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19pub struct MessageId(pub i32);
20
21impl MessageId {
22 pub const UNSOLICITED: MessageId = MessageId(0);
23 pub const FIRST: MessageId = MessageId(1);
24
25 pub const fn get(self) -> i32 {
26 self.0
27 }
28
29 pub fn next(self) -> MessageId {
32 match self.0.checked_add(1) {
33 Some(next) => MessageId(next),
34 None => MessageId::FIRST,
35 }
36 }
37}
38
39impl TryFrom<i64> for MessageId {
40 type Error = BerError;
41
42 fn try_from(id: i64) -> Result<Self, Self::Error> {
43 i32::try_from(id)
44 .ok()
45 .filter(|id| *id >= 0)
46 .map(MessageId)
47 .ok_or(BerError::InvalidInteger)
48 }
49}
50
51#[derive(Debug, Clone, PartialEq, Eq)]
53pub struct LdapMessage {
54 pub message_id: MessageId,
55 pub operation: LdapOperation,
56 pub controls: Vec<Control>,
57}
58
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub enum LdapOperation {
61 BindRequest(BindRequest),
62 BindResponse(BindResponse),
63 UnbindRequest,
64 SearchRequest(SearchRequest),
65 SearchResultEntry(SearchResultEntry),
66 SearchResultDone(LdapResult),
67 SearchResultReference(Vec<String>),
68 ModifyRequest(ModifyRequest),
69 ModifyResponse(LdapResult),
70 AddRequest(AddRequest),
71 AddResponse(LdapResult),
72 DeleteRequest(String),
73 DeleteResponse(LdapResult),
74 ModifyDnRequest(ModifyDnRequest),
75 ModifyDnResponse(LdapResult),
76 CompareRequest(CompareRequest),
77 CompareResponse(LdapResult),
78 AbandonRequest(MessageId),
79 ExtendedRequest(ExtendedRequest),
80 ExtendedResponse(ExtendedResponse),
81 IntermediateResponse(IntermediateResponse),
82}
83
84pub const STARTTLS_OID: &str = "1.3.6.1.4.1.1466.20037";
85pub const NOTICE_OF_DISCONNECTION_OID: &str = "1.3.6.1.4.1.1466.20036";
86pub const WHO_AM_I_OID: &str = "1.3.6.1.4.1.4203.1.11.3";
87
88const BIND_REQUEST: Tag = Tag::application(0);
90const BIND_RESPONSE: Tag = Tag::application(1);
91const UNBIND_REQUEST: Tag = Tag::application_primitive(2);
92const SEARCH_REQUEST: Tag = Tag::application(3);
93const SEARCH_RESULT_ENTRY: Tag = Tag::application(4);
94const SEARCH_RESULT_DONE: Tag = Tag::application(5);
95const MODIFY_REQUEST: Tag = Tag::application(6);
96const MODIFY_RESPONSE: Tag = Tag::application(7);
97const ADD_REQUEST: Tag = Tag::application(8);
98const ADD_RESPONSE: Tag = Tag::application(9);
99const DEL_REQUEST: Tag = Tag::application_primitive(10);
100const DEL_RESPONSE: Tag = Tag::application(11);
101const MODIFY_DN_REQUEST: Tag = Tag::application(12);
102const MODIFY_DN_RESPONSE: Tag = Tag::application(13);
103const COMPARE_REQUEST: Tag = Tag::application(14);
104const COMPARE_RESPONSE: Tag = Tag::application(15);
105const ABANDON_REQUEST: Tag = Tag::application_primitive(16);
106const SEARCH_RESULT_REFERENCE: Tag = Tag::application(19);
107const EXTENDED_REQUEST: Tag = Tag::application(23);
108const EXTENDED_RESPONSE: Tag = Tag::application(24);
109const INTERMEDIATE_RESPONSE: Tag = Tag::application(25);
110
111const SIMPLE: Tag = Tag::context(0);
112const SASL: Tag = Tag::context_constructed(3);
113const REFERRAL: Tag = Tag::context_constructed(3);
114const SERVER_SASL_CREDS: Tag = Tag::context(7);
115const NEW_SUPERIOR: Tag = Tag::context(0);
116const REQUEST_NAME: Tag = Tag::context(0);
117const REQUEST_VALUE: Tag = Tag::context(1);
118const RESPONSE_NAME: Tag = Tag::context(10);
119const RESPONSE_VALUE: Tag = Tag::context(11);
120const INTERMEDIATE_NAME: Tag = Tag::context(0);
121const INTERMEDIATE_VALUE: Tag = Tag::context(1);
122
123#[derive(Debug, Clone, PartialEq, Eq)]
126pub struct BindRequest {
127 pub version: i64,
128 pub name: String,
129 pub authentication: BindAuthentication,
130}
131
132#[derive(Clone, PartialEq, Eq)]
133pub enum BindAuthentication {
134 Simple(Zeroizing<Vec<u8>>),
135 Sasl {
136 mechanism: String,
137 credentials: Option<Zeroizing<Vec<u8>>>,
138 },
139}
140
141impl fmt::Debug for BindAuthentication {
142 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143 match self {
144 Self::Simple(_) => f.debug_tuple("Simple").field(&"[REDACTED]").finish(),
145 Self::Sasl { mechanism, .. } => f
146 .debug_struct("Sasl")
147 .field("mechanism", mechanism)
148 .field("credentials", &"[REDACTED]")
149 .finish(),
150 }
151 }
152}
153
154#[derive(Debug, Clone, PartialEq, Eq)]
155pub struct BindResponse {
156 pub result: LdapResult,
157 pub server_sasl_creds: Option<Vec<u8>>,
158}
159
160#[derive(Debug, Clone, PartialEq, Eq)]
161pub struct LdapResult {
162 pub code: ResultCode,
163 pub matched_dn: String,
164 pub diagnostic_message: String,
165 pub referral: Vec<String>,
166}
167
168#[derive(Debug, Clone, Copy, PartialEq, Eq)]
169pub enum SearchScope {
170 BaseObject = 0,
171 SingleLevel = 1,
172 WholeSubtree = 2,
173}
174
175impl SearchScope {
176 pub const ALL: [SearchScope; 3] = [Self::BaseObject, Self::SingleLevel, Self::WholeSubtree];
177
178 pub const fn as_str(self) -> &'static str {
180 match self {
181 Self::BaseObject => "base",
182 Self::SingleLevel => "one",
183 Self::WholeSubtree => "sub",
184 }
185 }
186}
187
188impl fmt::Display for SearchScope {
189 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
190 f.write_str(self.as_str())
191 }
192}
193
194impl std::str::FromStr for SearchScope {
195 type Err = ProtoError;
196
197 fn from_str(s: &str) -> Result<Self, Self::Err> {
198 Self::ALL
199 .into_iter()
200 .find(|scope| scope.as_str().eq_ignore_ascii_case(s))
201 .ok_or_else(|| ProtoError::Protocol(format!("unknown scope: {s}")))
202 }
203}
204
205#[derive(Debug, Clone, Copy, PartialEq, Eq)]
206pub enum DerefAliases {
207 NeverDerefAliases = 0,
208 DerefInSearching = 1,
209 DerefFindingBaseObj = 2,
210 DerefAlways = 3,
211}
212
213impl TryFrom<i64> for SearchScope {
214 type Error = ProtoError;
215
216 fn try_from(value: i64) -> Result<Self, Self::Error> {
217 match value {
218 0 => Ok(Self::BaseObject),
219 1 => Ok(Self::SingleLevel),
220 2 => Ok(Self::WholeSubtree),
221 n => Err(ProtoError::Protocol(format!("invalid search scope: {n}"))),
222 }
223 }
224}
225
226impl TryFrom<i64> for DerefAliases {
227 type Error = ProtoError;
228
229 fn try_from(value: i64) -> Result<Self, Self::Error> {
230 match value {
231 0 => Ok(Self::NeverDerefAliases),
232 1 => Ok(Self::DerefInSearching),
233 2 => Ok(Self::DerefFindingBaseObj),
234 3 => Ok(Self::DerefAlways),
235 n => Err(ProtoError::Protocol(format!("invalid deref aliases: {n}"))),
236 }
237 }
238}
239
240#[derive(Debug, Clone, PartialEq, Eq)]
241pub struct SearchRequest {
242 pub base_dn: String,
243 pub scope: SearchScope,
244 pub deref_aliases: DerefAliases,
245 pub size_limit: i32,
246 pub time_limit: i32,
247 pub types_only: bool,
248 pub filter: Filter,
249 pub attributes: Vec<String>,
250}
251
252#[derive(Debug, Clone, PartialEq, Eq)]
253pub struct SearchResultEntry {
254 pub dn: String,
255 pub attributes: Vec<PartialAttribute>,
256}
257
258#[derive(Debug, Clone, PartialEq, Eq)]
259pub struct PartialAttribute {
260 pub name: String,
261 pub values: Vec<Vec<u8>>,
262}
263
264impl PartialAttribute {
265 pub fn string_values(&self) -> Vec<&str> {
266 self.values
267 .iter()
268 .filter_map(|v| std::str::from_utf8(v).ok())
269 .collect()
270 }
271
272 pub fn first_string_value(&self) -> Option<&str> {
273 self.values
274 .first()
275 .and_then(|v| std::str::from_utf8(v).ok())
276 }
277
278 pub fn first_value(&self) -> Option<&[u8]> {
279 self.values.first().map(|v| v.as_slice())
280 }
281}
282
283impl SearchResultEntry {
284 pub fn attr(&self, name: &str) -> Option<&PartialAttribute> {
285 self.attributes
286 .iter()
287 .find(|a| a.name.eq_ignore_ascii_case(name))
288 }
289
290 pub fn first_value(&self, attr: &str) -> Option<&[u8]> {
291 self.attr(attr).and_then(|a| a.first_value())
292 }
293
294 pub fn first_string_value(&self, attr: &str) -> Option<&str> {
295 self.attr(attr).and_then(|a| a.first_string_value())
296 }
297}
298
299#[derive(Debug, Clone, PartialEq, Eq)]
300pub struct CompareRequest {
301 pub dn: String,
302 pub attr: String,
303 pub value: Vec<u8>,
304}
305
306#[derive(Debug, Clone, PartialEq, Eq)]
307pub struct AddRequest {
308 pub dn: String,
309 pub attributes: Vec<PartialAttribute>,
310}
311
312#[derive(Debug, Clone, PartialEq, Eq)]
313pub struct ModifyRequest {
314 pub dn: String,
315 pub changes: Vec<Modification>,
316}
317
318#[derive(Debug, Clone, PartialEq, Eq)]
319pub struct Modification {
320 pub operation: ModifyOperation,
321 pub attribute: PartialAttribute,
322}
323
324#[derive(Debug, Clone, Copy, PartialEq, Eq)]
325pub enum ModifyOperation {
326 Add = 0,
327 Delete = 1,
328 Replace = 2,
329 Increment = 3,
330}
331
332impl TryFrom<i64> for ModifyOperation {
333 type Error = ProtoError;
334
335 fn try_from(value: i64) -> Result<Self, Self::Error> {
336 match value {
337 0 => Ok(Self::Add),
338 1 => Ok(Self::Delete),
339 2 => Ok(Self::Replace),
340 3 => Ok(Self::Increment),
341 n => Err(ProtoError::Protocol(format!(
342 "invalid modify operation: {n}"
343 ))),
344 }
345 }
346}
347
348#[derive(Debug, Clone, PartialEq, Eq)]
349pub struct ModifyDnRequest {
350 pub dn: String,
351 pub new_rdn: String,
352 pub delete_old_rdn: bool,
353 pub new_superior: Option<String>,
354}
355
356#[derive(Debug, Clone, PartialEq, Eq)]
357pub struct ExtendedRequest {
358 pub oid: String,
359 pub value: Option<Vec<u8>>,
360}
361
362#[derive(Debug, Clone, PartialEq, Eq)]
363pub struct ExtendedResponse {
364 pub result: LdapResult,
365 pub oid: Option<String>,
366 pub value: Option<Vec<u8>>,
367}
368
369#[derive(Debug, Clone, PartialEq, Eq)]
370pub struct IntermediateResponse {
371 pub oid: Option<String>,
372 pub value: Option<Vec<u8>>,
373}
374
375pub trait HasLdapResult {
376 fn result(&self) -> &LdapResult;
377
378 fn is_success(&self) -> bool {
379 self.result().code.is_success()
380 }
381
382 fn is_referral(&self) -> bool {
383 self.result().code.is_referral()
384 }
385
386 fn referral_urls(&self) -> &[String] {
387 &self.result().referral
388 }
389}
390
391impl HasLdapResult for LdapResult {
392 fn result(&self) -> &LdapResult {
393 self
394 }
395}
396
397impl HasLdapResult for BindResponse {
398 fn result(&self) -> &LdapResult {
399 &self.result
400 }
401}
402
403impl HasLdapResult for ExtendedResponse {
404 fn result(&self) -> &LdapResult {
405 &self.result
406 }
407}
408
409impl LdapMessage {
412 pub fn encode(&self) -> Vec<u8> {
413 let mut w = BerWriter::new();
414 w.write_sequence(Tag::sequence(), |msg| {
415 msg.write_integer(i64::from(self.message_id.get()));
416 encode_operation(msg, &self.operation);
417 if !self.controls.is_empty() {
418 encode_controls(msg, &self.controls);
419 }
420 });
421 w.into_bytes()
422 }
423
424 pub fn decode(data: &[u8]) -> Result<Self, ProtoError> {
425 let mut r = BerReader::new(data);
426 let (message_id, tag, value, controls) = r.read_sequence_lax(Tag::sequence(), |msg| {
427 let message_id = MessageId::try_from(msg.read_integer()?)?;
428 let (tag, value) = msg.read_element()?;
429 let controls = if msg.peek_is(CONTROLS) {
430 decode_controls(msg)?
431 } else {
432 Vec::new()
433 };
434 Ok((message_id, tag, value, controls))
435 })?;
436 r.finish()?;
437
438 Ok(LdapMessage {
439 message_id,
440 operation: decode_operation(tag, value)?,
441 controls,
442 })
443 }
444}
445
446fn encode_operation(w: &mut BerWriter, op: &LdapOperation) {
447 match op {
448 LdapOperation::BindRequest(req) => {
449 w.write_sequence(BIND_REQUEST, |inner| {
450 inner.write_integer(req.version);
451 inner.write_bytes(req.name.as_bytes());
452 match &req.authentication {
453 BindAuthentication::Simple(pw) => {
454 inner.write_octet_string(SIMPLE, pw);
455 }
456 BindAuthentication::Sasl {
457 mechanism,
458 credentials,
459 } => {
460 inner.write_sequence(SASL, |sasl| {
461 sasl.write_bytes(mechanism.as_bytes());
462 if let Some(creds) = credentials {
463 sasl.write_bytes(creds);
464 }
465 });
466 }
467 }
468 });
469 }
470 LdapOperation::BindResponse(resp) => {
471 w.write_sequence(BIND_RESPONSE, |inner| {
472 encode_ldap_result(inner, &resp.result);
473 if let Some(creds) = &resp.server_sasl_creds {
474 inner.write_octet_string(SERVER_SASL_CREDS, creds);
475 }
476 });
477 }
478 LdapOperation::UnbindRequest => {
479 w.write_octet_string(UNBIND_REQUEST, &[]);
480 }
481 LdapOperation::SearchRequest(req) => {
482 w.write_sequence(SEARCH_REQUEST, |inner| {
483 inner.write_bytes(req.base_dn.as_bytes());
484 inner.write_enumerated(req.scope as i64);
485 inner.write_enumerated(req.deref_aliases as i64);
486 inner.write_integer(i64::from(req.size_limit));
487 inner.write_integer(i64::from(req.time_limit));
488 inner.write_boolean(req.types_only);
489 req.filter.encode(inner);
490 inner.write_sequence(Tag::sequence(), |attrs| {
491 for attr in &req.attributes {
492 attrs.write_bytes(attr.as_bytes());
493 }
494 });
495 });
496 }
497 LdapOperation::SearchResultEntry(entry) => {
498 w.write_sequence(SEARCH_RESULT_ENTRY, |inner| {
499 inner.write_bytes(entry.dn.as_bytes());
500 encode_attributes(inner, &entry.attributes);
501 });
502 }
503 LdapOperation::SearchResultDone(result) => {
504 encode_result_operation(w, SEARCH_RESULT_DONE, result);
505 }
506 LdapOperation::SearchResultReference(urls) => {
507 w.write_sequence(SEARCH_RESULT_REFERENCE, |inner| {
508 for url in urls {
509 inner.write_bytes(url.as_bytes());
510 }
511 });
512 }
513 LdapOperation::ModifyRequest(req) => {
514 w.write_sequence(MODIFY_REQUEST, |inner| {
515 inner.write_bytes(req.dn.as_bytes());
516 inner.write_sequence(Tag::sequence(), |changes| {
517 for modification in &req.changes {
518 changes.write_sequence(Tag::sequence(), |change| {
519 change.write_enumerated(modification.operation as i64);
520 encode_partial_attribute(change, &modification.attribute);
521 });
522 }
523 });
524 });
525 }
526 LdapOperation::ModifyResponse(result) => {
527 encode_result_operation(w, MODIFY_RESPONSE, result);
528 }
529 LdapOperation::AddRequest(req) => {
530 w.write_sequence(ADD_REQUEST, |inner| {
531 inner.write_bytes(req.dn.as_bytes());
532 encode_attributes(inner, &req.attributes);
533 });
534 }
535 LdapOperation::AddResponse(result) => {
536 encode_result_operation(w, ADD_RESPONSE, result);
537 }
538 LdapOperation::DeleteRequest(dn) => {
539 w.write_octet_string(DEL_REQUEST, dn.as_bytes());
540 }
541 LdapOperation::DeleteResponse(result) => {
542 encode_result_operation(w, DEL_RESPONSE, result);
543 }
544 LdapOperation::ModifyDnRequest(req) => {
545 w.write_sequence(MODIFY_DN_REQUEST, |inner| {
546 inner.write_bytes(req.dn.as_bytes());
547 inner.write_bytes(req.new_rdn.as_bytes());
548 inner.write_boolean(req.delete_old_rdn);
549 if let Some(sup) = &req.new_superior {
550 inner.write_octet_string(NEW_SUPERIOR, sup.as_bytes());
551 }
552 });
553 }
554 LdapOperation::ModifyDnResponse(result) => {
555 encode_result_operation(w, MODIFY_DN_RESPONSE, result);
556 }
557 LdapOperation::CompareRequest(req) => {
558 w.write_sequence(COMPARE_REQUEST, |inner| {
559 inner.write_bytes(req.dn.as_bytes());
560 inner.write_sequence(Tag::sequence(), |ava| {
561 ava.write_bytes(req.attr.as_bytes());
562 ava.write_bytes(&req.value);
563 });
564 });
565 }
566 LdapOperation::CompareResponse(result) => {
567 encode_result_operation(w, COMPARE_RESPONSE, result);
568 }
569 LdapOperation::AbandonRequest(id) => {
570 let bytes = ldap_client_ber::writer::encode_i64_bytes(i64::from(id.get()));
571 w.write_octet_string(ABANDON_REQUEST, &bytes);
572 }
573 LdapOperation::ExtendedRequest(req) => {
574 w.write_sequence(EXTENDED_REQUEST, |inner| {
575 inner.write_octet_string(REQUEST_NAME, req.oid.as_bytes());
576 if let Some(val) = &req.value {
577 inner.write_octet_string(REQUEST_VALUE, val);
578 }
579 });
580 }
581 LdapOperation::ExtendedResponse(resp) => {
582 w.write_sequence(EXTENDED_RESPONSE, |inner| {
583 encode_ldap_result(inner, &resp.result);
584 if let Some(oid) = &resp.oid {
585 inner.write_octet_string(RESPONSE_NAME, oid.as_bytes());
586 }
587 if let Some(val) = &resp.value {
588 inner.write_octet_string(RESPONSE_VALUE, val);
589 }
590 });
591 }
592 LdapOperation::IntermediateResponse(resp) => {
593 w.write_sequence(INTERMEDIATE_RESPONSE, |inner| {
594 if let Some(oid) = &resp.oid {
595 inner.write_octet_string(INTERMEDIATE_NAME, oid.as_bytes());
596 }
597 if let Some(val) = &resp.value {
598 inner.write_octet_string(INTERMEDIATE_VALUE, val);
599 }
600 });
601 }
602 }
603}
604
605fn encode_result_operation(w: &mut BerWriter, tag: Tag, result: &LdapResult) {
606 w.write_sequence(tag, |inner| encode_ldap_result(inner, result));
607}
608
609fn encode_ldap_result(w: &mut BerWriter, result: &LdapResult) {
610 w.write_enumerated(i64::from(result.code.code()));
611 w.write_bytes(result.matched_dn.as_bytes());
612 w.write_bytes(result.diagnostic_message.as_bytes());
613 if !result.referral.is_empty() {
614 w.write_sequence(REFERRAL, |urls| {
615 for url in &result.referral {
616 urls.write_bytes(url.as_bytes());
617 }
618 });
619 }
620}
621
622fn encode_attributes(w: &mut BerWriter, attributes: &[PartialAttribute]) {
623 w.write_sequence(Tag::sequence(), |attrs| {
624 for attr in attributes {
625 encode_partial_attribute(attrs, attr);
626 }
627 });
628}
629
630fn encode_partial_attribute(w: &mut BerWriter, attr: &PartialAttribute) {
631 w.write_sequence(Tag::sequence(), |inner| {
632 inner.write_bytes(attr.name.as_bytes());
633 inner.write_sequence(Tag::set(), |vals| {
634 for val in &attr.values {
635 vals.write_bytes(val);
636 }
637 });
638 });
639}
640
641fn decode_operation(tag: Tag, value: &[u8]) -> Result<LdapOperation, ProtoError> {
644 let mut r = BerReader::new(value);
645
646 let operation = match tag {
647 BIND_REQUEST => {
648 let version = r.read_integer()?;
649 let name = to_utf8(r.read_octet_string()?)?;
650 let authentication = match r.peek_tag()? {
651 SIMPLE => {
652 BindAuthentication::Simple(Zeroizing::new(r.read_implicit(SIMPLE)?.to_vec()))
653 }
654 SASL => r.read_sequence(SASL, |sasl| {
655 let mechanism = to_utf8(sasl.read_octet_string()?)?;
656 let credentials = if sasl.is_empty() {
657 None
658 } else {
659 Some(Zeroizing::new(sasl.read_octet_string()?.to_vec()))
660 };
661 Ok(BindAuthentication::Sasl {
662 mechanism,
663 credentials,
664 })
665 })?,
666 actual => {
667 return Err(BerError::UnexpectedTag {
668 expected: SIMPLE,
669 actual,
670 }
671 .into());
672 }
673 };
674 LdapOperation::BindRequest(BindRequest {
675 version,
676 name,
677 authentication,
678 })
679 }
680 BIND_RESPONSE => {
681 let result = decode_ldap_result(&mut r)?;
682 let server_sasl_creds = if r.peek_is(SERVER_SASL_CREDS) {
683 Some(r.read_implicit(SERVER_SASL_CREDS)?.to_vec())
684 } else {
685 None
686 };
687 LdapOperation::BindResponse(BindResponse {
688 result,
689 server_sasl_creds,
690 })
691 }
692 UNBIND_REQUEST => LdapOperation::UnbindRequest,
693 SEARCH_REQUEST => {
694 let base_dn = to_utf8(r.read_octet_string()?)?;
695 let scope = SearchScope::try_from(r.read_enumerated()?)?;
696 let deref_aliases = DerefAliases::try_from(r.read_enumerated()?)?;
697 let size_limit = to_i32(r.read_integer()?, "size limit")?;
698 let time_limit = to_i32(r.read_integer()?, "time limit")?;
699 let types_only = r.read_boolean()?;
700 let filter = Filter::decode(&mut r)?;
701 let attributes = r.read_sequence(Tag::sequence(), |attrs| {
702 attrs.read_each(|attr| to_utf8(attr.read_octet_string()?))
703 })?;
704 LdapOperation::SearchRequest(SearchRequest {
705 base_dn,
706 scope,
707 deref_aliases,
708 size_limit,
709 time_limit,
710 types_only,
711 filter,
712 attributes,
713 })
714 }
715 SEARCH_RESULT_ENTRY => {
716 let dn = to_utf8(r.read_octet_string()?)?;
717 let attributes = decode_attributes(&mut r)?;
718 LdapOperation::SearchResultEntry(SearchResultEntry { dn, attributes })
719 }
720 SEARCH_RESULT_DONE => LdapOperation::SearchResultDone(decode_ldap_result(&mut r)?),
721 SEARCH_RESULT_REFERENCE => {
722 LdapOperation::SearchResultReference(r.read_each(|r| to_utf8(r.read_octet_string()?))?)
723 }
724 MODIFY_REQUEST => {
725 let dn = to_utf8(r.read_octet_string()?)?;
726 let changes = r.read_sequence(Tag::sequence(), |changes| {
727 changes.read_each(|change| {
728 change.read_sequence(Tag::sequence(), |change| {
729 let operation = change.read_enumerated()?;
730 let attribute = decode_partial_attribute(change)?;
731 Ok((operation, attribute))
732 })
733 })
734 })?;
735 let changes = changes
736 .into_iter()
737 .map(|(operation, attribute)| {
738 Ok(Modification {
739 operation: ModifyOperation::try_from(operation)?,
740 attribute,
741 })
742 })
743 .collect::<Result<_, ProtoError>>()?;
744 LdapOperation::ModifyRequest(ModifyRequest { dn, changes })
745 }
746 MODIFY_RESPONSE => LdapOperation::ModifyResponse(decode_ldap_result(&mut r)?),
747 ADD_REQUEST => {
748 let dn = to_utf8(r.read_octet_string()?)?;
749 let attributes = decode_attributes(&mut r)?;
750 LdapOperation::AddRequest(AddRequest { dn, attributes })
751 }
752 ADD_RESPONSE => LdapOperation::AddResponse(decode_ldap_result(&mut r)?),
753 DEL_REQUEST => LdapOperation::DeleteRequest(to_utf8(value)?),
754 DEL_RESPONSE => LdapOperation::DeleteResponse(decode_ldap_result(&mut r)?),
755 MODIFY_DN_REQUEST => {
756 let dn = to_utf8(r.read_octet_string()?)?;
757 let new_rdn = to_utf8(r.read_octet_string()?)?;
758 let delete_old_rdn = r.read_boolean()?;
759 let new_superior = if r.peek_is(NEW_SUPERIOR) {
760 Some(to_utf8(r.read_implicit(NEW_SUPERIOR)?)?)
761 } else {
762 None
763 };
764 LdapOperation::ModifyDnRequest(ModifyDnRequest {
765 dn,
766 new_rdn,
767 delete_old_rdn,
768 new_superior,
769 })
770 }
771 MODIFY_DN_RESPONSE => LdapOperation::ModifyDnResponse(decode_ldap_result(&mut r)?),
772 COMPARE_REQUEST => {
773 let dn = to_utf8(r.read_octet_string()?)?;
774 let (attr, value) = r.read_sequence(Tag::sequence(), |ava| {
775 Ok((
776 to_utf8(ava.read_octet_string()?)?,
777 ava.read_octet_string()?.to_vec(),
778 ))
779 })?;
780 LdapOperation::CompareRequest(CompareRequest { dn, attr, value })
781 }
782 COMPARE_RESPONSE => LdapOperation::CompareResponse(decode_ldap_result(&mut r)?),
783 ABANDON_REQUEST => {
784 LdapOperation::AbandonRequest(MessageId::try_from(decode_i64_bytes(value)?)?)
785 }
786 EXTENDED_REQUEST => {
787 let oid = to_utf8(r.read_implicit(REQUEST_NAME)?)?;
788 let value = if r.peek_is(REQUEST_VALUE) {
789 Some(r.read_implicit(REQUEST_VALUE)?.to_vec())
790 } else {
791 None
792 };
793 LdapOperation::ExtendedRequest(ExtendedRequest { oid, value })
794 }
795 EXTENDED_RESPONSE => {
796 let result = decode_ldap_result(&mut r)?;
797 let mut oid = None;
798 let mut value = None;
799 while !r.is_empty() {
800 match r.peek_tag()? {
801 RESPONSE_NAME => oid = Some(to_utf8(r.read_implicit(RESPONSE_NAME)?)?),
802 RESPONSE_VALUE => value = Some(r.read_implicit(RESPONSE_VALUE)?.to_vec()),
803 _ => {
804 r.read_element()?;
805 }
806 }
807 }
808 LdapOperation::ExtendedResponse(ExtendedResponse { result, oid, value })
809 }
810 INTERMEDIATE_RESPONSE => {
811 let mut oid = None;
812 let mut value = None;
813 while !r.is_empty() {
814 match r.peek_tag()? {
815 INTERMEDIATE_NAME => {
816 oid = Some(to_utf8(r.read_implicit(INTERMEDIATE_NAME)?)?);
817 }
818 INTERMEDIATE_VALUE => {
819 value = Some(r.read_implicit(INTERMEDIATE_VALUE)?.to_vec());
820 }
821 _ => {
822 r.read_element()?;
823 }
824 }
825 }
826 LdapOperation::IntermediateResponse(IntermediateResponse { oid, value })
827 }
828 other => {
829 return Err(ProtoError::Protocol(format!(
830 "unknown operation tag: {other:?}"
831 )));
832 }
833 };
834 Ok(operation)
835}
836
837fn to_i32(value: i64, what: &str) -> Result<i32, ProtoError> {
838 i32::try_from(value).map_err(|_| ProtoError::Protocol(format!("{what} out of range: {value}")))
839}
840
841fn decode_ldap_result(r: &mut BerReader<'_>) -> Result<LdapResult, ProtoError> {
842 let code = ResultCode::from_i64(r.read_enumerated()?);
843 let matched_dn = to_utf8(r.read_octet_string()?)?;
844 let diagnostic_message = String::from_utf8_lossy(r.read_octet_string()?).into_owned();
846
847 let referral = if r.peek_is(REFERRAL) {
848 r.read_sequence(REFERRAL, |urls| {
849 urls.read_each(|url| to_utf8(url.read_octet_string()?))
850 })?
851 } else {
852 Vec::new()
853 };
854
855 Ok(LdapResult {
856 code,
857 matched_dn,
858 diagnostic_message,
859 referral,
860 })
861}
862
863fn decode_attributes(r: &mut BerReader<'_>) -> Result<Vec<PartialAttribute>, BerError> {
864 r.read_sequence(Tag::sequence(), |attrs| {
865 attrs.read_each(decode_partial_attribute)
866 })
867}
868
869fn decode_partial_attribute(r: &mut BerReader<'_>) -> Result<PartialAttribute, BerError> {
870 r.read_sequence(Tag::sequence(), |attr| {
871 let name = to_utf8(attr.read_octet_string()?)?;
872 let values = attr.read_sequence(Tag::set(), |vals| {
873 vals.read_each(|val| Ok(val.read_octet_string()?.to_vec()))
874 })?;
875 Ok(PartialAttribute { name, values })
876 })
877}