Skip to main content

mobius_gateway/command/
init.rs

1use super::*;
2
3pub(super) fn initialize(options: InitOptions) -> Result<()> {
4    let (store, config) = match options.cloudflare {
5        Some(CloudflareInit::Quick) => {
6            ConfigStore::initialize_quick_cloudflare(options.state_dir, options.listen)?
7        }
8        Some(CloudflareInit::Named { hostname, token }) => {
9            ConfigStore::initialize_named_cloudflare(
10                options.state_dir,
11                options.listen,
12                &hostname,
13                &token,
14            )?
15        }
16        None if options.tls.is_none() => {
17            ConfigStore::initialize_quick_cloudflare(options.state_dir, options.listen)?
18        }
19        None => ConfigStore::initialize(options.state_dir, options.listen, options.tls)?,
20    };
21    initialize_auth(&store)?;
22    println!("initialized möbius gateway");
23    print_listener(&config, None);
24    println!("run `mobius-gateway connect` to pair a client");
25    Ok(())
26}
27
28pub(super) fn initialize_auth(store: &ConfigStore) -> Result<()> {
29    if let Err(error) = AuthStore::initialize(store.auth_path()) {
30        return cleanup_failed_initialization(store, error);
31    }
32    Ok(())
33}
34
35pub(super) fn initialize_bootstrap(
36    state_dir: PathBuf,
37    save_local_client: fn(&Endpoint, String) -> Result<()>,
38) -> Result<()> {
39    let (store, config) = ConfigStore::initialize(state_dir, DEFAULT_LISTEN, None)?;
40    let initialized = AuthStore::initialize(store.auth_path()).and_then(|(auth, _)| {
41        let endpoint = direct_loopback_endpoint(&config)?;
42        let issued = auth.provision_local_client()?;
43        save_local_client(&endpoint, issued.token)
44    });
45    if let Err(error) = initialized {
46        return cleanup_failed_initialization(&store, error);
47    }
48    println!("initialized möbius gateway bootstrap");
49    print_listener(&config, None);
50    Ok(())
51}
52
53pub(super) fn direct_loopback_endpoint(config: &GatewayConfig) -> Result<Endpoint> {
54    if !config.listen.ip().is_loopback() || config.tls.is_some() || config.cloudflare.is_some() {
55        return Err(Error::Config(
56            "bootstrap commands require a direct plaintext loopback gateway".into(),
57        ));
58    }
59    loopback_endpoint(config)
60}
61
62fn cleanup_failed_initialization<T>(store: &ConfigStore, error: Error) -> Result<T> {
63    std::fs::remove_dir_all(store.state_dir()).map_err(|cleanup| {
64        Error::Config(format!(
65            "{error}; failed to remove incomplete gateway state at {}: {cleanup}",
66            store.state_dir().display()
67        ))
68    })?;
69    Err(error)
70}
71
72pub(super) fn provision_cloudflare_local_client(
73    auth: &AuthStore,
74    config: &GatewayConfig,
75) -> Result<Option<(Endpoint, String)>> {
76    if config.cloudflare.is_none() {
77        return Ok(None);
78    }
79    let endpoint = loopback_endpoint(config)?;
80    let issued = auth.provision_local_client()?;
81    Ok(Some((endpoint, issued.token)))
82}
83
84pub(super) fn loopback_endpoint(config: &GatewayConfig) -> Result<Endpoint> {
85    format!("tcp://{}", config.listen).parse()
86}
87
88/// Initializes one gateway with an account-free Cloudflare Quick Tunnel.
89pub fn initialize_quick_cloudflare(state_dir: PathBuf) -> Result<()> {
90    initialize(InitOptions {
91        state_dir,
92        listen: DEFAULT_LISTEN,
93        tls: None,
94        cloudflare: Some(CloudflareInit::Quick),
95    })
96}
97
98/// Initializes one gateway against a user-owned named Cloudflare Tunnel.
99pub fn initialize_named_cloudflare(
100    state_dir: PathBuf,
101    hostname: String,
102    token: String,
103) -> Result<()> {
104    initialize(InitOptions {
105        state_dir,
106        listen: DEFAULT_LISTEN,
107        tls: None,
108        cloudflare: Some(CloudflareInit::Named { hostname, token }),
109    })
110}
111
112/// Permanently removes previously confirmed gateway state after stopping its process.
113///
114/// # Errors
115///
116/// Returns an error unless the target is an empty real directory or contains a regular
117/// `gateway.toml` marker. Lifecycle or filesystem failures are also returned.
118pub fn reset_gateway_state(state_dir: PathBuf) -> Result<()> {
119    #[cfg(unix)]
120    {
121        let had_config = validate_reset_target(&state_dir, false)?;
122        let state_dir = fs::canonicalize(state_dir)?;
123        let _startup = StartupGuard::create(&state_dir)?;
124        if validate_reset_target(&state_dir, true)? != had_config {
125            return Err(invalid_reset_target(&state_dir));
126        }
127        stop_gateway(&state_dir, None)?;
128        fs::remove_dir_all(state_dir)?;
129        Ok(())
130    }
131    #[cfg(not(unix))]
132    {
133        let _ = state_dir;
134        Err(unsupported_lifecycle())
135    }
136}
137
138#[cfg(unix)]
139pub(super) fn validate_reset_target(path: &Path, ignore_startup_lock: bool) -> Result<bool> {
140    let metadata = fs::symlink_metadata(path)?;
141    if metadata.file_type().is_symlink() || !metadata.is_dir() {
142        return Err(invalid_reset_target(path));
143    }
144    let mut empty = true;
145    for entry in fs::read_dir(path)? {
146        let entry = entry?;
147        if ignore_startup_lock && entry.file_name() == STARTUP_FILE {
148            continue;
149        }
150        empty = false;
151    }
152    if empty {
153        return Ok(false);
154    }
155    let marker = fs::symlink_metadata(path.join(STATE_MARKER_FILE))
156        .map_err(|_| invalid_reset_target(path))?;
157    if !marker.is_file() || marker.file_type().is_symlink() {
158        return Err(invalid_reset_target(path));
159    }
160    Ok(true)
161}
162
163#[cfg(unix)]
164pub(super) fn invalid_reset_target(path: &Path) -> Error {
165    Error::Config(format!(
166        "refusing to reset {}: expected an empty directory or möbius gateway state with a regular {STATE_MARKER_FILE}",
167        path.display()
168    ))
169}