1use std::collections::BTreeMap;
8use std::fmt;
9use std::path::Path;
10use std::time::Duration;
11
12use datumesh_core::json::{self, Value};
13use datumesh_core::lexical;
14
15use crate::apikeys::ApiKeys;
16
17pub const DEFAULT_BUDGET: Duration = Duration::from_secs(1);
19
20pub const DEFAULT_BARRIER_TIMEOUT: Duration = Duration::from_secs(5);
22
23pub fn barrier_timeout_of(v: Option<String>) -> Result<Duration, ConfigError> {
25 match v {
26 None => Ok(DEFAULT_BARRIER_TIMEOUT),
27 Some(v) => match v.parse::<u64>() {
28 Ok(n) if n > 0 => Ok(Duration::from_millis(n)),
29 _ => Err(ConfigError::new("DATUMESH_BARRIER_TIMEOUT_MS", format!("not a positive number: {v}"))),
30 },
31 }
32}
33pub const DEFAULT_POOL_SIZE: usize = 32;
36pub const DEFAULT_BATCH_MAX: usize = 1000;
38pub const DEFAULT_SLICE_PAGE: usize = 1000;
40
41pub fn catalog_max_of(v: Option<String>) -> Result<usize, ConfigError> {
44 match v {
45 None => Ok(crate::catalog_build::DEFAULT_CATALOG_MAX),
46 Some(v) => match v.parse::<usize>() {
47 Ok(n) if n > 0 => Ok(n),
48 _ => Err(ConfigError::new("DATUMESH_CATALOG_MAX", format!("not a positive number: {v}"))),
49 },
50 }
51}
52pub const MAX_SLICE_PAGE: usize = 10_000;
54pub const MAX_SLICE_MEMBERS: usize = 1_048_576;
56
57#[non_exhaustive]
60#[derive(Clone, Debug, PartialEq, Eq)]
61pub struct RateLimits {
62 pub enabled: bool,
64 pub per_ip: u32,
66 pub ip_burst: u32,
68 pub per_key: u32,
71 pub verify_per_ip: u32,
73 pub calc_per_ip: u32,
76 pub batch_cells_per_token: u32,
79 pub series_per_ip: u32,
82 pub keys_per_ip: u32,
85}
86
87impl Default for RateLimits {
88 fn default() -> Self {
89 RateLimits {
90 enabled: true,
91 per_ip: 60,
92 ip_burst: 120,
93 per_key: 600,
94 verify_per_ip: 60,
95 calc_per_ip: 30,
96 batch_cells_per_token: 50,
97 series_per_ip: 30,
98 keys_per_ip: 5,
99 }
100 }
101}
102
103#[non_exhaustive]
106#[derive(Clone, Debug, PartialEq, Eq)]
107pub struct Ttls {
108 pub key_doc: Duration,
111 pub key_refetch: Duration,
113 pub mesh_doc: Duration,
115 pub binding: Duration,
118 pub current: Duration,
121 pub latest_max_age: Duration,
123 pub job: Duration,
126}
127
128impl Default for Ttls {
129 fn default() -> Self {
130 Ttls {
131 key_doc: Duration::from_secs(300),
132 key_refetch: Duration::from_secs(10),
133 mesh_doc: Duration::from_secs(300),
134 binding: Duration::from_secs(60),
135 current: Duration::from_secs(60),
136 latest_max_age: Duration::from_secs(10),
137 job: Duration::from_secs(300),
138 }
139 }
140}
141
142#[non_exhaustive]
144#[derive(Clone, Debug, PartialEq, Eq)]
145pub enum Rule {
146 Principals(Vec<String>),
149 Price {
152 amount: String,
154 currency: String,
156 },
157}
158
159#[non_exhaustive]
161#[derive(Clone, Debug, Default, PartialEq, Eq)]
162pub struct Policy {
163 pub rules: BTreeMap<String, Rule>,
165}
166
167impl Policy {
168 pub fn rule(&self, fn_name: &str) -> Option<&Rule> {
170 self.rules.get(fn_name)
171 }
172
173 pub fn from_json(bytes: &[u8]) -> Result<Policy, ConfigError> {
175 let v = json::parse(bytes).map_err(|e| ConfigError::new("policy", e.to_string()))?;
176 let mut rules = BTreeMap::new();
177 for (name, r) in v.as_object().ok_or_else(|| ConfigError::new("policy", "not an object"))? {
178 lexical::check_function_name(name, "$").map_err(|e| ConfigError::new("policy", e.to_string()))?;
179 let rule = if let Some(Value::Array(ps)) = r.get("principals") {
180 Rule::Principals(
181 ps.iter()
182 .map(|p| p.as_str().map(str::to_string).ok_or_else(|| ConfigError::new("policy", "principal")))
183 .collect::<Result<_, _>>()?,
184 )
185 } else if let Some(p) = r.get("price") {
186 let amount =
187 p.get("amount").and_then(Value::as_str).ok_or_else(|| ConfigError::new("policy", "amount"))?;
188 let currency =
189 p.get("currency").and_then(Value::as_str).ok_or_else(|| ConfigError::new("policy", "currency"))?;
190 lexical::check_number(amount, "$").map_err(|e| ConfigError::new("policy", e.to_string()))?;
191 if amount.starts_with('-') || amount == "0" || !lexical::is_currency(currency) {
192 return Err(ConfigError::new("policy", format!("price of {name}")));
193 }
194 Rule::Price { amount: amount.to_string(), currency: currency.to_string() }
195 } else {
196 return Err(ConfigError::new("policy", format!("rule of {name}")));
197 };
198 rules.insert(name.clone(), rule);
199 }
200 Ok(Policy { rules })
201 }
202}
203
204#[non_exhaustive]
206#[derive(Clone, Debug)]
207pub struct Config {
208 pub host: String,
211 pub base_url: Option<String>,
230 pub namespaces: Vec<String>,
233 pub budget: Duration,
235 pub pool_size: usize,
237 pub batch_max: usize,
239 pub test_cells: bool,
242 pub slice_page: usize,
244 pub slice_max: usize,
246 pub catalog_max: usize,
248 pub explain_depth: usize,
250 pub max_jobs: usize,
252 pub manifest_store_max: usize,
256 pub barrier_timeout: Duration,
259 pub rate: RateLimits,
261 pub ttl: Ttls,
263 pub trust_proxy: bool,
266 pub cross_mesh: bool,
268 pub cross_mesh_hosts: Option<Vec<String>>,
271 pub peers: BTreeMap<String, String>,
274 pub peer_timeout: Duration,
276 pub aliases: BTreeMap<String, String>,
278 pub policy: Policy,
280 pub catalog: BTreeMap<String, String>,
282 pub embed_url: Option<String>,
285 pub api_keys: ApiKeys,
287 pub publish_domains: PublishDomains,
290 pub log_dir: Option<std::path::PathBuf>,
293 pub(crate) series: Vec<crate::series::SeriesPage>,
295 pub key_names: bool,
299 pub key_challenge_ttl: Duration,
301 pub contact: Option<String>,
304 pub series_first_build_delay: Duration,
307 pub series_refresh: Duration,
309 pub catalog_first_build_delay: Duration,
312 pub catalog_refresh: Duration,
314 pub index_first_build_delay: Duration,
317 pub index_secs: Duration,
320 pub index_class_max: usize,
324 pub index_max: usize,
326 pub find_first_build_delay: Duration,
329 pub value_counts_refresh: Duration,
332 pub dictionary_max: usize,
335}
336
337#[non_exhaustive]
341#[derive(Clone, Debug, PartialEq, Eq, Default)]
342pub enum PublishDomains {
343 #[default]
345 Own,
346 Hosts(Vec<String>),
348 Any,
350}
351
352impl PublishDomains {
353 pub fn parse(v: &str) -> Result<PublishDomains, ConfigError> {
356 let v = v.trim();
357 if v.is_empty() {
358 return Ok(PublishDomains::Own);
359 }
360 if v == "*" {
361 return Ok(PublishDomains::Any);
362 }
363 let mut hosts = Vec::new();
364 for h in v.split(',').map(str::trim).filter(|h| !h.is_empty()) {
365 lexical::check_dns_name(h, "$").map_err(|e| ConfigError::new("DATUMESH_PUBLISH_DOMAINS", e.to_string()))?;
366 hosts.push(h.to_string());
367 }
368 Ok(if hosts.is_empty() { PublishDomains::Own } else { PublishDomains::Hosts(hosts) })
369 }
370
371 pub fn allows(&self, host: &str) -> bool {
373 match self {
374 PublishDomains::Own => false,
375 PublishDomains::Hosts(h) => h.iter().any(|x| x == host),
376 PublishDomains::Any => true,
377 }
378 }
379}
380
381impl Config {
382 pub fn new(host: impl Into<String>) -> Config {
384 let host = host.into();
385 Config {
386 namespaces: vec![host.clone()],
387 host,
388 base_url: None,
389 budget: DEFAULT_BUDGET,
390 pool_size: DEFAULT_POOL_SIZE,
391 batch_max: DEFAULT_BATCH_MAX,
392 test_cells: false,
393 slice_page: DEFAULT_SLICE_PAGE,
394 slice_max: MAX_SLICE_MEMBERS,
395 catalog_max: crate::catalog_build::DEFAULT_CATALOG_MAX,
396 explain_depth: 4,
397 max_jobs: 10_000,
398 manifest_store_max: 0,
399 barrier_timeout: DEFAULT_BARRIER_TIMEOUT,
400 rate: RateLimits::default(),
401 ttl: Ttls::default(),
402 trust_proxy: false,
403 cross_mesh: true,
404 cross_mesh_hosts: None,
405 peers: BTreeMap::new(),
406 peer_timeout: Duration::from_secs(10),
407 aliases: BTreeMap::new(),
408 policy: Policy::default(),
409 catalog: BTreeMap::new(),
410 embed_url: None,
411 api_keys: ApiKeys::default(),
412 publish_domains: PublishDomains::Own,
413 key_names: false,
414 key_challenge_ttl: Duration::from_secs(300),
415 contact: None,
416 series_first_build_delay: Duration::ZERO,
417 series_refresh: Duration::from_secs(300),
418 catalog_first_build_delay: Duration::ZERO,
419 catalog_refresh: Duration::from_secs(300),
420 index_first_build_delay: Duration::ZERO,
421 index_secs: Duration::from_secs(300),
422 index_class_max: 50_000,
423 index_max: 200_000,
424 find_first_build_delay: Duration::ZERO,
425 value_counts_refresh: Duration::from_secs(3600),
426 dictionary_max: 1000,
427 log_dir: None,
428 series: Vec::new(),
429 }
430 }
431
432 pub fn with_base_url(mut self, url: impl Into<String>) -> Config {
435 self.base_url = Some(url.into());
436 self
437 }
438
439 pub fn from_env() -> Result<Config, ConfigError> {
443 Config::from_vars(|k| std::env::var(k).ok())
444 }
445
446 pub fn from_vars(get: impl Fn(&str) -> Option<String>) -> Result<Config, ConfigError> {
448 let host = get("DATUMESH_HOST").ok_or_else(|| ConfigError::new("DATUMESH_HOST", "not set"))?;
449 let mut c = Config::new(host);
450 if let Some(v) = get("DATUMESH_BASE_URL").filter(|v| !v.is_empty()) {
451 c.base_url = Some(v);
452 }
453 if let Some(v) = get("DATUMESH_NAMESPACES") {
454 c.namespaces = v.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect();
455 }
456 let ms = |k: &str, d: Duration| -> Result<Duration, ConfigError> {
457 match get(k) {
458 Some(v) => v.parse::<u64>().map(Duration::from_millis).map_err(|e| ConfigError::new(k, e.to_string())),
459 None => Ok(d),
460 }
461 };
462 let secs = |k: &str, d: Duration| -> Result<Duration, ConfigError> {
463 match get(k) {
464 Some(v) => v.parse::<u64>().map(Duration::from_secs).map_err(|e| ConfigError::new(k, e.to_string())),
465 None => Ok(d),
466 }
467 };
468 let num = |k: &str, d: usize| -> Result<usize, ConfigError> {
469 match get(k) {
470 Some(v) => v.parse::<usize>().map_err(|e| ConfigError::new(k, e.to_string())),
471 None => Ok(d),
472 }
473 };
474 let flag = |k: &str, d: bool| -> Result<bool, ConfigError> {
475 match get(k).as_deref() {
476 None => Ok(d),
477 Some("1" | "true" | "yes") => Ok(true),
478 Some("0" | "false" | "no") => Ok(false),
479 Some(v) => Err(ConfigError::new(k, format!("not a boolean: {v}"))),
480 }
481 };
482 c.budget = ms("DATUMESH_BUDGET_MS", c.budget)?;
483 c.pool_size = num("DATUMESH_POOL_SIZE", c.pool_size)?;
484 c.batch_max = num("DATUMESH_BATCH_MAX", c.batch_max)?;
485 c.test_cells = flag("DATUMESH_TEST_CELLS", c.test_cells)?;
486 c.slice_page = num("DATUMESH_SLICE_PAGE", c.slice_page)?;
487 c.slice_max = num("DATUMESH_SLICE_MAX", c.slice_max)?;
488 c.catalog_max = catalog_max_of(get("DATUMESH_CATALOG_MAX"))?;
489 c.explain_depth = num("DATUMESH_EXPLAIN_DEPTH", c.explain_depth)?;
490 c.max_jobs = num("DATUMESH_MAX_JOBS", c.max_jobs)?;
491 c.manifest_store_max = num("DATUMESH_MANIFEST_STORE_MAX", c.manifest_store_max)?;
492 c.barrier_timeout = barrier_timeout_of(get("DATUMESH_BARRIER_TIMEOUT_MS"))?;
493 c.trust_proxy = flag("DATUMESH_TRUST_PROXY", c.trust_proxy)?;
494 c.cross_mesh = flag("DATUMESH_CROSS_MESH", c.cross_mesh)?;
495 c.rate.enabled = flag("DATUMESH_RATE_LIMITS", c.rate.enabled)?;
496 c.rate.per_ip = num("DATUMESH_RATE_PER_IP", c.rate.per_ip as usize)? as u32;
497 c.rate.ip_burst = num("DATUMESH_RATE_IP_BURST", c.rate.ip_burst as usize)? as u32;
498 c.rate.per_key = num("DATUMESH_RATE_PER_KEY", c.rate.per_key as usize)? as u32;
499 c.rate.verify_per_ip = num("DATUMESH_RATE_VERIFY_PER_IP", c.rate.verify_per_ip as usize)? as u32;
500 c.rate.series_per_ip = num("DATUMESH_RATE_SERIES_PER_IP", c.rate.series_per_ip as usize)? as u32;
501 c.rate.calc_per_ip = num("DATUMESH_RATE_CALC_PER_IP", c.rate.calc_per_ip as usize)? as u32;
502 c.rate.keys_per_ip = num("DATUMESH_RATE_KEYS_PER_IP", c.rate.keys_per_ip as usize)? as u32;
503 c.key_names = get("DATUMESH_KEY_NAMES").as_deref() == Some("1");
505 c.key_challenge_ttl = secs("DATUMESH_KEY_CHALLENGE_TTL_SECS", c.key_challenge_ttl)?;
506 c.contact = get("DATUMESH_CONTACT").map(|v| v.trim().to_string()).filter(|v| !v.is_empty());
507 c.series_first_build_delay = secs("DATUMESH_SERIES_FIRST_BUILD_DELAY_SECS", c.series_first_build_delay)?;
508 c.series_refresh = secs("DATUMESH_SERIES_REFRESH_SECS", c.series_refresh)?;
509 c.catalog_first_build_delay = secs("DATUMESH_CATALOG_FIRST_BUILD_DELAY_SECS", c.catalog_first_build_delay)?;
510 c.catalog_refresh = secs("DATUMESH_CATALOG_REFRESH_SECS", c.catalog_refresh)?;
511 c.index_first_build_delay = secs("DATUMESH_INDEX_FIRST_BUILD_DELAY_SECS", c.index_first_build_delay)?;
512 c.index_secs = secs("DATUMESH_INDEX_SECS", c.index_secs)?;
513 c.index_class_max = num("DATUMESH_INDEX_CLASS_MAX", c.index_class_max)?.max(1);
514 c.index_max = num("DATUMESH_INDEX_MAX", c.index_max)?.max(1);
515 c.find_first_build_delay = secs("DATUMESH_FIND_FIRST_BUILD_DELAY_SECS", c.find_first_build_delay)?;
516 c.value_counts_refresh = secs("DATUMESH_VALUE_COUNTS_SECS", c.value_counts_refresh)?;
517 c.dictionary_max = num("DATUMESH_DICTIONARY_MAX", c.dictionary_max)?;
518 c.ttl.key_doc = secs("DATUMESH_TTL_KEY_DOC", c.ttl.key_doc)?;
519 c.ttl.mesh_doc = secs("DATUMESH_TTL_MESH_DOC", c.ttl.mesh_doc)?;
520 c.ttl.binding = secs("DATUMESH_TTL_BINDING", c.ttl.binding)?;
521 c.ttl.current = secs("DATUMESH_TTL_CURRENT", c.ttl.current)?;
522 c.ttl.latest_max_age = secs("DATUMESH_LATEST_MAX_AGE", c.ttl.latest_max_age)?;
523 c.ttl.job = secs("DATUMESH_JOB_TTL", c.ttl.job)?;
524 c.peer_timeout = ms("DATUMESH_PEER_TIMEOUT_MS", c.peer_timeout)?;
525 if let Some(v) = get("DATUMESH_CROSS_MESH_HOSTS") {
526 c.cross_mesh_hosts = Some(v.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect());
527 }
528 if let Some(v) = get("DATUMESH_PEERS") {
529 for pair in v.split(',').map(str::trim).filter(|s| !s.is_empty()) {
530 let (h, o) =
531 pair.split_once('=').ok_or_else(|| ConfigError::new("DATUMESH_PEERS", "host=origin pairs"))?;
532 c.peers.insert(h.trim().to_string(), o.trim().trim_end_matches('/').to_string());
533 }
534 }
535 if let Some(p) = get("DATUMESH_ALIASES_FILE") {
536 c.aliases = string_map(&read_file(&p)?, "DATUMESH_ALIASES_FILE")?;
537 }
538 if let Some(p) = get("DATUMESH_CATALOG_FILE") {
539 c.catalog = string_map(&read_file(&p)?, "DATUMESH_CATALOG_FILE")?;
540 }
541 if let Some(v) = get("DATUMESH_EMBED_URL").filter(|v| !v.trim().is_empty()) {
542 c.embed_url = Some(v.trim().trim_end_matches('/').to_string());
543 }
544 if let Some(p) = get("DATUMESH_POLICY_FILE") {
545 c.policy = Policy::from_json(&read_file(&p)?)?;
546 }
547 if let Some(p) = get("DATUMESH_API_KEYS_FILE") {
548 c.api_keys = ApiKeys::parse(&read_secret_file(Path::new(&p))?)?;
549 }
550 c.publish_domains = PublishDomains::parse(&get("DATUMESH_PUBLISH_DOMAINS").unwrap_or_default())?;
551 if let Some(p) = get("DATUMESH_SERIES_FILE").filter(|p| !p.trim().is_empty()) {
552 c.series = crate::series::parse(&read_file(&p)?)?;
553 }
554 if let Some(d) = get("DATUMESH_LOG_DIR").filter(|d| !d.trim().is_empty()) {
555 c.log_dir = Some(std::path::PathBuf::from(d));
556 }
557 c.check()?;
558 Ok(c)
559 }
560
561 pub fn check(&self) -> Result<(), ConfigError> {
564 lexical::check_dns_name(&self.host, "$").map_err(|e| ConfigError::new("host", e.to_string()))?;
565 if self.series_refresh < Duration::from_secs(1) {
566 return Err(ConfigError::new("DATUMESH_SERIES_REFRESH_SECS", "at least 1 second"));
567 }
568 if self.catalog_refresh < Duration::from_secs(1) {
569 return Err(ConfigError::new("DATUMESH_CATALOG_REFRESH_SECS", "at least 1 second"));
570 }
571 if self.value_counts_refresh < Duration::from_secs(1) {
572 return Err(ConfigError::new("DATUMESH_VALUE_COUNTS_SECS", "at least 1 second"));
573 }
574 if self.dictionary_max == 0 {
575 return Err(ConfigError::new("DATUMESH_DICTIONARY_MAX", "at least 1"));
576 }
577 if let Some(c) = &self.contact {
578 if c.chars().any(|ch| ch.is_whitespace() || ch.is_control()) {
579 return Err(ConfigError::new("DATUMESH_CONTACT", "an address without spaces"));
580 }
581 }
582 if let Some(u) = &self.base_url {
583 check_base_url(&self.host, u).map_err(|e| ConfigError::new("base URL", format!("{u}: {e}")))?;
584 }
585 for h in &self.namespaces {
586 lexical::check_dns_name(h, "$").map_err(|e| ConfigError::new("namespaces", e.to_string()))?;
587 }
588 for (h, o) in &self.peers {
589 lexical::check_dns_name(h, "$").map_err(|e| ConfigError::new("peers", e.to_string()))?;
590 if !(o.starts_with("http://") || o.starts_with("https://")) {
591 return Err(ConfigError::new("peers", format!("{o}: not an http(s) origin")));
592 }
593 }
594 for (a, n) in &self.aliases {
595 lexical::check_function_name(n, "$").map_err(|e| ConfigError::new("aliases", format!("{a}: {e}")))?;
596 }
597 if self.pool_size == 0 || self.batch_max == 0 || self.slice_page == 0 || self.slice_max == 0 {
598 return Err(ConfigError::new("sizes", "the pool, batch and slice bounds must be positive"));
599 }
600 if self.ttl.job < Duration::from_secs(300) {
601 return Err(ConfigError::new("job TTL", "at least 300 s (SPEC 5.5)"));
602 }
603 if self.budget.is_zero() {
604 return Err(ConfigError::new("budget", "must be positive"));
605 }
606 Ok(())
607 }
608
609 pub fn owns(&self, host: &str) -> bool {
611 self.namespaces.iter().any(|h| h == host)
612 }
613
614 pub fn origin(&self) -> String {
616 format!("https://{}", self.host)
617 }
618
619 pub fn mesh_document_base(&self) -> String {
622 self.base_url.clone().unwrap_or_else(|| self.origin())
623 }
624}
625
626#[non_exhaustive]
628#[derive(Clone, Copy, Debug, PartialEq, Eq)]
629pub enum BaseUrlError {
630 Scheme,
632 HttpRootedHost,
635 HttpNotLoopback,
638 Host,
641 Port,
643 Path,
645 TrailingSlash,
647 Query,
649 Fragment,
651}
652
653impl fmt::Display for BaseUrlError {
654 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
655 f.write_str(match self {
656 BaseUrlError::Scheme => "not an https:// or http:// URL",
657 BaseUrlError::HttpRootedHost => "http:// is for an unrooted host (under .invalid) only",
658 BaseUrlError::HttpNotLoopback => "http:// is for 127.0.0.1, [::1] and localhost only",
659 BaseUrlError::Host => "not a host name, IPv4 address or bracketed IPv6 address",
660 BaseUrlError::Port => "not a port from 1 to 65535",
661 BaseUrlError::Path => "a path (the base URL is a scheme, a host and a port)",
662 BaseUrlError::TrailingSlash => "a trailing slash",
663 BaseUrlError::Query => "a query",
664 BaseUrlError::Fragment => "a fragment",
665 })
666 }
667}
668
669impl std::error::Error for BaseUrlError {}
670
671pub fn check_base_url(host: &str, url: &str) -> Result<(), BaseUrlError> {
678 let mesh_host = host;
679 let (http, rest) = if let Some(r) = url.strip_prefix("https://") {
680 (false, r)
681 } else if let Some(r) = url.strip_prefix("http://") {
682 (true, r)
683 } else {
684 return Err(BaseUrlError::Scheme);
685 };
686 if rest.contains('#') {
687 return Err(BaseUrlError::Fragment);
688 }
689 if rest.contains('?') {
690 return Err(BaseUrlError::Query);
691 }
692 let (authority, path) = rest.split_at(rest.find('/').unwrap_or(rest.len()));
693 match path {
694 "" => {}
695 "/" => return Err(BaseUrlError::TrailingSlash),
696 _ => return Err(BaseUrlError::Path),
697 }
698 if authority.contains('@') {
699 return Err(BaseUrlError::Host);
700 }
701 let (host, port) = if let Some(r) = authority.strip_prefix('[') {
702 let (inside, after) = r.split_once(']').ok_or(BaseUrlError::Host)?;
703 inside.parse::<std::net::Ipv6Addr>().map_err(|_| BaseUrlError::Host)?;
704 let port = match after {
705 "" => None,
706 p => Some(p.strip_prefix(':').ok_or(BaseUrlError::Host)?),
707 };
708 (&authority[..inside.len() + 2], port)
709 } else {
710 let (host, port) = match authority.split_once(':') {
711 Some((h, p)) => (h, Some(p)),
712 None => (authority, None),
713 };
714 if host.parse::<std::net::Ipv4Addr>().is_err() && !is_dns_name(host) {
715 return Err(BaseUrlError::Host);
716 }
717 (host, port)
718 };
719 if let Some(p) = port {
720 let ok = !p.is_empty() && p.len() <= 5 && p.bytes().all(|b| b.is_ascii_digit());
721 if !ok || !(1..=65535).contains(&p.parse::<u32>().unwrap_or(0)) {
722 return Err(BaseUrlError::Port);
723 }
724 }
725 if http && !is_unrooted(mesh_host) {
726 return Err(BaseUrlError::HttpRootedHost);
727 }
728 if http && !matches!(host, "127.0.0.1" | "[::1]" | "localhost") {
729 return Err(BaseUrlError::HttpNotLoopback);
730 }
731 Ok(())
732}
733
734pub fn is_unrooted(host: &str) -> bool {
737 host.rsplit('.').next() == Some("invalid")
738}
739
740fn is_dns_name(h: &str) -> bool {
743 !h.is_empty()
744 && h.len() <= 253
745 && h.split('.').all(|l| {
746 !l.is_empty()
747 && l.len() <= 63
748 && !l.starts_with('-')
749 && !l.ends_with('-')
750 && l.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
751 })
752}
753
754fn string_map(bytes: &[u8], what: &str) -> Result<BTreeMap<String, String>, ConfigError> {
755 let v = json::parse(bytes).map_err(|e| ConfigError::new(what, e.to_string()))?;
756 let mut out = BTreeMap::new();
757 for (k, x) in v.as_object().ok_or_else(|| ConfigError::new(what, "not an object"))? {
758 let s = x.as_str().ok_or_else(|| ConfigError::new(what, format!("{k}: not a string")))?;
759 out.insert(k.clone(), s.to_string());
760 }
761 Ok(out)
762}
763
764fn read_file(path: &str) -> Result<Vec<u8>, ConfigError> {
765 std::fs::read(path).map_err(|e| ConfigError::new(path, e.to_string()))
766}
767
768pub fn read_secret_file(path: &Path) -> Result<Vec<u8>, ConfigError> {
771 let what = path.display().to_string();
772 let meta = std::fs::metadata(path).map_err(|e| ConfigError::new(&what, e.to_string()))?;
773 #[cfg(unix)]
774 {
775 use std::os::unix::fs::PermissionsExt;
776 let mode = meta.permissions().mode() & 0o777;
777 if mode & 0o077 != 0 {
778 return Err(ConfigError::new(&what, format!("mode {mode:o}: a secret file must be 0600")));
779 }
780 }
781 #[cfg(not(unix))]
782 let _ = meta;
783 std::fs::read(path).map_err(|e| ConfigError::new(&what, e.to_string()))
784}
785
786#[derive(Clone, Debug, PartialEq, Eq)]
788pub struct ConfigError {
789 what: String,
790 detail: String,
791}
792
793impl ConfigError {
794 pub(crate) fn new(what: &str, detail: impl Into<String>) -> ConfigError {
795 ConfigError { what: what.to_string(), detail: detail.into() }
796 }
797}
798
799impl fmt::Display for ConfigError {
800 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
801 write!(f, "configuration: {}: {}", self.what, self.detail)
802 }
803}
804
805impl std::error::Error for ConfigError {}