Debian Codegraph @

.cargo/vendor/delharc/src/header.rs

raw
1 //! # **LHA** header and related types.
2 #[cfg(feature = "std")]
3 use std::path::PathBuf;
4 #[cfg(feature = "std")]
5 use std::borrow::Cow;
6 #[cfg(not(feature = "std"))]
7 use alloc::{boxed::Box, string::String, borrow::Cow};
8 use chrono::{LocalResult, prelude::*};
9
10 mod compression;
11 mod ostype;
12 mod msdos;
13 mod parser;
14 mod timestamp;
15
16 use parser::ext::*;
17
18 pub use msdos::*;
19 pub use compression::*;
20 pub use ostype::*;
21 pub use parser::*;
22 pub use timestamp::*;
23
24 /// Semi-parsed LHA header.
25 #[derive(Debug, Clone)]
26 pub struct LhaHeader {
27 /// Header level: 0, 1, 2 or 3.
28 pub level: u8,
29 /// Raw compression identifier.
30 pub compression: [u8;5],
31 /// Compressed file size.
32 pub compressed_size: u64,
33 /// Original file size.
34 pub original_size: u64,
35 /// A raw filename for level 1 or 0 headers, might be empty. Always being empty for levels 2 or 3.
36 ///
37 /// In this instance the filename is stored in extra headers.
38 pub filename: Box<[u8]>,
39 /// MS-DOS attributes.
40 pub msdos_attrs: MsDosAttrs,
41 /// File's last modified date, format depends on the header level.
42 ///
43 /// * Level 0 and 1 - MS-DOS format (no time zone).
44 /// * Level 2 and 3 - Unix timestamp (UTC).
45 ///
46 /// The "last modified" timestamp can also be found in the extended area and extra headers, as well as
47 /// other kinds of timestamps (- last access, created).
48 pub last_modified: u32,
49 /// A raw OS-TYPE.
50 pub os_type: u8,
51 /// Uncompressed file's CRC-16.
52 pub file_crc: u16,
53 /// An extended area as raw bytes.
54 pub extended_area: Box<[u8]>,
55 /// The size of the first extra header.
56 pub first_header_len: u32,
57 /// The extra headers' data.
58 pub extra_headers: Box<[u8]>,
59 }
60
61 impl Default for LhaHeader {
62 fn default() -> Self {
63 LhaHeader {
64 level: 0,
65 compression: [0;5],
66 compressed_size: 0,
67 original_size: 0,
68 filename: Box::new([]),
69 msdos_attrs: MsDosAttrs::ARCHIVE,
70 last_modified: 0,
71 os_type: 0,
72 file_crc: 0,
73 extended_area: Box::new([]),
74 first_header_len: 0,
75 extra_headers: Box::new([]),
76 }
77 }
78 }
79
80 impl LhaHeader {
81 /// Return whether the archive is an empty directory or a symbolic link.
82 pub fn is_directory(&self) -> bool {
83 self.compression_method().ok()
84 .filter(CompressionMethod::is_directory)
85 .is_some()
86 }
87 /// Attempt to parse the `os_type` field and return the `OsType` enum on success.
88 pub fn parse_os_type(&self) -> Result<OsType, UnrecognizedOsType> {
89 OsType::try_from(self.os_type)
90 }
91 /// Attempt to parse the extended area, extra headers and as a last resort the `last_modified` field
92 /// taking into account the header level, and on success return an instance of [`DateTime<Utc>`][DateTime]
93 /// or a [NaiveDateTime] wrapped in an `TimestampResult` enum.
94 pub fn parse_last_modified(&self) -> TimestampResult {
95 for header in self.iter_extra() {
96 match header {
97 [EXT_HEADER_UNIX_TIME, data @ ..] => {
98 if let Some(ts) = data.get(0..4).and_then(read_u32) {
99 return Utc.timestamp_opt(ts as i64, 0).into()
100 }
101 }
102 [EXT_HEADER_MSDOS_TIME, data @ ..] if data.len() == 24 => {
103 if let Some(mtime) = read_u64(&data[8..16]) {
104 return parse_win_filetime(mtime).into()
105 }
106 }
107 _ => {}
108 }
109 }
110 if self.level < 2 {
111 match self.parse_os_type() {
112 Ok(OsType::Unix)|Ok(OsType::Osk) => {
113 if let Some(ts) = self.extended_area.get(1..5).and_then(read_u32) {
114 return Utc.timestamp_opt(ts as i64, 0).into()
115 }
116 }
117 _ => {}
118 }
119 parse_msdos_datetime(self.last_modified).into()
120 }
121 else {
122 Utc.timestamp_opt(self.last_modified as i64, 0).into()
123 }
124 }
125 /// Attempt to parse the `compression` method field and return the `CompressionMethod` enum on success.
126 pub fn compression_method(&self) -> Result<CompressionMethod, UnrecognizedCompressionMethod> {
127 CompressionMethod::try_from(&self.compression)
128 }
129 /// Attempt to parse the `filename` field and search extended data for the directory and an
130 /// alternative file name and return a `PathBuf`.
131 ///
132 /// The method converts all non-ASCII or control characters to `%xx` sequences and all system
133 /// specific directory separator characters to `_` in file names.
134 ///
135 /// Malicious path components, like `..`, `.` or `//` are stripped from the path names.
136 ///
137 /// # Notes
138 /// * If the path name could not be found the returned `PathBuf` will be empty.
139 /// * Some filesystems may still reject the file or path names if path names include some forbidden
140 /// characters, e.g. `?` or `*` in `Windows`.
141 /// * This method makes its best effort to return a non-absolute path name, however it is not guaranteed,
142 /// so make sure the path is not absolute before creating a file or a directory.
143 /// * If the archive OS is [OsType::Amiga] the file name parsing terminates before the `nul` character.
144 ///
145 /// # `no_std`
146 ///
147 /// This method is only available with `std` feature enabled.
148 #[cfg(feature = "std")]
149 pub fn parse_pathname(&self) -> PathBuf {
150 let mut path = PathBuf::new();
151 let mut filename = Cow::Borrowed("");
152 let nilterm = self.parse_os_type() == Ok(OsType::Amiga);
153 for header in self.iter_extra() {
154 match header {
155 [EXT_HEADER_FILENAME, data @ ..] => {
156 filename = parse_str_nilterm(data, nilterm, false);
157 },
158 [EXT_HEADER_PATH, data @ ..] => {
159 parse_pathname(data, &mut path);
160 }
161 _ => {}
162 }
163 }
164 if filename.is_empty() {
165 let data = if nilterm {
166 split_data_at_nil_or_end(&self.filename).0
167 }
168 else {
169 &self.filename
170 };
171 parse_pathname(data, &mut path);
172 }
173 else {
174 path.push(filename.as_ref());
175 }
176 path
177 }
178 /// Attempt to parse the `filename` field and search extended data for the directory and an
179 /// alternative file name and return a `String` with a possible path to a `filename`,
180 /// separated by '`/`' characters.
181 ///
182 /// This method is like [`LhaHeader::parse_pathname`] but will return a `String` instead of
183 /// `PathBuf` and can be used without `std` feature enabled.
184 pub fn parse_pathname_to_str(&self) -> String {
185 let mut path = String::new();
186 let mut filename = Cow::Borrowed("");
187 let nilterm = self.parse_os_type() == Ok(OsType::Amiga);
188 for header in self.iter_extra() {
189 match header {
190 [EXT_HEADER_FILENAME, data @ ..] => {
191 filename = parse_str_nilterm(data, nilterm, false);
192 },
193 [EXT_HEADER_PATH, data @ ..] => {
194 parse_pathname_to_str(data, &mut path);
195 }
196 _ => {}
197 }
198 }
199 if filename.is_empty() {
200 let data = if nilterm {
201 split_data_at_nil_or_end(&self.filename).0
202 }
203 else {
204 &self.filename
205 };
206 parse_pathname_to_str(data, &mut path);
207 }
208 else {
209 if !path.is_empty() {
210 path.push('/');
211 }
212 path.push_str(filename.as_ref());
213 }
214 path
215 }
216 /// Attempts to find and return the file comment field in extended header data.
217 ///
218 /// The routine converts all non-ASCII or control characters to `%xx` sequences.
219 ///
220 /// # Notes
221 /// Some archives made on [OsType::Amiga] can have a comment embedded in the filename field
222 /// after the `nul` character. If the comment could not be found in extended data, an attempt
223 /// is made to extract the comment from the filename if the archive OS supports it.
224 pub fn parse_comment(&self) -> Option<Cow<str>> {
225 let mut raw_filename = &self.filename[..];
226 for header in self.iter_extra() {
227 match header {
228 [EXT_HEADER_FILENAME, data @ ..] => {
229 raw_filename = data;
230 },
231 [EXT_HEADER_COMMENT, data @ ..] => {
232 let comment = parse_str_nilterm(data, false, true);
233 if !comment.is_empty() {
234 return Some(comment)
235 }
236 }
237 _ => {}
238 }
239 }
240 if self.parse_os_type() == Ok(OsType::Amiga) {
241 split_data_at_nil_or_end(raw_filename)
242 .1
243 .map(|data| parse_str_nilterm(data, false, true))
244 }
245 else {
246 None
247 }
248 }
249 }
250
251 /// Returns a `NaiveDateTime` on success from MS-DOS timestamp format.
252 ///
253 /// ```text
254 /// bit 24 16 8 0
255 /// 76543210 76543210 76543210 76543210
256 /// YYYYYYYM MMMDDDDD hhhhhmmm mmmsssss
257 /// ```
258 ///
259 /// | Sym. | Description |
260 /// |------|---------------------------------------------|
261 /// | Y | The year from 1980 (0 = 1980) |
262 /// | M | Month. [1, 12] |
263 /// | D | Day. [1, 31] |
264 /// | h | Hour. [0, 23]. |
265 /// | m | Minute. [0, 59]. |
266 /// | s | 2 seconds. [0, 29] (in units of 2 seconds). |
267 pub fn parse_msdos_datetime(ts: u32) -> Option<NaiveDateTime> {
268 let sec = ts << 1 & 0x3e;
269 let min = ts >> 5 & 0x3f;
270 let hour = ts >> 11 & 0x1f;
271 let day = ts >> 16 & 0x1f;
272 let mon = ts >> 21 & 0xf;
273 let year = 1980 + (ts >> 25 & 0x7f) as i32;
274 NaiveDate::from_ymd_opt(year, mon, day).and_then(|d| d.and_hms_opt(hour, min, sec))
275 }
276
277 /// Returns a `DateTime<Utc>` on success from Windows [FILETIME] format.
278 ///
279 /// [FILETIME]: https://docs.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-filetime
280 pub fn parse_win_filetime(filetime: u64) -> LocalResult<DateTime<Utc>> {
281 if let Some(ft) = i64::try_from(filetime).ok().and_then(|ft|
282 ft.checked_sub(116_444_736_000_000_000))
283 {
284 let secs = ft / 10_000_000;
285 let nanos = (ft % 10_000_000) as u32 * 100;
286 return Utc.timestamp_opt(secs, nanos)
287 }
288 LocalResult::None
289 }