diff --git a/Cargo.toml b/Cargo.toml index 7fd3472..29ad459 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,21 +12,39 @@ gzip = ["dep:flate2"] members = ["cli"] [dependencies] -const-hex = "1" -digest = "0.11" -flate2 = { version = "1", optional = true } -rustc-hash = "2" -rust-i18n = "4" -rusqlite = { version = "0.40", features = ["bundled"] } -serde = { version = "1", features = ["derive"] } -serde_json = "1" -sha3 = "0.12" + +# Handling package files (core functions) tar = "0.4" tempfile = "3" -thiserror = "2" -toml = "1" -itertools = "0.15" -ureq = { version = "3", features = ["socks-proxy"] } + +# Remote repository support url = { version = "2", features = ["serde"] } -nix = { version = "0.31", features = ["fs"] } +ureq = { version = "3", features = ["socks-proxy"] } + +# Graph algorithms +itertools = "0.15" + +# Security +digest = "0.11" +const-hex = "1" +sha3 = "0.12" + +# File formats +serde = { version = "1", features = ["derive"] } +serde_json = "1" +toml = "1" +rusqlite = { version = "0.41" } + +# Error handling +thiserror = "2" + +# Optional features +flate2 = { version = "1", optional = true } zstd = { version = "0.14", optional = true } + +# Performance optimizations +rustc-hash = "2" + +# Misc +rust-i18n = "4" +nix = { version = "0.31", features = ["fs"] } diff --git a/INSTALL.md b/INSTALL.md index 741ca78..46f2752 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -2,6 +2,14 @@ ## Building Packie +### Feature Flags + +We have these feature flags that are enabled by default. Generally, you should not disable them, or compatibility +with existing package files might be broken: + +- `zstd`: Support of Zstandard-compressed package files +- `gzip`: Support of Gzip-compressed package files + ### Environment Variables These environment variables affect building of Packie: diff --git a/README.md b/README.md index e66b712..9c4a340 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,7 @@ # Packie Packie is the SemiOS package manager. + +# Build & Install + +Refer to [INSTALL.md](INSTALL.md) for details of building the package manager. diff --git a/cli/src/info.rs b/cli/src/info.rs index 499ea1f..5f81c31 100644 --- a/cli/src/info.rs +++ b/cli/src/info.rs @@ -129,6 +129,9 @@ fn print_info(info: &ComprehensivePackageInfo) { info.pkg_manifest.description ); } + if let Some(license) = &info.pkg_manifest.license { + println!(" {}: {}", t!("info.print_info.license"), license); + } if !info.pkg_manifest.maintainers.is_empty() { println!(" {}:", t!("info.print_info.maintainers")); for i in info.pkg_manifest.maintainers.iter() { diff --git a/cli/src/update.rs b/cli/src/update.rs index 3b77089..bddb1bf 100644 --- a/cli/src/update.rs +++ b/cli/src/update.rs @@ -4,37 +4,40 @@ use packie::{PackieBuilder, repo::SyncEvent}; use rust_i18n::t; #[derive(Debug, Parser)] -pub struct Cli {} +pub struct Cli { + repo: Option, +} pub fn main(cli: Cli) -> Result<(), crate::Error> { let mut packie = PackieBuilder::new().build()?; let progress_bar = ProgressBar::new(0).with_style(crate::common::progress_style_multidownload()); - packie - .sync_repo() - .on_event(|ev| match ev { - SyncEvent::BeginRepo(repo) => { - progress_bar.set_prefix(repo.clone()); - progress_bar.println(t!("update.begin_repo", repo = repo)); + let mut sync_repo = packie.sync_repo().on_event(|ev| match ev { + SyncEvent::BeginRepo(repo) => { + progress_bar.set_prefix(repo.clone()); + progress_bar.println(t!("update.begin_repo", repo = repo)); + } + SyncEvent::Progress(progress) => { + progress_bar.set_length(progress.total_bytes); + progress_bar.set_position(progress.downloaded_bytes); + } + SyncEvent::Error(repo, url, err) => match (repo, url) { + (Some(repo), Some(url)) => { + progress_bar.println(format!( + "failed to update repository \"{repo}\" from \"{url}\": {err}" + )); } - SyncEvent::Progress(progress) => { - progress_bar.set_length(progress.total_bytes); - progress_bar.set_position(progress.downloaded_bytes); + (Some(repo), None) => { + progress_bar.println(format!("failed to update repository \"{repo}\": {err}")); } - SyncEvent::Error(repo, url, err) => match (repo, url) { - (Some(repo), Some(url)) => { - progress_bar.println(format!( - "failed to update repository \"{repo}\" from \"{url}\": {err}" - )); - } - (Some(repo), None) => { - progress_bar.println(format!("failed to update repository \"{repo}\": {err}")); - } - _ => { - progress_bar.println(format!("failed to update repositories: {err}")); - } - }, - }) - .run(); + _ => { + progress_bar.println(format!("failed to update repositories: {err}")); + } + }, + }); + if let Some(repo) = cli.repo { + sync_repo = sync_repo.repo(repo); + } + sync_repo.run(); Ok(()) } diff --git a/cli/src/upgrade.rs b/cli/src/upgrade.rs index ebdcc93..e9e1ba9 100644 --- a/cli/src/upgrade.rs +++ b/cli/src/upgrade.rs @@ -15,12 +15,12 @@ pub struct Cli { #[arg(short, long)] yes: bool, - items: Option>, + items: Vec, } pub fn main(cli: Cli) -> Result<(), crate::Error> { let mut packie = PackieBuilder::new().build()?; - let ops = packie.calculate_upgradation(cli.items.unwrap_or_default())?; + let ops = packie.calculate_upgradation(cli.items)?; if ops.is_empty() { eprintln!("{}", t!("upgrade.nothing_to_do")); diff --git a/locales/packie-cli/main.yml b/locales/packie-cli/main.yml index 7efe68d..f4a166b 100644 --- a/locales/packie-cli/main.yml +++ b/locales/packie-cli/main.yml @@ -103,6 +103,10 @@ info.print_info.description: en: "Description" zh-CN: "描述" ja: "説明" +info.print_info.license: + en: "License" + zh-CN: "许可协议" + ja: "ライセンス" info.print_info.maintainers: en: "Maintainers" zh-CN: "维护者" diff --git a/src/common/checksum.rs b/src/common/checksum.rs index 99cda26..0a05117 100644 --- a/src/common/checksum.rs +++ b/src/common/checksum.rs @@ -1,41 +1,58 @@ use digest::{Digest, DynDigest}; use std::{fs::File, io::Read, path::Path}; -pub const DEFAULT_HASHER: &str = "sha3-512"; +pub trait HashAlgorithm: DynDigest { + fn name(&self) -> &'static str; +} +impl HashAlgorithm for sha3::Sha3_512 { + fn name(&self) -> &'static str { + "sha3-512" + } +} -pub fn find_hasher(s: &str) -> std::io::Result> { +pub trait HashAlgorithmExt { + fn hash_reader(self, rdr: &mut R) -> std::io::Result; + fn hash_file(self, path: impl AsRef) -> std::io::Result; +} +impl HashAlgorithmExt for Box { + fn hash_reader(mut self, rdr: &mut R) -> std::io::Result { + let mut buf = vec![0u8; 4096]; + loop { + let n = rdr.read(&mut buf)?; + self.update(&buf[..n]); + if n == 0 { + break; + } + } + Ok(format!( + "{}:{}", + self.name(), + const_hex::encode(self.finalize()), + )) + } + + fn hash_file(self, path: impl AsRef) -> std::io::Result { + self.hash_reader(&mut File::open(path)?) + } +} + +pub fn algorithm(s: &str) -> std::io::Result> { match s { "sha3-512" => Ok(Box::new(sha3::Sha3_512::new())), _ => Err(std::io::ErrorKind::InvalidInput.into()), } } -pub fn hash_reader(hasher_name: &str, reader: &mut R) -> std::io::Result { - let mut buf = [0u8; 1024]; - let mut hasher = find_hasher(hasher_name)?; - loop { - let n = reader.read(&mut buf)?; - hasher.update(&buf[..n]); - if n == 0 { - break; - } - } - Ok(format!( - "{hasher_name}:{}", - const_hex::encode(hasher.finalize()), - )) +pub fn default_algorithm() -> Box { + algorithm("sha3-512").unwrap() } pub fn verify_reader(reader: &mut R, expected: &str) -> std::io::Result { - let hasher = expected.split(':').next().unwrap(); - let hash = hash_reader(hasher, reader)?; + let algo = expected.split(':').next().unwrap(); + let hash = algorithm(algo)?.hash_reader(reader)?; Ok(hash == expected) } -pub fn hash_file>(hasher: &str, path: P) -> std::io::Result { - hash_reader(hasher, &mut File::open(path)?) -} - pub fn verify_file>(path: P, expected: &str) -> std::io::Result { verify_reader(&mut File::open(path)?, expected) } diff --git a/src/common/io.rs b/src/common/io.rs new file mode 100644 index 0000000..7db03a8 --- /dev/null +++ b/src/common/io.rs @@ -0,0 +1,44 @@ +use std::io::{Read, Seek, SeekFrom}; + +pub enum Decompress { + #[cfg(feature = "zstd")] + Zstd(zstd::Decoder<'static, std::io::BufReader>), + + #[cfg(feature = "gzip")] + Gzip(flate2::read::GzDecoder), +} +impl Decompress { + pub fn new(mut _rdr: R) -> std::io::Result { + #[cfg(feature = "zstd")] + if stream_starts_with(&mut _rdr, &[0x28, 0xb5, 0x2f, 0xfd])? { + return Ok(Self::Zstd(zstd::Decoder::new(_rdr)?)); + } + + #[cfg(feature = "gzip")] + if stream_starts_with(&mut _rdr, &[0x1F, 0x8B])? { + return Ok(Self::Gzip(flate2::read::GzDecoder::new(_rdr))); + } + + Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "Unknown compression algorithm", + )) + } +} +impl Read for Decompress { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + match self { + #[cfg(feature = "zstd")] + Self::Zstd(d) => d.read(buf), + #[cfg(feature = "gzip")] + Self::Gzip(d) => d.read(buf), + } + } +} + +fn stream_starts_with(stream: &mut (impl Read + Seek), magic: &[u8]) -> std::io::Result { + let mut magic_buf = vec![0u8; magic.len()]; + stream.read_exact(&mut magic_buf)?; + stream.seek(SeekFrom::Start(0))?; + Ok(magic_buf == magic) +} diff --git a/src/common/mod.rs b/src/common/mod.rs index 9e42455..1abf50c 100644 --- a/src/common/mod.rs +++ b/src/common/mod.rs @@ -1,46 +1,13 @@ pub mod checksum; pub mod fs; +pub mod io; pub mod macros; pub use fs::*; -use std::{ - io::{Read, Seek, SeekFrom}, - time::SystemTime, -}; - -pub fn decompress( - mut raw: impl Read + Seek + Send + Sync + 'static, -) -> std::io::Result> { - #[cfg(feature = "zstd")] - if stream_starts_with(&mut raw, &[0x28, 0xb5, 0x2f, 0xfd])? { - return Ok(Box::new(zstd::Decoder::new(raw)?)); - } - - #[cfg(feature = "gzip")] - if stream_starts_with(&mut raw, &[0x1F, 0x8B])? { - return Ok(Box::new(flate2::read::GzDecoder::new(raw))); - } - - Err(std::io::Error::new( - std::io::ErrorKind::InvalidData, - "Unknown compression algorithm", - )) -} - -fn stream_starts_with( - stream: &mut (impl Read + Seek + Send + Sync + 'static), - magic: &[u8], -) -> std::io::Result { - let mut magic_buf = vec![0u8; magic.len()]; - stream.read_exact(&mut magic_buf)?; - stream.seek(SeekFrom::Start(0))?; - Ok(magic_buf == magic) -} - pub fn timestamp_secs() -> i64 { - SystemTime::now() - .duration_since(SystemTime::UNIX_EPOCH) + std::time::SystemTime::now() + .duration_since(std::time::SystemTime::UNIX_EPOCH) .map(|d| d.as_secs() as i64) .unwrap_or_else(|e| -(e.duration().as_secs() as i64)) } diff --git a/src/graph.rs b/src/graph.rs index 3002a32..d699a42 100644 --- a/src/graph.rs +++ b/src/graph.rs @@ -114,7 +114,7 @@ impl super::Packie { ) -> Result, GraphError> { // Collect all package idents required to upgrade let mut installations = Vec::with_capacity(pkgspecs.len()); - if installations.is_empty() { + if pkgspecs.is_empty() { self.for_each_installation(|x| Ok::<_, rusqlite::Error>(installations.push(x))) .unwrap(); } else { diff --git a/src/package.rs b/src/package.rs index 3661fa5..024098e 100644 --- a/src/package.rs +++ b/src/package.rs @@ -1,4 +1,5 @@ use crate::{ + common::io::Decompress, link::LinksFile, version::{Version, VersionFilter}, }; @@ -22,7 +23,7 @@ impl Package { /// Opens a package file. pub fn open>(path: P) -> Result { let open_file = File::open(path.as_ref()).map_err(PackageError::Open)?; - let decompressed_file = crate::common::decompress(open_file).map_err(PackageError::Open)?; + let decompressed_file = Decompress::new(open_file).map_err(PackageError::Open)?; let mut archive = tar::Archive::new(decompressed_file); let extracted_dir = TempDir::new().map_err(PackageError::Open)?; @@ -87,6 +88,9 @@ pub struct PkgManifest { #[serde(default)] pub description: String, + /// License of the software. + pub license: Option, + /// Package maintainers. #[serde(default)] pub maintainers: Vec, diff --git a/src/repo/download.rs b/src/repo/download.rs index 6d68cd2..7ce3049 100644 --- a/src/repo/download.rs +++ b/src/repo/download.rs @@ -5,6 +5,7 @@ use std::{ path::PathBuf, }; +#[derive(Debug)] pub struct Download

