| 1 |
//! Types that specify what is contained in a ZIP. |
| 2 |
use crate::cp437::FromCp437; |
| 3 |
use crate::write::{FileOptionExtension, FileOptions}; |
| 4 |
use path::{Component, Path, PathBuf}; |
| 5 |
use std::fmt; |
| 6 |
use std::mem; |
| 7 |
use std::path; |
| 8 |
use std::sync::{Arc, OnceLock}; |
| 9 |
|
| 10 |
#[cfg(feature = "chrono")] |
| 11 |
use chrono::{Datelike, NaiveDate, NaiveDateTime, NaiveTime, Timelike}; |
| 12 |
|
| 13 |
use crate::result::{ZipError, ZipResult}; |
| 14 |
use crate::spec::{self, FixedSizeBlock}; |
| 15 |
|
| 16 |
pub(crate) mod ffi { |
| 17 |
pub const S_IFDIR: u32 = 0o0040000; |
| 18 |
pub const S_IFREG: u32 = 0o0100000; |
| 19 |
pub const S_IFLNK: u32 = 0o0120000; |
| 20 |
} |
| 21 |
|
| 22 |
use crate::extra_fields::ExtraField; |
| 23 |
use crate::result::DateTimeRangeError; |
| 24 |
use crate::spec::is_dir; |
| 25 |
use crate::types::ffi::S_IFDIR; |
| 26 |
use crate::CompressionMethod; |
| 27 |
#[cfg(feature = "time")] |
| 28 |
use time::{error::ComponentRange, Date, Month, OffsetDateTime, PrimitiveDateTime, Time}; |
| 29 |
|
| 30 |
pub(crate) struct ZipRawValues { |
| 31 |
pub(crate) crc32: u32, |
| 32 |
pub(crate) compressed_size: u64, |
| 33 |
pub(crate) uncompressed_size: u64, |
| 34 |
} |
| 35 |
|
| 36 |
#[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 37 |
#[repr(u8)] |
| 38 |
pub enum System { |
| 39 |
Dos = 0, |
| 40 |
Unix = 3, |
| 41 |
Unknown, |
| 42 |
} |
| 43 |
|
| 44 |
impl From<u8> for System { |
| 45 |
fn from(system: u8) -> Self { |
| 46 |
match system { |
| 47 |
0 => Self::Dos, |
| 48 |
3 => Self::Unix, |
| 49 |
_ => Self::Unknown, |
| 50 |
} |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
impl From<System> for u8 { |
| 55 |
fn from(system: System) -> Self { |
| 56 |
match system { |
| 57 |
System::Dos => 0, |
| 58 |
System::Unix => 3, |
| 59 |
System::Unknown => 4, |
| 60 |
} |
| 61 |
} |
| 62 |
} |
| 63 |
|
| 64 |
/// Representation of a moment in time. |
| 65 |
/// |
| 66 |
/// Zip files use an old format from DOS to store timestamps, |
| 67 |
/// with its own set of peculiarities. |
| 68 |
/// For example, it has a resolution of 2 seconds! |
| 69 |
/// |
| 70 |
/// A [`DateTime`] can be stored directly in a zipfile with [`FileOptions::last_modified_time`], |
| 71 |
/// or read from one with [`ZipFile::last_modified`](crate::read::ZipFile::last_modified). |
| 72 |
/// |
| 73 |
/// # Warning |
| 74 |
/// |
| 75 |
/// Because there is no timezone associated with the [`DateTime`], they should ideally only |
| 76 |
/// be used for user-facing descriptions. |
| 77 |
/// |
| 78 |
/// Modern zip files store more precise timestamps; see [`crate::extra_fields::ExtendedTimestamp`] |
| 79 |
/// for details. |
| 80 |
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] |
| 81 |
pub struct DateTime { |
| 82 |
year: u16, |
| 83 |
month: u8, |
| 84 |
day: u8, |
| 85 |
hour: u8, |
| 86 |
minute: u8, |
| 87 |
second: u8, |
| 88 |
} |
| 89 |
|
| 90 |
impl DateTime { |
| 91 |
/// Returns the current time if possible, otherwise the default of 1980-01-01. |
| 92 |
#[cfg(feature = "time")] |
| 93 |
pub fn default_for_write() -> Self { |
| 94 |
OffsetDateTime::now_utc() |
| 95 |
.try_into() |
| 96 |
.unwrap_or_else(|_| DateTime::default()) |
| 97 |
} |
| 98 |
|
| 99 |
/// Returns the current time if possible, otherwise the default of 1980-01-01. |
| 100 |
#[cfg(not(feature = "time"))] |
| 101 |
pub fn default_for_write() -> Self { |
| 102 |
DateTime::default() |
| 103 |
} |
| 104 |
} |
| 105 |
|
| 106 |
#[cfg(fuzzing)] |
| 107 |
impl arbitrary::Arbitrary<'_> for DateTime { |
| 108 |
fn arbitrary(u: &mut arbitrary::Unstructured) -> arbitrary::Result<Self> { |
| 109 |
Ok(DateTime { |
| 110 |
year: u.int_in_range(1980..=2107)?, |
| 111 |
month: u.int_in_range(1..=12)?, |
| 112 |
day: u.int_in_range(1..=31)?, |
| 113 |
hour: u.int_in_range(0..=23)?, |
| 114 |
minute: u.int_in_range(0..=59)?, |
| 115 |
second: u.int_in_range(0..=58)?, |
| 116 |
}) |
| 117 |
} |
| 118 |
} |
| 119 |
|
| 120 |
#[cfg(feature = "chrono")] |
| 121 |
impl TryFrom<NaiveDateTime> for DateTime { |
| 122 |
type Error = DateTimeRangeError; |
| 123 |
|
| 124 |
fn try_from(value: NaiveDateTime) -> Result<Self, Self::Error> { |
| 125 |
DateTime::from_date_and_time( |
| 126 |
value.year().try_into()?, |
| 127 |
value.month().try_into()?, |
| 128 |
value.day().try_into()?, |
| 129 |
value.hour().try_into()?, |
| 130 |
value.minute().try_into()?, |
| 131 |
value.second().try_into()?, |
| 132 |
) |
| 133 |
} |
| 134 |
} |
| 135 |
|
| 136 |
#[cfg(feature = "chrono")] |
| 137 |
impl TryFrom<DateTime> for NaiveDateTime { |
| 138 |
type Error = DateTimeRangeError; |
| 139 |
|
| 140 |
fn try_from(value: DateTime) -> Result<Self, Self::Error> { |
| 141 |
let date = NaiveDate::from_ymd_opt(value.year.into(), value.month.into(), value.day.into()) |
| 142 |
.ok_or(DateTimeRangeError)?; |
| 143 |
let time = |
| 144 |
NaiveTime::from_hms_opt(value.hour.into(), value.minute.into(), value.second.into()) |
| 145 |
.ok_or(DateTimeRangeError)?; |
| 146 |
Ok(NaiveDateTime::new(date, time)) |
| 147 |
} |
| 148 |
} |
| 149 |
|
| 150 |
impl TryFrom<(u16, u16)> for DateTime { |
| 151 |
type Error = DateTimeRangeError; |
| 152 |
|
| 153 |
#[inline] |
| 154 |
fn try_from(values: (u16, u16)) -> Result<Self, Self::Error> { |
| 155 |
Self::try_from_msdos(values.0, values.1) |
| 156 |
} |
| 157 |
} |
| 158 |
|
| 159 |
impl From<DateTime> for (u16, u16) { |
| 160 |
#[inline] |
| 161 |
fn from(dt: DateTime) -> Self { |
| 162 |
(dt.datepart(), dt.timepart()) |
| 163 |
} |
| 164 |
} |
| 165 |
|
| 166 |
impl Default for DateTime { |
| 167 |
/// Constructs an 'default' datetime of 1980-01-01 00:00:00 |
| 168 |
fn default() -> DateTime { |
| 169 |
DateTime { |
| 170 |
year: 1980, |
| 171 |
month: 1, |
| 172 |
day: 1, |
| 173 |
hour: 0, |
| 174 |
minute: 0, |
| 175 |
second: 0, |
| 176 |
} |
| 177 |
} |
| 178 |
} |
| 179 |
|
| 180 |
impl fmt::Display for DateTime { |
| 181 |
#[inline] |
| 182 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 183 |
write!( |
| 184 |
f, |
| 185 |
"{:04}-{:02}-{:02} {:02}:{:02}:{:02}", |
| 186 |
self.year, self.month, self.day, self.hour, self.minute, self.second |
| 187 |
) |
| 188 |
} |
| 189 |
} |
| 190 |
|
| 191 |
impl DateTime { |
| 192 |
/// Converts an msdos (u16, u16) pair to a DateTime object |
| 193 |
/// |
| 194 |
/// # Safety |
| 195 |
/// The caller must ensure the date and time are valid. |
| 196 |
pub const unsafe fn from_msdos_unchecked(datepart: u16, timepart: u16) -> DateTime { |
| 197 |
let seconds = (timepart & 0b0000000000011111) << 1; |
| 198 |
let minutes = (timepart & 0b0000011111100000) >> 5; |
| 199 |
let hours = (timepart & 0b1111100000000000) >> 11; |
| 200 |
let days = datepart & 0b0000000000011111; |
| 201 |
let months = (datepart & 0b0000000111100000) >> 5; |
| 202 |
let years = (datepart & 0b1111111000000000) >> 9; |
| 203 |
|
| 204 |
DateTime { |
| 205 |
year: years + 1980, |
| 206 |
month: months as u8, |
| 207 |
day: days as u8, |
| 208 |
hour: hours as u8, |
| 209 |
minute: minutes as u8, |
| 210 |
second: seconds as u8, |
| 211 |
} |
| 212 |
} |
| 213 |
|
| 214 |
/// Converts an msdos (u16, u16) pair to a DateTime object if it represents a valid date and |
| 215 |
/// time. |
| 216 |
pub fn try_from_msdos(datepart: u16, timepart: u16) -> Result<DateTime, DateTimeRangeError> { |
| 217 |
let seconds = (timepart & 0b0000000000011111) << 1; |
| 218 |
let minutes = (timepart & 0b0000011111100000) >> 5; |
| 219 |
let hours = (timepart & 0b1111100000000000) >> 11; |
| 220 |
let days = datepart & 0b0000000000011111; |
| 221 |
let months = (datepart & 0b0000000111100000) >> 5; |
| 222 |
let years = (datepart & 0b1111111000000000) >> 9; |
| 223 |
Self::from_date_and_time( |
| 224 |
years.checked_add(1980).ok_or(DateTimeRangeError)?, |
| 225 |
months.try_into()?, |
| 226 |
days.try_into()?, |
| 227 |
hours.try_into()?, |
| 228 |
minutes.try_into()?, |
| 229 |
seconds.try_into()?, |
| 230 |
) |
| 231 |
} |
| 232 |
|
| 233 |
/// Constructs a DateTime from a specific date and time |
| 234 |
/// |
| 235 |
/// The bounds are: |
| 236 |
/// * year: [1980, 2107] |
| 237 |
/// * month: [1, 12] |
| 238 |
/// * day: [1, 28..=31] |
| 239 |
/// * hour: [0, 23] |
| 240 |
/// * minute: [0, 59] |
| 241 |
/// * second: [0, 58] |
| 242 |
pub fn from_date_and_time( |
| 243 |
year: u16, |
| 244 |
month: u8, |
| 245 |
day: u8, |
| 246 |
hour: u8, |
| 247 |
minute: u8, |
| 248 |
second: u8, |
| 249 |
) -> Result<DateTime, DateTimeRangeError> { |
| 250 |
fn is_leap_year(year: u16) -> bool { |
| 251 |
(year % 4 == 0) && ((year % 25 != 0) || (year % 16 == 0)) |
| 252 |
} |
| 253 |
|
| 254 |
if (1980..=2107).contains(&year) |
| 255 |
&& (1..=12).contains(&month) |
| 256 |
&& (1..=31).contains(&day) |
| 257 |
&& hour <= 23 |
| 258 |
&& minute <= 59 |
| 259 |
&& second <= 60 |
| 260 |
{ |
| 261 |
let second = second.min(58); // exFAT can't store leap seconds |
| 262 |
let max_day = match month { |
| 263 |
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31, |
| 264 |
4 | 6 | 9 | 11 => 30, |
| 265 |
2 if is_leap_year(year) => 29, |
| 266 |
2 => 28, |
| 267 |
_ => unreachable!(), |
| 268 |
}; |
| 269 |
if day > max_day { |
| 270 |
return Err(DateTimeRangeError); |
| 271 |
} |
| 272 |
Ok(DateTime { |
| 273 |
year, |
| 274 |
month, |
| 275 |
day, |
| 276 |
hour, |
| 277 |
minute, |
| 278 |
second, |
| 279 |
}) |
| 280 |
} else { |
| 281 |
Err(DateTimeRangeError) |
| 282 |
} |
| 283 |
} |
| 284 |
|
| 285 |
/// Indicates whether this date and time can be written to a zip archive. |
| 286 |
pub fn is_valid(&self) -> bool { |
| 287 |
DateTime::from_date_and_time( |
| 288 |
self.year, |
| 289 |
self.month, |
| 290 |
self.day, |
| 291 |
self.hour, |
| 292 |
self.minute, |
| 293 |
self.second, |
| 294 |
) |
| 295 |
.is_ok() |
| 296 |
} |
| 297 |
|
| 298 |
#[cfg(feature = "time")] |
| 299 |
/// Converts a OffsetDateTime object to a DateTime |
| 300 |
/// |
| 301 |
/// Returns `Err` when this object is out of bounds |
| 302 |
#[deprecated(since = "0.6.4", note = "use `DateTime::try_from()` instead")] |
| 303 |
pub fn from_time(dt: OffsetDateTime) -> Result<DateTime, DateTimeRangeError> { |
| 304 |
dt.try_into() |
| 305 |
} |
| 306 |
|
| 307 |
/// Gets the time portion of this datetime in the msdos representation |
| 308 |
pub const fn timepart(&self) -> u16 { |
| 309 |
((self.second as u16) >> 1) | ((self.minute as u16) << 5) | ((self.hour as u16) << 11) |
| 310 |
} |
| 311 |
|
| 312 |
/// Gets the date portion of this datetime in the msdos representation |
| 313 |
pub const fn datepart(&self) -> u16 { |
| 314 |
(self.day as u16) | ((self.month as u16) << 5) | ((self.year - 1980) << 9) |
| 315 |
} |
| 316 |
|
| 317 |
#[cfg(feature = "time")] |
| 318 |
/// Converts the DateTime to a OffsetDateTime structure |
| 319 |
#[deprecated(since = "1.3.1", note = "use `OffsetDateTime::try_from()` instead")] |
| 320 |
pub fn to_time(&self) -> Result<OffsetDateTime, ComponentRange> { |
| 321 |
(*self).try_into() |
| 322 |
} |
| 323 |
|
| 324 |
/// Get the year. There is no epoch, i.e. 2018 will be returned as 2018. |
| 325 |
pub const fn year(&self) -> u16 { |
| 326 |
self.year |
| 327 |
} |
| 328 |
|
| 329 |
/// Get the month, where 1 = january and 12 = december |
| 330 |
/// |
| 331 |
/// # Warning |
| 332 |
/// |
| 333 |
/// When read from a zip file, this may not be a reasonable value |
| 334 |
pub const fn month(&self) -> u8 { |
| 335 |
self.month |
| 336 |
} |
| 337 |
|
| 338 |
/// Get the day |
| 339 |
/// |
| 340 |
/// # Warning |
| 341 |
/// |
| 342 |
/// When read from a zip file, this may not be a reasonable value |
| 343 |
pub const fn day(&self) -> u8 { |
| 344 |
self.day |
| 345 |
} |
| 346 |
|
| 347 |
/// Get the hour |
| 348 |
/// |
| 349 |
/// # Warning |
| 350 |
/// |
| 351 |
/// When read from a zip file, this may not be a reasonable value |
| 352 |
pub const fn hour(&self) -> u8 { |
| 353 |
self.hour |
| 354 |
} |
| 355 |
|
| 356 |
/// Get the minute |
| 357 |
/// |
| 358 |
/// # Warning |
| 359 |
/// |
| 360 |
/// When read from a zip file, this may not be a reasonable value |
| 361 |
pub const fn minute(&self) -> u8 { |
| 362 |
self.minute |
| 363 |
} |
| 364 |
|
| 365 |
/// Get the second |
| 366 |
/// |
| 367 |
/// # Warning |
| 368 |
/// |
| 369 |
/// When read from a zip file, this may not be a reasonable value |
| 370 |
pub const fn second(&self) -> u8 { |
| 371 |
self.second |
| 372 |
} |
| 373 |
} |
| 374 |
|
| 375 |
#[cfg(feature = "time")] |
| 376 |
impl TryFrom<OffsetDateTime> for DateTime { |
| 377 |
type Error = DateTimeRangeError; |
| 378 |
|
| 379 |
fn try_from(dt: OffsetDateTime) -> Result<Self, Self::Error> { |
| 380 |
if dt.year() >= 1980 && dt.year() <= 2107 { |
| 381 |
Ok(DateTime { |
| 382 |
year: dt.year().try_into()?, |
| 383 |
month: dt.month().into(), |
| 384 |
day: dt.day(), |
| 385 |
hour: dt.hour(), |
| 386 |
minute: dt.minute(), |
| 387 |
second: dt.second(), |
| 388 |
}) |
| 389 |
} else { |
| 390 |
Err(DateTimeRangeError) |
| 391 |
} |
| 392 |
} |
| 393 |
} |
| 394 |
|
| 395 |
#[cfg(feature = "time")] |
| 396 |
impl TryFrom<DateTime> for OffsetDateTime { |
| 397 |
type Error = ComponentRange; |
| 398 |
|
| 399 |
fn try_from(dt: DateTime) -> Result<Self, Self::Error> { |
| 400 |
let date = Date::from_calendar_date(dt.year as i32, Month::try_from(dt.month)?, dt.day)?; |
| 401 |
let time = Time::from_hms(dt.hour, dt.minute, dt.second)?; |
| 402 |
Ok(PrimitiveDateTime::new(date, time).assume_utc()) |
| 403 |
} |
| 404 |
} |
| 405 |
|
| 406 |
pub const MIN_VERSION: u8 = 10; |
| 407 |
pub const DEFAULT_VERSION: u8 = 45; |
| 408 |
|
| 409 |
/// Structure representing a ZIP file. |
| 410 |
#[derive(Debug, Clone)] |
| 411 |
pub struct ZipFileData { |
| 412 |
/// Compatibility of the file attribute information |
| 413 |
pub system: System, |
| 414 |
/// Specification version |
| 415 |
pub version_made_by: u8, |
| 416 |
/// True if the file is encrypted. |
| 417 |
pub encrypted: bool, |
| 418 |
/// True if file_name and file_comment are UTF8 |
| 419 |
pub is_utf8: bool, |
| 420 |
/// True if the file uses a data-descriptor section |
| 421 |
pub using_data_descriptor: bool, |
| 422 |
/// Compression method used to store the file |
| 423 |
pub compression_method: crate::compression::CompressionMethod, |
| 424 |
/// Compression level to store the file |
| 425 |
pub compression_level: Option<i64>, |
| 426 |
/// Last modified time. This will only have a 2 second precision. |
| 427 |
pub last_modified_time: Option<DateTime>, |
| 428 |
/// CRC32 checksum |
| 429 |
pub crc32: u32, |
| 430 |
/// Size of the file in the ZIP |
| 431 |
pub compressed_size: u64, |
| 432 |
/// Size of the file when extracted |
| 433 |
pub uncompressed_size: u64, |
| 434 |
/// Name of the file |
| 435 |
pub file_name: Box<str>, |
| 436 |
/// Raw file name. To be used when file_name was incorrectly decoded. |
| 437 |
pub file_name_raw: Box<[u8]>, |
| 438 |
/// Extra field usually used for storage expansion |
| 439 |
pub extra_field: Option<Arc<Vec<u8>>>, |
| 440 |
/// Extra field only written to central directory |
| 441 |
pub central_extra_field: Option<Arc<Vec<u8>>>, |
| 442 |
/// File comment |
| 443 |
pub file_comment: Box<str>, |
| 444 |
/// Specifies where the local header of the file starts |
| 445 |
pub header_start: u64, |
| 446 |
/// Specifies where the extra data of the file starts |
| 447 |
pub extra_data_start: Option<u64>, |
| 448 |
/// Specifies where the central header of the file starts |
| 449 |
/// |
| 450 |
/// Note that when this is not known, it is set to 0 |
| 451 |
pub central_header_start: u64, |
| 452 |
/// Specifies where the compressed data of the file starts |
| 453 |
pub data_start: OnceLock<u64>, |
| 454 |
/// External file attributes |
| 455 |
pub external_attributes: u32, |
| 456 |
/// Reserve local ZIP64 extra field |
| 457 |
pub large_file: bool, |
| 458 |
/// AES mode if applicable |
| 459 |
pub aes_mode: Option<(AesMode, AesVendorVersion, CompressionMethod)>, |
| 460 |
/// Specifies where in the extra data the AES metadata starts |
| 461 |
pub aes_extra_data_start: u64, |
| 462 |
|
| 463 |
/// extra fields, see <https://libzip.org/specifications/extrafld.txt> |
| 464 |
pub extra_fields: Vec<ExtraField>, |
| 465 |
} |
| 466 |
|
| 467 |
impl ZipFileData { |
| 468 |
#[allow(dead_code)] |
| 469 |
pub fn is_dir(&self) -> bool { |
| 470 |
is_dir(&self.file_name) |
| 471 |
} |
| 472 |
|
| 473 |
pub fn file_name_sanitized(&self) -> PathBuf { |
| 474 |
let no_null_filename = match self.file_name.find('\0') { |
| 475 |
Some(index) => &self.file_name[0..index], |
| 476 |
None => &self.file_name, |
| 477 |
} |
| 478 |
.to_string(); |
| 479 |
|
| 480 |
// zip files can contain both / and \ as separators regardless of the OS |
| 481 |
// and as we want to return a sanitized PathBuf that only supports the |
| 482 |
// OS separator let's convert incompatible separators to compatible ones |
| 483 |
let separator = path::MAIN_SEPARATOR; |
| 484 |
let opposite_separator = match separator { |
| 485 |
'/' => '\\', |
| 486 |
_ => '/', |
| 487 |
}; |
| 488 |
let filename = |
| 489 |
no_null_filename.replace(&opposite_separator.to_string(), &separator.to_string()); |
| 490 |
|
| 491 |
Path::new(&filename) |
| 492 |
.components() |
| 493 |
.filter(|component| matches!(*component, Component::Normal(..))) |
| 494 |
.fold(PathBuf::new(), |mut path, ref cur| { |
| 495 |
path.push(cur.as_os_str()); |
| 496 |
path |
| 497 |
}) |
| 498 |
} |
| 499 |
|
| 500 |
pub(crate) fn enclosed_name(&self) -> Option<PathBuf> { |
| 501 |
if self.file_name.contains('\0') { |
| 502 |
return None; |
| 503 |
} |
| 504 |
let path = PathBuf::from(self.file_name.to_string()); |
| 505 |
let mut depth = 0usize; |
| 506 |
for component in path.components() { |
| 507 |
match component { |
| 508 |
Component::Prefix(_) | Component::RootDir => return None, |
| 509 |
Component::ParentDir => depth = depth.checked_sub(1)?, |
| 510 |
Component::Normal(_) => depth += 1, |
| 511 |
Component::CurDir => (), |
| 512 |
} |
| 513 |
} |
| 514 |
Some(path) |
| 515 |
} |
| 516 |
|
| 517 |
/// Get unix mode for the file |
| 518 |
pub(crate) const fn unix_mode(&self) -> Option<u32> { |
| 519 |
if self.external_attributes == 0 { |
| 520 |
return None; |
| 521 |
} |
| 522 |
|
| 523 |
match self.system { |
| 524 |
System::Unix => Some(self.external_attributes >> 16), |
| 525 |
System::Dos => { |
| 526 |
// Interpret MS-DOS directory bit |
| 527 |
let mut mode = if 0x10 == (self.external_attributes & 0x10) { |
| 528 |
ffi::S_IFDIR | 0o0775 |
| 529 |
} else { |
| 530 |
ffi::S_IFREG | 0o0664 |
| 531 |
}; |
| 532 |
if 0x01 == (self.external_attributes & 0x01) { |
| 533 |
// Read-only bit; strip write permissions |
| 534 |
mode &= 0o0555; |
| 535 |
} |
| 536 |
Some(mode) |
| 537 |
} |
| 538 |
_ => None, |
| 539 |
} |
| 540 |
} |
| 541 |
|
| 542 |
/// PKZIP version needed to open this file (from APPNOTE 4.4.3.2). |
| 543 |
pub fn version_needed(&self) -> u16 { |
| 544 |
let compression_version: u16 = match self.compression_method { |
| 545 |
CompressionMethod::Stored => MIN_VERSION.into(), |
| 546 |
#[cfg(feature = "_deflate-any")] |
| 547 |
CompressionMethod::Deflated => 20, |
| 548 |
#[cfg(feature = "bzip2")] |
| 549 |
CompressionMethod::Bzip2 => 46, |
| 550 |
#[cfg(feature = "deflate64")] |
| 551 |
CompressionMethod::Deflate64 => 21, |
| 552 |
#[cfg(feature = "lzma")] |
| 553 |
CompressionMethod::Lzma => 63, |
| 554 |
// APPNOTE doesn't specify a version for Zstandard |
| 555 |
_ => DEFAULT_VERSION as u16, |
| 556 |
}; |
| 557 |
let crypto_version: u16 = if self.aes_mode.is_some() { |
| 558 |
51 |
| 559 |
} else if self.encrypted { |
| 560 |
20 |
| 561 |
} else { |
| 562 |
10 |
| 563 |
}; |
| 564 |
let misc_feature_version: u16 = if self.large_file { |
| 565 |
45 |
| 566 |
} else if self |
| 567 |
.unix_mode() |
| 568 |
.is_some_and(|mode| mode & S_IFDIR == S_IFDIR) |
| 569 |
{ |
| 570 |
// file is directory |
| 571 |
20 |
| 572 |
} else { |
| 573 |
10 |
| 574 |
}; |
| 575 |
compression_version |
| 576 |
.max(crypto_version) |
| 577 |
.max(misc_feature_version) |
| 578 |
} |
| 579 |
#[inline(always)] |
| 580 |
pub(crate) fn extra_field_len(&self) -> usize { |
| 581 |
self.extra_field |
| 582 |
.as_ref() |
| 583 |
.map(|v| v.len()) |
| 584 |
.unwrap_or_default() |
| 585 |
} |
| 586 |
#[inline(always)] |
| 587 |
pub(crate) fn central_extra_field_len(&self) -> usize { |
| 588 |
self.central_extra_field |
| 589 |
.as_ref() |
| 590 |
.map(|v| v.len()) |
| 591 |
.unwrap_or_default() |
| 592 |
} |
| 593 |
|
| 594 |
#[allow(clippy::too_many_arguments)] |
| 595 |
pub(crate) fn initialize_local_block<S, T: FileOptionExtension>( |
| 596 |
name: S, |
| 597 |
options: &FileOptions<T>, |
| 598 |
raw_values: ZipRawValues, |
| 599 |
header_start: u64, |
| 600 |
extra_data_start: Option<u64>, |
| 601 |
aes_extra_data_start: u64, |
| 602 |
compression_method: crate::compression::CompressionMethod, |
| 603 |
aes_mode: Option<(AesMode, AesVendorVersion, CompressionMethod)>, |
| 604 |
extra_field: Option<Arc<Vec<u8>>>, |
| 605 |
) -> Self |
| 606 |
where |
| 607 |
S: Into<Box<str>>, |
| 608 |
{ |
| 609 |
let permissions = options.permissions.unwrap_or(0o100644); |
| 610 |
let file_name: Box<str> = name.into(); |
| 611 |
let file_name_raw: Box<[u8]> = file_name.bytes().collect(); |
| 612 |
let mut local_block = ZipFileData { |
| 613 |
system: System::Unix, |
| 614 |
version_made_by: DEFAULT_VERSION, |
| 615 |
encrypted: options.encrypt_with.is_some(), |
| 616 |
using_data_descriptor: false, |
| 617 |
is_utf8: !file_name.is_ascii(), |
| 618 |
compression_method, |
| 619 |
compression_level: options.compression_level, |
| 620 |
last_modified_time: Some(options.last_modified_time), |
| 621 |
crc32: raw_values.crc32, |
| 622 |
compressed_size: raw_values.compressed_size, |
| 623 |
uncompressed_size: raw_values.uncompressed_size, |
| 624 |
file_name, // Never used for saving, but used as map key in insert_file_data() |
| 625 |
file_name_raw, |
| 626 |
extra_field, |
| 627 |
central_extra_field: options.extended_options.central_extra_data().cloned(), |
| 628 |
file_comment: String::with_capacity(0).into_boxed_str(), |
| 629 |
header_start, |
| 630 |
data_start: OnceLock::new(), |
| 631 |
central_header_start: 0, |
| 632 |
external_attributes: permissions << 16, |
| 633 |
large_file: options.large_file, |
| 634 |
aes_mode, |
| 635 |
extra_fields: Vec::new(), |
| 636 |
extra_data_start, |
| 637 |
aes_extra_data_start, |
| 638 |
}; |
| 639 |
local_block.version_made_by = local_block.version_needed() as u8; |
| 640 |
local_block |
| 641 |
} |
| 642 |
|
| 643 |
pub(crate) fn from_local_block<R: std::io::Read>( |
| 644 |
block: ZipLocalEntryBlock, |
| 645 |
reader: &mut R, |
| 646 |
) -> ZipResult<Self> { |
| 647 |
let ZipLocalEntryBlock { |
| 648 |
// magic, |
| 649 |
version_made_by, |
| 650 |
flags, |
| 651 |
compression_method, |
| 652 |
last_mod_time, |
| 653 |
last_mod_date, |
| 654 |
crc32, |
| 655 |
compressed_size, |
| 656 |
uncompressed_size, |
| 657 |
file_name_length, |
| 658 |
extra_field_length, |
| 659 |
.. |
| 660 |
} = block; |
| 661 |
|
| 662 |
let encrypted: bool = flags & 1 == 1; |
| 663 |
if encrypted { |
| 664 |
return Err(ZipError::UnsupportedArchive( |
| 665 |
"Encrypted files are not supported", |
| 666 |
)); |
| 667 |
} |
| 668 |
|
| 669 |
/* FIXME: these were previously incorrect: add testing! */ |
| 670 |
/* flags & (1 << 3) != 0 */ |
| 671 |
let using_data_descriptor: bool = flags & (1 << 3) == 1 << 3; |
| 672 |
if using_data_descriptor { |
| 673 |
return Err(ZipError::UnsupportedArchive( |
| 674 |
"The file length is not available in the local header", |
| 675 |
)); |
| 676 |
} |
| 677 |
|
| 678 |
/* flags & (1 << 1) != 0 */ |
| 679 |
let is_utf8: bool = flags & (1 << 11) != 0; |
| 680 |
let compression_method = crate::CompressionMethod::parse_from_u16(compression_method); |
| 681 |
let file_name_length: usize = file_name_length.into(); |
| 682 |
let extra_field_length: usize = extra_field_length.into(); |
| 683 |
|
| 684 |
let mut file_name_raw = vec![0u8; file_name_length]; |
| 685 |
reader.read_exact(&mut file_name_raw)?; |
| 686 |
let mut extra_field = vec![0u8; extra_field_length]; |
| 687 |
reader.read_exact(&mut extra_field)?; |
| 688 |
|
| 689 |
let file_name: Box<str> = match is_utf8 { |
| 690 |
true => String::from_utf8_lossy(&file_name_raw).into(), |
| 691 |
false => file_name_raw.clone().from_cp437().into(), |
| 692 |
}; |
| 693 |
|
| 694 |
let system: u8 = (version_made_by >> 8).try_into().unwrap(); |
| 695 |
Ok(ZipFileData { |
| 696 |
system: System::from(system), |
| 697 |
/* NB: this strips the top 8 bits! */ |
| 698 |
version_made_by: version_made_by as u8, |
| 699 |
encrypted, |
| 700 |
using_data_descriptor, |
| 701 |
is_utf8, |
| 702 |
compression_method, |
| 703 |
compression_level: None, |
| 704 |
last_modified_time: DateTime::try_from_msdos(last_mod_date, last_mod_time).ok(), |
| 705 |
crc32, |
| 706 |
compressed_size: compressed_size.into(), |
| 707 |
uncompressed_size: uncompressed_size.into(), |
| 708 |
file_name, |
| 709 |
file_name_raw: file_name_raw.into(), |
| 710 |
extra_field: Some(Arc::new(extra_field)), |
| 711 |
central_extra_field: None, |
| 712 |
file_comment: String::with_capacity(0).into_boxed_str(), // file comment is only available in the central directory |
| 713 |
// header_start and data start are not available, but also don't matter, since seeking is |
| 714 |
// not available. |
| 715 |
header_start: 0, |
| 716 |
data_start: OnceLock::new(), |
| 717 |
central_header_start: 0, |
| 718 |
// The external_attributes field is only available in the central directory. |
| 719 |
// We set this to zero, which should be valid as the docs state 'If input came |
| 720 |
// from standard input, this field is set to zero.' |
| 721 |
external_attributes: 0, |
| 722 |
large_file: false, |
| 723 |
aes_mode: None, |
| 724 |
extra_fields: Vec::new(), |
| 725 |
extra_data_start: None, |
| 726 |
aes_extra_data_start: 0, |
| 727 |
}) |
| 728 |
} |
| 729 |
|
| 730 |
fn is_utf8(&self) -> bool { |
| 731 |
std::str::from_utf8(&self.file_name_raw).is_ok() |
| 732 |
} |
| 733 |
|
| 734 |
fn is_ascii(&self) -> bool { |
| 735 |
self.file_name_raw.is_ascii() |
| 736 |
} |
| 737 |
|
| 738 |
fn flags(&self) -> u16 { |
| 739 |
let utf8_bit: u16 = if self.is_utf8() && !self.is_ascii() { |
| 740 |
1u16 << 11 |
| 741 |
} else { |
| 742 |
0 |
| 743 |
}; |
| 744 |
let encrypted_bit: u16 = if self.encrypted { 1u16 << 0 } else { 0 }; |
| 745 |
|
| 746 |
utf8_bit | encrypted_bit |
| 747 |
} |
| 748 |
|
| 749 |
fn clamp_size_field(&self, field: u64) -> u32 { |
| 750 |
if self.large_file { |
| 751 |
spec::ZIP64_BYTES_THR as u32 |
| 752 |
} else { |
| 753 |
field.min(spec::ZIP64_BYTES_THR).try_into().unwrap() |
| 754 |
} |
| 755 |
} |
| 756 |
|
| 757 |
pub(crate) fn local_block(&self) -> ZipResult<ZipLocalEntryBlock> { |
| 758 |
let compressed_size: u32 = self.clamp_size_field(self.compressed_size); |
| 759 |
let uncompressed_size: u32 = self.clamp_size_field(self.uncompressed_size); |
| 760 |
|
| 761 |
let extra_block_len: usize = self |
| 762 |
.zip64_extra_field_block() |
| 763 |
.map(|block| block.full_size()) |
| 764 |
.unwrap_or(0); |
| 765 |
let extra_field_length: u16 = (self.extra_field_len() + extra_block_len) |
| 766 |
.try_into() |
| 767 |
.map_err(|_| ZipError::InvalidArchive("Extra data field is too large"))?; |
| 768 |
|
| 769 |
let last_modified_time = self |
| 770 |
.last_modified_time |
| 771 |
.unwrap_or_else(DateTime::default_for_write); |
| 772 |
Ok(ZipLocalEntryBlock { |
| 773 |
magic: ZipLocalEntryBlock::MAGIC, |
| 774 |
version_made_by: self.version_needed(), |
| 775 |
flags: self.flags(), |
| 776 |
compression_method: self.compression_method.serialize_to_u16(), |
| 777 |
last_mod_time: last_modified_time.timepart(), |
| 778 |
last_mod_date: last_modified_time.datepart(), |
| 779 |
crc32: self.crc32, |
| 780 |
compressed_size, |
| 781 |
uncompressed_size, |
| 782 |
file_name_length: self.file_name_raw.len().try_into().unwrap(), |
| 783 |
extra_field_length, |
| 784 |
}) |
| 785 |
} |
| 786 |
|
| 787 |
pub(crate) fn block(&self, zip64_extra_field_length: u16) -> ZipCentralEntryBlock { |
| 788 |
let extra_field_len: u16 = self.extra_field_len().try_into().unwrap(); |
| 789 |
let central_extra_field_len: u16 = self.central_extra_field_len().try_into().unwrap(); |
| 790 |
let last_modified_time = self |
| 791 |
.last_modified_time |
| 792 |
.unwrap_or_else(DateTime::default_for_write); |
| 793 |
ZipCentralEntryBlock { |
| 794 |
magic: ZipCentralEntryBlock::MAGIC, |
| 795 |
version_made_by: (self.system as u16) << 8 |
| 796 |
| (self.version_made_by as u16).max(self.version_needed()), |
| 797 |
version_to_extract: self.version_needed(), |
| 798 |
flags: self.flags(), |
| 799 |
compression_method: self.compression_method.serialize_to_u16(), |
| 800 |
last_mod_time: last_modified_time.timepart(), |
| 801 |
last_mod_date: last_modified_time.datepart(), |
| 802 |
crc32: self.crc32, |
| 803 |
compressed_size: self |
| 804 |
.compressed_size |
| 805 |
.min(spec::ZIP64_BYTES_THR) |
| 806 |
.try_into() |
| 807 |
.unwrap(), |
| 808 |
uncompressed_size: self |
| 809 |
.uncompressed_size |
| 810 |
.min(spec::ZIP64_BYTES_THR) |
| 811 |
.try_into() |
| 812 |
.unwrap(), |
| 813 |
file_name_length: self.file_name_raw.len().try_into().unwrap(), |
| 814 |
extra_field_length: zip64_extra_field_length |
| 815 |
+ extra_field_len |
| 816 |
+ central_extra_field_len, |
| 817 |
file_comment_length: self.file_comment.as_bytes().len().try_into().unwrap(), |
| 818 |
disk_number: 0, |
| 819 |
internal_file_attributes: 0, |
| 820 |
external_file_attributes: self.external_attributes, |
| 821 |
offset: self |
| 822 |
.header_start |
| 823 |
.min(spec::ZIP64_BYTES_THR) |
| 824 |
.try_into() |
| 825 |
.unwrap(), |
| 826 |
} |
| 827 |
} |
| 828 |
|
| 829 |
pub(crate) fn zip64_extra_field_block(&self) -> Option<Zip64ExtraFieldBlock> { |
| 830 |
let uncompressed_size: Option<u64> = |
| 831 |
if self.uncompressed_size >= spec::ZIP64_BYTES_THR || self.large_file { |
| 832 |
Some(spec::ZIP64_BYTES_THR) |
| 833 |
} else { |
| 834 |
None |
| 835 |
}; |
| 836 |
let compressed_size: Option<u64> = |
| 837 |
if self.compressed_size >= spec::ZIP64_BYTES_THR || self.large_file { |
| 838 |
Some(spec::ZIP64_BYTES_THR) |
| 839 |
} else { |
| 840 |
None |
| 841 |
}; |
| 842 |
let header_start: Option<u64> = if self.header_start >= spec::ZIP64_BYTES_THR { |
| 843 |
Some(spec::ZIP64_BYTES_THR) |
| 844 |
} else { |
| 845 |
None |
| 846 |
}; |
| 847 |
|
| 848 |
let mut size: u16 = 0; |
| 849 |
if uncompressed_size.is_some() { |
| 850 |
size += mem::size_of::<u64>() as u16; |
| 851 |
} |
| 852 |
if compressed_size.is_some() { |
| 853 |
size += mem::size_of::<u64>() as u16; |
| 854 |
} |
| 855 |
if header_start.is_some() { |
| 856 |
size += mem::size_of::<u64>() as u16; |
| 857 |
} |
| 858 |
if size == 0 { |
| 859 |
return None; |
| 860 |
} |
| 861 |
|
| 862 |
Some(Zip64ExtraFieldBlock { |
| 863 |
magic: spec::ExtraFieldMagic::ZIP64_EXTRA_FIELD_TAG, |
| 864 |
size, |
| 865 |
uncompressed_size, |
| 866 |
compressed_size, |
| 867 |
header_start, |
| 868 |
}) |
| 869 |
} |
| 870 |
} |
| 871 |
|
| 872 |
#[derive(Copy, Clone, Debug)] |
| 873 |
#[repr(packed)] |
| 874 |
pub(crate) struct ZipCentralEntryBlock { |
| 875 |
magic: spec::Magic, |
| 876 |
pub version_made_by: u16, |
| 877 |
pub version_to_extract: u16, |
| 878 |
pub flags: u16, |
| 879 |
pub compression_method: u16, |
| 880 |
pub last_mod_time: u16, |
| 881 |
pub last_mod_date: u16, |
| 882 |
pub crc32: u32, |
| 883 |
pub compressed_size: u32, |
| 884 |
pub uncompressed_size: u32, |
| 885 |
pub file_name_length: u16, |
| 886 |
pub extra_field_length: u16, |
| 887 |
pub file_comment_length: u16, |
| 888 |
pub disk_number: u16, |
| 889 |
pub internal_file_attributes: u16, |
| 890 |
pub external_file_attributes: u32, |
| 891 |
pub offset: u32, |
| 892 |
} |
| 893 |
|
| 894 |
impl FixedSizeBlock for ZipCentralEntryBlock { |
| 895 |
const MAGIC: spec::Magic = spec::Magic::CENTRAL_DIRECTORY_HEADER_SIGNATURE; |
| 896 |
|
| 897 |
#[inline(always)] |
| 898 |
fn magic(self) -> spec::Magic { |
| 899 |
self.magic |
| 900 |
} |
| 901 |
|
| 902 |
const WRONG_MAGIC_ERROR: ZipError = |
| 903 |
ZipError::InvalidArchive("Invalid Central Directory header"); |
| 904 |
|
| 905 |
to_and_from_le![ |
| 906 |
(magic, spec::Magic), |
| 907 |
(version_made_by, u16), |
| 908 |
(version_to_extract, u16), |
| 909 |
(flags, u16), |
| 910 |
(compression_method, u16), |
| 911 |
(last_mod_time, u16), |
| 912 |
(last_mod_date, u16), |
| 913 |
(crc32, u32), |
| 914 |
(compressed_size, u32), |
| 915 |
(uncompressed_size, u32), |
| 916 |
(file_name_length, u16), |
| 917 |
(extra_field_length, u16), |
| 918 |
(file_comment_length, u16), |
| 919 |
(disk_number, u16), |
| 920 |
(internal_file_attributes, u16), |
| 921 |
(external_file_attributes, u32), |
| 922 |
(offset, u32), |
| 923 |
]; |
| 924 |
} |
| 925 |
|
| 926 |
#[derive(Copy, Clone, Debug)] |
| 927 |
#[repr(packed)] |
| 928 |
pub(crate) struct ZipLocalEntryBlock { |
| 929 |
magic: spec::Magic, |
| 930 |
pub version_made_by: u16, |
| 931 |
pub flags: u16, |
| 932 |
pub compression_method: u16, |
| 933 |
pub last_mod_time: u16, |
| 934 |
pub last_mod_date: u16, |
| 935 |
pub crc32: u32, |
| 936 |
pub compressed_size: u32, |
| 937 |
pub uncompressed_size: u32, |
| 938 |
pub file_name_length: u16, |
| 939 |
pub extra_field_length: u16, |
| 940 |
} |
| 941 |
|
| 942 |
impl FixedSizeBlock for ZipLocalEntryBlock { |
| 943 |
const MAGIC: spec::Magic = spec::Magic::LOCAL_FILE_HEADER_SIGNATURE; |
| 944 |
|
| 945 |
#[inline(always)] |
| 946 |
fn magic(self) -> spec::Magic { |
| 947 |
self.magic |
| 948 |
} |
| 949 |
|
| 950 |
const WRONG_MAGIC_ERROR: ZipError = ZipError::InvalidArchive("Invalid local file header"); |
| 951 |
|
| 952 |
to_and_from_le![ |
| 953 |
(magic, spec::Magic), |
| 954 |
(version_made_by, u16), |
| 955 |
(flags, u16), |
| 956 |
(compression_method, u16), |
| 957 |
(last_mod_time, u16), |
| 958 |
(last_mod_date, u16), |
| 959 |
(crc32, u32), |
| 960 |
(compressed_size, u32), |
| 961 |
(uncompressed_size, u32), |
| 962 |
(file_name_length, u16), |
| 963 |
(extra_field_length, u16), |
| 964 |
]; |
| 965 |
} |
| 966 |
|
| 967 |
#[derive(Copy, Clone, Debug)] |
| 968 |
pub(crate) struct Zip64ExtraFieldBlock { |
| 969 |
magic: spec::ExtraFieldMagic, |
| 970 |
size: u16, |
| 971 |
uncompressed_size: Option<u64>, |
| 972 |
compressed_size: Option<u64>, |
| 973 |
header_start: Option<u64>, |
| 974 |
// Excluded fields: |
| 975 |
// u32: disk start number |
| 976 |
} |
| 977 |
|
| 978 |
impl Zip64ExtraFieldBlock { |
| 979 |
pub fn full_size(&self) -> usize { |
| 980 |
assert!(self.size > 0); |
| 981 |
self.size as usize + mem::size_of::<spec::ExtraFieldMagic>() + mem::size_of::<u16>() |
| 982 |
} |
| 983 |
|
| 984 |
pub fn serialize(self) -> Box<[u8]> { |
| 985 |
let Self { |
| 986 |
magic, |
| 987 |
size, |
| 988 |
uncompressed_size, |
| 989 |
compressed_size, |
| 990 |
header_start, |
| 991 |
} = self; |
| 992 |
|
| 993 |
let full_size = self.full_size(); |
| 994 |
|
| 995 |
let mut ret = Vec::with_capacity(full_size); |
| 996 |
ret.extend(magic.to_le_bytes()); |
| 997 |
ret.extend(u16::to_le_bytes(size)); |
| 998 |
|
| 999 |
if let Some(uncompressed_size) = uncompressed_size { |
| 1000 |
ret.extend(u64::to_le_bytes(uncompressed_size)); |
| 1001 |
} |
| 1002 |
if let Some(compressed_size) = compressed_size { |
| 1003 |
ret.extend(u64::to_le_bytes(compressed_size)); |
| 1004 |
} |
| 1005 |
if let Some(header_start) = header_start { |
| 1006 |
ret.extend(u64::to_le_bytes(header_start)); |
| 1007 |
} |
| 1008 |
debug_assert_eq!(ret.len(), full_size); |
| 1009 |
|
| 1010 |
ret.into_boxed_slice() |
| 1011 |
} |
| 1012 |
} |
| 1013 |
|
| 1014 |
/// The encryption specification used to encrypt a file with AES. |
| 1015 |
/// |
| 1016 |
/// According to the [specification](https://www.winzip.com/win/en/aes_info.html#winzip11) AE-2 |
| 1017 |
/// does not make use of the CRC check. |
| 1018 |
#[derive(Copy, Clone, Debug)] |
| 1019 |
#[repr(u16)] |
| 1020 |
pub enum AesVendorVersion { |
| 1021 |
Ae1 = 0x0001, |
| 1022 |
Ae2 = 0x0002, |
| 1023 |
} |
| 1024 |
|
| 1025 |
/// AES variant used. |
| 1026 |
#[derive(Copy, Clone, Debug)] |
| 1027 |
#[cfg_attr(fuzzing, derive(arbitrary::Arbitrary))] |
| 1028 |
#[repr(u8)] |
| 1029 |
pub enum AesMode { |
| 1030 |
/// 128-bit AES encryption. |
| 1031 |
Aes128 = 0x01, |
| 1032 |
/// 192-bit AES encryption. |
| 1033 |
Aes192 = 0x02, |
| 1034 |
/// 256-bit AES encryption. |
| 1035 |
Aes256 = 0x03, |
| 1036 |
} |
| 1037 |
|
| 1038 |
#[cfg(feature = "aes-crypto")] |
| 1039 |
impl AesMode { |
| 1040 |
/// Length of the salt for the given AES mode. |
| 1041 |
pub const fn salt_length(&self) -> usize { |
| 1042 |
self.key_length() / 2 |
| 1043 |
} |
| 1044 |
|
| 1045 |
/// Length of the key for the given AES mode. |
| 1046 |
pub const fn key_length(&self) -> usize { |
| 1047 |
match self { |
| 1048 |
Self::Aes128 => 16, |
| 1049 |
Self::Aes192 => 24, |
| 1050 |
Self::Aes256 => 32, |
| 1051 |
} |
| 1052 |
} |
| 1053 |
} |
| 1054 |
|
| 1055 |
#[cfg(test)] |
| 1056 |
mod test { |
| 1057 |
#[test] |
| 1058 |
fn system() { |
| 1059 |
use super::System; |
| 1060 |
assert_eq!(u8::from(System::Dos), 0u8); |
| 1061 |
assert_eq!(System::Dos as u8, 0u8); |
| 1062 |
assert_eq!(System::Unix as u8, 3u8); |
| 1063 |
assert_eq!(u8::from(System::Unix), 3u8); |
| 1064 |
assert_eq!(System::from(0), System::Dos); |
| 1065 |
assert_eq!(System::from(3), System::Unix); |
| 1066 |
assert_eq!(u8::from(System::Unknown), 4u8); |
| 1067 |
assert_eq!(System::Unknown as u8, 4u8); |
| 1068 |
} |
| 1069 |
|
| 1070 |
#[test] |
| 1071 |
fn sanitize() { |
| 1072 |
use super::*; |
| 1073 |
let file_name = "/path/../../../../etc/./passwd\0/etc/shadow".to_string(); |
| 1074 |
let data = ZipFileData { |
| 1075 |
system: System::Dos, |
| 1076 |
version_made_by: 0, |
| 1077 |
encrypted: false, |
| 1078 |
using_data_descriptor: false, |
| 1079 |
is_utf8: true, |
| 1080 |
compression_method: crate::compression::CompressionMethod::Stored, |
| 1081 |
compression_level: None, |
| 1082 |
last_modified_time: None, |
| 1083 |
crc32: 0, |
| 1084 |
compressed_size: 0, |
| 1085 |
uncompressed_size: 0, |
| 1086 |
file_name: file_name.clone().into_boxed_str(), |
| 1087 |
file_name_raw: file_name.into_bytes().into_boxed_slice(), |
| 1088 |
extra_field: None, |
| 1089 |
central_extra_field: None, |
| 1090 |
file_comment: String::with_capacity(0).into_boxed_str(), |
| 1091 |
header_start: 0, |
| 1092 |
extra_data_start: None, |
| 1093 |
data_start: OnceLock::new(), |
| 1094 |
central_header_start: 0, |
| 1095 |
external_attributes: 0, |
| 1096 |
large_file: false, |
| 1097 |
aes_mode: None, |
| 1098 |
aes_extra_data_start: 0, |
| 1099 |
extra_fields: Vec::new(), |
| 1100 |
}; |
| 1101 |
assert_eq!(data.file_name_sanitized(), PathBuf::from("path/etc/passwd")); |
| 1102 |
} |
| 1103 |
|
| 1104 |
#[test] |
| 1105 |
#[allow(clippy::unusual_byte_groupings)] |
| 1106 |
fn datetime_default() { |
| 1107 |
use super::DateTime; |
| 1108 |
let dt = DateTime::default(); |
| 1109 |
assert_eq!(dt.timepart(), 0); |
| 1110 |
assert_eq!(dt.datepart(), 0b0000000_0001_00001); |
| 1111 |
} |
| 1112 |
|
| 1113 |
#[test] |
| 1114 |
#[allow(clippy::unusual_byte_groupings)] |
| 1115 |
fn datetime_max() { |
| 1116 |
use super::DateTime; |
| 1117 |
let dt = DateTime::from_date_and_time(2107, 12, 31, 23, 59, 58).unwrap(); |
| 1118 |
assert_eq!(dt.timepart(), 0b10111_111011_11101); |
| 1119 |
assert_eq!(dt.datepart(), 0b1111111_1100_11111); |
| 1120 |
} |
| 1121 |
|
| 1122 |
#[test] |
| 1123 |
fn datetime_equality() { |
| 1124 |
use super::DateTime; |
| 1125 |
|
| 1126 |
let dt = DateTime::from_date_and_time(2018, 11, 17, 10, 38, 30).unwrap(); |
| 1127 |
assert_eq!( |
| 1128 |
dt, |
| 1129 |
DateTime::from_date_and_time(2018, 11, 17, 10, 38, 30).unwrap() |
| 1130 |
); |
| 1131 |
assert_ne!(dt, DateTime::default()); |
| 1132 |
} |
| 1133 |
|
| 1134 |
#[test] |
| 1135 |
fn datetime_order() { |
| 1136 |
use std::cmp::Ordering; |
| 1137 |
|
| 1138 |
use super::DateTime; |
| 1139 |
|
| 1140 |
let dt = DateTime::from_date_and_time(2018, 11, 17, 10, 38, 30).unwrap(); |
| 1141 |
assert_eq!( |
| 1142 |
dt.cmp(&DateTime::from_date_and_time(2018, 11, 17, 10, 38, 30).unwrap()), |
| 1143 |
Ordering::Equal |
| 1144 |
); |
| 1145 |
// year |
| 1146 |
assert!(dt < DateTime::from_date_and_time(2019, 11, 17, 10, 38, 30).unwrap()); |
| 1147 |
assert!(dt > DateTime::from_date_and_time(2017, 11, 17, 10, 38, 30).unwrap()); |
| 1148 |
// month |
| 1149 |
assert!(dt < DateTime::from_date_and_time(2018, 12, 17, 10, 38, 30).unwrap()); |
| 1150 |
assert!(dt > DateTime::from_date_and_time(2018, 10, 17, 10, 38, 30).unwrap()); |
| 1151 |
// day |
| 1152 |
assert!(dt < DateTime::from_date_and_time(2018, 11, 18, 10, 38, 30).unwrap()); |
| 1153 |
assert!(dt > DateTime::from_date_and_time(2018, 11, 16, 10, 38, 30).unwrap()); |
| 1154 |
// hour |
| 1155 |
assert!(dt < DateTime::from_date_and_time(2018, 11, 17, 11, 38, 30).unwrap()); |
| 1156 |
assert!(dt > DateTime::from_date_and_time(2018, 11, 17, 9, 38, 30).unwrap()); |
| 1157 |
// minute |
| 1158 |
assert!(dt < DateTime::from_date_and_time(2018, 11, 17, 10, 39, 30).unwrap()); |
| 1159 |
assert!(dt > DateTime::from_date_and_time(2018, 11, 17, 10, 37, 30).unwrap()); |
| 1160 |
// second |
| 1161 |
assert!(dt < DateTime::from_date_and_time(2018, 11, 17, 10, 38, 31).unwrap()); |
| 1162 |
assert!(dt > DateTime::from_date_and_time(2018, 11, 17, 10, 38, 29).unwrap()); |
| 1163 |
} |
| 1164 |
|
| 1165 |
#[test] |
| 1166 |
fn datetime_display() { |
| 1167 |
use super::DateTime; |
| 1168 |
|
| 1169 |
assert_eq!(format!("{}", DateTime::default()), "1980-01-01 00:00:00"); |
| 1170 |
assert_eq!( |
| 1171 |
format!( |
| 1172 |
"{}", |
| 1173 |
DateTime::from_date_and_time(2018, 11, 17, 10, 38, 30).unwrap() |
| 1174 |
), |
| 1175 |
"2018-11-17 10:38:30" |
| 1176 |
); |
| 1177 |
assert_eq!( |
| 1178 |
format!( |
| 1179 |
"{}", |
| 1180 |
DateTime::from_date_and_time(2107, 12, 31, 23, 59, 58).unwrap() |
| 1181 |
), |
| 1182 |
"2107-12-31 23:59:58" |
| 1183 |
); |
| 1184 |
} |
| 1185 |
|
| 1186 |
#[test] |
| 1187 |
fn datetime_bounds() { |
| 1188 |
use super::DateTime; |
| 1189 |
|
| 1190 |
assert!(DateTime::from_date_and_time(2000, 1, 1, 23, 59, 60).is_ok()); |
| 1191 |
assert!(DateTime::from_date_and_time(2000, 1, 1, 24, 0, 0).is_err()); |
| 1192 |
assert!(DateTime::from_date_and_time(2000, 1, 1, 0, 60, 0).is_err()); |
| 1193 |
assert!(DateTime::from_date_and_time(2000, 1, 1, 0, 0, 61).is_err()); |
| 1194 |
|
| 1195 |
assert!(DateTime::from_date_and_time(2107, 12, 31, 0, 0, 0).is_ok()); |
| 1196 |
assert!(DateTime::from_date_and_time(1980, 1, 1, 0, 0, 0).is_ok()); |
| 1197 |
assert!(DateTime::from_date_and_time(1979, 1, 1, 0, 0, 0).is_err()); |
| 1198 |
assert!(DateTime::from_date_and_time(1980, 0, 1, 0, 0, 0).is_err()); |
| 1199 |
assert!(DateTime::from_date_and_time(1980, 1, 0, 0, 0, 0).is_err()); |
| 1200 |
assert!(DateTime::from_date_and_time(2108, 12, 31, 0, 0, 0).is_err()); |
| 1201 |
assert!(DateTime::from_date_and_time(2107, 13, 31, 0, 0, 0).is_err()); |
| 1202 |
assert!(DateTime::from_date_and_time(2107, 12, 32, 0, 0, 0).is_err()); |
| 1203 |
|
| 1204 |
assert!(DateTime::from_date_and_time(2018, 1, 31, 0, 0, 0).is_ok()); |
| 1205 |
assert!(DateTime::from_date_and_time(2018, 2, 28, 0, 0, 0).is_ok()); |
| 1206 |
assert!(DateTime::from_date_and_time(2018, 2, 29, 0, 0, 0).is_err()); |
| 1207 |
assert!(DateTime::from_date_and_time(2018, 3, 31, 0, 0, 0).is_ok()); |
| 1208 |
assert!(DateTime::from_date_and_time(2018, 4, 30, 0, 0, 0).is_ok()); |
| 1209 |
assert!(DateTime::from_date_and_time(2018, 4, 31, 0, 0, 0).is_err()); |
| 1210 |
assert!(DateTime::from_date_and_time(2018, 5, 31, 0, 0, 0).is_ok()); |
| 1211 |
assert!(DateTime::from_date_and_time(2018, 6, 30, 0, 0, 0).is_ok()); |
| 1212 |
assert!(DateTime::from_date_and_time(2018, 6, 31, 0, 0, 0).is_err()); |
| 1213 |
assert!(DateTime::from_date_and_time(2018, 7, 31, 0, 0, 0).is_ok()); |
| 1214 |
assert!(DateTime::from_date_and_time(2018, 8, 31, 0, 0, 0).is_ok()); |
| 1215 |
assert!(DateTime::from_date_and_time(2018, 9, 30, 0, 0, 0).is_ok()); |
| 1216 |
assert!(DateTime::from_date_and_time(2018, 9, 31, 0, 0, 0).is_err()); |
| 1217 |
assert!(DateTime::from_date_and_time(2018, 10, 31, 0, 0, 0).is_ok()); |
| 1218 |
assert!(DateTime::from_date_and_time(2018, 11, 30, 0, 0, 0).is_ok()); |
| 1219 |
assert!(DateTime::from_date_and_time(2018, 11, 31, 0, 0, 0).is_err()); |
| 1220 |
assert!(DateTime::from_date_and_time(2018, 12, 31, 0, 0, 0).is_ok()); |
| 1221 |
|
| 1222 |
// leap year: divisible by 4 |
| 1223 |
assert!(DateTime::from_date_and_time(2024, 2, 29, 0, 0, 0).is_ok()); |
| 1224 |
// leap year: divisible by 100 and by 400 |
| 1225 |
assert!(DateTime::from_date_and_time(2000, 2, 29, 0, 0, 0).is_ok()); |
| 1226 |
// common year: divisible by 100 but not by 400 |
| 1227 |
assert!(DateTime::from_date_and_time(2100, 2, 29, 0, 0, 0).is_err()); |
| 1228 |
} |
| 1229 |
|
| 1230 |
#[cfg(feature = "time")] |
| 1231 |
use time::{format_description::well_known::Rfc3339, OffsetDateTime}; |
| 1232 |
|
| 1233 |
#[cfg(feature = "time")] |
| 1234 |
#[test] |
| 1235 |
fn datetime_try_from_offset_datetime() { |
| 1236 |
use time::macros::datetime; |
| 1237 |
|
| 1238 |
use super::DateTime; |
| 1239 |
|
| 1240 |
// 2018-11-17 10:38:30 |
| 1241 |
let dt = DateTime::try_from(datetime!(2018-11-17 10:38:30 UTC)).unwrap(); |
| 1242 |
assert_eq!(dt.year(), 2018); |
| 1243 |
assert_eq!(dt.month(), 11); |
| 1244 |
assert_eq!(dt.day(), 17); |
| 1245 |
assert_eq!(dt.hour(), 10); |
| 1246 |
assert_eq!(dt.minute(), 38); |
| 1247 |
assert_eq!(dt.second(), 30); |
| 1248 |
} |
| 1249 |
|
| 1250 |
#[cfg(feature = "time")] |
| 1251 |
#[test] |
| 1252 |
fn datetime_try_from_bounds() { |
| 1253 |
use super::DateTime; |
| 1254 |
use time::macros::datetime; |
| 1255 |
|
| 1256 |
// 1979-12-31 23:59:59 |
| 1257 |
assert!(DateTime::try_from(datetime!(1979-12-31 23:59:59 UTC)).is_err()); |
| 1258 |
|
| 1259 |
// 1980-01-01 00:00:00 |
| 1260 |
assert!(DateTime::try_from(datetime!(1980-01-01 00:00:00 UTC)).is_ok()); |
| 1261 |
|
| 1262 |
// 2107-12-31 23:59:59 |
| 1263 |
assert!(DateTime::try_from(datetime!(2107-12-31 23:59:59 UTC)).is_ok()); |
| 1264 |
|
| 1265 |
// 2108-01-01 00:00:00 |
| 1266 |
assert!(DateTime::try_from(datetime!(2108-01-01 00:00:00 UTC)).is_err()); |
| 1267 |
} |
| 1268 |
|
| 1269 |
#[cfg(feature = "time")] |
| 1270 |
#[test] |
| 1271 |
fn offset_datetime_try_from_datetime() { |
| 1272 |
use time::macros::datetime; |
| 1273 |
|
| 1274 |
use super::DateTime; |
| 1275 |
|
| 1276 |
// 2018-11-17 10:38:30 UTC |
| 1277 |
let dt = |
| 1278 |
OffsetDateTime::try_from(DateTime::try_from_msdos(0x4D71, 0x54CF).unwrap()).unwrap(); |
| 1279 |
assert_eq!(dt, datetime!(2018-11-17 10:38:30 UTC)); |
| 1280 |
} |
| 1281 |
|
| 1282 |
#[cfg(feature = "time")] |
| 1283 |
#[test] |
| 1284 |
fn offset_datetime_try_from_bounds() { |
| 1285 |
use super::DateTime; |
| 1286 |
|
| 1287 |
// 1980-00-00 00:00:00 |
| 1288 |
assert!(OffsetDateTime::try_from(unsafe { |
| 1289 |
DateTime::from_msdos_unchecked(0x0000, 0x0000) |
| 1290 |
}) |
| 1291 |
.is_err()); |
| 1292 |
|
| 1293 |
// 2107-15-31 31:63:62 |
| 1294 |
assert!(OffsetDateTime::try_from(unsafe { |
| 1295 |
DateTime::from_msdos_unchecked(0xFFFF, 0xFFFF) |
| 1296 |
}) |
| 1297 |
.is_err()); |
| 1298 |
} |
| 1299 |
|
| 1300 |
#[test] |
| 1301 |
#[allow(deprecated)] |
| 1302 |
fn time_conversion() { |
| 1303 |
use super::DateTime; |
| 1304 |
let dt = DateTime::try_from_msdos(0x4D71, 0x54CF).unwrap(); |
| 1305 |
assert_eq!(dt.year(), 2018); |
| 1306 |
assert_eq!(dt.month(), 11); |
| 1307 |
assert_eq!(dt.day(), 17); |
| 1308 |
assert_eq!(dt.hour(), 10); |
| 1309 |
assert_eq!(dt.minute(), 38); |
| 1310 |
assert_eq!(dt.second(), 30); |
| 1311 |
|
| 1312 |
let dt = DateTime::try_from((0x4D71, 0x54CF)).unwrap(); |
| 1313 |
assert_eq!(dt.year(), 2018); |
| 1314 |
assert_eq!(dt.month(), 11); |
| 1315 |
assert_eq!(dt.day(), 17); |
| 1316 |
assert_eq!(dt.hour(), 10); |
| 1317 |
assert_eq!(dt.minute(), 38); |
| 1318 |
assert_eq!(dt.second(), 30); |
| 1319 |
|
| 1320 |
#[cfg(feature = "time")] |
| 1321 |
assert_eq!( |
| 1322 |
dt.to_time().unwrap().format(&Rfc3339).unwrap(), |
| 1323 |
"2018-11-17T10:38:30Z" |
| 1324 |
); |
| 1325 |
|
| 1326 |
assert_eq!(<(u16, u16)>::from(dt), (0x4D71, 0x54CF)); |
| 1327 |
} |
| 1328 |
|
| 1329 |
#[test] |
| 1330 |
#[allow(deprecated)] |
| 1331 |
fn time_out_of_bounds() { |
| 1332 |
use super::DateTime; |
| 1333 |
let dt = unsafe { DateTime::from_msdos_unchecked(0xFFFF, 0xFFFF) }; |
| 1334 |
assert_eq!(dt.year(), 2107); |
| 1335 |
assert_eq!(dt.month(), 15); |
| 1336 |
assert_eq!(dt.day(), 31); |
| 1337 |
assert_eq!(dt.hour(), 31); |
| 1338 |
assert_eq!(dt.minute(), 63); |
| 1339 |
assert_eq!(dt.second(), 62); |
| 1340 |
|
| 1341 |
#[cfg(feature = "time")] |
| 1342 |
assert!(dt.to_time().is_err()); |
| 1343 |
|
| 1344 |
let dt = unsafe { DateTime::from_msdos_unchecked(0x0000, 0x0000) }; |
| 1345 |
assert_eq!(dt.year(), 1980); |
| 1346 |
assert_eq!(dt.month(), 0); |
| 1347 |
assert_eq!(dt.day(), 0); |
| 1348 |
assert_eq!(dt.hour(), 0); |
| 1349 |
assert_eq!(dt.minute(), 0); |
| 1350 |
assert_eq!(dt.second(), 0); |
| 1351 |
|
| 1352 |
#[cfg(feature = "time")] |
| 1353 |
assert!(dt.to_time().is_err()); |
| 1354 |
} |
| 1355 |
|
| 1356 |
#[cfg(feature = "time")] |
| 1357 |
#[test] |
| 1358 |
fn time_at_january() { |
| 1359 |
use super::DateTime; |
| 1360 |
|
| 1361 |
// 2020-01-01 00:00:00 |
| 1362 |
let clock = OffsetDateTime::from_unix_timestamp(1_577_836_800).unwrap(); |
| 1363 |
|
| 1364 |
assert!(DateTime::try_from(clock).is_ok()); |
| 1365 |
} |
| 1366 |
} |