| 1 | // Copyright (C) 2020 Francois Marier |
| 2 | // |
| 3 | // This program is free software: you can redistribute it and/or modify |
| 4 | // it under the terms of the GNU General Public License as published by |
| 5 | // the Free Software Foundation, either version 3 of the License, or |
| 6 | // (at your option) any later version. |
| 7 | // |
| 8 | // This program is distributed in the hope that it will be useful, |
| 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 11 | // GNU General Public License for more details. |
| 12 | // |
| 13 | // You should have received a copy of the GNU General Public License |
| 14 | // along with this program. If not, see <https://www.gnu.org/licenses/>. |
| 15 | |
| 16 | #![forbid(unsafe_code)] |
| 17 | |
| 18 | mod main_test; |
| 19 | |
| 20 | use glob::glob; |
| 21 | use std::ffi::{OsStr, OsString}; |
| 22 | use std::fs::{self, File}; |
| 23 | use std::io::{self, BufRead}; |
| 24 | use std::path::{self, Path, PathBuf}; |
| 25 | use std::process; |
| 26 | |
| 27 | const GLOBAL_CONFIG: &str = "/etc/safe-rm.conf"; |
| 28 | const LOCAL_GLOBAL_CONFIG: &str = "/usr/local/etc/safe-rm.conf"; |
| 29 | const USER_CONFIG: &str = ".config/safe-rm"; |
| 30 | const LEGACY_USER_CONFIG: &str = ".safe-rm"; |
| 31 | |
| 32 | const REAL_RM: &str = "/bin/rm"; |
| 33 | |
| 34 | const DEFAULT_PATHS: &[&str] = &[ |
| 35 | "/bin", |
| 36 | "/boot", |
| 37 | "/dev", |
| 38 | "/etc", |
| 39 | "/home", |
| 40 | "/initrd", |
| 41 | "/lib", |
| 42 | "/lib32", |
| 43 | "/lib64", |
| 44 | "/proc", |
| 45 | "/root", |
| 46 | "/sbin", |
| 47 | "/sys", |
| 48 | "/usr", |
| 49 | "/usr/bin", |
| 50 | "/usr/include", |
| 51 | "/usr/lib", |
| 52 | "/usr/local", |
| 53 | "/usr/local/bin", |
| 54 | "/usr/local/include", |
| 55 | "/usr/local/sbin", |
| 56 | "/usr/local/share", |
| 57 | "/usr/sbin", |
| 58 | "/usr/share", |
| 59 | "/usr/src", |
| 60 | "/var", |
| 61 | ]; |
| 62 | |
| 63 | const MAX_GLOB_EXPANSION: usize = 256; |
| 64 | |
| 65 | fn read_config<P: AsRef<Path>>(filename: P) -> Option<Vec<PathBuf>> { |
| 66 | let mut paths = Vec::new(); |
| 67 | if !filename.as_ref().exists() { |
| 68 | // Not all config files are expected to be present. |
| 69 | // If they're missing, we silently skip them. |
| 70 | return Some(paths); |
| 71 | } |
| 72 | let f = File::open(&filename).ok().or_else(|| { |
| 73 | println!( |
| 74 | "safe-rm: Could not open configuration file: {}", |
| 75 | filename.as_ref().display() |
| 76 | ); |
| 77 | None |
| 78 | })?; |
| 79 | |
| 80 | let reader = io::BufReader::new(f); |
| 81 | for line_result in reader.lines() { |
| 82 | if let Some(line_paths) = parse_line(filename.as_ref().display(), line_result) { |
| 83 | paths.extend(line_paths.into_iter()); |
| 84 | } |
| 85 | } |
| 86 | Some(paths) |
| 87 | } |
| 88 | |
| 89 | fn parse_line(filename: path::Display, line_result: io::Result<String>) -> Option<Vec<PathBuf>> { |
| 90 | let line = line_result.ok().or_else(|| { |
| 91 | println!("safe-rm: Ignoring unreadable line in {}.", filename); |
| 92 | None |
| 93 | })?; |
| 94 | let entries = glob(&line).ok().or_else(|| { |
| 95 | println!( |
| 96 | "safe-rm: Invalid glob pattern \"{}\" found in {} and ignored.", |
| 97 | line, filename |
| 98 | ); |
| 99 | None |
| 100 | })?; |
| 101 | |
| 102 | let mut paths = Vec::new(); |
| 103 | |
| 104 | for entry in entries { |
| 105 | match entry { |
| 106 | Ok(path) => { |
| 107 | if paths.len() >= MAX_GLOB_EXPANSION { |
| 108 | println!( |
| 109 | "safe-rm: Glob \"{}\" found in {} expands to more than {} paths. Ignoring the rest.", |
| 110 | line, filename, MAX_GLOB_EXPANSION |
| 111 | ); |
| 112 | return Some(paths); |
| 113 | } |
| 114 | paths.push(path); |
| 115 | } |
| 116 | Err(_) => println!( |
| 117 | "safe-rm: Ignored unreadable path while expanding glob \"{}\" from {}.", |
| 118 | line, filename |
| 119 | ), |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | Some(paths) |
| 124 | } |
| 125 | |
| 126 | fn symlink_canonicalize(path: &Path) -> Option<PathBuf> { |
| 127 | // Relative paths need to be prefixed by "./" to have a parent dir. |
| 128 | let mut explicit_path = path.to_path_buf(); |
| 129 | if explicit_path.is_relative() { |
| 130 | explicit_path = Path::new(".").join(path); |
| 131 | } |
| 132 | |
| 133 | // Convert from relative to absolute path but don't follow the symlink. |
| 134 | // We do this by: |
| 135 | // 1. splitting directory and base file name |
| 136 | // 2. canonicalizing the directory |
| 137 | // 3. recombining directory and file name |
| 138 | let parent: Option<PathBuf> = match explicit_path.parent() { |
| 139 | Some(dir) => match dir.canonicalize() { |
| 140 | Ok(normalized_parent) => Some(normalized_parent), |
| 141 | Err(_) => None, |
| 142 | }, |
| 143 | None => Some(PathBuf::from("/")), |
| 144 | }; |
| 145 | return match parent { |
| 146 | Some(dir) => match path.file_name() { |
| 147 | Some(file_name) => Some(dir.join(file_name)), |
| 148 | None => match dir.parent() { |
| 149 | // file_name == ".." |
| 150 | Some(parent_dir) => Some(parent_dir.to_path_buf()), |
| 151 | None => Some(PathBuf::from("/")), // Stop at the root. |
| 152 | }, |
| 153 | }, |
| 154 | None => None, |
| 155 | }; |
| 156 | } |
| 157 | |
| 158 | fn normalize_path(arg: &OsStr) -> OsString { |
| 159 | let path = Path::new(arg); |
| 160 | |
| 161 | // Handle symlinks. |
| 162 | if let Ok(metadata) = path.symlink_metadata() { |
| 163 | if metadata.file_type().is_symlink() { |
| 164 | return match symlink_canonicalize(&path) { |
| 165 | Some(normalized_path) => normalized_path.into_os_string(), |
| 166 | None => OsString::from(arg), |
| 167 | }; |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | // Handle normal files. |
| 172 | match path.canonicalize() { |
| 173 | Ok(normalized_pathname) => normalized_pathname.into_os_string(), |
| 174 | Err(_) => OsString::from(arg), |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | fn filter_arguments( |
| 179 | args: impl Iterator<Item = OsString>, |
| 180 | protected_paths: &[PathBuf], |
| 181 | ) -> Vec<OsString> { |
| 182 | let mut filtered_args = Vec::new(); |
| 183 | for arg in args { |
| 184 | if protected_paths.contains(&PathBuf::from(normalize_path(&arg))) { |
| 185 | println!("safe-rm: Skipping {}.", arg.to_string_lossy()); |
| 186 | } else { |
| 187 | filtered_args.push(arg); |
| 188 | } |
| 189 | } |
| 190 | filtered_args |
| 191 | } |
| 192 | |
| 193 | fn read_config_files(globals: &[&str], locals: &[&str]) -> Vec<PathBuf> { |
| 194 | let mut protected_paths = Vec::new(); |
| 195 | |
| 196 | for config_file in globals { |
| 197 | if let Some(paths) = read_config(config_file) { |
| 198 | protected_paths.extend(paths.into_iter()); |
| 199 | } |
| 200 | } |
| 201 | if let Ok(value) = std::env::var("HOME") { |
| 202 | let home_dir = Path::new(&value); |
| 203 | for config_file in locals { |
| 204 | if let Some(paths) = read_config(&home_dir.join(Path::new(config_file))) { |
| 205 | protected_paths.extend(paths.into_iter()); |
| 206 | } |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | if protected_paths.is_empty() { |
| 211 | for path in DEFAULT_PATHS { |
| 212 | protected_paths.push(PathBuf::from(path)); |
| 213 | } |
| 214 | } |
| 215 | protected_paths.sort(); |
| 216 | protected_paths.dedup(); |
| 217 | |
| 218 | protected_paths |
| 219 | } |
| 220 | |
| 221 | fn run( |
| 222 | rm_binary: &str, |
| 223 | args: impl Iterator<Item = OsString>, |
| 224 | globals: &[&str], |
| 225 | locals: &[&str], |
| 226 | ) -> i32 { |
| 227 | let protected_paths = read_config_files(globals, locals); |
| 228 | let filtered_args = filter_arguments(args, &protected_paths); |
| 229 | |
| 230 | // Run the real rm command, returning with the same error code. |
| 231 | match process::Command::new(rm_binary) |
| 232 | .args(&filtered_args) |
| 233 | .status() |
| 234 | { |
| 235 | Ok(status) => status.code().unwrap_or(1), |
| 236 | Err(_) => { |
| 237 | println!("safe-rm: Failed to run the {} command.", REAL_RM); |
| 238 | 1 |
| 239 | } |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | fn ensure_real_rm_is_callable() -> io::Result<()> { |
| 244 | // Make sure we're not calling ourselves recursively. |
| 245 | if fs::canonicalize(REAL_RM)? == fs::canonicalize(std::env::current_exe()?)? { |
| 246 | println!("safe-rm: Cannot find the real \"rm\" binary."); |
| 247 | process::exit(1); |
| 248 | } |
| 249 | Ok(()) |
| 250 | } |
| 251 | |
| 252 | fn main() { |
| 253 | if let Err(e) = ensure_real_rm_is_callable() { |
| 254 | println!( |
| 255 | "safe-rm: Cannot check that the real \"rm\" binary is callable: {}", |
| 256 | e |
| 257 | ); |
| 258 | } |
| 259 | process::exit(run( |
| 260 | REAL_RM, |
| 261 | std::env::args_os().skip(1), |
| 262 | &[GLOBAL_CONFIG, LOCAL_GLOBAL_CONFIG], |
| 263 | &[USER_CONFIG, LEGACY_USER_CONFIG], |
| 264 | )); |
| 265 | } |