{ from: String, to: PathBuf, @@ -50,16 +51,9 @@ impl Download

{ return Ok(()); } - let mut temp_file_path = self.to.clone(); - temp_file_path.add_extension("tmp"); - let mut temp_file = File::options() - .create(true) - .append(true) - .open(&temp_file_path) - .map_err(DownloadError::Filesystem)?; - let seek = temp_file - .seek(std::io::SeekFrom::Current(0)) - .map_err(DownloadError::Filesystem)?; + let mut file = DownloadingFile::open(&self.to)?; + let seek = file.cursor()?; + file.set_expected_checksum(self.checksum_required.clone()); let mut resp = ureq::get(&self.from) .header(ureq::http::header::RANGE, format!("bytes={seek}-")) @@ -69,7 +63,7 @@ impl Download

{ let total = body.content_length().unwrap_or_default() + seek; let mut sum = seek; - let mut buf = [0; 1024]; + let mut buf = [0; 4096]; let mut body_reader = body.as_reader(); loop { @@ -79,27 +73,79 @@ impl Download

{ if len == 0 { break; } - temp_file - .write_all(&buf[..len]) + file.write_all(&buf[..len]) .map_err(DownloadError::Filesystem)?; sum += len as u64; (self.on_progress)(sum, total); } - if let Some(expected) = self.checksum_required.as_ref() { - let verified = - crate::common::checksum::verify_file(&temp_file_path, expected).unwrap_or_default(); + file.finish()?; + + Ok(()) + } +} + +#[derive(Debug)] +pub struct DownloadingFile { + temp_path: PathBuf, + actual_path: PathBuf, + fd: File, + expected_checksum: Option, +} +impl DownloadingFile { + pub fn open(path: impl Into) -> Result { + let actual_path = path.into(); + let mut temp_path = actual_path.clone(); + temp_path.add_extension("tmp"); + let fd = File::options() + .create(true) + .append(true) + .open(&temp_path) + .map_err(DownloadError::Filesystem)?; + Ok(Self { + temp_path, + actual_path, + fd, + expected_checksum: None, + }) + } + + pub fn cursor(&mut self) -> Result { + self.fd + .seek(std::io::SeekFrom::Current(0)) + .map_err(DownloadError::Filesystem) + } + + pub fn set_expected_checksum(&mut self, expected: impl Into>) { + self.expected_checksum = expected.into(); + } + + pub fn finish(self) -> Result<(), DownloadError> { + drop(self.fd); + + if let Some(expected) = self.expected_checksum { + let verified = crate::common::checksum::verify_file(&self.temp_path, &expected) + .unwrap_or_default(); if !verified { - _ = std::fs::remove_file(&temp_file_path); + _ = std::fs::remove_file(&self.temp_path); return Err(DownloadError::Checksum); } } - std::fs::rename(temp_file_path, &self.to).map_err(DownloadError::Filesystem)?; + std::fs::rename(self.temp_path, &self.actual_path).map_err(DownloadError::Filesystem)?; Ok(()) } } +impl Write for DownloadingFile { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.fd.write(buf) + } + + fn flush(&mut self) -> std::io::Result<()> { + self.fd.flush() + } +} #[derive(Debug, thiserror::Error)] pub enum DownloadError { diff --git a/src/repo/serve.rs b/src/repo/serve.rs index 2cd32f8..4aff362 100644 --- a/src/repo/serve.rs +++ b/src/repo/serve.rs @@ -1,5 +1,5 @@ use crate::{ - common::checksum::DEFAULT_HASHER, + common::checksum::HashAlgorithmExt, package::{Package, PkgIdent}, repo::{RepoDb, RepoPackage, download::Download}, }; @@ -71,7 +71,7 @@ impl RepoServeDir { let pkg_manifest = package.manifest()?; let download_size = std::fs::metadata(path)?.len(); let installed_size = package.installed_size()?; - let checksum = crate::common::checksum::hash_file(DEFAULT_HASHER, path)?; + let checksum = crate::common::checksum::default_algorithm().hash_file(path)?; let repo_package = RepoPackage { repo_name: None,