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
//! ZIP file extra field

use std::{fs::Metadata, io::Write};

use cfg_if::cfg_if;
use tokio::io::AsyncWrite;

/// This is a structure containing [`ExtraField`]s associated with a file or directory in a zip
/// file, mostly used for filesystem properties, and this is the only functionality implemented
/// here.
///
/// The [`new_from_fs`](Self::new_from_fs) method will use the metadata the filesystem provides to
/// construct the collection.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ExtraFields {
    pub(crate) values: Vec<ExtraField>,
}

impl ExtraFields {
    /// Create a new set of [`ExtraField`]s. [`Self::new_from_fs`] should be preferred.
    ///
    /// # Safety
    ///
    /// All fields must have valid values depending on the field type.
    pub unsafe fn new<I>(fields: I) -> Self
        where
            I: IntoIterator<Item=ExtraField>,
    {
        Self {
            values: fields.into_iter().collect(),
        }
    }

    /// This method will use the filesystem metadata to get the properties that can be stored in
    /// ZIP [`ExtraFields`].
    ///
    /// The behavior is dependent on the target platform. Will return an empty set if the target os
    /// is not Windows or Linux and not of UNIX family.
    pub fn new_from_fs(metadata: &Metadata) -> Self {
        cfg_if! {
            if #[cfg(target_os = "windows")] {
                Self::new_windows(metadata)
            } else if #[cfg(target_os = "linux")] {
                Self::new_linux(metadata)
            } else if #[cfg(all(unix, not(target_os = "linux")))] {
                Self::new_unix(metadata)
            } else {
                Self::default()
            }
        }
    }

    #[cfg(target_os = "linux")]
    fn new_linux(metadata: &Metadata) -> Self {
        use std::os::linux::fs::MetadataExt;

        let mod_time = Some(metadata.st_mtime() as i32);
        let ac_time = Some(metadata.st_atime() as i32);
        let cr_time = Some(metadata.st_ctime() as i32);

        let uid = metadata.st_uid();
        let gid = metadata.st_gid();

        Self {
            values: vec![
                ExtraField::UnixExtendedTimestamp {
                    mod_time,
                    ac_time,
                    cr_time,
                },
                ExtraField::UnixAttrs { uid, gid },
            ],
        }
    }

    #[cfg(all(unix, not(target_os = "linux")))]
    #[allow(dead_code)]
    fn new_unix(metadata: &Metadata) -> Self {
        use std::os::unix::fs::MetadataExt;

        let mod_time = Some(metadata.mtime() as i32);
        let ac_time = Some(metadata.atime() as i32);
        let cr_time = Some(metadata.ctime() as i32);

        let uid = metadata.uid();
        let gid = metadata.gid();

        Self {
            values: vec![
                ExtraField::UnixExtendedTimestamp {
                    mod_time,
                    ac_time,
                    cr_time,
                },
                ExtraField::UnixAttrs { uid, gid },
            ],
        }
    }

    #[cfg(target_os = "windows")]
    fn new_windows(metadata: &Metadata) -> Self {
        use std::os::windows::fs::MetadataExt;

        let mtime = metadata.last_write_time();
        let atime = metadata.last_access_time();
        let ctime = metadata.creation_time();

        Self {
            values: vec![ExtraField::Ntfs {
                mtime,
                atime,
                ctime,
            }],
        }
    }

    pub(crate) fn data_length<const CENTRAL_HEADER: bool>(&self) -> u16 {
        self.values
            .iter()
            .map(|f| 4 + f.field_size::<CENTRAL_HEADER>())
            .sum()
    }

    pub(crate) fn write<W: Write, const CENTRAL_HEADER: bool>(
        &self,
        writer: &mut W,
    ) -> std::io::Result<()> {
        for field in &self.values {
            field.write::<_, CENTRAL_HEADER>(writer)?;
        }
        Ok(())
    }

    pub(crate) async fn write_with_tokio<W: AsyncWrite + Unpin, const CENTRAL_HEADER: bool>(
        &self,
        writer: &mut W,
    ) -> std::io::Result<()> {
        for field in &self.values {
            field.write_with_tokio::<_, CENTRAL_HEADER>(writer).await?;
        }
        Ok(())
    }
}

