| 1 |
// Copyright 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 parsing and building command-server messages. |
| 7 |
|
| 8 |
use std::error; |
| 9 |
use std::ffi::OsStr; |
| 10 |
use std::ffi::OsString; |
| 11 |
use std::io; |
| 12 |
use std::os::unix::ffi::OsStrExt; |
| 13 |
use std::path::PathBuf; |
| 14 |
|
| 15 |
use bytes::BufMut; |
| 16 |
use bytes::Bytes; |
| 17 |
use bytes::BytesMut; |
| 18 |
pub use tokio_hglib::message::*; // re-exports |
| 19 |
|
| 20 |
/// Shell command type requested by the server. |
| 21 |
#[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 22 |
pub enum CommandType { |
| 23 |
/// Pager should be spawned. |
| 24 |
Pager, |
| 25 |
/// Shell command should be executed to send back the result code. |
| 26 |
System, |
| 27 |
} |
| 28 |
|
| 29 |
/// Shell command requested by the server. |
| 30 |
#[derive(Clone, Debug, Eq, PartialEq)] |
| 31 |
pub struct CommandSpec { |
| 32 |
pub command: OsString, |
| 33 |
pub current_dir: OsString, |
| 34 |
pub envs: Vec<(OsString, OsString)>, |
| 35 |
} |
| 36 |
|
| 37 |
/// Parses "S" channel request into command type and spec. |
| 38 |
pub fn parse_command_spec( |
| 39 |
data: Bytes, |
| 40 |
) -> io::Result<(CommandType, CommandSpec)> { |
| 41 |
let mut split = data.split(|&c| c == b'\0'); |
| 42 |
let ctype = parse_command_type( |
| 43 |
split.next().ok_or(new_parse_error("missing type"))?, |
| 44 |
)?; |
| 45 |
let command = split.next().ok_or(new_parse_error("missing command"))?; |
| 46 |
let current_dir = |
| 47 |
split.next().ok_or(new_parse_error("missing current dir"))?; |
| 48 |
|
| 49 |
let mut envs = Vec::new(); |
| 50 |
for l in split { |
| 51 |
let mut s = l.splitn(2, |&c| c == b'='); |
| 52 |
let k = s.next().unwrap(); |
| 53 |
let v = s.next().ok_or(new_parse_error("malformed env"))?; |
| 54 |
envs.push(( |
| 55 |
OsStr::from_bytes(k).to_owned(), |
| 56 |
OsStr::from_bytes(v).to_owned(), |
| 57 |
)); |
| 58 |
} |
| 59 |
|
| 60 |
let spec = CommandSpec { |
| 61 |
command: OsStr::from_bytes(command).to_owned(), |
| 62 |
current_dir: OsStr::from_bytes(current_dir).to_owned(), |
| 63 |
envs: envs, |
| 64 |
}; |
| 65 |
Ok((ctype, spec)) |
| 66 |
} |
| 67 |
|
| 68 |
fn parse_command_type(value: &[u8]) -> io::Result<CommandType> { |
| 69 |
match value { |
| 70 |
b"pager" => Ok(CommandType::Pager), |
| 71 |
b"system" => Ok(CommandType::System), |
| 72 |
_ => Err(new_parse_error(format!( |
| 73 |
"unknown command type: {}", |
| 74 |
decode_latin1(value) |
| 75 |
))), |
| 76 |
} |
| 77 |
} |
| 78 |
|
| 79 |
/// Client-side instruction requested by the server. |
| 80 |
#[derive(Clone, Debug, Eq, PartialEq)] |
| 81 |
pub enum Instruction { |
| 82 |
Exit(i32), |
| 83 |
Reconnect, |
| 84 |
Redirect(PathBuf), |
| 85 |
Unlink(PathBuf), |
| 86 |
} |
| 87 |
|
| 88 |
/// Parses validation result into instructions. |
| 89 |
pub fn parse_instructions(data: Bytes) -> io::Result<Vec<Instruction>> { |
| 90 |
let mut instructions = Vec::new(); |
| 91 |
for l in data.split(|&c| c == b'\0') { |
| 92 |
if l.is_empty() { |
| 93 |
continue; |
| 94 |
} |
| 95 |
let mut s = l.splitn(2, |&c| c == b' '); |
| 96 |
let inst = match (s.next().unwrap(), s.next()) { |
| 97 |
(b"exit", Some(arg)) => decode_latin1(arg) |
| 98 |
.parse() |
| 99 |
.map(Instruction::Exit) |
| 100 |
.map_err(|_| { |
| 101 |
new_parse_error(format!("invalid exit code: {:?}", arg)) |
| 102 |
})?, |
| 103 |
(b"reconnect", None) => Instruction::Reconnect, |
| 104 |
(b"redirect", Some(arg)) => { |
| 105 |
Instruction::Redirect(OsStr::from_bytes(arg).to_owned().into()) |
| 106 |
} |
| 107 |
(b"unlink", Some(arg)) => { |
| 108 |
Instruction::Unlink(OsStr::from_bytes(arg).to_owned().into()) |
| 109 |
} |
| 110 |
_ => { |
| 111 |
return Err(new_parse_error(format!( |
| 112 |
"unknown command: {:?}", |
| 113 |
l |
| 114 |
))); |
| 115 |
} |
| 116 |
}; |
| 117 |
instructions.push(inst); |
| 118 |
} |
| 119 |
Ok(instructions) |
| 120 |
} |
| 121 |
|
| 122 |
// allocate large buffer as environment variables can be quite long |
| 123 |
const INITIAL_PACKED_ENV_VARS_CAPACITY: usize = 4096; |
| 124 |
|
| 125 |
/// Packs environment variables of platform encoding into bytes. |
| 126 |
/// |
| 127 |
/// # Panics |
| 128 |
/// |
| 129 |
/// Panics if key or value contains `\0` character, or key contains '=' |
| 130 |
/// character. |
| 131 |
pub fn pack_env_vars_os( |
| 132 |
vars: impl IntoIterator<Item = (impl AsRef<OsStr>, impl AsRef<OsStr>)>, |
| 133 |
) -> Bytes { |
| 134 |
let mut vars_iter = vars.into_iter(); |
| 135 |
if let Some((k, v)) = vars_iter.next() { |
| 136 |
let mut dst = BytesMut::with_capacity(INITIAL_PACKED_ENV_VARS_CAPACITY); |
| 137 |
pack_env_into(&mut dst, k.as_ref(), v.as_ref()); |
| 138 |
for (k, v) in vars_iter { |
| 139 |
dst.reserve(1); |
| 140 |
dst.put_u8(b'\0'); |
| 141 |
pack_env_into(&mut dst, k.as_ref(), v.as_ref()); |
| 142 |
} |
| 143 |
dst.freeze() |
| 144 |
} else { |
| 145 |
Bytes::new() |
| 146 |
} |
| 147 |
} |
| 148 |
|
| 149 |
fn pack_env_into(dst: &mut BytesMut, k: &OsStr, v: &OsStr) { |
| 150 |
assert!(!k.as_bytes().contains(&0), "key shouldn't contain NUL"); |
| 151 |
assert!(!k.as_bytes().contains(&b'='), "key shouldn't contain '='"); |
| 152 |
assert!(!v.as_bytes().contains(&0), "value shouldn't contain NUL"); |
| 153 |
dst.reserve(k.as_bytes().len() + 1 + v.as_bytes().len()); |
| 154 |
dst.put_slice(k.as_bytes()); |
| 155 |
dst.put_u8(b'='); |
| 156 |
dst.put_slice(v.as_bytes()); |
| 157 |
} |
| 158 |
|
| 159 |
fn decode_latin1(s: impl AsRef<[u8]>) -> String { |
| 160 |
s.as_ref().iter().map(|&c| c as char).collect() |
| 161 |
} |
| 162 |
|
| 163 |
fn new_parse_error( |
| 164 |
error: impl Into<Box<dyn error::Error + Send + Sync>>, |
| 165 |
) -> io::Error { |
| 166 |
io::Error::new(io::ErrorKind::InvalidData, error) |
| 167 |
} |
| 168 |
|
| 169 |
#[cfg(test)] |
| 170 |
mod tests { |
| 171 |
use std::os::unix::ffi::OsStringExt; |
| 172 |
use std::panic; |
| 173 |
|
| 174 |
use super::*; |
| 175 |
|
| 176 |
#[test] |
| 177 |
fn parse_command_spec_good() { |
| 178 |
let src = [ |
| 179 |
b"pager".as_ref(), |
| 180 |
b"less -FRX".as_ref(), |
| 181 |
b"/tmp".as_ref(), |
| 182 |
b"LANG=C".as_ref(), |
| 183 |
b"HGPLAIN=".as_ref(), |
| 184 |
] |
| 185 |
.join(&0); |
| 186 |
let spec = CommandSpec { |
| 187 |
command: os_string_from(b"less -FRX"), |
| 188 |
current_dir: os_string_from(b"/tmp"), |
| 189 |
envs: vec![ |
| 190 |
(os_string_from(b"LANG"), os_string_from(b"C")), |
| 191 |
(os_string_from(b"HGPLAIN"), os_string_from(b"")), |
| 192 |
], |
| 193 |
}; |
| 194 |
assert_eq!( |
| 195 |
parse_command_spec(Bytes::from(src)).unwrap(), |
| 196 |
(CommandType::Pager, spec) |
| 197 |
); |
| 198 |
} |
| 199 |
|
| 200 |
#[test] |
| 201 |
fn parse_command_spec_too_short() { |
| 202 |
assert!(parse_command_spec(Bytes::from_static(b"")).is_err()); |
| 203 |
assert!(parse_command_spec(Bytes::from_static(b"pager")).is_err()); |
| 204 |
assert!(parse_command_spec(Bytes::from_static(b"pager\0less")).is_err()); |
| 205 |
} |
| 206 |
|
| 207 |
#[test] |
| 208 |
fn parse_command_spec_malformed_env() { |
| 209 |
assert!(parse_command_spec(Bytes::from_static( |
| 210 |
b"pager\0less\0/tmp\0HOME" |
| 211 |
)) |
| 212 |
.is_err()); |
| 213 |
} |
| 214 |
|
| 215 |
#[test] |
| 216 |
fn parse_command_spec_unknown_type() { |
| 217 |
assert!(parse_command_spec(Bytes::from_static(b"paper\0less")).is_err()); |
| 218 |
} |
| 219 |
|
| 220 |
#[test] |
| 221 |
fn parse_instructions_good() { |
| 222 |
let src = [ |
| 223 |
b"exit 123".as_ref(), |
| 224 |
b"reconnect".as_ref(), |
| 225 |
b"redirect /whatever".as_ref(), |
| 226 |
b"unlink /someother".as_ref(), |
| 227 |
] |
| 228 |
.join(&0); |
| 229 |
let insts = vec![ |
| 230 |
Instruction::Exit(123), |
| 231 |
Instruction::Reconnect, |
| 232 |
Instruction::Redirect(path_buf_from(b"/whatever")), |
| 233 |
Instruction::Unlink(path_buf_from(b"/someother")), |
| 234 |
]; |
| 235 |
assert_eq!(parse_instructions(Bytes::from(src)).unwrap(), insts); |
| 236 |
} |
| 237 |
|
| 238 |
#[test] |
| 239 |
fn parse_instructions_empty() { |
| 240 |
assert_eq!(parse_instructions(Bytes::new()).unwrap(), vec![]); |
| 241 |
assert_eq!( |
| 242 |
parse_instructions(Bytes::from_static(b"\0")).unwrap(), |
| 243 |
vec![] |
| 244 |
); |
| 245 |
} |
| 246 |
|
| 247 |
#[test] |
| 248 |
fn parse_instructions_malformed_exit_code() { |
| 249 |
assert!(parse_instructions(Bytes::from_static(b"exit foo")).is_err()); |
| 250 |
} |
| 251 |
|
| 252 |
#[test] |
| 253 |
fn parse_instructions_missing_argument() { |
| 254 |
assert!(parse_instructions(Bytes::from_static(b"exit")).is_err()); |
| 255 |
assert!(parse_instructions(Bytes::from_static(b"redirect")).is_err()); |
| 256 |
assert!(parse_instructions(Bytes::from_static(b"unlink")).is_err()); |
| 257 |
} |
| 258 |
|
| 259 |
#[test] |
| 260 |
fn parse_instructions_unknown_command() { |
| 261 |
assert!(parse_instructions(Bytes::from_static(b"quit 0")).is_err()); |
| 262 |
} |
| 263 |
|
| 264 |
#[test] |
| 265 |
fn pack_env_vars_os_good() { |
| 266 |
assert_eq!( |
| 267 |
pack_env_vars_os(vec![] as Vec<(OsString, OsString)>), |
| 268 |
Bytes::new() |
| 269 |
); |
| 270 |
assert_eq!( |
| 271 |
pack_env_vars_os(vec![os_string_pair_from(b"FOO", b"bar")]), |
| 272 |
Bytes::from_static(b"FOO=bar") |
| 273 |
); |
| 274 |
assert_eq!( |
| 275 |
pack_env_vars_os(vec![ |
| 276 |
os_string_pair_from(b"FOO", b""), |
| 277 |
os_string_pair_from(b"BAR", b"baz") |
| 278 |
]), |
| 279 |
Bytes::from_static(b"FOO=\0BAR=baz") |
| 280 |
); |
| 281 |
} |
| 282 |
|
| 283 |
#[test] |
| 284 |
fn pack_env_vars_os_large_key() { |
| 285 |
let mut buf = vec![b'A'; INITIAL_PACKED_ENV_VARS_CAPACITY]; |
| 286 |
let envs = vec![os_string_pair_from(&buf, b"")]; |
| 287 |
buf.push(b'='); |
| 288 |
assert_eq!(pack_env_vars_os(envs), Bytes::from(buf)); |
| 289 |
} |
| 290 |
|
| 291 |
#[test] |
| 292 |
fn pack_env_vars_os_large_value() { |
| 293 |
let mut buf = vec![b'A', b'=']; |
| 294 |
buf.resize(INITIAL_PACKED_ENV_VARS_CAPACITY + 1, b'a'); |
| 295 |
let envs = vec![os_string_pair_from(&buf[..1], &buf[2..])]; |
| 296 |
assert_eq!(pack_env_vars_os(envs), Bytes::from(buf)); |
| 297 |
} |
| 298 |
|
| 299 |
#[test] |
| 300 |
fn pack_env_vars_os_nul_eq() { |
| 301 |
assert!(panic::catch_unwind(|| { |
| 302 |
pack_env_vars_os(vec![os_string_pair_from(b"\0", b"")]) |
| 303 |
}) |
| 304 |
.is_err()); |
| 305 |
assert!(panic::catch_unwind(|| { |
| 306 |
pack_env_vars_os(vec![os_string_pair_from(b"FOO", b"\0bar")]) |
| 307 |
}) |
| 308 |
.is_err()); |
| 309 |
assert!(panic::catch_unwind(|| { |
| 310 |
pack_env_vars_os(vec![os_string_pair_from(b"FO=", b"bar")]) |
| 311 |
}) |
| 312 |
.is_err()); |
| 313 |
assert_eq!( |
| 314 |
pack_env_vars_os(vec![os_string_pair_from(b"FOO", b"=ba")]), |
| 315 |
Bytes::from_static(b"FOO==ba") |
| 316 |
); |
| 317 |
} |
| 318 |
|
| 319 |
fn os_string_from(s: &[u8]) -> OsString { |
| 320 |
OsString::from_vec(s.to_vec()) |
| 321 |
} |
| 322 |
|
| 323 |
fn os_string_pair_from(k: &[u8], v: &[u8]) -> (OsString, OsString) { |
| 324 |
(os_string_from(k), os_string_from(v)) |
| 325 |
} |
| 326 |
|
| 327 |
fn path_buf_from(s: &[u8]) -> PathBuf { |
| 328 |
os_string_from(s).into() |
| 329 |
} |
| 330 |
} |