1use crate::{Error, ErrorKind, Result, auth::Mechanism};
4use std::{collections::BTreeMap, time::Duration};
5#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
6pub struct Address {
7 pub host: String,
8 pub port: u16,
9}
10impl Address {
11 pub fn parse(s: &str) -> Result<Self> {
12 let (host, port) = if let Some(rest) = s.strip_prefix('[') {
13 let (h, t) = rest
14 .split_once(']')
15 .ok_or_else(|| parse_error("Invalid IPv6 address"))?;
16 h.parse::<std::net::Ipv6Addr>()
17 .map_err(|_| parse_error("Invalid IPv6 address"))?;
18 (
19 h,
20 if t.is_empty() {
21 27017
22 } else {
23 parse_port(
24 t.strip_prefix(':')
25 .ok_or_else(|| parse_error("Invalid host"))?,
26 )?
27 },
28 )
29 } else {
30 if s.matches(':').count() > 1 {
31 return Err(parse_error("IPv6 addresses must be bracketed"));
32 }
33 if let Some((h, p)) = s.split_once(':') {
34 (h, parse_port(p)?)
35 } else {
36 (s, 27017)
37 }
38 };
39 let host = decode(host)?.to_lowercase();
40 if host.is_empty()
41 || host
42 .chars()
43 .any(|c| c.is_whitespace() || matches!(c, '/' | '?' | '#' | '@' | '[' | ']'))
44 {
45 return Err(parse_error("Invalid hostname"));
46 }
47 Ok(Self { host, port })
48 }
49 pub fn authority(&self) -> String {
50 if self.host.contains(':') {
51 format!("[{}]:{}", self.host, self.port)
52 } else {
53 format!("{}:{}", self.host, self.port)
54 }
55 }
56}
57fn parse_port(s: &str) -> Result<u16> {
58 s.parse::<u16>()
59 .ok()
60 .filter(|&n| n != 0)
61 .ok_or_else(|| parse_error("Invalid port"))
62}
63#[derive(Clone)]
64pub struct Credential {
65 pub username: String,
66 pub password: String,
67 pub source: String,
68 pub mechanism: Option<Mechanism>,
69}
70impl std::fmt::Debug for Credential {
71 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72 f.debug_struct("Credential")
73 .field("username", &self.username)
74 .field("source", &self.source)
75 .field("mechanism", &self.mechanism)
76 .finish_non_exhaustive()
77 }
78}
79#[derive(Clone, Copy, Debug, PartialEq, Eq)]
80pub enum ReadPreference {
81 Primary,
82 PrimaryPreferred,
83 Secondary,
84 SecondaryPreferred,
85 Nearest,
86}
87impl ReadPreference {
88 pub fn parse(s: &str) -> Result<Self> {
89 Ok(match s {
90 "primary" => Self::Primary,
91 "primaryPreferred" => Self::PrimaryPreferred,
92 "secondary" => Self::Secondary,
93 "secondaryPreferred" => Self::SecondaryPreferred,
94 "nearest" => Self::Nearest,
95 _ => return Err(parse_error("Invalid read preference mode")),
96 })
97 }
98 pub fn as_str(self) -> &'static str {
99 match self {
100 Self::Primary => "primary",
101 Self::PrimaryPreferred => "primaryPreferred",
102 Self::Secondary => "secondary",
103 Self::SecondaryPreferred => "secondaryPreferred",
104 Self::Nearest => "nearest",
105 }
106 }
107}
108#[derive(Clone, Debug)]
109pub struct Options {
110 pub seeds: Vec<Address>,
111 pub srv: Option<String>,
112 pub database: Option<String>,
113 pub credential: Option<Credential>,
114 pub tls: bool,
115 pub direct: bool,
116 pub replica_set: Option<String>,
117 pub app_name: Option<String>,
118 pub connect_timeout: Duration,
119 pub server_selection_timeout: Duration,
120 pub socket_timeout: Duration,
121 pub heartbeat: Duration,
122 pub local_threshold: Duration,
123 pub min_pool_size: usize,
124 pub max_pool_size: usize,
125 pub max_connecting: usize,
126 pub wait_queue_timeout: Duration,
127 pub max_idle_time: Duration,
128 pub retry_reads: bool,
129 pub retry_writes: bool,
130 pub read_preference: ReadPreference,
131 pub read_preference_tags: Vec<BTreeMap<String, String>>,
132 pub max_staleness: Option<Duration>,
133 pub compressors: Vec<String>,
134 pub raw: BTreeMap<String, String>,
135}
136#[derive(Clone, Debug, PartialEq, Eq)]
137pub enum ResolutionRequest {
138 Srv { name: String },
139 Txt { name: String },
140}
141impl Options {
142 pub fn parse(uri: &str) -> Result<Self> {
143 let (srv, rest) = if let Some(s) = uri.strip_prefix("mongodb://") {
144 (false, s)
145 } else if let Some(s) = uri.strip_prefix("mongodb+srv://") {
146 (true, s)
147 } else {
148 return Err(parse_error(
149 "Invalid scheme, expected connection string to start with mongodb:// or mongodb+srv://",
150 ));
151 };
152 if rest.contains('#') {
153 return Err(parse_error("Unescaped # in connection string"));
154 }
155 let (authority, tail) = rest.split_once('/').unwrap_or((rest, ""));
156 if authority.contains('?') {
157 return Err(parse_error(
158 "Connection string must have a slash before options",
159 ));
160 }
161 let (user, hosts) = if let Some((u, h)) = authority.rsplit_once('@') {
162 if u.contains('@') {
163 return Err(parse_error("Username and password must be escaped"));
164 }
165 (Some(u), h)
166 } else {
167 (None, authority)
168 };
169 let mut seeds = Vec::new();
170 for h in hosts.split(',') {
171 let a = Address::parse(h)?;
172 if !seeds.contains(&a) {
173 seeds.push(a);
174 }
175 }
176 if srv && (seeds.len() != 1 || hosts.contains(':') || !seeds[0].host.contains('.')) {
177 return Err(parse_error(
178 "mongodb+srv URI must include one hostname and no port",
179 ));
180 }
181 let (db, query) = tail.split_once('?').unwrap_or((tail, ""));
182 let db = decode(db)?;
183 if db
184 .chars()
185 .any(|c| matches!(c, '/' | '\\' | ' ' | '.' | '"' | '$' | '\0'))
186 {
187 return Err(parse_error("Invalid database name"));
188 }
189 let mut raw = BTreeMap::new();
190 let mut tags = Vec::new();
191 for item in query.split('&').filter(|s| !s.is_empty()) {
192 let (k, v) = item
193 .split_once('=')
194 .ok_or_else(|| parse_error("Connection string option requires a value"))?;
195 let k = k.to_ascii_lowercase();
196 let v = decode(v)?;
197 if k == "readpreferencetags" {
198 let mut tag = BTreeMap::new();
199 for t in v.split(',').filter(|t| !t.is_empty()) {
200 let (k, v) = t
201 .split_once(':')
202 .ok_or_else(|| parse_error("Invalid read preference tags"))?;
203 tag.insert(k.to_owned(), v.to_owned());
204 }
205 tags.push(tag);
206 } else if raw.insert(k, v).is_some() {
207 return Err(parse_error("Duplicate connection string option"));
208 }
209 }
210 let mut out = Self {
211 srv: if srv {
212 Some(seeds[0].host.clone())
213 } else {
214 None
215 },
216 seeds,
217 database: if db.is_empty() { None } else { Some(db) },
218 credential: None,
219 tls: srv,
220 direct: false,
221 replica_set: None,
222 app_name: None,
223 connect_timeout: Duration::from_secs(30),
224 server_selection_timeout: Duration::from_secs(30),
225 socket_timeout: Duration::ZERO,
226 heartbeat: Duration::from_secs(10),
227 local_threshold: Duration::from_millis(15),
228 min_pool_size: 0,
229 max_pool_size: 100,
230 max_connecting: 2,
231 wait_queue_timeout: Duration::ZERO,
232 max_idle_time: Duration::ZERO,
233 retry_reads: true,
234 retry_writes: true,
235 read_preference: ReadPreference::Primary,
236 read_preference_tags: tags,
237 max_staleness: None,
238 compressors: Vec::new(),
239 raw,
240 };
241 out.apply_options()?;
242 if let Some(user) = user {
243 let (u, p) = user
244 .split_once(':')
245 .ok_or_else(|| parse_error("SCRAM credentials require a password"))?;
246 if u.is_empty()
247 || u.contains([':', '/', '?', '[', ']'])
248 || p.contains([':', '/', '?', '[', ']'])
249 {
250 return Err(parse_error("Username and password must be escaped"));
251 }
252 let mechanism = out
253 .raw
254 .get("authmechanism")
255 .map(|s| Mechanism::parse(s))
256 .transpose()?;
257 out.credential = Some(Credential {
258 username: decode(u)?,
259 password: decode(p)?,
260 source: out
261 .raw
262 .get("authsource")
263 .cloned()
264 .or_else(|| out.database.clone())
265 .unwrap_or_else(|| "admin".into()),
266 mechanism,
267 });
268 }
269 if out.raw.contains_key("authmechanism") && out.credential.is_none() {
270 return Err(parse_error("Authentication requires a username"));
271 }
272 Ok(out)
273 }
274 fn apply_options(&mut self) -> Result<()> {
275 for (k, v) in &self.raw {
276 match k.as_str() {
277 "tls" | "ssl" => self.tls = boolean(v)?,
278 "directconnection" => self.direct = boolean(v)?,
279 "replicaset" => {
280 if v.is_empty() {
281 return Err(parse_error("replicaSet cannot be empty"));
282 }
283 self.replica_set = Some(v.clone());
284 }
285 "appname" => {
286 if v.len() > 128 {
287 return Err(parse_error("appName must be at most 128 bytes"));
288 }
289 self.app_name = Some(v.clone());
290 }
291 "connecttimeoutms" => self.connect_timeout = millis(v)?,
292 "serverselectiontimeoutms" => self.server_selection_timeout = millis(v)?,
293 "sockettimeoutms" => self.socket_timeout = millis(v)?,
294 "heartbeatfrequencyms" => self.heartbeat = millis(v)?,
295 "localthresholdms" => self.local_threshold = millis(v)?,
296 "waitqueuetimeoutms" => self.wait_queue_timeout = millis(v)?,
297 "maxidletimems" => self.max_idle_time = millis(v)?,
298 "minpoolsize" => self.min_pool_size = integer(v)?,
299 "maxpoolsize" => self.max_pool_size = integer(v)?,
300 "maxconnecting" => self.max_connecting = integer(v)?,
301 "retryreads" => self.retry_reads = boolean(v)?,
302 "retrywrites" => self.retry_writes = boolean(v)?,
303 "readpreference" => self.read_preference = ReadPreference::parse(v)?,
304 "maxstalenessseconds" => {
305 self.max_staleness = if v == "-1" {
306 None
307 } else {
308 Some(Duration::from_secs(integer(v)? as u64))
309 }
310 }
311 "compressors" => {
312 self.compressors = v
313 .split(',')
314 .filter(|v| !v.is_empty())
315 .map(str::to_owned)
316 .collect();
317 if self.compressors.iter().any(|c| c != "zlib") {
318 return Err(parse_error("Only zlib compression is supported"));
319 }
320 }
321 "authsource" => {
322 if v.is_empty() {
323 return Err(parse_error("authSource cannot be empty"));
324 }
325 }
326 "authmechanism" => {
327 Mechanism::parse(v)?;
328 }
329 "w" => {
330 if v.is_empty() || v.starts_with('-') {
331 return Err(parse_error("Invalid write concern w"));
332 }
333 }
334 "journal" => {
335 boolean(v)?;
336 }
337 "wtimeoutms" => {
338 millis(v)?;
339 }
340 "readconcernlevel" => {}
341 _ => {
342 return Err(Error::new(
343 ErrorKind::Parse,
344 format!("option {k} is not supported"),
345 ));
346 }
347 }
348 }
349 if self
350 .raw
351 .get("tls")
352 .zip(self.raw.get("ssl"))
353 .is_some_and(|(a, b)| a != b)
354 {
355 return Err(parse_error("tls and ssl options conflict"));
356 }
357 if self.direct && (self.seeds.len() != 1 || self.srv.is_some()) {
358 return Err(parse_error(
359 "directConnection requires exactly one non-SRV host",
360 ));
361 }
362 if self.raw.get("w").is_some_and(|v| v == "0")
363 && self.raw.get("journal").is_some_and(|v| v == "true")
364 {
365 return Err(parse_error("w=0 cannot be combined with journal=true"));
366 }
367 if self.heartbeat < Duration::from_millis(500)
368 || self.max_connecting == 0
369 || (self.max_pool_size != 0 && self.min_pool_size > self.max_pool_size)
370 {
371 return Err(parse_error("Invalid heartbeat or pool size"));
372 }
373 if self.read_preference == ReadPreference::Primary
374 && (self.read_preference_tags.iter().any(|t| !t.is_empty())
375 || self.max_staleness.is_some())
376 {
377 return Err(parse_error(
378 "Primary read preference cannot be combined with tags or maxStalenessSeconds",
379 ));
380 }
381 Ok(())
382 }
383 pub fn resolution_requests(&self) -> Option<[ResolutionRequest; 2]> {
384 self.srv.as_ref().map(|s| {
385 [
386 ResolutionRequest::Srv {
387 name: format!("_mongodb._tcp.{s}"),
388 },
389 ResolutionRequest::Txt { name: s.clone() },
390 ]
391 })
392 }
393 pub fn resolve(&mut self, records: &[Address], txt: &[String]) -> Result<()> {
395 let srv = self
396 .srv
397 .as_ref()
398 .ok_or_else(|| parse_error("Not an SRV connection"))?;
399 if records.is_empty() || txt.len() > 1 {
400 return Err(parse_error("Invalid SRV/TXT response"));
401 }
402 let labels: Vec<_> = srv.split('.').collect();
403 let domain = if labels.len() >= 3 {
404 labels[1..].join(".")
405 } else {
406 srv.clone()
407 };
408 let suffix = format!(".{domain}");
409 for r in records {
410 if !r
411 .host
412 .trim_end_matches('.')
413 .to_ascii_lowercase()
414 .ends_with(&suffix)
415 {
416 return Err(parse_error("SRV host does not share parent domain"));
417 }
418 }
419 if let Some(t) = txt.first() {
420 for option in t.split('&') {
421 let (k, v) = option
422 .split_once('=')
423 .ok_or_else(|| parse_error("Invalid TXT options"))?;
424 let k = k.to_ascii_lowercase();
425 if !matches!(k.as_str(), "authsource" | "replicaset") {
426 return Err(parse_error("Unsupported TXT option"));
427 }
428 self.raw.entry(k).or_insert(decode(v)?);
429 }
430 }
431 self.seeds = records
432 .iter()
433 .map(|a| Address {
434 host: a.host.trim_end_matches('.').to_ascii_lowercase(),
435 port: a.port,
436 })
437 .collect();
438 self.apply_options()?;
439 if let Some(c) = &mut self.credential
440 && let Some(s) = self.raw.get("authsource")
441 {
442 c.source = s.clone();
443 }
444 Ok(())
445 }
446}
447fn parse_error(m: &'static str) -> Error {
448 Error::new(ErrorKind::Parse, m)
449}
450fn boolean(s: &str) -> Result<bool> {
451 match s {
452 "true" => Ok(true),
453 "false" => Ok(false),
454 _ => Err(parse_error("Boolean option must be true or false")),
455 }
456}
457fn integer(s: &str) -> Result<usize> {
458 if s.is_empty() || !s.bytes().all(|c| c.is_ascii_digit()) {
459 return Err(parse_error("Expected a nonnegative integer"));
460 }
461 s.parse()
462 .map_err(|_| parse_error("Integer option out of range"))
463}
464fn millis(s: &str) -> Result<Duration> {
465 Ok(Duration::from_millis(integer(s)? as u64))
466}
467fn decode(s: &str) -> Result<String> {
468 let mut b = Vec::with_capacity(s.len());
469 let mut i = 0;
470 while i < s.len() {
471 let c = s.as_bytes()[i];
472 if c == b'%' {
473 let h = s
474 .as_bytes()
475 .get(i + 1..i + 3)
476 .ok_or_else(|| parse_error("Invalid percent escape"))?;
477 let x = |v: u8| char::from(v).to_digit(16);
478 let v = x(h[0])
479 .zip(x(h[1]))
480 .map(|(a, b)| (a * 16 + b) as u8)
481 .ok_or_else(|| parse_error("Invalid percent escape"))?;
482 b.push(v);
483 i += 3;
484 } else {
485 b.push(c);
486 i += 1;
487 }
488 }
489 if b.contains(&0) {
490 return Err(parse_error("NUL in connection string"));
491 }
492 String::from_utf8(b).map_err(|_| parse_error("Invalid UTF-8 escape"))
493}