├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── examples ├── async.rs ├── bind.rs ├── bind_ssl.rs ├── search.rs └── search_async.rs └── src ├── bind.rs ├── ldap.rs ├── lib.rs ├── protocol.rs ├── search.rs ├── service.rs └── sync.rs /.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore vim swapfiles 2 | *.swp 3 | *.vim 4 | 5 | # Exuberant Ctags 6 | tags 7 | 8 | # Ignore build directory 9 | /build/ 10 | /target/ 11 | 12 | Cargo.lock 13 | 14 | /rfcs/ 15 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors = ["Gregor Reitzenstein "] 3 | description = "Pure Rust LDAP Implementation (Not abandonware anymore!)" 4 | documentation = "https://docs.rs/ldap" 5 | keywords = ["ldap", "libldap"] 6 | license = "MIT/Apache-2.0" 7 | name = "ldap" 8 | readme = "README.md" 9 | repository = "https://github.com/dequbed/rust-ldap" 10 | version = "0.4.0" 11 | 12 | [dependencies] 13 | byteorder = "1.0.0" 14 | futures = "0.1" 15 | log = "0.3.6" 16 | native-tls = "0.1.1" 17 | tokio-core = "0.1" 18 | tokio-proto = "0.1" 19 | tokio-service = "0.1" 20 | tokio-tls = { version = "0.1.2", features = [ "tokio-proto" ] } 21 | 22 | [dependencies.asnom] 23 | git = "https://github.com/dequbed/asnom.git" 24 | 25 | [dependencies.rfc4515] 26 | git = "https://github.com/dequbed/rfc4515.git" 27 | 28 | [dev-dependencies] 29 | env_logger = "0.4.2" 30 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | 204 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 |

rust-ldap

3 |
4 | 5 | A Pure-Rust LDAP Library using Tokio & Futures. 6 |
7 | 8 | 9 | rust-ldap on crates.io 10 | 11 | 12 | docs: release versions documentation 13 | 14 |