/// Extra data that can be associated with a file or directory.
///
/// This library only implements the filesystem properties in NTFS and UNIX format.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExtraField {
    /// NTFS file properties.
    Ntfs {
        /// Last modification timestamp
        mtime: u64,
        /// Last access timestamp
        atime: u64,
        /// File/directory creation timestamp
        ctime: u64,
    },
    /// Info-Zip extended unix timestamp. Each part is optional by definition, but will be
    /// populated by [`ExtraFields::new_from_fs`].
    UnixExtendedTimestamp {
        /// Last modification timestamp
        mod_time: Option<i32>,
        /// Last access timestamp
        ac_time: Option<i32>,
        /// Creation timestamp
        cr_time: Option<i32>,
    },
    /// UNIX file/directory attributes defined by Info-Zip.
    UnixAttrs {
        /// UID of the owner
        uid: u32,
        /// GID of the group
        gid: u32,
    },
}

const MOD_TIME_PRESENT: u8 = 1;
const AC_TIME_PRESENT: u8 = 1 << 1;
const CR_TIME_PRESENT: u8 = 1 << 2;

impl ExtraField {
    #[inline]
    fn header_id(&self) -> u16 {
        match self {
            Self::Ntfs {
                mtime: _,
                atime: _,
                ctime: _,
            } => 0x000a,
            Self::UnixExtendedTimestamp {
                mod_time: _,
                ac_time: _,
                cr_time: _,
            } => 0x5455,
            Self::UnixAttrs { uid: _, gid: _ } => 0x7875,
        }
    }

    #[inline]
    const fn optional_field_size<T: Sized>(field: &Option<T>) -> u16 {
        match field {
            Some(_) => std::mem::size_of::<T>() as u16,
            None => 0,
        }
    }

    #[inline]
    const fn field_size<const CENTRAL_HEADER: bool>(&self) -> u16 {
        match self {
            Self::Ntfs {
                mtime: _,
                atime: _,
                ctime: _,
            } => 32,
            Self::UnixExtendedTimestamp {
                mod_time,
                ac_time,
                cr_time,
            } => {
                1 + Self::optional_field_size(mod_time) + {
                    if !CENTRAL_HEADER {
                        Self::optional_field_size(ac_time) + Self::optional_field_size(cr_time)
                    } else {
                        0
                    }
                }
            }
            Self::UnixAttrs { uid: _, gid: _ } => 11,
        }
    }

    #[inline]
    const fn if_present(val: Option<i32>, if_present: u8) -> u8 {
        match val {
            Some(_) => if_present,
            None => 0,
        }
    }

    const NTFS_FIELD_LEN: usize = 32;
    const UNIX_ATTRS_LEN: usize = 11;

    pub(crate) fn write<W: Write, const CENTRAL_HEADER: bool>(
        self,
        writer: &mut W,
    ) -> std::io::Result<()> {
        // Header ID
        writer.write_all(&self.header_id().to_le_bytes())?;
        // Field data size
        writer.write_all(&self.field_size::<CENTRAL_HEADER>().to_le_bytes())?;

        match self {
            Self::Ntfs {
                mtime,
                atime,
                ctime,
            } => {
                // Writing to a temporary in-memory array
                let mut field = [0; Self::NTFS_FIELD_LEN];
                {
                    let mut field_buf: &mut [u8] = &mut field;

                    // Reserved field
                    field_buf.write_all(&0_u32.to_le_bytes())?;

                    // Tag1 number
                    field_buf.write_all(&1_u16.to_le_bytes())?;
                    // Tag1 size
                    field_buf.write_all(&24_u16.to_le_bytes())?;

                    // Mtime
                    field_buf.write_all(&mtime.to_le_bytes())?;
                    // Atime
                    field_buf.write_all(&atime.to_le_bytes())?;
                    // Ctime
                    field_buf.write_all(&ctime.to_le_bytes())?;
                }

                writer.write_all(&field)?;
            }
            Self::UnixExtendedTimestamp {
                mod_time,
                ac_time,
                cr_time,
            } => {
                let flags = Self::if_present(mod_time, MOD_TIME_PRESENT)
                    | Self::if_present(ac_time, AC_TIME_PRESENT)
                    | Self::if_present(cr_time, CR_TIME_PRESENT);
                writer.write_all(&[flags])?;
                if let Some(mod_time) = mod_time {
                    writer.write_all(&mod_time.to_le_bytes())?;
                }
                if !CENTRAL_HEADER {
                    if let Some(ac_time) = ac_time {
                        writer.write_all(&ac_time.to_le_bytes())?;
                    }
                    if let Some(cr_time) = cr_time {
                        writer.write_all(&cr_time.to_le_bytes())?;
                    }
                }
            }
            Self::UnixAttrs { uid, gid } => {
                // Writing to a temporary in-memory array
                let mut field = [0; Self::UNIX_ATTRS_LEN];
                {
                    let mut field_buf: &mut [u8] = &mut field;

                    // Version of the field
                    field_buf.write_all(&[1])?;
                    // UID size
                    field_buf.write_all(&[4])?;
                    // UID
                    field_buf.write_all(&uid.to_le_bytes())?;
                    // GID size
                    field_buf.write_all(&[4])?;
                    // GID
                    field_buf.write_all(&gid.to_le_bytes())?;
                }

                writer.write_all(&field)?;
            }
        }

        Ok(())
    }

