diff --git a/cli/src/commands/serve_web.rs b/cli/src/commands/serve_web.rs index 9b4a0c47b15d7..d9e525af6c693 100644 --- a/cli/src/commands/serve_web.rs +++ b/cli/src/commands/serve_web.rs @@ -5,6 +5,8 @@ use std::collections::HashMap; use std::convert::Infallible; +use std::fs; +use std::io::{Read, Write}; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; @@ -13,7 +15,6 @@ use std::time::{Duration, Instant}; use const_format::concatcp; use hyper::service::{make_service_fn, service_fn}; use hyper::{Body, Request, Response, Server}; -use tempfile::{tempdir, TempDir}; use tokio::io::{AsyncBufReadExt, BufReader}; use tokio::pin; @@ -77,21 +78,15 @@ pub async fn serve_web(ctx: CommandContext, mut args: ServeWebArgs) -> Result Result>, } -struct ConnectionTokenFile { - path: PathBuf, - _dir: TempDir, // implements Drop to delete the dir -} - -impl ConnectionTokenFile { - fn new(connection_token: &str) -> std::io::Result { - let d = tempdir()?; - let path = d.path().join("connection-token"); - std::fs::write(&path, connection_token)?; - Ok(ConnectionTokenFile { path, _dir: d }) +fn mint_connection_token(path: &Path, prefer_token: Option) -> std::io::Result { + #[cfg(not(windows))] + use std::os::unix::fs::OpenOptionsExt; + + let mut f = fs::OpenOptions::new(); + f.create(true); + f.write(true); + f.read(true); + #[cfg(not(windows))] + f.mode(0o600); + let mut f = f.open(path)?; + + if prefer_token.is_none() { + let mut t = String::new(); + f.read_to_string(&mut t)?; + let t = t.trim(); + if !t.is_empty() { + return Ok(t.to_string()); + } } - fn path(&self) -> &Path { - &self.path - } + f.set_len(0)?; + let prefer_token = prefer_token.unwrap_or_else(|| uuid::Uuid::new_v4().to_string()); + f.write_all(prefer_token.as_bytes())?; + Ok(prefer_token) }