15 | 16 | Feel free to join #rust-ldap on Mozilla IRC for questions & general chat. 17 | 18 | 19 | ### RFC compliance 20 | 21 | - [x] Bind (4.2) 22 | - [ ] Unbind (4.3) 23 | - [ ] Search (4.5) 24 | - [ ] Modify (4.6) 25 | - [ ] Add (4.7) 26 | - [ ] Delete (4.8) 27 | - [ ] Modify DN (4.9) 28 | - [ ] Compare (4.10) 29 | - [ ] Abandon (4.11) 30 | - [ ] Extended Operation (4.12) 31 | - [ ] TLS / STARTTLS (4.14 / 5) 32 | 33 | ### rfc4515 (Search Filter String Representation) 34 | 35 | The search filter crate [has moved](https://github.com/dequbed/rfc4515). 36 | 37 | ## License 38 | 39 | Licensed under either of 40 | 41 | * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 42 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 43 | 44 | at your option. 45 | -------------------------------------------------------------------------------- /examples/async.rs: -------------------------------------------------------------------------------- 1 | extern crate tokio_core; 2 | extern crate futures; 3 | extern crate ldap; 4 | 5 | use futures::Future; 6 | use tokio_core::reactor::Core; 7 | use ldap::Ldap; 8 | 9 | 10 | fn main() { 11 | // TODO better error handling 12 | let mut core = Core::new().unwrap(); 13 | let handle = core.handle(); 14 | let addr = "127.0.0.1:389".parse().unwrap(); 15 | 16 | core.run(futures::lazy(|| { 17 | Ldap::connect(&addr, &handle) 18 | .and_then(|ldap| { 19 | ldap.simple_bind("cn=root,dc=plabs".to_string(), "asdf".to_string()) 20 | }) 21 | .map(|res| { 22 | if res { 23 | println!("Bind succeeded!"); 24 | } else { 25 | println!("Bind failed! :("); 26 | } 27 | }) 28 | })).unwrap(); 29 | } 30 | -------------------------------------------------------------------------------- /examples/bind.rs: -------------------------------------------------------------------------------- 1 | extern crate ldap; 2 | 3 | use ldap::LdapSync; 4 | 5 | pub fn main() { 6 | let addr = "127.0.0.1:389".parse().unwrap(); 7 | 8 | let mut ldap = LdapSync::connect(&addr).unwrap(); 9 | 10 | let res = ldap.simple_bind("cn=root,dc=plabs".to_string(), "asdf".to_string()).unwrap(); 11 | 12 | if res { 13 | println!("Bind succeeded!"); 14 | } else { 15 | println!("Bind failed! :("); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /examples/bind_ssl.rs: -------------------------------------------------------------------------------- 1 | extern crate ldap; 2 | 3 | use ldap::LdapSync; 4 | 5 | pub fn main() { 6 | let addr = "example.org:636"; 7 | 8 | let mut ldap = LdapSync::connect_ssl(&addr).unwrap(); 9 | 10 | let res = ldap.simple_bind("cn=root,dc=example,dc=org".to_string(), "secret".to_string()).unwrap(); 11 | 12 | if res { 13 | println!("Bind succeeded!"); 14 | } else { 15 | println!("Bind failed! :("); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /examples/search.rs: -------------------------------------------------------------------------------- 1 | extern crate ldap; 2 | 3 | use ldap::LdapSync; 4 | 5 | pub fn main() { 6 | let addr = "127.0.0.1:389".parse().unwrap(); 7 | 8 | let mut ldap = LdapSync::connect(&addr).unwrap(); 9 | 10 | let res = ldap.simple_bind("cn=root,dc=plabs".to_string(), "asdf".to_string()).unwrap(); 11 | 12 | if res { 13 | println!("Bind succeeded!"); 14 | let res2 = ldap.search("dc=plabs".to_string(), 15 | ldap::Scope::WholeSubtree, 16 | ldap::DerefAliases::Never, 17 | false, 18 | "(objectClass=*)".to_string(), 19 | vec![]); 20 | println!("Search result: {:?}", res2); 21 | } else { 22 | println!("Bind failed! :("); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /examples/search_async.rs: -------------------------------------------------------------------------------- 1 | extern crate tokio_core; 2 | extern crate ldap; 3 | 4 | use tokio_core::reactor::{Core, Handle}; 5 | use ldap::Ldap; 6 | 7 | pub fn main() { 8 | let addr = "127.0.0.1:389".parse().unwrap(); 9 | 10 | let mut core = Core::new().unwrap(); 11 | let handle = core.handle(); 12 | 13 | let ldap = core.run(Ldap::connect(&addr, &handle)).unwrap(); 14 | let bind = core.run(ldap.simple_bind("cn=root,dc=plabs".to_string(), "asdf".to_string())); 15 | 16 | let search_results = core.run(ldap.search("dc=plabs".to_string(), 17 | ldap::Scope::WholeSubtree, 18 | ldap::DerefAliases::Never, 19 | false, 20 | "(objectClass=*)".to_string(), 21 | vec![])); 22 | 23 | println!("Search Results: {:?}", search_results) 24 | } 25 | -------------------------------------------------------------------------------- /src/bind.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | 3 | use asnom::structures::{Tag, Sequence, Integer, OctetString}; 4 | 5 | use asnom::common::TagClass::*; 6 | 7 | use asnom::structures::ASNTag; 8 | 9 | use futures::Future; 10 | use tokio_service::Service; 11 | 12 | use ldap::Ldap; 13 | use service::LdapMessage; 14 | 15 | impl Ldap { 16 | pub fn simple_bind(&self, dn: String, pw: String) -> 17 | Box> { 18 | let req = Tag::Sequence(Sequence { 19 | id: 0, 20 | class: Application, 21 | inner: vec![ 22 | Tag::Integer(Integer { 23 | inner: 3, 24 | .. Default::default() 25 | }), 26 | Tag::OctetString(OctetString { 27 | inner: dn.into_bytes(), 28 | .. Default::default() 29 | }), 30 | Tag::OctetString(OctetString { 31 | id: 0, 32 | class: Context, 33 | inner: pw.into_bytes(), 34 | }) 35 | ], 36 | }); 37 | 38 | let fut = self.call(req).and_then(|res| 39 | match res { 40 | LdapMessage::Once(Tag::StructureTag(tag)) => { 41 | if let Some(i) = tag.expect_constructed() { 42 | return Ok(i[0] == Tag::Integer(Integer { 43 | id: 10, 44 | class: Universal, 45 | inner: 0 46 | }).into_structure()) 47 | } else { 48 | return Ok(false) 49 | } 50 | } 51 | _ => unimplemented!(), 52 | } 53 | ); 54 | 55 | Box::new(fut) 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/ldap.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | use std::iter; 3 | use std::net::{SocketAddr, ToSocketAddrs}; 4 | 5 | use asnom::structures::Tag; 6 | use futures::{future, Future}; 7 | use native_tls::TlsConnector; 8 | use tokio_core::reactor::Handle; 9 | use tokio_proto::util::client_proxy::ClientProxy; 10 | use tokio_proto::TcpClient; 11 | use tokio_service::Service; 12 | use tokio_tls::proto::Client as TlsClient; 13 | 14 | use protocol::LdapProto; 15 | use service::{LdapMessage, TokioMessage}; 16 | 17 | pub struct Ldap { 18 | inner: ClientTypeMap>, 19 | } 20 | 21 | impl Ldap { 22 | pub fn connect(addr: &SocketAddr, handle: &Handle) -> 23 | Box> { 24 | let ret = TcpClient::new(LdapProto) 25 | .connect(addr, handle) 26 | .map(|client_proxy| { 27 | let typemap = ClientTypeMap { inner: client_proxy }; 28 | Ldap { inner: typemap } 29 | }); 30 | Box::new(ret) 31 | } 32 | 33 | pub fn connect_ssl(addr: &str, handle: &Handle) -> 34 | Box> { 35 | if addr.parse::().ok().is_some() { 36 | return Box::new(future::err(io::Error::new(io::ErrorKind::Other, "SSL connection must be by hostname"))); 37 | } 38 | let sockaddr = addr.to_socket_addrs().unwrap_or(vec![].into_iter()).next(); 39 | if sockaddr.is_none() { 40 | return Box::new(future::err(io::Error::new(io::ErrorKind::Other, "no addresses found"))); 41 | } 42 | let wrapper = TlsClient::new(LdapProto, 43 | TlsConnector::builder().expect("tls_builder").build().expect("connector"), 44 | addr.split(':').next().expect("hostname")); 45 | let ret = TcpClient::new(wrapper) 46 | .connect(&sockaddr.unwrap(), handle) 47 | .map(|client_proxy| { 48 | let typemap = ClientTypeMap { inner: client_proxy }; 49 | Ldap { inner: typemap } 50 | }); 51 | Box::new(ret) 52 | } 53 | } 54 | 55 | impl Service for Ldap { 56 | type Request = Tag; 57 | type Response = LdapMessage; 58 | type Error = io::Error; 59 | type Future = Box>; 60 | 61 | fn call(&self, req: Self::Request) -> Self::Future { 62 | self.inner.call(LdapMessage::Once(req)) 63 | } 64 | } 65 | 66 | struct ClientTypeMap { 67 | inner: T 68 | } 69 | 70 | impl Service for ClientTypeMap 71 | where T: Service, 72 | T::Future: 'static { 73 | type Request = LdapMessage; 74 | type Response = LdapMessage; 75 | type Error = io::Error; 76 | type Future = Box>; 77 | 78 | fn call(&self, req: LdapMessage) -> Self::Future { 79 | Box::new(self.inner.call(req.into()).map(LdapMessage::from)) 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | extern crate asnom; 2 | extern crate rfc4515; 3 | 4 | extern crate futures; 5 | extern crate native_tls; 6 | extern crate tokio_core; 7 | extern crate tokio_proto; 8 | extern crate tokio_service; 9 | extern crate tokio_tls; 10 | extern crate byteorder; 11 | 12 | #[macro_use] 13 | extern crate log; 14 | 15 | mod ldap; 16 | mod sync; 17 | mod protocol; 18 | mod service; 19 | 20 | mod bind; 21 | mod search; 22 | 23 | pub use ldap::Ldap; 24 | pub use sync::LdapSync; 25 | 26 | pub use search::{Scope, DerefAliases, SearchEntry}; 27 | -------------------------------------------------------------------------------- /src/protocol.rs: -------------------------------------------------------------------------------- 1 | use tokio_core::io::{Io, Codec, EasyBuf, Framed}; 2 | use std::io; 3 | use std::collections::HashSet; 4 | 5 | use tokio_proto::streaming::multiplex::{Frame, ClientProto}; 6 | 7 | use asnom::common; 8 | use asnom::IResult; 9 | use asnom::structures::{Tag, Integer, Sequence, ASNTag}; 10 | use asnom::parse::Parser; 11 | use asnom::ConsumerState; 12 | use asnom::Move; 13 | use asnom::Input; 14 | use asnom::Consumer; 15 | 16 | use asnom::parse::{parse_tag, parse_uint}; 17 | use asnom::write; 18 | 19 | #[derive(Debug, Clone)] 20 | pub struct LdapCodec { 21 | search_seen: HashSet, 22 | } 23 | 24 | impl Codec for LdapCodec { 25 | type In = Frame; 26 | type Out = Frame; 27 | 28 | fn decode(&mut self, buf: &mut EasyBuf) -> Result, io::Error> { 29 | let mut parser = Parser::new(); 30 | match parser.handle(Input::Element(buf.as_slice())) { 31 | &ConsumerState::Done(amt, ref tag) => { 32 | match amt { 33 | Move::Consume(amt) => { 34 | buf.drain_to(amt); 35 | 36 | let tag = tag.clone(); 37 | if let Some(mut tags) = tag.match_id(16u64).and_then(|x| x.expect_constructed()) { 38 | let protoop = tags.pop().unwrap(); 39 | let msgid: Vec = tags.pop().unwrap() 40 | .match_class(common::TagClass::Universal) 41 | .and_then(|x| x.match_id(2u64)) 42 | .and_then(|x| x.expect_primitive()).unwrap(); 43 | if let IResult::Done(_, id) = parse_uint(msgid.as_slice()) { 44 | return match protoop.id { 45 | // SearchResultEntry 46 | 4 => { 47 | debug!("Received a search result entry"); 48 | // We have already received the first of those results, so we only 49 | // send a body frame. 50 | if self.search_seen.contains(&id) { 51 | Ok(Some(Frame::Body { 52 | id: id as u64, 53 | chunk: Some(Tag::StructureTag(protoop)), 54 | })) 55 | } // If we haven't yet seen that search, we need to initially send a whole message 56 | else { 57 | self.search_seen.insert(id); 58 | Ok(Some(Frame::Message { 59 | id: id as u64, 60 | message: Tag::StructureTag(protoop), 61 | body: true, 62 | solo: false, 63 | })) 64 | } 65 | }, 66 | // SearchResultDone 67 | 5 => { 68 | debug!("Received a search result done"); 69 | let seen_res_entry = self.search_seen.contains(&id); 70 | self.search_seen.remove(&id); 71 | if seen_res_entry { 72 | Ok(Some(Frame::Body { 73 | id: id as u64, 74 | chunk: None, 75 | })) 76 | } else { 77 | Ok(Some(Frame::Message { 78 | id: id as u64, 79 | message: Tag::StructureTag(protoop), 80 | body: false, 81 | solo: false, 82 | })) 83 | } 84 | }, 85 | // Any other Message 86 | _ => { 87 | debug!("Received a tag id {}", id); 88 | Ok(Some(Frame::Message { 89 | id: id as u64, 90 | message: Tag::StructureTag(protoop), 91 | body: false, 92 | solo: false, 93 | })) 94 | }, 95 | } 96 | } 97 | } 98 | 99 | return Err(io::Error::new(io::ErrorKind::Other, "Invalid (RequestId, Tag) received.")); 100 | }, 101 | Move::Seek(_) => Err(io::Error::from(io::ErrorKind::Other)), 102 | Move::Await(_) => Ok(None) 103 | } 104 | }, 105 | &ConsumerState::Continue(_) => Ok(None), 106 | &ConsumerState::Error(_e) => Err(io::Error::from(io::ErrorKind::Other)), 107 | } 108 | } 109 | 110 | fn encode(&mut self, msg: Self::Out, into: &mut Vec) -> io::Result<()> { 111 | match msg { 112 | Frame::Message {message, id, body: _, solo: _} => { 113 | let outtag = Tag::Sequence(Sequence { 114 | inner: vec![ 115 | Tag::Integer(Integer { 116 | inner: id as i64, 117 | .. Default::default() 118 | }), 119 | message, 120 | ], 121 | .. Default::default() 122 | }); 123 | 124 | let outstruct = outtag.into_structure(); 125 | trace!("Sending packet: {:?}", &outstruct); 126 | try!(write::encode_into(into, outstruct)); 127 | Ok(()) 128 | }, 129 | _ => unimplemented!(), 130 | } 131 | } 132 | } 133 | 134 | pub struct LdapProto; 135 | 136 | impl ClientProto for LdapProto { 137 | type Request = Tag; 138 | type RequestBody = Tag; 139 | type Response = Tag; 140 | type ResponseBody = Tag; 141 | type Error = io::Error; 142 | 143 | /// `Framed` is the return value of `io.framed(LineCodec)` 144 | type Transport = Framed; 145 | type BindTransport = Result; 146 | 147 | fn bind_transport(&self, io: T) -> Self::BindTransport { 148 | let ldapcodec = LdapCodec { search_seen: HashSet::new() }; 149 | Ok(io.framed(ldapcodec)) 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /src/search.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | use std::collections::HashMap; 3 | 4 | use asnom::structure::StructureTag; 5 | use asnom::structures::{Tag, Sequence, Integer, OctetString, Boolean}; 6 | use asnom::common::TagClass::*; 7 | 8 | use rfc4515::parse; 9 | 10 | use futures::{Future, stream, Stream}; 11 | use tokio_service::Service; 12 | 13 | use ldap::Ldap; 14 | use service::{LdapMessage, LdapMessageStream}; 15 | 16 | #[derive(Clone, Copy, Debug, PartialEq)] 17 | pub enum Scope { 18 | BaseObject = 0, 19 | SingleLevel = 1, 20 | WholeSubtree = 2, 21 | } 22 | 23 | #[derive(Clone, Copy, Debug, PartialEq)] 24 | pub enum DerefAliases { 25 | Never = 0, 26 | InSearch = 1, 27 | FindingBaseObject = 2, 28 | Always = 3, 29 | } 30 | 31 | #[derive(Clone, Debug, PartialEq)] 32 | pub enum SearchEntry { 33 | Reference(Vec), 34 | Object { 35 | object_name: String, 36 | attributes: HashMap>, 37 | }, 38 | } 39 | 40 | impl SearchEntry { 41 | pub fn construct(tag: Tag) -> SearchEntry { 42 | match tag { 43 | Tag::StructureTag(t) => { 44 | match t.id { 45 | // Search Result Entry 46 | // Search Result Done (if the result set is empty) 47 | 4|5 => { 48 | let mut tags = t.expect_constructed().unwrap(); 49 | let attributes = tags.pop().unwrap(); 50 | let object_name = tags.pop().unwrap(); 51 | let object_name = String::from_utf8(object_name.expect_primitive().unwrap()).unwrap(); 52 | 53 | let a = construct_attributes(attributes.expect_constructed().unwrap_or(vec![])).unwrap(); 54 | 55 | SearchEntry::Object { 56 | object_name: object_name, 57 | attributes: a, 58 | } 59 | }, 60 | // Search Result Reference 61 | 19 => { 62 | // TODO actually handle this case 63 | SearchEntry::Reference(vec![]) 64 | }, 65 | _ => panic!("Search received a non-search tag!"), 66 | } 67 | } 68 | _ => unimplemented!() 69 | } 70 | } 71 | } 72 | 73 | fn construct_attributes(tags: Vec) -> Option>> { 74 | let mut map = HashMap::new(); 75 | for tag in tags.into_iter() { 76 | let mut inner = tag.expect_constructed().unwrap(); 77 | 78 | let values = inner.pop().unwrap(); 79 | let valuev = values.expect_constructed().unwrap() 80 | .into_iter() 81 | .map(|t| t.expect_primitive().unwrap()) 82 | .map(|v| String::from_utf8(v).unwrap()) 83 | .collect(); 84 | let key = inner.pop().unwrap(); 85 | let keystr = String::from_utf8(key.expect_primitive().unwrap()).unwrap(); 86 | 87 | map.insert(keystr, valuev); 88 | } 89 | 90 | Some(map) 91 | } 92 | 93 | impl Ldap { 94 | pub fn search(&self, 95 | base: String, 96 | scope: Scope, 97 | deref: DerefAliases, 98 | typesonly: bool, 99 | filter: String, 100 | attrs: Vec) -> 101 | Box, Error = io::Error>> { 102 | let req = Tag::Sequence(Sequence { 103 | id: 3, 104 | class: Application, 105 | inner: vec![ 106 | Tag::OctetString(OctetString { 107 | inner: base.into_bytes(), 108 | .. Default::default() 109 | }), 110 | Tag::Integer(Integer { 111 | inner: scope as i64, 112 | .. Default::default() 113 | }), 114 | Tag::Integer(Integer { 115 | inner: deref as i64, 116 | .. Default::default() 117 | }), 118 | Tag::Integer(Integer { 119 | inner: 0, 120 | .. Default::default() 121 | }), 122 | Tag::Integer(Integer { 123 | inner: 0, 124 | .. Default::default() 125 | }), 126 | Tag::Boolean(Boolean { 127 | inner: typesonly, 128 | .. Default::default() 129 | }), 130 | parse(&filter).unwrap(), 131 | Tag::Sequence(Sequence { 132 | inner: attrs.into_iter().map(|s| 133 | Tag::OctetString(OctetString { inner: s.into_bytes(), ..Default::default() })).collect(), 134 | .. Default::default() 135 | }) 136 | ], 137 | }); 138 | 139 | let fut = self.call(req).and_then(|res| { 140 | let ostr = match res { 141 | LdapMessage::Stream(first, body) => { 142 | let fstr = stream::once(Ok(first)); 143 | fstr.chain(body) 144 | }, 145 | LdapMessage::Once(first) => { 146 | let fstr = stream::once(Ok(first)); 147 | fstr.chain(LdapMessageStream::empty()) 148 | }, 149 | }; 150 | ostr.map(|x| SearchEntry::construct(x)) 151 | .collect() 152 | .and_then(|x| Ok(x)) 153 | }); 154 | 155 | Box::new(fut) 156 | } 157 | } 158 | 159 | -------------------------------------------------------------------------------- /src/service.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | 3 | use asnom::structures::Tag; 4 | 5 | use futures::{Stream, Poll}; 6 | 7 | use tokio_proto::streaming::{Body, Message}; 8 | 9 | #[derive(Debug)] 10 | pub enum LdapMessage { 11 | Once(Tag), 12 | Stream(Tag, LdapMessageStream), 13 | } 14 | 15 | #[derive(Debug)] 16 | pub struct LdapMessageStream { 17 | inner: Body, 18 | } 19 | 20 | impl LdapMessageStream { 21 | pub fn empty() -> LdapMessageStream { 22 | LdapMessageStream { 23 | inner: Body::empty() 24 | } 25 | } 26 | } 27 | 28 | impl Stream for LdapMessageStream { 29 | type Item = Tag; 30 | type Error = io::Error; 31 | 32 | fn poll(&mut self) -> Poll, io::Error> { 33 | self.inner.poll() 34 | } 35 | } 36 | 37 | pub type TokioMessage = Message>; 38 | 39 | impl From for LdapMessage { 40 | fn from(src: TokioMessage) -> Self { 41 | match src { 42 | Message::WithoutBody(tag) => LdapMessage::Once(tag), 43 | Message::WithBody(tag, body) => 44 | LdapMessage::Stream(tag, LdapMessageStream { inner: body }) 45 | } 46 | } 47 | } 48 | 49 | impl From for TokioMessage { 50 | fn from(src: LdapMessage) -> Self { 51 | match src { 52 | LdapMessage::Once(tag) => Message::WithoutBody(tag), 53 | LdapMessage::Stream(tag, body) => { 54 | let LdapMessageStream { inner } = body; 55 | Message::WithBody(tag, inner) 56 | } 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/sync.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | use std::net::SocketAddr; 3 | 4 | use ldap::Ldap; 5 | use search::{Scope, DerefAliases, SearchEntry}; 6 | 7 | use tokio_core::reactor::{Core, Handle}; 8 | 9 | pub struct LdapSync { 10 | inner: Ldap, 11 | core: Core, 12 | } 13 | 14 | impl LdapSync { 15 | pub fn connect(addr: &SocketAddr) -> Result { 16 | // TODO better error handling 17 | let mut core = Core::new().unwrap(); 18 | let handle = core.handle(); 19 | 20 | let ldapfut = Ldap::connect(addr, &handle); 21 | let ldap = try!(core.run(ldapfut)); 22 | 23 | Ok(LdapSync { inner: ldap, core: core }) 24 | } 25 | 26 | pub fn connect_ssl(addr: &str) -> Result { 27 | // TODO better error handling 28 | let mut core = Core::new().unwrap(); 29 | let handle = core.handle(); 30 | 31 | let ldapfut = Ldap::connect_ssl(addr, &handle); 32 | let ldap = try!(core.run(ldapfut)); 33 | 34 | Ok(LdapSync { inner: ldap, core: core }) 35 | } 36 | 37 | pub fn simple_bind(&mut self, dn: String, pw: String) -> io::Result { 38 | self.core.run(self.inner.simple_bind(dn, pw)) 39 | } 40 | 41 | pub fn search(&mut self, 42 | base: String, 43 | scope: Scope, 44 | deref: DerefAliases, 45 | typesonly: bool, 46 | filter: String, 47 | attrs: Vec) -> io::Result> { 48 | self.core.run(self.inner.search(base, scope, deref, typesonly, filter, attrs)) 49 | } 50 | } 51 | --------------------------------------------------------------------------------