    pub(crate) async fn write_with_tokio<W: AsyncWrite + Unpin, const CENTRAL_HEADER: bool>(
        self,
        writer: &mut W,
    ) -> std::io::Result<()> {
        use tokio::io::AsyncWriteExt;
        // Header ID
        writer.write_all(&self.header_id().to_le_bytes()).await?;
        // Field data size
        writer.write_all(&self.field_size::<CENTRAL_HEADER>().to_le_bytes()).await?;

        match self {
            Self::Ntfs {
                mtime,
                atime,
                ctime,
            } => {
                // Writing to a temporary in-memory array
                let mut field = [0; Self::NTFS_FIELD_LEN];
                {
                    let mut field_buf: &mut [u8] = &mut field;

                    // Reserved field
                    field_buf.write_all(&0_u32.to_le_bytes())?;

                    // Tag1 number
                    field_buf.write_all(&1_u16.to_le_bytes())?;
                    // Tag1 size
                    field_buf.write_all(&24_u16.to_le_bytes())?;

                    // Mtime
                    field_buf.write_all(&mtime.to_le_bytes())?;
                    // Atime
                    field_buf.write_all(&atime.to_le_bytes())?;
                    // Ctime
                    field_buf.write_all(&ctime.to_le_bytes())?;
                }

                writer.write_all(&field).await?;
            }
            Self::UnixExtendedTimestamp {
                mod_time,
                ac_time,
                cr_time,
            } => {
                let flags = Self::if_present(mod_time, MOD_TIME_PRESENT)
                    | Self::if_present(ac_time, AC_TIME_PRESENT)
                    | Self::if_present(cr_time, CR_TIME_PRESENT);
                writer.write_all(&[flags]).await?;
                if let Some(mod_time) = mod_time {
                    writer.write_all(&mod_time.to_le_bytes()).await?;
                }
                if !CENTRAL_HEADER {
                    if let Some(ac_time) = ac_time {
                        writer.write_all(&ac_time.to_le_bytes()).await?;
                    }
                    if let Some(cr_time) = cr_time {
                        writer.write_all(&cr_time.to_le_bytes()).await?;
                    }
                }
            }
            Self::UnixAttrs { uid, gid } => {
                // Writing to a temporary in-memory array
                let mut field = [0; Self::UNIX_ATTRS_LEN];
                {
                    let mut field_buf: &mut [u8] = &mut field;

                    // Version of the field
                    field_buf.write_all(&[1])?;
                    // UID size
                    field_buf.write_all(&[4])?;
                    // UID
                    field_buf.write_all(&uid.to_le_bytes())?;
                    // GID size
                    field_buf.write_all(&[4])?;
                    // GID
                    field_buf.write_all(&gid.to_le_bytes())?;
                }

                writer.write_all(&field).await?;
            }
        }

        Ok(())
    }
}