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