Skip to main content

mist/
lib.rs

1//! # Mist: Private DNS for Local-First Networking
2#![allow(clippy::tabs_in_doc_comments, clippy::unnecessary_lazy_evaluations)]
3//! Mist gives Land its own private DNS so editor components can find each
4//! other on `*.editor.land` without touching the public internet. All queries
5//! resolve to `127.0.0.1`. No external DNS leaks, no configuration needed.
6//!
7//! ## Features
8//!
9//! - **Private DNS Zone**: Authoritative zone for `*.editor.land` domains
10//! - **Local Resolution**: All editor.land queries resolve to `127.0.0.1`.
11//! - **Dynamic Port Allocation**: Automatically finds available ports using
12//!   portpicker
13//! - **Async/Sync Support**: Both async and blocking server implementations
14//!
15//! ## Example
16//!
17//! ```rust,no_run
18//! use Mist::start;
19//!
20//! #[tokio::main]
21//! async fn main() -> anyhow::Result<()> {
22//! 	// Start the DNS server (tries port 5353 first, then finds an available one)
23//! 	let port = start(5353)?;
24//!
25//! 	println!("DNS server running on port {}", port);
26//!
27//! 	// The server runs in the background
28//! 	// Use DNS_PORT to get the port number elsewhere
29//!
30//! 	Ok(())
31//! }
32//! ```
33
34use std::thread;
35
36use anyhow::Result;
37use once_cell::sync::OnceCell;
38
39// Public module exports (PascalCase per project convention)
40pub mod Server;
41pub mod Zone;
42pub mod Resolver;
43pub mod ForwardSecurity;
44
45/// Global DNS port number.
46///
47/// This static cell stores the port number that the DNS server is running on.
48/// It is set once when [`start`] is called and remains constant thereafter.
49///
50/// # Example
51///
52/// ```rust
53/// use Mist::dns_port;
54///
55/// // Returns the port number, or 0 if the server hasn't been started
56/// let port = dns_port();
57/// ```
58pub static DNS_PORT:OnceCell<u16> = OnceCell::new();
59
60/// Returns the DNS port number.
61///
62/// Returns the port that the DNS server is listening on, or `0` if the
63/// server has not been started yet.
64///
65/// # Returns
66///
67/// The port number (0-65535), or 0 if the server hasn't started.
68///
69/// # Example
70///
71/// ```rust
72/// use Mist::dns_port;
73///
74/// let port = dns_port();
75/// if port > 0 {
76/// 	println!("DNS server is running on port {}", port);
77/// } else {
78/// 	println!("DNS server has not been started");
79/// }
80/// ```
81pub fn dns_port() -> u16 { *DNS_PORT.get().unwrap_or(&0) }
82
83/// Starts the DNS server for the CodeEditorLand private network.
84///
85/// This function performs the following steps:
86/// 1. Uses portpicker to find an available port (tries `preferred_port` first)
87/// 2. Sets the `DNS_PORT` global variable
88/// 3. Builds the DNS catalog with the `editor.land` zone
89/// 4. Spawns the DNS server as a background task
90/// 5. Returns the port number
91///
92/// The DNS server runs in the background and can be stopped by dropping
93/// the application.
94///
95/// # Parameters
96///
97/// * `preferred_port` - The preferred port number to use. If this port is
98///   already in use, portpicker will find an alternative available port.
99///
100/// # Returns
101///
102/// Returns `Ok(port)` with the port number the server is listening on,
103/// or an error if the server failed to start.
104///
105/// # Example
106///
107/// ```rust,no_run
108/// use Mist::start;
109///
110/// #[tokio::main]
111/// async fn main() -> anyhow::Result<()> {
112/// 	// Start DNS server, preferring port 5353
113/// 	let port = start(5353)?;
114/// 	println!("DNS server started on port {}", port);
115/// 	tokio::signal::ctrl_c().await?;
116/// 	Ok(())
117/// }
118/// ```
119pub fn start(preferred_port:u16) -> Result<u16> {
120	// Step 1: Find an available port using portpicker
121	// Try the preferred port first, then pick a random available one
122	let port = portpicker::pick_unused_port()
123		.or_else(|| {
124			// If pick_unused_port returns None, try the preferred port explicitly
125			Some(preferred_port)
126		})
127		.ok_or_else(|| anyhow::anyhow!("Failed to find an available port"))?;
128
129	// Step 2: Set the DNS_PORT globally
130	DNS_PORT
131		.set(port)
132		.map_err(|_| anyhow::anyhow!("DNS port has already been set"))?;
133
134	// Step 3: Build the DNS catalog
135	let catalog = Server::BuildCatalog(port)?;
136
137	// Step 4: Spawn the DNS server as a background task
138	thread::spawn(move || {
139		if let Err(e) = Server::ServeSync(catalog, port) {
140			eprintln!("DNS server error: {:?}", e);
141		}
142	});
143
144	// Step 5: Return the port number
145	Ok(port)
146}
147
148#[cfg(test)]
149mod tests {
150	use super::*;
151
152	#[test]
153	fn test_dns_port_initial_state() {
154		// Initially, DNS_PORT should be 0
155		let port = dns_port();
156		assert_eq!(port, 0);
157	}
158
159	#[test]
160	fn test_dns_port_starts_server() {
161		// Test that we can start the DNS server
162		let preferred_port = 15353; // Use a non-standard port for testing
163
164		let result = start(preferred_port);
165
166		// The server should start successfully
167		assert!(result.is_ok(), "Failed to start DNS server");
168
169		let port = result.unwrap();
170
171		// The port should be within valid range
172		assert!(port >= 1024, "Port should be >= 1024");
173		assert!(port <= 65535, "Port should be <= 65535");
174
175		// DNS_PORT should now return the same port
176		let retrieved_port = dns_port();
177		assert_eq!(port, retrieved_port, "DNS_PORT should match returned port");
178	}
179
180	#[test]
181	fn test_start_fails_on_second_call() {
182		// Starting the server twice should fail
183		let port1 = start(15354);
184		assert!(port1.is_ok(), "First start should succeed");
185
186		let port2 = start(15355);
187		assert!(port2.is_err(), "Second start should fail");
188	}
189
190	#[test]
191	fn test_build_catalog_api() {
192		let catalog = Server::BuildCatalog(15356);
193		assert!(catalog.is_ok(), "Should be able to build catalog");
194	}
195
196	#[test]
197	fn test_build_zone_api() {
198		let zone = Zone::EditorLandZone();
199		assert!(zone.is_ok(), "Should be able to build zone");
200	}
201}