Show More
@@ -1,241 +1,266 b'' | |||
|
1 | 1 | // Copyright 2011, 2018 Yuya Nishihara <yuya@tcha.org> |
|
2 | 2 | // |
|
3 | 3 | // This software may be used and distributed according to the terms of the |
|
4 | 4 | // GNU General Public License version 2 or any later version. |
|
5 | 5 | |
|
6 | 6 | //! Utility for locating command-server process. |
|
7 | 7 | |
|
8 | 8 | use futures::future::{self, Either, Loop}; |
|
9 | 9 | use std::env; |
|
10 | 10 | use std::ffi::{OsStr, OsString}; |
|
11 | 11 | use std::fs::{self, DirBuilder}; |
|
12 | 12 | use std::io; |
|
13 | 13 | use std::os::unix::ffi::{OsStrExt, OsStringExt}; |
|
14 | 14 | use std::os::unix::fs::{DirBuilderExt, MetadataExt}; |
|
15 | 15 | use std::path::{Path, PathBuf}; |
|
16 | 16 | use std::process::{self, Command}; |
|
17 | 17 | use std::time::Duration; |
|
18 | 18 | use tokio::prelude::*; |
|
19 | 19 | use tokio_hglib::UnixClient; |
|
20 | 20 | use tokio_process::{Child, CommandExt}; |
|
21 | 21 | use tokio_timer; |
|
22 | 22 | |
|
23 | use super::message::ServerSpec; | |
|
23 | 24 | use super::procutil; |
|
24 | 25 | |
|
26 | const REQUIRED_SERVER_CAPABILITIES: &[&str] = &["attachio", "chdir", "runcommand"]; | |
|
27 | ||
|
25 | 28 | /// Helper to connect to and spawn a server process. |
|
26 | 29 | #[derive(Clone, Debug)] |
|
27 | 30 | pub struct Locator { |
|
28 | 31 | hg_command: OsString, |
|
29 | 32 | current_dir: PathBuf, |
|
30 | 33 | env_vars: Vec<(OsString, OsString)>, |
|
31 | 34 | process_id: u32, |
|
32 | 35 | base_sock_path: PathBuf, |
|
33 | 36 | timeout: Duration, |
|
34 | 37 | } |
|
35 | 38 | |
|
36 | 39 | impl Locator { |
|
37 | 40 | /// Creates locator capturing the current process environment. |
|
38 | 41 | /// |
|
39 | 42 | /// If no `$CHGSOCKNAME` is specified, the socket directory will be |
|
40 | 43 | /// created as necessary. |
|
41 | 44 | pub fn prepare_from_env() -> io::Result<Locator> { |
|
42 | 45 | Ok(Locator { |
|
43 | 46 | hg_command: default_hg_command(), |
|
44 | 47 | current_dir: env::current_dir()?, |
|
45 | 48 | env_vars: env::vars_os().collect(), |
|
46 | 49 | process_id: process::id(), |
|
47 | 50 | base_sock_path: prepare_server_socket_path()?, |
|
48 | 51 | timeout: default_timeout(), |
|
49 | 52 | }) |
|
50 | 53 | } |
|
51 | 54 | |
|
52 | 55 | /// Temporary socket path for this client process. |
|
53 | 56 | fn temp_sock_path(&self) -> PathBuf { |
|
54 | 57 | let src = self.base_sock_path.as_os_str().as_bytes(); |
|
55 | 58 | let mut buf = Vec::with_capacity(src.len() + 6); // "{src}.{pid}".len() |
|
56 | 59 | buf.extend_from_slice(src); |
|
57 | 60 | buf.extend_from_slice(format!(".{}", self.process_id).as_bytes()); |
|
58 | 61 | OsString::from_vec(buf).into() |
|
59 | 62 | } |
|
60 | 63 | |
|
61 | 64 | /// Connects to the server. |
|
62 | 65 | /// |
|
63 | 66 | /// The server process will be spawned if not running. |
|
64 | 67 | pub fn connect(self) -> impl Future<Item = (Self, UnixClient), Error = io::Error> { |
|
65 | 68 | self.try_connect() |
|
66 | 69 | } |
|
67 | 70 | |
|
68 | 71 | /// Tries to connect to the existing server, or spawns new if not running. |
|
69 | 72 | fn try_connect(self) -> impl Future<Item = (Self, UnixClient), Error = io::Error> { |
|
70 | 73 | debug!("try connect to {}", self.base_sock_path.display()); |
|
71 |
UnixClient::connect(self.base_sock_path.clone()) |
|
|
74 | UnixClient::connect(self.base_sock_path.clone()) | |
|
75 | .then(|res| match res { | |
|
72 | 76 | Ok(client) => Either::A(future::ok((self, client))), |
|
73 | 77 | Err(_) => Either::B(self.spawn_connect()), |
|
74 | 78 | }) |
|
79 | .and_then(|(loc, client)| { | |
|
80 | check_server_capabilities(client.server_spec())?; | |
|
81 | Ok((loc, client)) | |
|
82 | }) | |
|
75 | 83 | } |
|
76 | 84 | |
|
77 | 85 | /// Spawns new server process and connects to it. |
|
78 | 86 | /// |
|
79 | 87 | /// The server will be spawned at the current working directory, then |
|
80 | 88 | /// chdir to "/", so that the server will load configs from the target |
|
81 | 89 | /// repository. |
|
82 | 90 | fn spawn_connect(self) -> impl Future<Item = (Self, UnixClient), Error = io::Error> { |
|
83 | 91 | let sock_path = self.temp_sock_path(); |
|
84 | 92 | debug!("start cmdserver at {}", sock_path.display()); |
|
85 | 93 | Command::new(&self.hg_command) |
|
86 | 94 | .arg("serve") |
|
87 | 95 | .arg("--cmdserver") |
|
88 | 96 | .arg("chgunix") |
|
89 | 97 | .arg("--address") |
|
90 | 98 | .arg(&sock_path) |
|
91 | 99 | .arg("--daemon-postexec") |
|
92 | 100 | .arg("chdir:/") |
|
93 | 101 | .current_dir(&self.current_dir) |
|
94 | 102 | .env_clear() |
|
95 | 103 | .envs(self.env_vars.iter().cloned()) |
|
96 | 104 | .env("CHGINTERNALMARK", "") |
|
97 | 105 | .spawn_async() |
|
98 | 106 | .into_future() |
|
99 | 107 | .and_then(|server| self.connect_spawned(server, sock_path)) |
|
100 | 108 | .and_then(|(loc, client, sock_path)| { |
|
101 | 109 | debug!( |
|
102 | 110 | "rename {} to {}", |
|
103 | 111 | sock_path.display(), |
|
104 | 112 | loc.base_sock_path.display() |
|
105 | 113 | ); |
|
106 | 114 | fs::rename(&sock_path, &loc.base_sock_path)?; |
|
107 | 115 | Ok((loc, client)) |
|
108 | 116 | }) |
|
109 | 117 | } |
|
110 | 118 | |
|
111 | 119 | /// Tries to connect to the just spawned server repeatedly until timeout |
|
112 | 120 | /// exceeded. |
|
113 | 121 | fn connect_spawned( |
|
114 | 122 | self, |
|
115 | 123 | server: Child, |
|
116 | 124 | sock_path: PathBuf, |
|
117 | 125 | ) -> impl Future<Item = (Self, UnixClient, PathBuf), Error = io::Error> { |
|
118 | 126 | debug!("try connect to {} repeatedly", sock_path.display()); |
|
119 | 127 | let connect = future::loop_fn(sock_path, |sock_path| { |
|
120 | 128 | UnixClient::connect(sock_path.clone()).then(|res| { |
|
121 | 129 | match res { |
|
122 | 130 | Ok(client) => Either::A(future::ok(Loop::Break((client, sock_path)))), |
|
123 | 131 | Err(_) => { |
|
124 | 132 | // try again with slight delay |
|
125 | 133 | let fut = tokio_timer::sleep(Duration::from_millis(10)) |
|
126 | 134 | .map(|()| Loop::Continue(sock_path)) |
|
127 | 135 | .map_err(|err| io::Error::new(io::ErrorKind::Other, err)); |
|
128 | 136 | Either::B(fut) |
|
129 | 137 | } |
|
130 | 138 | } |
|
131 | 139 | }) |
|
132 | 140 | }); |
|
133 | 141 | |
|
134 | 142 | // waits for either connection established or server failed to start |
|
135 | 143 | connect |
|
136 | 144 | .select2(server) |
|
137 | 145 | .map_err(|res| res.split().0) |
|
138 | 146 | .timeout(self.timeout) |
|
139 | 147 | .map_err(|err| { |
|
140 | 148 | err.into_inner().unwrap_or_else(|| { |
|
141 | 149 | io::Error::new( |
|
142 | 150 | io::ErrorKind::TimedOut, |
|
143 | 151 | "timed out while connecting to server", |
|
144 | 152 | ) |
|
145 | 153 | }) |
|
146 | 154 | }) |
|
147 | 155 | .and_then(|res| { |
|
148 | 156 | match res { |
|
149 | 157 | Either::A(((client, sock_path), server)) => { |
|
150 | 158 | server.forget(); // continue to run in background |
|
151 | 159 | Ok((self, client, sock_path)) |
|
152 | 160 | } |
|
153 | 161 | Either::B((st, _)) => Err(io::Error::new( |
|
154 | 162 | io::ErrorKind::Other, |
|
155 | 163 | format!("server exited too early: {}", st), |
|
156 | 164 | )), |
|
157 | 165 | } |
|
158 | 166 | }) |
|
159 | 167 | } |
|
160 | 168 | } |
|
161 | 169 | |
|
162 | 170 | /// Determines the server socket to connect to. |
|
163 | 171 | /// |
|
164 | 172 | /// If no `$CHGSOCKNAME` is specified, the socket directory will be created |
|
165 | 173 | /// as necessary. |
|
166 | 174 | fn prepare_server_socket_path() -> io::Result<PathBuf> { |
|
167 | 175 | if let Some(s) = env::var_os("CHGSOCKNAME") { |
|
168 | 176 | Ok(PathBuf::from(s)) |
|
169 | 177 | } else { |
|
170 | 178 | let mut path = default_server_socket_dir(); |
|
171 | 179 | create_secure_dir(&path)?; |
|
172 | 180 | path.push("server"); |
|
173 | 181 | Ok(path) |
|
174 | 182 | } |
|
175 | 183 | } |
|
176 | 184 | |
|
177 | 185 | /// Determines the default server socket path as follows. |
|
178 | 186 | /// |
|
179 | 187 | /// 1. `$XDG_RUNTIME_DIR/chg` |
|
180 | 188 | /// 2. `$TMPDIR/chg$UID` |
|
181 | 189 | /// 3. `/tmp/chg$UID` |
|
182 | 190 | pub fn default_server_socket_dir() -> PathBuf { |
|
183 | 191 | // XDG_RUNTIME_DIR should be ignored if it has an insufficient permission. |
|
184 | 192 | // https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html |
|
185 | 193 | if let Some(Ok(s)) = env::var_os("XDG_RUNTIME_DIR").map(check_secure_dir) { |
|
186 | 194 | let mut path = PathBuf::from(s); |
|
187 | 195 | path.push("chg"); |
|
188 | 196 | path |
|
189 | 197 | } else { |
|
190 | 198 | let mut path = env::temp_dir(); |
|
191 | 199 | path.push(format!("chg{}", procutil::get_effective_uid())); |
|
192 | 200 | path |
|
193 | 201 | } |
|
194 | 202 | } |
|
195 | 203 | |
|
196 | 204 | /// Determines the default hg command. |
|
197 | 205 | pub fn default_hg_command() -> OsString { |
|
198 | 206 | // TODO: maybe allow embedding the path at compile time (or load from hgrc) |
|
199 | 207 | env::var_os("CHGHG") |
|
200 | 208 | .or(env::var_os("HG")) |
|
201 | 209 | .unwrap_or(OsStr::new("hg").to_owned()) |
|
202 | 210 | } |
|
203 | 211 | |
|
204 | 212 | fn default_timeout() -> Duration { |
|
205 | 213 | let secs = env::var("CHGTIMEOUT") |
|
206 | 214 | .ok() |
|
207 | 215 | .and_then(|s| s.parse().ok()) |
|
208 | 216 | .unwrap_or(60); |
|
209 | 217 | Duration::from_secs(secs) |
|
210 | 218 | } |
|
211 | 219 | |
|
212 | 220 | /// Creates a directory which the other users cannot access to. |
|
213 | 221 | /// |
|
214 | 222 | /// If the directory already exists, tests its permission. |
|
215 | 223 | fn create_secure_dir<P>(path: P) -> io::Result<()> |
|
216 | 224 | where |
|
217 | 225 | P: AsRef<Path>, |
|
218 | 226 | { |
|
219 | 227 | DirBuilder::new() |
|
220 | 228 | .mode(0o700) |
|
221 | 229 | .create(path.as_ref()) |
|
222 | 230 | .or_else(|err| { |
|
223 | 231 | if err.kind() == io::ErrorKind::AlreadyExists { |
|
224 | 232 | check_secure_dir(path).map(|_| ()) |
|
225 | 233 | } else { |
|
226 | 234 | Err(err) |
|
227 | 235 | } |
|
228 | 236 | }) |
|
229 | 237 | } |
|
230 | 238 | |
|
231 | 239 | fn check_secure_dir<P>(path: P) -> io::Result<P> |
|
232 | 240 | where |
|
233 | 241 | P: AsRef<Path>, |
|
234 | 242 | { |
|
235 | 243 | let a = fs::symlink_metadata(path.as_ref())?; |
|
236 | 244 | if a.is_dir() && a.uid() == procutil::get_effective_uid() && (a.mode() & 0o777) == 0o700 { |
|
237 | 245 | Ok(path) |
|
238 | 246 | } else { |
|
239 | 247 | Err(io::Error::new(io::ErrorKind::Other, "insecure directory")) |
|
240 | 248 | } |
|
241 | 249 | } |
|
250 | ||
|
251 | fn check_server_capabilities(spec: &ServerSpec) -> io::Result<()> { | |
|
252 | let unsupported: Vec<_> = REQUIRED_SERVER_CAPABILITIES | |
|
253 | .iter() | |
|
254 | .cloned() | |
|
255 | .filter(|&s| !spec.capabilities.contains(s)) | |
|
256 | .collect(); | |
|
257 | if unsupported.is_empty() { | |
|
258 | Ok(()) | |
|
259 | } else { | |
|
260 | let msg = format!( | |
|
261 | "insufficient server capabilities: {}", | |
|
262 | unsupported.join(", ") | |
|
263 | ); | |
|
264 | Err(io::Error::new(io::ErrorKind::Other, msg)) | |
|
265 | } | |
|
266 | } |
General Comments 0
You need to be logged in to leave comments.
Login now