1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
|
use crate::cfg::config::Config;
use std::{
fs::{self, File, create_dir_all},
io,
os::unix::fs::PermissionsExt,
path::Path,
};
use flate2::read::GzDecoder;
use tar::Archive;
use toml;
use super::types::{Build, Install, Package, Setts};
pub trait ArchiveOperations {
fn extract_archive(path_to_archive: &str) -> Result<(), std::io::Error>;
fn check(path_to_archive: String) -> Result<bool, std::io::Error>;
fn loadmeta(
minimal_package_meta: &mut Package,
) -> Result<(Install, Option<Setts>, Option<Build>), std::io::Error>;
fn validate_custom_script(script: &str) -> Result<(), std::io::Error>;
fn validate_path(path: &str, base_dir: &Path) -> Result<std::path::PathBuf, std::io::Error>;
}
impl ArchiveOperations for Package {
/// Extracts a .tar.gz archive to the cache directory specified in Config.
///
/// This function handles opening the archive file, decompressing it with GzDecoder,
/// and unpacking the contents into the configured cache directory.
///
/// # Arguments
/// * `path_to_archive` - A string representing the path to the .tar.gz file.
///
/// # Returns
/// * `Ok(())` if the archive is successfully unpacked.
/// * `Err(std::io::Error)` if there's an issue opening, reading, or unpacking the archive.
fn extract_archive(path_to_archive: &str) -> Result<(), std::io::Error> {
let config = Config::parse().map_err(|e| std::io::Error::other(e.to_string()))?;
let cache_dir = &config.paths.cache_dir;
create_dir_all(cache_dir)?;
// Extract to temporary directory first
let temp_dir = Path::new(cache_dir).join("temp_extract");
if temp_dir.exists() {
fs::remove_dir_all(&temp_dir)?;
}
fs::create_dir_all(&temp_dir)?;
let file = File::open(path_to_archive)?;
let gz = GzDecoder::new(file);
let mut archive = Archive::new(gz);
// Unpack into temporary directory
match archive.unpack(&temp_dir) {
Ok(()) => Ok(()),
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => Ok(()),
Err(e) => Err(e),
}?;
// Read package name from INSTALL file to determine final directory
let install_path = temp_dir.join("INSTALL");
if !install_path.exists() {
// Try to find INSTALL in subdirectories
for entry in fs::read_dir(&temp_dir)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
let install_in_subdir = path.join("INSTALL");
if install_in_subdir.exists() {
// Move contents to temp_dir
for item in fs::read_dir(&path)? {
let item = item?;
let item_path = item.path();
let dest_path = temp_dir.join(item_path.file_name().unwrap());
fs::rename(&item_path, &dest_path)?;
}
fs::remove_dir(&path)?;
break;
}
}
}
}
let mut install_path = None;
let mut pkg_dir_name = None;
let root_install = temp_dir.join("INSTALL");
if root_install.exists() {
install_path = Some(root_install);
pkg_dir_name = Some("package".to_string());
} else {
for entry in fs::read_dir(&temp_dir)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
let install_in_subdir = path.join("INSTALL");
if install_in_subdir.exists() {
install_path = Some(install_in_subdir);
pkg_dir_name =
Some(path.file_name().unwrap().to_string_lossy().to_string());
break;
}
}
}
}
let install_path = install_path.ok_or_else(|| {
io::Error::new(io::ErrorKind::NotFound, "INSTALL file not found in archive")
})?;
let install_content = fs::read_to_string(&install_path)?;
let install_meta: Install = toml::from_str(&install_content)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
let final_dir_name = format!(
"{}-{}",
install_meta.package.name, install_meta.package.version
);
let final_dir = Path::new(cache_dir).join(&final_dir_name);
if final_dir.exists() {
fs::remove_dir_all(&final_dir)?;
}
fs::create_dir_all(&final_dir)?;
if pkg_dir_name.clone().unwrap() == "package" {
for entry in fs::read_dir(&temp_dir)? {
let entry = entry?;
let src_path = entry.path();
let dest_path = final_dir.join(src_path.file_name().unwrap());
fs::rename(&src_path, &dest_path)?;
}
fs::remove_dir(&temp_dir)?;
} else {
let pkg_subdir = temp_dir.join(pkg_dir_name.clone().unwrap());
fs::rename(&pkg_subdir, &final_dir)?;
fs::remove_dir(&temp_dir)?;
}
Ok(())
}
/// Load meta information from the .mesk archive.
///
/// This function parses the meta information from the .mesk archive,
/// which includes the package name, version, architecture, description,
/// installation path, user, group, mode, and custom installation script
/// and deserializing this information. Returns (Install, Option<Setts>, Option<Build>)
///
/// The function expects the 'INSTALL', 'SETTS', and 'BUILD' files to be present
/// in the `config.paths.cache_dir`. It specifically requires the 'INSTALL' file.
///
/// # Errors
///
/// Returns an error if the `cache_dir` cannot be created, if the required 'INSTALL' file
/// is not found, or if the 'INSTALL' file is empty.
#[allow(clippy::type_complexity)]
fn loadmeta(
minimal_package_meta: &mut Package,
) -> Result<(Install, Option<Setts>, Option<Build>), std::io::Error> {
// Changed return type for more flexibility
/*
Example INSTALL format:
[package]
name = "my-package"
version = "1.0.0"
arch = "X86_64"
descr = "Just example INSTALL script"
license = "BSD-2-Clause"
url = "/repo/my-package.mesk"
git_repo = "https://github.com/example/my-package.git"
[install]
path = "/usr/bin/my-package"
dependencies = ["package", "i2pd", "llvm-19-devel", "etc..."] # Leave it empty if there are no dependencies
user = "root"
group = "root"
mode = "755"
Also [install] can be
path = "/usr/bin/my-package"
user = "root"
group = "root"
mode = "755"
custom_script = "./install.sh" OR
custom_script = """
echo "Installing my-package"
sudo apt-get install my-package
"""
If there is a custom_script field, mesk will not automatically install your package and other fields in [install] will not be required.
*/
let config = Config::parse().map_err(|e| std::io::Error::other(e.to_string()))?;
fs::create_dir_all(&config.paths.cache_dir)?;
let cache_dir = &config.paths.cache_dir;
let pkg_dir_name = format!(
"{}-{}",
minimal_package_meta.name, minimal_package_meta.version
);
let install_path = Path::new(cache_dir).join(format!("{}/INSTALL", pkg_dir_name));
let setts_path = Path::new(cache_dir).join(format!("{}/SETTS", pkg_dir_name));
let build_path = Path::new(cache_dir).join(format!("{}/BUILD", pkg_dir_name));
if !install_path.exists() {
return Err(io::Error::new(
io::ErrorKind::NotFound,
"File INSTALL not found in cache directory",
));
}
let install_content = fs::read_to_string(&install_path)?;
let install_meta: Install = toml::from_str(&install_content)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
let mut setts_meta: Option<Setts> = None;
let mut build_meta: Option<Build> = None;
if setts_path.exists() {
let setts_content = fs::read_to_string(&setts_path)?;
setts_meta = Some(
toml::from_str(&setts_content)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?,
);
}
if build_path.exists() {
let build_content = fs::read_to_string(&build_path)?;
build_meta = Some(
toml::from_str(&build_content)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?,
);
}
if let Some(ref _script) = install_meta.install.custom_script {
log::warn!(
"Custom script found for package: {}",
install_meta.package.name
);
} else {
log::info!(
"No custom script for package: {}",
install_meta.package.name
);
}
Ok((install_meta, setts_meta, build_meta))
}
/// Checks if the archive contains INSTALL, SETTS and BUILD files.
///
/// Checks if INSTALL file exists and is not empty. If it does not exist or is empty, returns an error.
/// Checks SETTS and BUILD (if present) and logs предупреждения, если они пустые или отсутствуют.
/// Ожидаем структуру: <cachedir>/<packagename>/{INSTALL, SETTS, BUILD, ...}.
///
/// # Errors
/// * Returns an error if INSTALL file does not exist or is empty.
/// * Returns an error if INSTALL file is empty.
fn check(path_to_archive: String) -> Result<bool, std::io::Error> {
Self::extract_archive(&path_to_archive)?;
let config = Config::parse().map_err(|e| std::io::Error::other(e.to_string()))?;
let cache_root = Path::new(&config.paths.cache_dir);
fn find_install(root: &Path) -> Result<Vec<std::path::PathBuf>, std::io::Error> {
let mut installs = Vec::new();
for entry in fs::read_dir(root)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
installs.extend(find_install(&path)?);
} else if path.file_name().and_then(|n| n.to_str()) == Some("INSTALL") {
installs.push(path);
}
}
Ok(installs)
}
let installs = find_install(cache_root)?;
if installs.is_empty() {
return Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
"INSTALL file not found in archive",
));
}
if installs.len() > 1 {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"Multiple INSTALL files found in archive; expected exactly one",
));
}
let install_path = &installs[0];
let pkg_dir = install_path.parent().ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
"INSTALL has no parent directory",
)
})?;
if pkg_dir.parent() != Some(cache_root) {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"Invalid meta-files layout: expected <cachedir>/<packagename>/INSTALL",
));
}
let setts_path = pkg_dir.join("SETTS");
let build_path = pkg_dir.join("BUILD");
let install_content = std::fs::read_to_string(install_path)?;
if install_content.trim().is_empty() {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"INSTALL file is empty",
));
}
if !setts_path.exists() {
log::warn!("SETTS file not found in archive. Make sure you dont need this.");
} else {
let setts_content = std::fs::read_to_string(&setts_path)?;
if setts_content.trim().is_empty() {
log::warn!("SETTS file is empty. Make sure you dont need this.");
}
}
if !build_path.exists() {
log::warn!("BUILD file not found in archive. Make sure you dont need this.");
} else {
let build_content = std::fs::read_to_string(&build_path)?;
if build_content.trim().is_empty() {
log::warn!("BUILD file is empty. Make sure you dont need this.");
}
}
let content = std::fs::read_to_string(install_path).map_err(|e| {
log::warn!("Failed to read file: {}", e);
e
})?;
let install_content: Result<Install, toml::de::Error> = toml::from_str(&content);
log::info!("Validating arch...");
let install_parsed = match install_content {
Ok(v) => v,
Err(e) => {
log::error!("Arch mismatch while parsing INSTALL: {}", e);
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("Arch mismatch: {}", e),
));
}
};
if std::env::consts::ARCH != install_parsed.package.arch.as_str() {
let pkg_arch = &install_parsed.package.arch;
log::error!(
"Arch mismatch. Package arch: {:?}, Host arch: {}",
pkg_arch,
std::env::consts::ARCH
);
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"Arch mismatch",
));
}
Ok(true)
}
/// Validates a custom script for security and basic syntax
/// Now only minimal validation is performed
fn validate_custom_script(script: &str) -> Result<(), std::io::Error> {
// Check for dangerous commands
let dangerous_patterns = [
"rm -rf /",
"sudo rm",
"chmod 777",
"chown root",
"dd if=",
"mkfs",
"fdisk",
"format",
":(){ :|:& };:",
];
for pattern in &dangerous_patterns {
if script.contains(pattern) {
return Err(std::io::Error::other(format!(
"Dangerous command detected in script: {}",
pattern
)));
}
}
// Check for script path existence if it's a file path
if script.starts_with("./") {
let script_path = Path::new(script);
if !script_path.exists() {
return Err(std::io::Error::other(format!(
"Script file not found: {}",
script
)));
}
// Check if it's executable
let metadata = fs::metadata(script_path)?;
if !metadata.permissions().mode() & 0o111 != 0 {
log::warn!("Script {} is not executable", script);
}
}
Ok(())
}
/// Validates and sanitizes a file path for security
fn validate_path(path: &str, base_dir: &Path) -> Result<std::path::PathBuf, std::io::Error> {
let path = Path::new(path);
// Convert to absolute path
let absolute_path = if path.is_absolute() {
path.to_path_buf()
} else {
base_dir.join(path)
};
// Normalize the path
let normalized = match absolute_path.canonicalize() {
Ok(p) => p,
Err(_) => {
// If canonicalization fails, at least clean up the path
let mut cleaned = std::path::PathBuf::new();
for component in absolute_path.components() {
match component {
std::path::Component::ParentDir => {
// Don't go above base directory
if cleaned.pop() {
// Successfully removed parent
} else {
return Err(std::io::Error::other(
"Path traversal attempt detected",
));
}
}
std::path::Component::CurDir => {
// Skip current directory
}
_ => cleaned.push(component),
}
}
cleaned
}
};
// Ensure the path is within the base directory (for relative paths)
if !path.is_absolute()
&& let Ok(base_absolute) = base_dir.canonicalize()
&& !normalized.starts_with(&base_absolute)
{
return Err(std::io::Error::other(
"Path is outside of allowed directory",
));
}
Ok(normalized)
}
}
|