| 1 |
// Copyright 2011, 2018 Yuya Nishihara <[email protected]> |
| 2 |
// |
| 3 |
// This software may be used and distributed according to the terms of the |
| 4 |
// GNU General Public License version 2 or any later version. |
| 5 |
|
| 6 |
//! Utility for locating command-server process. |
| 7 |
|
| 8 |
use std::env; |
| 9 |
use std::ffi::OsStr; |
| 10 |
use std::ffi::OsString; |
| 11 |
use std::fs::DirBuilder; |
| 12 |
use std::fs::{self}; |
| 13 |
use std::io; |
| 14 |
use std::os::unix::ffi::OsStrExt; |
| 15 |
use std::os::unix::ffi::OsStringExt; |
| 16 |
use std::os::unix::fs::DirBuilderExt; |
| 17 |
use std::os::unix::fs::MetadataExt; |
| 18 |
use std::path::Path; |
| 19 |
use std::path::PathBuf; |
| 20 |
use std::process::Child; |
| 21 |
use std::process::Command; |
| 22 |
use std::process::{self}; |
| 23 |
use std::time::Duration; |
| 24 |
use std::time::Instant; |
| 25 |
|
| 26 |
use log::debug; |
| 27 |
use tokio::time; |
| 28 |
|
| 29 |
use crate::clientext::ChgClient; |
| 30 |
use crate::message::Instruction; |
| 31 |
use crate::message::ServerSpec; |
| 32 |
use crate::procutil; |
| 33 |
|
| 34 |
const REQUIRED_SERVER_CAPABILITIES: &[&str] = |
| 35 |
&["attachio", "chdir", "runcommand", "setenv", "setumask2", "validate"]; |
| 36 |
|
| 37 |
/// Helper to connect to and spawn a server process. |
| 38 |
#[derive(Clone, Debug)] |
| 39 |
pub struct Locator { |
| 40 |
hg_command: OsString, |
| 41 |
hg_early_args: Vec<OsString>, |
| 42 |
current_dir: PathBuf, |
| 43 |
env_vars: Vec<(OsString, OsString)>, |
| 44 |
process_id: u32, |
| 45 |
base_sock_path: PathBuf, |
| 46 |
redirect_sock_path: Option<PathBuf>, |
| 47 |
timeout: Duration, |
| 48 |
} |
| 49 |
|
| 50 |
impl Locator { |
| 51 |
/// Creates locator capturing the current process environment. |
| 52 |
/// |
| 53 |
/// If no `$CHGSOCKNAME` is specified, the socket directory will be |
| 54 |
/// created as necessary. |
| 55 |
pub fn prepare_from_env() -> io::Result<Locator> { |
| 56 |
Ok(Locator { |
| 57 |
hg_command: default_hg_command(), |
| 58 |
hg_early_args: Vec::new(), |
| 59 |
current_dir: env::current_dir()?, |
| 60 |
env_vars: env::vars_os().collect(), |
| 61 |
process_id: process::id(), |
| 62 |
base_sock_path: prepare_server_socket_path()?, |
| 63 |
redirect_sock_path: None, |
| 64 |
timeout: default_timeout(), |
| 65 |
}) |
| 66 |
} |
| 67 |
|
| 68 |
/// Temporary socket path for this client process. |
| 69 |
fn temp_sock_path(&self) -> PathBuf { |
| 70 |
let src = self.base_sock_path.as_os_str().as_bytes(); |
| 71 |
let mut buf = Vec::with_capacity(src.len() + 6); // "{src}.{pid}".len() |
| 72 |
buf.extend_from_slice(src); |
| 73 |
buf.extend_from_slice(format!(".{}", self.process_id).as_bytes()); |
| 74 |
OsString::from_vec(buf).into() |
| 75 |
} |
| 76 |
|
| 77 |
/// Specifies the arguments to be passed to the server at start. |
| 78 |
pub fn set_early_args( |
| 79 |
&mut self, |
| 80 |
args: impl IntoIterator<Item = impl AsRef<OsStr>>, |
| 81 |
) { |
| 82 |
self.hg_early_args = |
| 83 |
args.into_iter().map(|a| a.as_ref().to_owned()).collect(); |
| 84 |
} |
| 85 |
|
| 86 |
/// Connects to the server. |
| 87 |
/// |
| 88 |
/// The server process will be spawned if not running. |
| 89 |
pub async fn connect(&mut self) -> io::Result<ChgClient> { |
| 90 |
for _cnt in 0..10 { |
| 91 |
let mut client = self.try_connect().await?; |
| 92 |
let instructions = client.validate(&self.hg_early_args).await?; |
| 93 |
let reconnect = self.run_instructions(&instructions)?; |
| 94 |
if !reconnect { |
| 95 |
return Ok(client); |
| 96 |
} |
| 97 |
} |
| 98 |
|
| 99 |
let msg = format!( |
| 100 |
concat!( |
| 101 |
"too many redirections.\n", |
| 102 |
"Please make sure {:?} is not a wrapper which ", |
| 103 |
"changes sensitive environment variables ", |
| 104 |
"before executing hg. If you have to use a ", |
| 105 |
"wrapper, wrap chg instead of hg.", |
| 106 |
), |
| 107 |
self.hg_command |
| 108 |
); |
| 109 |
Err(io::Error::new(io::ErrorKind::Other, msg)) |
| 110 |
} |
| 111 |
|
| 112 |
/// Runs instructions received from the server. |
| 113 |
/// |
| 114 |
/// Returns true if the client should try connecting to the other server. |
| 115 |
fn run_instructions( |
| 116 |
&mut self, |
| 117 |
instructions: &[Instruction], |
| 118 |
) -> io::Result<bool> { |
| 119 |
let mut reconnect = false; |
| 120 |
for inst in instructions { |
| 121 |
debug!("instruction: {:?}", inst); |
| 122 |
match inst { |
| 123 |
Instruction::Exit(_) => { |
| 124 |
// Just returns the current connection to run the |
| 125 |
// unparsable command and report the error |
| 126 |
return Ok(false); |
| 127 |
} |
| 128 |
Instruction::Reconnect => { |
| 129 |
reconnect = true; |
| 130 |
} |
| 131 |
Instruction::Redirect(path) => { |
| 132 |
if path.parent() != self.base_sock_path.parent() { |
| 133 |
let msg = format!( |
| 134 |
"insecure redirect instruction from server: {}", |
| 135 |
path.display() |
| 136 |
); |
| 137 |
return Err(io::Error::new( |
| 138 |
io::ErrorKind::InvalidData, |
| 139 |
msg, |
| 140 |
)); |
| 141 |
} |
| 142 |
self.redirect_sock_path = Some(path.to_owned()); |
| 143 |
reconnect = true; |
| 144 |
} |
| 145 |
Instruction::Unlink(path) => { |
| 146 |
if path.parent() != self.base_sock_path.parent() { |
| 147 |
let msg = format!( |
| 148 |
"insecure unlink instruction from server: {}", |
| 149 |
path.display() |
| 150 |
); |
| 151 |
return Err(io::Error::new( |
| 152 |
io::ErrorKind::InvalidData, |
| 153 |
msg, |
| 154 |
)); |
| 155 |
} |
| 156 |
fs::remove_file(path).unwrap_or(()); // may race |
| 157 |
} |
| 158 |
} |
| 159 |
} |
| 160 |
|
| 161 |
Ok(reconnect) |
| 162 |
} |
| 163 |
|
| 164 |
/// Tries to connect to the existing server, or spawns new if not running. |
| 165 |
async fn try_connect(&mut self) -> io::Result<ChgClient> { |
| 166 |
let sock_path = self |
| 167 |
.redirect_sock_path |
| 168 |
.as_ref() |
| 169 |
.unwrap_or(&self.base_sock_path) |
| 170 |
.clone(); |
| 171 |
debug!("try connect to {}", sock_path.display()); |
| 172 |
let mut client = match ChgClient::connect(sock_path).await { |
| 173 |
Ok(client) => client, |
| 174 |
Err(_) => { |
| 175 |
// Prevent us from being re-connected to the outdated |
| 176 |
// master server: We were told by the server to redirect |
| 177 |
// to redirect_sock_path, which didn't work. We do not |
| 178 |
// want to connect to the same master server again |
| 179 |
// because it would probably tell us the same thing. |
| 180 |
if self.redirect_sock_path.is_some() { |
| 181 |
fs::remove_file(&self.base_sock_path).unwrap_or(()); |
| 182 |
// may race |
| 183 |
} |
| 184 |
self.spawn_connect().await? |
| 185 |
} |
| 186 |
}; |
| 187 |
check_server_capabilities(client.server_spec())?; |
| 188 |
// It's purely optional, and the server might not support this command. |
| 189 |
if client.server_spec().capabilities.contains("setprocname") { |
| 190 |
client |
| 191 |
.set_process_name(format!("chg[worker/{}]", self.process_id)) |
| 192 |
.await?; |
| 193 |
} |
| 194 |
client.set_current_dir(&self.current_dir).await?; |
| 195 |
client.set_env_vars_os(self.env_vars.iter().cloned()).await?; |
| 196 |
Ok(client) |
| 197 |
} |
| 198 |
|
| 199 |
/// Spawns new server process and connects to it. |
| 200 |
/// |
| 201 |
/// The server will be spawned at the current working directory, then |
| 202 |
/// chdir to "/", so that the server will load configs from the target |
| 203 |
/// repository. |
| 204 |
async fn spawn_connect(&mut self) -> io::Result<ChgClient> { |
| 205 |
let sock_path = self.temp_sock_path(); |
| 206 |
debug!("start cmdserver at {}", sock_path.display()); |
| 207 |
let server = Command::new(&self.hg_command) |
| 208 |
.arg("serve") |
| 209 |
.arg("--cmdserver") |
| 210 |
.arg("chgunix") |
| 211 |
.arg("--address") |
| 212 |
.arg(&sock_path) |
| 213 |
.arg("--daemon-postexec") |
| 214 |
.arg("chdir:/") |
| 215 |
.args(&self.hg_early_args) |
| 216 |
.current_dir(&self.current_dir) |
| 217 |
.env_clear() |
| 218 |
.envs(self.env_vars.iter().cloned()) |
| 219 |
.env("CHGINTERNALMARK", "") |
| 220 |
.spawn()?; |
| 221 |
let client = self.connect_spawned(server, &sock_path).await?; |
| 222 |
debug!( |
| 223 |
"rename {} to {}", |
| 224 |
sock_path.display(), |
| 225 |
self.base_sock_path.display() |
| 226 |
); |
| 227 |
fs::rename(&sock_path, &self.base_sock_path)?; |
| 228 |
Ok(client) |
| 229 |
} |
| 230 |
|
| 231 |
/// Tries to connect to the just spawned server repeatedly until timeout |
| 232 |
/// exceeded. |
| 233 |
async fn connect_spawned( |
| 234 |
&mut self, |
| 235 |
mut server: Child, |
| 236 |
sock_path: &Path, |
| 237 |
) -> io::Result<ChgClient> { |
| 238 |
debug!("try connect to {} repeatedly", sock_path.display()); |
| 239 |
// waits for either connection established or server failed to start |
| 240 |
let start_time = Instant::now(); |
| 241 |
while start_time.elapsed() < self.timeout { |
| 242 |
if let Ok(client) = ChgClient::connect(&sock_path).await { |
| 243 |
// server handle is dropped here, but the detached process |
| 244 |
// will continue running in background |
| 245 |
return Ok(client); |
| 246 |
} |
| 247 |
|
| 248 |
if let Some(st) = server.try_wait()? { |
| 249 |
return Err(io::Error::new( |
| 250 |
io::ErrorKind::Other, |
| 251 |
format!("server exited too early: {}", st), |
| 252 |
)); |
| 253 |
} |
| 254 |
|
| 255 |
// try again with slight delay |
| 256 |
time::delay_for(Duration::from_millis(10)).await; |
| 257 |
} |
| 258 |
|
| 259 |
Err(io::Error::new( |
| 260 |
io::ErrorKind::TimedOut, |
| 261 |
"timed out while connecting to server", |
| 262 |
)) |
| 263 |
} |
| 264 |
} |
| 265 |
|
| 266 |
/// Determines the server socket to connect to. |
| 267 |
/// |
| 268 |
/// If no `$CHGSOCKNAME` is specified, the socket directory will be created |
| 269 |
/// as necessary. |
| 270 |
fn prepare_server_socket_path() -> io::Result<PathBuf> { |
| 271 |
if let Some(s) = env::var_os("CHGSOCKNAME") { |
| 272 |
Ok(PathBuf::from(s)) |
| 273 |
} else { |
| 274 |
let mut path = default_server_socket_dir(); |
| 275 |
create_secure_dir(&path)?; |
| 276 |
path.push("server"); |
| 277 |
Ok(path) |
| 278 |
} |
| 279 |
} |
| 280 |
|
| 281 |
/// Determines the default server socket path as follows. |
| 282 |
/// |
| 283 |
/// 1. `$XDG_RUNTIME_DIR/chg` |
| 284 |
/// 2. `$TMPDIR/chg$UID` |
| 285 |
/// 3. `/tmp/chg$UID` |
| 286 |
pub fn default_server_socket_dir() -> PathBuf { |
| 287 |
// XDG_RUNTIME_DIR should be ignored if it has an insufficient permission. |
| 288 |
// https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html |
| 289 |
if let Some(Ok(s)) = env::var_os("XDG_RUNTIME_DIR").map(check_secure_dir) { |
| 290 |
let mut path = PathBuf::from(s); |
| 291 |
path.push("chg"); |
| 292 |
path |
| 293 |
} else { |
| 294 |
let mut path = env::temp_dir(); |
| 295 |
path.push(format!("chg{}", procutil::get_effective_uid())); |
| 296 |
path |
| 297 |
} |
| 298 |
} |
| 299 |
|
| 300 |
/// Determines the default hg command. |
| 301 |
pub fn default_hg_command() -> OsString { |
| 302 |
// TODO: maybe allow embedding the path at compile time (or load from hgrc) |
| 303 |
env::var_os("CHGHG") |
| 304 |
.or(env::var_os("HG")) |
| 305 |
.unwrap_or(OsStr::new("hg").to_owned()) |
| 306 |
} |
| 307 |
|
| 308 |
fn default_timeout() -> Duration { |
| 309 |
let secs = |
| 310 |
env::var("CHGTIMEOUT").ok().and_then(|s| s.parse().ok()).unwrap_or(60); |
| 311 |
Duration::from_secs(secs) |
| 312 |
} |
| 313 |
|
| 314 |
/// Creates a directory which the other users cannot access to. |
| 315 |
/// |
| 316 |
/// If the directory already exists, tests its permission. |
| 317 |
fn create_secure_dir(path: impl AsRef<Path>) -> io::Result<()> { |
| 318 |
DirBuilder::new().mode(0o700).create(path.as_ref()).or_else(|err| { |
| 319 |
if err.kind() == io::ErrorKind::AlreadyExists { |
| 320 |
check_secure_dir(path).map(|_| ()) |
| 321 |
} else { |
| 322 |
Err(err) |
| 323 |
} |
| 324 |
}) |
| 325 |
} |
| 326 |
|
| 327 |
fn check_secure_dir<P>(path: P) -> io::Result<P> |
| 328 |
where |
| 329 |
P: AsRef<Path>, |
| 330 |
{ |
| 331 |
let a = fs::symlink_metadata(path.as_ref())?; |
| 332 |
if a.is_dir() |
| 333 |
&& a.uid() == procutil::get_effective_uid() |
| 334 |
&& (a.mode() & 0o777) == 0o700 |
| 335 |
{ |
| 336 |
Ok(path) |
| 337 |
} else { |
| 338 |
Err(io::Error::new(io::ErrorKind::Other, "insecure directory")) |
| 339 |
} |
| 340 |
} |
| 341 |
|
| 342 |
fn check_server_capabilities(spec: &ServerSpec) -> io::Result<()> { |
| 343 |
let unsupported: Vec<_> = REQUIRED_SERVER_CAPABILITIES |
| 344 |
.iter() |
| 345 |
.cloned() |
| 346 |
.filter(|&s| !spec.capabilities.contains(s)) |
| 347 |
.collect(); |
| 348 |
if unsupported.is_empty() { |
| 349 |
Ok(()) |
| 350 |
} else { |
| 351 |
let msg = format!( |
| 352 |
"insufficient server capabilities: {}", |
| 353 |
unsupported.join(", ") |
| 354 |
); |
| 355 |
Err(io::Error::new(io::ErrorKind::Other, msg)) |
| 356 |
} |
| 357 |
} |
| 358 |
|
| 359 |
/// Collects arguments which need to be passed to the server at start. |
| 360 |
pub fn collect_early_args( |
| 361 |
args: impl IntoIterator<Item = impl AsRef<OsStr>>, |
| 362 |
) -> Vec<OsString> { |
| 363 |
let mut args_iter = args.into_iter(); |
| 364 |
let mut early_args = Vec::new(); |
| 365 |
while let Some(arg) = args_iter.next() { |
| 366 |
let argb = arg.as_ref().as_bytes(); |
| 367 |
if argb == b"--" { |
| 368 |
break; |
| 369 |
} else if argb.starts_with(b"--") { |
| 370 |
let mut split = argb[2..].splitn(2, |&c| c == b'='); |
| 371 |
match split.next().unwrap() { |
| 372 |
b"traceback" => { |
| 373 |
if split.next().is_none() { |
| 374 |
early_args.push(arg.as_ref().to_owned()); |
| 375 |
} |
| 376 |
} |
| 377 |
b"config" | b"cwd" | b"repo" | b"repository" => { |
| 378 |
if split.next().is_some() { |
| 379 |
// --<flag>=<val> |
| 380 |
early_args.push(arg.as_ref().to_owned()); |
| 381 |
} else { |
| 382 |
// --<flag> <val> |
| 383 |
args_iter.next().map(|val| { |
| 384 |
early_args.push(arg.as_ref().to_owned()); |
| 385 |
early_args.push(val.as_ref().to_owned()); |
| 386 |
}); |
| 387 |
} |
| 388 |
} |
| 389 |
_ => {} |
| 390 |
} |
| 391 |
} else if argb.starts_with(b"-R") { |
| 392 |
if argb.len() > 2 { |
| 393 |
// -R<val> |
| 394 |
early_args.push(arg.as_ref().to_owned()); |
| 395 |
} else { |
| 396 |
// -R <val> |
| 397 |
args_iter.next().map(|val| { |
| 398 |
early_args.push(arg.as_ref().to_owned()); |
| 399 |
early_args.push(val.as_ref().to_owned()); |
| 400 |
}); |
| 401 |
} |
| 402 |
} |
| 403 |
} |
| 404 |
|
| 405 |
early_args |
| 406 |
} |
| 407 |
|
| 408 |
#[cfg(test)] |
| 409 |
mod tests { |
| 410 |
use super::*; |
| 411 |
|
| 412 |
#[test] |
| 413 |
fn collect_early_args_some() { |
| 414 |
assert!(collect_early_args(&[] as &[&OsStr]).is_empty()); |
| 415 |
assert!(collect_early_args(&["log"]).is_empty()); |
| 416 |
assert_eq!( |
| 417 |
collect_early_args(&["log", "-Ra", "foo"]), |
| 418 |
os_string_vec_from(&[b"-Ra"]) |
| 419 |
); |
| 420 |
assert_eq!( |
| 421 |
collect_early_args(&["log", "-R", "repo", "", "--traceback", "a"]), |
| 422 |
os_string_vec_from(&[b"-R", b"repo", b"--traceback"]) |
| 423 |
); |
| 424 |
assert_eq!( |
| 425 |
collect_early_args(&["log", "--config", "diff.git=1", "-q"]), |
| 426 |
os_string_vec_from(&[b"--config", b"diff.git=1"]) |
| 427 |
); |
| 428 |
assert_eq!( |
| 429 |
collect_early_args(&["--cwd=..", "--repository", "r", "log"]), |
| 430 |
os_string_vec_from(&[b"--cwd=..", b"--repository", b"r"]) |
| 431 |
); |
| 432 |
assert_eq!( |
| 433 |
collect_early_args(&["log", "--repo=r", "--repos", "a"]), |
| 434 |
os_string_vec_from(&[b"--repo=r"]) |
| 435 |
); |
| 436 |
} |
| 437 |
|
| 438 |
#[test] |
| 439 |
fn collect_early_args_orphaned() { |
| 440 |
assert!(collect_early_args(&["log", "-R"]).is_empty()); |
| 441 |
assert!(collect_early_args(&["log", "--config"]).is_empty()); |
| 442 |
} |
| 443 |
|
| 444 |
#[test] |
| 445 |
fn collect_early_args_unwanted_value() { |
| 446 |
assert!(collect_early_args(&["log", "--traceback="]).is_empty()); |
| 447 |
} |
| 448 |
|
| 449 |
fn os_string_vec_from(v: &[&[u8]]) -> Vec<OsString> { |
| 450 |
v.iter().map(|s| OsStr::from_bytes(s).to_owned()).collect() |
| 451 |
} |
| 452 |
} |