Skip to main content

zip_framing/
kind.rs

1use crate::{
2    CentralDirectoryEntry, Error, HostSystem, constants::version, invalid, record::array_at,
3    wire::wire_enum,
4};
5
6/// A ZIP member's kind, determined from its reconciled metadata.
7///
8/// This describes the archive entry without imposing an extraction policy. Link
9/// targets from a PKWARE UNIX extra field are nonempty UTF-8 without NUL bytes.
10/// Targets in payloads have not been validated.
11#[derive(Clone, Debug, Eq, PartialEq)]
12#[non_exhaustive]
13pub enum EntryKind {
14    /// A regular file, including entries with no explicit file type.
15    File,
16    /// A directory.
17    Directory,
18    /// A symbolic link with a target in the UNIX extra field or payload.
19    SymbolicLink {
20        /// The target from the PKWARE UNIX extra field, if any.
21        unix_target: Option<String>,
22    },
23    /// A character device.
24    CharacterDevice {
25        /// Device numbers from the PKWARE UNIX extra field, if any.
26        numbers: Option<DeviceNumbers>,
27    },
28    /// A block device.
29    BlockDevice {
30        /// Device numbers from the PKWARE UNIX extra field, if any.
31        numbers: Option<DeviceNumbers>,
32    },
33    /// A named pipe.
34    Fifo,
35    /// A UNIX socket.
36    Socket,
37    /// A DOS volume label.
38    VolumeLabel,
39    /// An unrecognized UNIX file type, masked from the mode.
40    Unknown {
41        /// The masked UNIX file-type bits.
42        mode: u16,
43    },
44}
45
46impl EntryKind {
47    pub(crate) fn resolve(
48        directory: &CentralDirectoryEntry,
49        unix_data: Option<Vec<u8>>,
50        attributes: &ExternalAttributes,
51    ) -> Result<Self, Error> {
52        let position = directory.position();
53        let has_directory_suffix = directory.path().ends_with('/');
54        let file_type = match (
55            UnixFileType::from_mode(attributes.unix_mode),
56            has_directory_suffix || attributes.dos_directory,
57        ) {
58            (UnixFileType::Unspecified | UnixFileType::Directory, true) => UnixFileType::Directory,
59            (file_type, false) => file_type,
60            _ => return Err(invalid(position, "inconsistent file attributes")),
61        };
62        if attributes.dos_volume_label && file_type != UnixFileType::Unspecified {
63            return Err(invalid(position, "inconsistent file attributes"));
64        }
65        if file_type == UnixFileType::Directory && !has_directory_suffix {
66            return Err(invalid(position, "directory filename must end with '/'"));
67        }
68
69        if (attributes.dos_volume_label
70            || matches!(
71                file_type,
72                UnixFileType::Directory
73                    | UnixFileType::CharacterDevice
74                    | UnixFileType::BlockDevice
75                    | UnixFileType::Fifo
76                    | UnixFileType::Socket
77            ))
78            && directory.size() != 0
79        {
80            return Err(invalid(position, "non-file member has payload data"));
81        }
82
83        if file_type == UnixFileType::SymbolicLink && directory.size() == 0 && unix_data.is_none() {
84            return Err(invalid(position, "empty symbolic-link target"));
85        }
86
87        let has_type_data = unix_data.as_ref().is_some_and(|data| !data.is_empty());
88        Ok(match file_type {
89            UnixFileType::SymbolicLink => Self::SymbolicLink {
90                unix_target: unix_data
91                    .map(|data| parse_link_target(data, position))
92                    .transpose()?,
93            },
94            UnixFileType::CharacterDevice => Self::CharacterDevice {
95                numbers: DeviceNumbers::parse(unix_data, position)?,
96            },
97            UnixFileType::BlockDevice => Self::BlockDevice {
98                numbers: DeviceNumbers::parse(unix_data, position)?,
99            },
100            // APPNOTE 4.5.7 gives hard links a target but no distinct file type.
101            UnixFileType::Unspecified | UnixFileType::Regular
102                if has_type_data && !attributes.dos_volume_label =>
103            {
104                return Err(Error::Unsupported {
105                    position,
106                    feature: "ambiguous UNIX hard link",
107                });
108            }
109            _ if has_type_data => return Err(invalid(position, "unexpected UNIX file-type data")),
110            UnixFileType::Unspecified if attributes.dos_volume_label => Self::VolumeLabel,
111            UnixFileType::Unspecified | UnixFileType::Regular => Self::File,
112            UnixFileType::Directory => Self::Directory,
113            UnixFileType::Fifo => Self::Fifo,
114            UnixFileType::Socket => Self::Socket,
115            UnixFileType::Unknown(mode) => Self::Unknown { mode },
116        })
117    }
118
119    /// Minimum extraction version for the resolved kind.
120    pub(crate) fn minimum_version(&self) -> u16 {
121        match self {
122            Self::VolumeLabel => version::V1_1,
123            Self::Directory => version::V2_0,
124            _ => version::BASE,
125        }
126    }
127}
128
129/// Device numbers from a PKWARE UNIX extra field.
130#[derive(Clone, Copy, Debug, Eq, PartialEq)]
131pub struct DeviceNumbers {
132    /// The device's major number.
133    pub major: u32,
134    /// The device's minor number.
135    pub minor: u32,
136}
137
138impl DeviceNumbers {
139    fn parse(data: Option<Vec<u8>>, position: u64) -> Result<Option<Self>, Error> {
140        let Some(data) = data else {
141            return Ok(None);
142        };
143
144        let bytes: [u8; 8] = data
145            .as_slice()
146            .try_into()
147            .map_err(|_| invalid(position, "invalid UNIX device numbers"))?;
148        Ok(Some(Self {
149            major: u32::from_le_bytes(array_at::<0, 4, _>(&bytes)),
150            minor: u32::from_le_bytes(array_at::<4, 4, _>(&bytes)),
151        }))
152    }
153}
154
155fn parse_link_target(data: Vec<u8>, position: u64) -> Result<String, Error> {
156    if data.is_empty() {
157        return Err(invalid(position, "empty symbolic-link target"));
158    }
159    let target =
160        String::from_utf8(data).map_err(|_| invalid(position, "non-UTF-8 UNIX link target"))?;
161    if target.contains('\0') {
162        return Err(invalid(position, "NUL in UNIX link target"));
163    }
164    Ok(target)
165}
166
167wire_enum! {
168    /// The file type after masking out the permission bits.
169    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
170    pub(crate) enum UnixFileType(u16) {
171        Unspecified = 0,
172        Regular = 0o100000,
173        Directory = 0o040000,
174        SymbolicLink = 0o120000,
175        CharacterDevice = 0o020000,
176        BlockDevice = 0o060000,
177        Fifo = 0o010000,
178        Socket = 0o140000,
179    }
180}
181
182impl UnixFileType {
183    pub(crate) fn from_mode(mode: u16) -> Self {
184        // S_IFMT selects the file type, excluding permissions.
185        Self::from(mode & 0o170000)
186    }
187}
188
189/// An extracted form of a central directory entry's "external attributes" field.
190///
191/// See [`CentralDirectoryEntry::external_attributes`].
192pub(crate) struct ExternalAttributes {
193    /// The UNIX file mode.
194    ///
195    /// This is not standardized in the APPNOTE, but implementations that want to convey
196    /// UNIX-style file modes conventionally store the lower 16 bits of `st_mode` into
197    /// the upper 16 bits of the external attributes.
198    pub(crate) unix_mode: u16,
199
200    /// Whether the entry is marked with the DOS directory attribute.
201    ///
202    /// APPNOTE defines this for MS-DOS, but implementations widely use it to hint whether a
203    /// member is a directory regardless of host platform. We reconcile this attribute with the
204    /// conventional `/` suffix and the UNIX file type when determining the member's kind.
205    /// See [`crate::Entry::kind`].
206    dos_directory: bool,
207
208    /// Whether the entry represents the disk/volume's name, rather than a regular file.
209    ///
210    /// This is classified as [`EntryKind::VolumeLabel`].
211    dos_volume_label: bool,
212}
213
214impl ExternalAttributes {
215    /// The DOS/FAT volume-label attribute.
216    ///
217    /// APPNOTE 4.4.15 places DOS attributes in the low byte for MS-DOS entries.
218    /// The bit value is `FAT_DIRENT_ATTR_VOLUME_ID` in
219    /// [Microsoft's FAT header](https://github.com/microsoft/Windows-driver-samples/blob/main/filesys/fastfat/fat.h).
220    const DOS_VOLUME_LABEL: u32 = 0x08;
221
222    /// The DOS/FAT directory attribute.
223    ///
224    /// APPNOTE 4.4.15 places DOS attributes in the low byte for MS-DOS entries.
225    /// The bit value is `FAT_DIRENT_ATTR_DIRECTORY` in
226    /// [Microsoft's FAT header](https://github.com/microsoft/Windows-driver-samples/blob/main/filesys/fastfat/fat.h).
227    pub(crate) const DOS_DIRECTORY: u32 = 0x10;
228
229    /// See the comment on [`ExternalAttributes::unix_mode`].
230    pub(crate) const UNIX_MODE_SHIFT: u32 = 16;
231
232    pub(crate) fn new(host_system: HostSystem, raw: u32) -> Self {
233        let has_dos_attributes = matches!(
234            host_system,
235            HostSystem::MsDos
236                | HostSystem::Unix
237                | HostSystem::Os2Hpfs
238                | HostSystem::WindowsNtfs
239                | HostSystem::Vfat
240                | HostSystem::Darwin
241        );
242
243        Self {
244            unix_mode: if matches!(host_system, HostSystem::Unix | HostSystem::Darwin) {
245                (raw >> Self::UNIX_MODE_SHIFT) as u16
246            } else {
247                0
248            },
249            dos_directory: has_dos_attributes && raw & Self::DOS_DIRECTORY != 0,
250            dos_volume_label: has_dos_attributes && raw & Self::DOS_VOLUME_LABEL != 0,
251        }
252    }
253}
254
255#[cfg(test)]
256mod tests {
257    use crate::HostSystem;
258
259    use super::ExternalAttributes;
260
261    #[test]
262    fn interprets_external_attributes_according_to_the_host() {
263        for (host, unix_mode, has_dos_attributes) in [
264            (HostSystem::MsDos, 0, true),
265            (HostSystem::Unix, 0o100755, true),
266            (HostSystem::Os2Hpfs, 0, true),
267            (HostSystem::WindowsNtfs, 0, true),
268            (HostSystem::Vfat, 0, true),
269            (HostSystem::Darwin, 0o100755, true),
270            (HostSystem::Amiga, 0, false),
271            (HostSystem::Unknown(255), 0, false),
272        ] {
273            let attributes = ExternalAttributes::new(host, (0o100755 << 16) | 0x10);
274            assert_eq!(attributes.unix_mode, unix_mode, "host {host:?}");
275            assert_eq!(
276                attributes.dos_directory, has_dos_attributes,
277                "host {host:?}"
278            );
279            assert!(!attributes.dos_volume_label, "host {host:?}");
280
281            let attributes = ExternalAttributes::new(host, 0x08);
282            assert_eq!(attributes.unix_mode, 0, "host {host:?}");
283            assert!(!attributes.dos_directory, "host {host:?}");
284            assert_eq!(
285                attributes.dos_volume_label, has_dos_attributes,
286                "host {host:?}"
287            );
288        }
289    }
290}