sett 0.4.0

Rust port of sett (data compression, encryption and transfer tool).
Documentation
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
use super::error;
use std::{borrow::Cow, io};

use chrono::{DateTime, Datelike, TimeZone, Timelike, Utc};
use tokio::io::AsyncReadExt as _;

// Specification: https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT

const LOCAL_FILE_HEADER_SIGNATURE: u32 = 0x04034b50;
const DATA_DESCRIPTOR_SIGNATURE: u32 = 0x08074b50;
const CENTRAL_DIRECTORY_HEADER_SIGNATURE: u32 = 0x02014b50;
const CENTRAL_DIRECTORY_END_SIGNATURE: u32 = 0x06054b50;
const ZIP64_CENTRAL_DIRECTORY_END_SIGNATURE: u32 = 0x06064b50;
const ZIP64_CENTRAL_DIRECTORY_END_LOCATOR_SIGNATURE: u32 = 0x07064b50;

const UNIX: u8 = 3;
const DEFAULT_VERSION: u16 = 45; // File uses ZIP64 format extensions
const VERSION_MADE_BY: u16 = ((UNIX as u16) << 8) | DEFAULT_VERSION;

pub(super) const ZIP64_THRESHOLD_FILES: u64 = u16::MAX as u64;
pub(super) const ZIP64_THRESHOLD_BYTES: u64 = u32::MAX as u64;

fn to_msdos_time(dt: DateTime<Utc>) -> u16 {
    ((dt.second() as u16) >> 1) | ((dt.minute() as u16) << 5) | ((dt.hour() as u16) << 11)
}
fn to_msdos_date(dt: DateTime<Utc>) -> u16 {
    (dt.day() as u16) | ((dt.month() as u16) << 5) | (((dt.year() - 1980) as u16) << 9)
}

fn from_msdos_datetime(date: u16, time: u16) -> DateTime<Utc> {
    let year = ((date >> 9) & 0b1111111) as i32 + 1980;
    let month = ((date >> 5) & 0b1111) as u32;
    let day = (date & 0b11111) as u32;
    let hour = ((time >> 11) & 0b11111) as u32;
    let minute = ((time >> 5) & 0b111111) as u32;
    let second = ((time & 0b11111) as u32) << 1;
    if let chrono::offset::LocalResult::Single(dt) =
        Utc.with_ymd_and_hms(year, month, day, hour, minute, second)
    {
        dt
    } else {
        "1980-01-01T00:00:00Z"
            .parse::<DateTime<Utc>>()
            .expect("this conversion can never fail")
    }
}

/// Convert cp437 encoded data to UTF-8.
///
/// This is a limited implementation that only supports a subset of cp437.
/// However, this is enough to handle the file names in sett-compatible ZIP archives,
/// especially that sett itself uses UTF-8 encoding for file names.
/// This means that this function might only be necessary for packages created by
/// other tools.
fn cp437_to_utf8(data: &[u8]) -> Cow<'_, str> {
    String::from_utf8_lossy(data)
}

#[derive(Debug, Default, PartialEq)]
pub(super) struct LocalFileHeader<'a> {
    pub(super) compression_method: u16,
    pub(super) crc32: u32,
    pub(super) flags: u16,
    pub(super) modified: DateTime<Utc>,
    pub(super) name: Cow<'a, str>,
    pub(super) size: u32,
    pub(super) header_size: u32,
}

impl LocalFileHeader<'_> {
    pub(super) fn build(&self) -> Vec<u8> {
        let mut buffer = Vec::with_capacity(30 + self.name.len());
        // Local file header signature
        buffer.extend(&LOCAL_FILE_HEADER_SIGNATURE.to_le_bytes());
        // Minimum version needed to extract
        buffer.extend(&DEFAULT_VERSION.to_le_bytes());
        // General purpose bit flag
        buffer.extend(&self.flags.to_le_bytes());
        // Compression method: store
        buffer.extend(&self.compression_method.to_le_bytes());
        // Modification time
        buffer.extend(&to_msdos_time(self.modified).to_le_bytes());
        // Modification date
        buffer.extend(&to_msdos_date(self.modified).to_le_bytes());
        // CRC-32 of uncompressed data
        buffer.extend(&self.crc32.to_le_bytes());
        // Compressed size (0xffffffff for ZIP64)
        buffer.extend(&self.size.to_le_bytes());
        // Uncompressed size (0xffffffff for ZIP64)
        buffer.extend(&self.size.to_le_bytes());
        // File name length
        buffer.extend(&(self.name.len() as u16).to_le_bytes());
        // Extra field length
        buffer.extend(&0u16.to_le_bytes());
        // File name
        buffer.extend(self.name.as_bytes());
        buffer
    }

    /// Parse a local file header.
    ///
    /// The reader must be positioned at the start of the local file header.
    ///
    /// Please note, that it's preferable to use the central directory header
    /// (instead of the local one) for accessing file metadata.
    pub(super) async fn parse<R: tokio::io::AsyncBufRead + Unpin>(
        reader: &mut R,
    ) -> Result<Self, error::HeaderParseError> {
        const HEADER_MIN_LENGTH: usize = 30;
        let mut buffer = [0u8; HEADER_MIN_LENGTH];
        reader.read_exact(&mut buffer).await?;
        if buffer[0..4] != LOCAL_FILE_HEADER_SIGNATURE.to_le_bytes() {
            return Err(error::HeaderParseError::InvalidSignature);
        }
        let name_len = bytes_to_u16(&buffer, 26) as usize;
        let flags = bytes_to_u16(&buffer, 6);
        let is_utf8 = flags & (1 << 11) != 0;
        let mut name = vec![0u8; name_len];
        reader.read_exact(&mut name).await?;
        let name = if is_utf8 {
            String::from_utf8_lossy(&name)
        } else {
            cp437_to_utf8(&name)
        };
        let extra_field_len = bytes_to_u16(&buffer, 28);
        Ok(Self {
            compression_method: bytes_to_u16(&buffer, 8),
            crc32: bytes_to_u32(&buffer, 14),
            flags,
            modified: from_msdos_datetime(bytes_to_u16(&buffer, 12), bytes_to_u16(&buffer, 10)),
            name: name.into_owned().into(),
            size: bytes_to_u32(&buffer, 18),
            header_size: HEADER_MIN_LENGTH as u32 + name_len as u32 + extra_field_len as u32,
        })
    }
}

#[derive(Debug)]
pub(super) struct DataDescriptor {
    pub(super) crc32: u32,
    pub(super) size: u64,
}

impl DataDescriptor {
    pub(super) fn build(&self) -> Vec<u8> {
        let mut buffer = Vec::with_capacity(24);
        buffer.extend(&DATA_DESCRIPTOR_SIGNATURE.to_le_bytes());
        buffer.extend(&self.crc32.to_le_bytes());
        if self.size >= ZIP64_THRESHOLD_BYTES {
            buffer.extend(&self.size.to_le_bytes()); // Compressed size
            buffer.extend(&self.size.to_le_bytes()); // Uncompressed size
        } else {
            buffer.extend(&(self.size as u32).to_le_bytes()); // Compressed size
            buffer.extend(&(self.size as u32).to_le_bytes()); // Uncompressed size
        }
        buffer
    }
}

#[derive(Debug, Default, PartialEq)]
pub(super) struct CentralDirectoryHeader<'a> {
    pub(super) compression_method: u16,
    pub(super) crc32: u32,
    pub(super) external_attributes: u32,
    pub(super) flags: u16,
    pub(super) modified: DateTime<Utc>,
    pub(super) name: Cow<'a, str>,
    pub(super) offset: u64,
    pub(super) size: u64,
}

impl CentralDirectoryHeader<'_> {
    pub(super) fn build(&self) -> Vec<u8> {
        let mut buffer = Vec::with_capacity(82);
        let size_u32 = self.size.min(ZIP64_THRESHOLD_BYTES) as u32;
        let zip64_extra_field = self.build_zip64_extra_field();

        // Central file header signature
        buffer.extend(&CENTRAL_DIRECTORY_HEADER_SIGNATURE.to_le_bytes());
        // Version made by
        buffer.extend(&VERSION_MADE_BY.to_le_bytes());
        // Minimum version needed to extract
        buffer.extend(&DEFAULT_VERSION.to_le_bytes());
        // General purpose bit flag
        buffer.extend(&self.flags.to_le_bytes());
        // Compression method (0 = stored)
        buffer.extend(&self.compression_method.to_le_bytes());
        // Last mod file time
        buffer.extend(&to_msdos_time(self.modified).to_le_bytes());
        // Last mod file date
        buffer.extend(&to_msdos_date(self.modified).to_le_bytes());
        // CRC-32
        buffer.extend(&self.crc32.to_le_bytes());
        // Compressed size
        buffer.extend(&size_u32.to_le_bytes());
        // Uncompressed size
        buffer.extend(&size_u32.to_le_bytes());
        // File name length
        buffer.extend(&(self.name.len() as u16).to_le_bytes());
        // Extra field length
        buffer.extend(&(zip64_extra_field.len() as u16).to_le_bytes());
        // File comment length
        buffer.extend(&0u16.to_le_bytes());
        // Disk number start
        buffer.extend(&0u16.to_le_bytes());
        // Internal file attributes
        buffer.extend(&0u16.to_le_bytes());
        // External file attributes
        buffer.extend(&self.external_attributes.to_le_bytes());
        // Relative offset of local header
        buffer.extend(&(self.offset.min(ZIP64_THRESHOLD_BYTES) as u32).to_le_bytes());
        // File name
        buffer.extend(self.name.as_bytes());
        // Extra field
        buffer.extend(zip64_extra_field);

        buffer
    }

    fn zip64_extra_field_size(size: u64, offset: u64) -> u16 {
        let is_zip64_size = size >= ZIP64_THRESHOLD_BYTES;
        let is_zip64_offset = offset >= ZIP64_THRESHOLD_BYTES;
        match (is_zip64_size, is_zip64_offset) {
            (true, true) => 24,
            (true, false) => 16,
            (false, true) => 8,
            (false, false) => 0,
        }
    }

    fn build_zip64_extra_field(&self) -> Vec<u8> {
        let size_internal = Self::zip64_extra_field_size(self.size, self.offset);
        if size_internal == 0 {
            return Vec::with_capacity(0);
        }
        let mut buffer = Vec::with_capacity(28);
        // Zip64 extended information extra field tag
        buffer.extend(&1u16.to_le_bytes());
        // Size of this "extra" block
        buffer.extend(size_internal.to_le_bytes());

        if self.size >= ZIP64_THRESHOLD_BYTES {
            // Original uncompressed file size
            buffer.extend(self.size.to_le_bytes());
            // Compressed file size
            buffer.extend(self.size.to_le_bytes());
        }
        if self.offset >= ZIP64_THRESHOLD_BYTES {
            // Offset of local header record
            buffer.extend(self.offset.to_le_bytes());
        }
        buffer
    }

    pub(super) fn find<R: io::Read + io::Seek>(
        reader: &mut R,
    ) -> Result<u64, error::SeekHeaderError> {
        let mut buffer = [0u8; 4];
        while let Ok(()) = reader.read_exact(&mut buffer[3..4]) {
            if buffer == CENTRAL_DIRECTORY_HEADER_SIGNATURE.to_le_bytes() {
                return Ok(reader.seek(io::SeekFrom::Current(-4))?);
            }
            buffer.rotate_left(1);
        }
        Err(error::SeekHeaderError::NotFound(
            "Zip/Zip64 central directory header not found",
        ))
    }

    /// Parse the "extra field" section of a Zip or Zip64 file. Return the file
    /// size and file offset, and move the `reader` pointer just past the end
    /// of the "extra field" section.
    ///
    /// # Arguments
    ///
    /// * `reader`: reading handle of the central directory header.
    /// * `file_size`: file size as given in the "compressed size" section of
    ///   the central directory header. For files in Zip format, this value
    ///   will be returned by the function. For files in Zip64 format, the
    ///   file size read from the "Zip64 info" field will be returned.
    /// * `file_offset`: same as `file_size`, but for the
    ///   "relative offset of local header" section.
    /// * `extra_field_size`: size in bytes of the "extra field" section
    ///   being parsed.
    fn parse_extra_field<R: io::Read + io::Seek>(
        reader: &mut R,
        file_size: u64,
        file_offset: u64,
        extra_field_size: u16,
    ) -> Result<(u64, u64), error::HeaderParseError> {
        let position_start = reader.stream_position()?;
        let mut file_size = file_size;
        let mut file_offset = file_offset;

        // If the file size requires the Zip64 format, parse the "extra field"
        // fields until a "Zip64 info" field is found.
        // Each field in the "extra field" section starts with a header
        // consisting of a "header ID" (2 bytes) followed by the field's
        // size (2 bytes). The "header ID" of a "Zip64 info" field is
        // `0x01`.
        if file_size == ZIP64_THRESHOLD_BYTES || file_offset == ZIP64_THRESHOLD_BYTES {
            if extra_field_size < Self::zip64_extra_field_size(file_size, file_offset) {
                return Err(error::HeaderParseError::InvalidExtraField);
            }
            let mut buffer = [0u8; 4];
            loop {
                reader.read_exact(&mut buffer)?;
                let field_header = bytes_to_u16(&buffer, 0);
                let field_size = bytes_to_u16(&buffer, 2);

                // If current field is a "Zip64 info" field, the search is over.
                if field_header == 1 {
                    // Retrieve file size info from 'Zip64 info' field.
                    if file_size == ZIP64_THRESHOLD_BYTES {
                        let mut buffer = [0u8; 16];
                        reader.read_exact(&mut buffer)?;
                        let uncompressed_size = bytes_to_u64(&buffer, 0);
                        let compressed_size = bytes_to_u64(&buffer, 8);
                        if uncompressed_size != compressed_size {
                            return Err(error::HeaderParseError::InvalidInput);
                        }
                        file_size = uncompressed_size;
                    }
                    // Retrieve file offset info from 'Zip64 info' field.
                    if file_offset == ZIP64_THRESHOLD_BYTES {
                        let mut buffer = [0u8; 8];
                        reader.read_exact(&mut buffer)?;
                        file_offset = u64::from_le_bytes(buffer);
                    }
                    break;
                }
                // Otherwise skip to the end of the current extra field. If
                // the end of the "extra field" section is reached without
                // having found a "Zip64 info" field, the Zip64 file does not
                // comply with the specifications.
                let position_current = reader.seek(io::SeekFrom::Current(field_size as i64))?;
                if position_current - position_start >= extra_field_size as u64 {
                    return Err(error::HeaderParseError::MissingZipInfo(
                        "invalid Zip64 central directory header: no 'Zip64 info' \
                    field found in 'extra field' section",
                    ));
                }
            }
        }

        // Skip the unread remainder of the "extra field" section, if any.
        let bytes_left =
            extra_field_size as i64 - (reader.stream_position()? - position_start) as i64;
        reader.seek(io::SeekFrom::Current(bytes_left))?;

        Ok((file_size, file_offset))
    }

    /// Parse a central directory header.
    ///
    /// The reader must be positioned at the start of the central directory header.
    /// This function will read the entire header (skipping comments). As a result,
    /// the reader's final position will be just after the header.
    pub(super) fn parse<R: io::Read + io::Seek>(
        reader: &mut R,
    ) -> Result<Self, error::HeaderParseError> {
        let mut buffer = [0u8; 46];
        reader.read_exact(&mut buffer)?;
        if buffer[0..4] != CENTRAL_DIRECTORY_HEADER_SIGNATURE.to_le_bytes() {
            return Err(error::HeaderParseError::InvalidSignature);
        }
        let name_len = bytes_to_u16(&buffer, 28) as usize;
        let flags = bytes_to_u16(&buffer, 8);
        let is_utf8 = flags & (1 << 11) != 0;

        let mut name = vec![0u8; name_len];
        reader.read_exact(&mut name)?;
        let name = if is_utf8 {
            String::from_utf8_lossy(&name)
        } else {
            cp437_to_utf8(&name)
        };

        // Retrieve file size (uncompressed) and file offset. If the file is
        // in Zip64 format, this information is found in the "extra field"
        // section of the central directory header.
        let (size, offset) = Self::parse_extra_field(
            reader,
            bytes_to_u32(&buffer, 20) as u64,
            bytes_to_u32(&buffer, 42) as u64,
            bytes_to_u16(&buffer, 30),
        )?;

        // Skip comment section.
        let comment_len = bytes_to_u16(&buffer, 32);
        reader.seek(io::SeekFrom::Current(comment_len as i64))?;

        Ok(Self {
            flags,
            compression_method: bytes_to_u16(&buffer, 10),
            modified: from_msdos_datetime(bytes_to_u16(&buffer, 14), bytes_to_u16(&buffer, 12)),
            crc32: bytes_to_u32(&buffer, 16),
            external_attributes: bytes_to_u32(&buffer, 38),
            name: name.into_owned().into(),
            size,
            offset,
        })
    }
}

fn bytes_to_u16(buf: &[u8], offset: usize) -> u16 {
    u16::from_le_bytes([buf[offset], buf[offset + 1]])
}

fn bytes_to_u32(buf: &[u8], offset: usize) -> u32 {
    u32::from_le_bytes([
        buf[offset],
        buf[offset + 1],
        buf[offset + 2],
        buf[offset + 3],
    ])
}

fn bytes_to_u64(buf: &[u8], offset: usize) -> u64 {
    u64::from_le_bytes([
        buf[offset],
        buf[offset + 1],
        buf[offset + 2],
        buf[offset + 3],
        buf[offset + 4],
        buf[offset + 5],
        buf[offset + 6],
        buf[offset + 7],
    ])
}

#[derive(Debug, Default, PartialEq)]
pub(super) struct CentralDirectoryEnd {
    pub(super) disk_number: u16,
    pub(super) disk_with_central_directory: u16,
    pub(super) disk_number_of_records: u16,
    pub(super) total_number_of_records: u16,
    pub(super) central_directory_size: u32,
    pub(super) central_directory_offset: u32,
    pub(super) comment: Vec<u8>,
}

impl CentralDirectoryEnd {
    const MIN_HEADER_SIZE: usize = 22;

    pub(super) fn build(&self) -> Vec<u8> {
        let mut buffer = Vec::with_capacity(Self::MIN_HEADER_SIZE);
        // End of directory signature
        buffer.extend(&CENTRAL_DIRECTORY_END_SIGNATURE.to_le_bytes());
        // Number of this disk
        buffer.extend(&self.disk_number.to_le_bytes());
        // Disk where central directory starts
        buffer.extend(&self.disk_with_central_directory.to_le_bytes());
        // Number of central directory records on this disk
        buffer.extend(&self.disk_number_of_records.to_le_bytes());
        // Total number of central directory records
        buffer.extend(&self.total_number_of_records.to_le_bytes());
        // Size of central directory (0xffffffff for ZIP64)
        buffer.extend(&self.central_directory_size.to_le_bytes());
        // Offset of central directory (0xffffffff for ZIP64)
        buffer.extend(&self.central_directory_offset.to_le_bytes());
        // Comment length
        buffer.extend(&(self.comment.len() as u16).to_le_bytes());
        // Comment
        buffer.extend(&self.comment);
        buffer
    }

    /// Find a ZIP header and position the reader at its beginning.
    pub(super) fn find<R: io::Read + io::Seek>(
        reader: &mut R,
    ) -> Result<u64, error::SeekHeaderError> {
        const COMMENT_SIZE: u64 = u16::MAX as u64;
        let end = reader.seek(io::SeekFrom::End(0))?;
        reader.seek(io::SeekFrom::Start(
            end.saturating_sub(Self::MIN_HEADER_SIZE as u64 + COMMENT_SIZE),
        ))?;
        let mut buffer = [0u8; 4];
        while let Ok(()) = reader.read_exact(&mut buffer[3..4]) {
            if buffer == CENTRAL_DIRECTORY_END_SIGNATURE.to_le_bytes() {
                return Ok(reader.seek(io::SeekFrom::Current(-4))?);
            }
            buffer.rotate_left(1);
        }
        Err(error::SeekHeaderError::NotFound(
            "Central directory end not found",
        ))
    }

    pub(super) fn parse(reader: &mut impl io::Read) -> Result<Self, error::HeaderParseError> {
        let mut buffer = [0u8; Self::MIN_HEADER_SIZE];
        reader
            .read_exact(&mut buffer)
            .map_err(|_| error::HeaderParseError::InvalidSignature)?;
        if buffer[0..4] != CENTRAL_DIRECTORY_END_SIGNATURE.to_le_bytes() {
            return Err(error::HeaderParseError::InvalidSignature);
        }
        Ok(Self {
            disk_number: bytes_to_u16(&buffer, 4),
            disk_with_central_directory: bytes_to_u16(&buffer, 6),
            disk_number_of_records: bytes_to_u16(&buffer, 8),
            total_number_of_records: bytes_to_u16(&buffer, 10),
            central_directory_size: bytes_to_u32(&buffer, 12),
            central_directory_offset: bytes_to_u32(&buffer, 16),
            comment: {
                let mut comment = vec![0u8; bytes_to_u16(&buffer, 20) as usize];
                reader.read_exact(&mut comment)?;
                comment
            },
        })
    }

    pub(super) fn size(&self) -> u64 {
        (Self::MIN_HEADER_SIZE + self.comment.len()) as u64
    }
}

#[derive(Debug, Clone, PartialEq)]
pub(super) struct Zip64CentralDirectoryEnd {
    pub(super) record_size: u64,
    pub(super) version_made_by: u16,
    pub(super) version_needed_to_extract: u16,
    pub(super) disk_number: u32,
    pub(super) disk_with_central_directory: u32,
    pub(super) disk_number_of_records: u64,
    pub(super) total_number_of_records: u64,
    pub(super) central_directory_size: u64,
    pub(super) central_directory_offset: u64,
}

impl Default for Zip64CentralDirectoryEnd {
    fn default() -> Self {
        Self {
            record_size: 44,
            version_made_by: VERSION_MADE_BY,
            version_needed_to_extract: DEFAULT_VERSION,
            disk_number: 0,
            disk_with_central_directory: 0,
            disk_number_of_records: 0,
            total_number_of_records: 0,
            central_directory_size: 0,
            central_directory_offset: 0,
        }
    }
}

impl Zip64CentralDirectoryEnd {
    pub(super) fn build(&self) -> Vec<u8> {
        let mut buffer = Vec::with_capacity(56);
        // Zip64 end of central directory record signature
        buffer.extend(&ZIP64_CENTRAL_DIRECTORY_END_SIGNATURE.to_le_bytes());
        // Record size
        buffer.extend(&self.record_size.to_le_bytes());
        // Version made by
        buffer.extend(&self.version_made_by.to_le_bytes());
        // Minimum version needed to extract
        buffer.extend(&self.version_needed_to_extract.to_le_bytes());
        // Number of this disk
        buffer.extend(&self.disk_number.to_le_bytes());
        // Disk where central directory starts
        buffer.extend(&self.disk_with_central_directory.to_le_bytes());
        // Number of central directory records on this disk
        buffer.extend(&self.disk_number_of_records.to_le_bytes());
        // Total number of central directory records
        buffer.extend(&self.total_number_of_records.to_le_bytes());
        // Size of central directory
        buffer.extend(&self.central_directory_size.to_le_bytes());
        // Offset of central directory
        buffer.extend(&self.central_directory_offset.to_le_bytes());

        buffer
    }

    /// Find the ZIP64 end of central directory record.
    ///
    /// For performance reasons the reader should be at the expected start of the ZIP64
    /// end of central directory record, which can be retrieved from the ZIP64 end of
    /// central directory locator.
    ///
    /// ZIP format permits prepending a ZIP archive with arbitrary data.
    /// We need to compensate for this when calculating the offset of the
    /// central directory.
    pub(super) fn find<R: io::Read + io::Seek>(
        reader: &mut R,
    ) -> Result<u64, error::SeekHeaderError> {
        let mut buffer = [0u8; 4];
        while let Ok(()) = reader.read_exact(&mut buffer[3..4]) {
            if buffer == ZIP64_CENTRAL_DIRECTORY_END_SIGNATURE.to_le_bytes() {
                return Ok(reader.seek(io::SeekFrom::Current(-4))?);
            }
            buffer.rotate_left(1);
        }
        Err(error::SeekHeaderError::NotFound(
            "Zip64 central directory end not found",
        ))
    }

    pub(super) fn parse<R: io::Read + io::Seek>(
        reader: &mut R,
    ) -> Result<Self, error::HeaderParseError> {
        let mut buffer = [0u8; 56];
        reader.read_exact(&mut buffer)?;
        if buffer[0..4] != ZIP64_CENTRAL_DIRECTORY_END_SIGNATURE.to_le_bytes() {
            return Err(error::HeaderParseError::InvalidSignature);
        }
        Ok(Self {
            record_size: bytes_to_u64(&buffer, 4),
            version_made_by: bytes_to_u16(&buffer, 12),
            version_needed_to_extract: bytes_to_u16(&buffer, 14),
            disk_number: bytes_to_u32(&buffer, 16),
            disk_with_central_directory: bytes_to_u32(&buffer, 20),
            disk_number_of_records: bytes_to_u64(&buffer, 24),
            total_number_of_records: bytes_to_u64(&buffer, 32),
            central_directory_size: bytes_to_u64(&buffer, 40),
            central_directory_offset: bytes_to_u64(&buffer, 48),
        })
    }
}

#[derive(Debug, Clone, PartialEq)]
pub(super) struct Zip64CentralDirectoryEndLocator {
    pub(super) disk_with_zip64_central_directory_end: u32,
    pub(super) zip64_central_directory_end_offset: u64,
    pub(super) total_number_of_disks: u32,
}

impl Zip64CentralDirectoryEndLocator {
    pub(super) const SIZE: u64 = 20;

    pub(super) fn build(&self) -> Vec<u8> {
        let mut buffer = Vec::with_capacity(20);
        // Zip64 end of central directory locator signature
        buffer.extend(&ZIP64_CENTRAL_DIRECTORY_END_LOCATOR_SIGNATURE.to_le_bytes());
        // Number of the disk with the start of the zip64 end of central directory
        buffer.extend(&self.disk_with_zip64_central_directory_end.to_le_bytes());
        // Relative offset of the zip64 end of central directory record
        buffer.extend(&self.zip64_central_directory_end_offset.to_le_bytes());
        // Total number of disks
        buffer.extend(&self.total_number_of_disks.to_le_bytes());
        buffer
    }

    pub(super) fn parse(
        reader: &mut impl io::Read,
    ) -> Result<Option<Self>, error::HeaderParseError> {
        let mut buffer = [0u8; 20];
        reader.read_exact(&mut buffer)?;
        if bytes_to_u32(&buffer, 0) == ZIP64_CENTRAL_DIRECTORY_END_LOCATOR_SIGNATURE {
            return Ok(Some(Self {
                disk_with_zip64_central_directory_end: bytes_to_u32(&buffer, 4),
                zip64_central_directory_end_offset: bytes_to_u64(&buffer, 8),
                total_number_of_disks: bytes_to_u32(&buffer, 16),
            }));
        }
        Ok(None)
    }
}

#[cfg(test)]
mod tests {
    use std::io::Cursor;

    use chrono::TimeZone;

    use super::*;

    #[test]
    fn test_to_msdos_time() {
        let dt = Utc.with_ymd_and_hms(2006, 10, 11, 15, 40, 56).unwrap();
        assert_eq!(0x7d1cu16, to_msdos_time(dt));
    }

    #[test]
    fn test_to_msdos_date() {
        let dt = Utc.with_ymd_and_hms(2006, 10, 11, 15, 40, 56).unwrap();
        assert_eq!(0x354bu16, to_msdos_date(dt));
    }

    #[test]
    fn test_from_msdos_time() {
        let dt = Utc.with_ymd_and_hms(2006, 10, 11, 15, 40, 56).unwrap();
        assert_eq!(dt, from_msdos_datetime(0x354b, 0x7d1c));
    }

    #[tokio::test]
    async fn test_local_file_header() {
        const LOCAL_FILE_HEADER_RAW: [u8; 38] = [
            0x50, 0x4b, 0x03, 0x04, // Local file header signature
            0x2d, 0x00, // Minimum version needed to extract
            0x00, 0x00, // General purpose bit flag
            0x00, 0x00, // Compression method (0 = stored)
            0x1c, 0x7d, // Last mod file time
            0x4b, 0x35, // Last mod file date
            0x00, 0x00, 0x00, 0x00, // CRC-32
            0x2a, 0x00, 0x00, 0x00, // Compressed size
            0x2a, 0x00, 0x00, 0x00, // Uncompressed size
            0x08, 0x00, // File name length
            0x00, 0x00, // Extra field length
            0x74, 0x65, 0x73, 0x74, 0x2e, 0x74, 0x78, 0x74, // File name
        ];
        let header = LocalFileHeader {
            compression_method: 0,
            crc32: 0,
            flags: 0,
            modified: Utc.with_ymd_and_hms(2006, 10, 11, 15, 40, 56).unwrap(),
            name: Cow::Borrowed("test.txt"),
            size: 42,
            header_size: 38,
        };
        assert_eq!(LOCAL_FILE_HEADER_RAW, header.build().as_slice());
        assert_eq!(
            header,
            LocalFileHeader::parse(&mut Cursor::new(LOCAL_FILE_HEADER_RAW))
                .await
                .unwrap()
        );
    }

    #[test]
    fn test_data_descriptor_32() {
        let descriptor = DataDescriptor {
            crc32: 0x12345678u32,
            size: 42,
        };
        let expected = [
            0x50, 0x4b, 0x07, 0x08, // Data descriptor signature
            0x78, 0x56, 0x34, 0x12, // CRC-32
            0x2a, 0x00, 0x00, 0x00, // Compressed size
            0x2a, 0x00, 0x00, 0x00, // Uncompressed size
        ];
        assert_eq!(expected, descriptor.build().as_slice());
    }

    #[test]
    fn test_data_descriptor_64() {
        let descriptor = DataDescriptor {
            crc32: 0x12345678u32,
            size: u32::MAX as u64 * 2,
        };
        let expected = [
            0x50, 0x4b, 0x07, 0x08, // Data descriptor signature
            0x78, 0x56, 0x34, 0x12, // CRC-32
            0xfe, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, // Compressed size
            0xfe, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, // Uncompressed size
        ];
        assert_eq!(expected, descriptor.build().as_slice());
    }

    #[test]
    fn test_central_directory_header() {
        fn generate_central_directory_header(zip64: bool) -> CentralDirectoryHeader<'static> {
            CentralDirectoryHeader {
                compression_method: 0,
                crc32: 0x12345678u32,
                external_attributes: 0o100644 << 16,
                flags: 0,
                modified: Utc.with_ymd_and_hms(2006, 10, 11, 15, 40, 56).unwrap(),
                name: Cow::Borrowed("test.txt"),
                offset: if zip64 { u32::MAX as u64 * 2 } else { 0xff },
                size: if zip64 { u32::MAX as u64 * 2 } else { 42 },
            }
        }
        const CENTRAL_DIRECTORY_HEADER_ZIP32_RAW: [u8; 54] = [
            0x50, 0x4b, 0x01, 0x02, // Central file header signature
            0x2d, 0x03, // Version made by
            0x2d, 0x00, // Version needed to extract
            0x00, 0x00, // General purpose bit flag
            0x00, 0x00, // Compression method (0 = stored)
            0x1c, 0x7d, // Last mod file time
            0x4b, 0x35, // Last mod file date
            0x78, 0x56, 0x34, 0x12, // CRC-32
            0x2a, 0x00, 0x00, 0x00, // Compressed size
            0x2a, 0x00, 0x00, 0x00, // Uncompressed size
            0x08, 0x00, // File name length
            0x00, 0x00, // Extra field length
            0x00, 0x00, // File comment length
            0x00, 0x00, // Disk number where file starts
            0x00, 0x00, // Internal file attributes
            0x00, 0x00, 0xa4, 0x81, // External file attributes
            0xff, 0x00, 0x00, 0x00, // Relative offset of local file header
            0x74, 0x65, 0x73, 0x74, 0x2e, 0x74, 0x78, 0x74, // File name
        ];

        const CENTRAL_DIRECTORY_HEADER_ZIP64_RAW: [u8; 82] = [
            0x50, 0x4b, 0x01, 0x02, // Central file header signature
            0x2d, 0x03, // Version made by
            0x2d, 0x00, // Version needed to extract
            0x00, 0x00, // General purpose bit flag
            0x00, 0x00, // Compression method (0 = stored)
            0x1c, 0x7d, // Last mod file time
            0x4b, 0x35, // Last mod file date
            0x78, 0x56, 0x34, 0x12, // CRC-32
            0xff, 0xff, 0xff, 0xff, // Compressed size
            0xff, 0xff, 0xff, 0xff, // Uncompressed size
            0x08, 0x00, // File name length
            0x1c, 0x00, // Extra field length
            0x00, 0x00, // File comment length
            0x00, 0x00, // Disk number where file starts
            0x00, 0x00, // Internal file attributes
            0x00, 0x00, 0xa4, 0x81, // External file attributes
            0xff, 0xff, 0xff, 0xff, // Relative offset of local file header
            0x74, 0x65, 0x73, 0x74, 0x2e, 0x74, 0x78, 0x74, // File name
            // Extra field
            0x01, 0x00, // Zip64 extended information extra field
            0x18, 0x00, // Size of this extra field
            0xfe, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, // Original size
            0xfe, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, // Compressed size
            0xfe, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, // Offset
        ];
        assert_eq!(
            CENTRAL_DIRECTORY_HEADER_ZIP32_RAW,
            generate_central_directory_header(false).build().as_slice()
        );
        assert_eq!(
            CENTRAL_DIRECTORY_HEADER_ZIP64_RAW,
            generate_central_directory_header(true).build().as_slice()
        );
        assert_eq!(
            generate_central_directory_header(false),
            CentralDirectoryHeader::parse(&mut Cursor::new(CENTRAL_DIRECTORY_HEADER_ZIP32_RAW))
                .unwrap()
        );
        assert_eq!(
            generate_central_directory_header(true),
            CentralDirectoryHeader::parse(&mut Cursor::new(CENTRAL_DIRECTORY_HEADER_ZIP64_RAW))
                .unwrap()
        );
    }

    #[test]
    fn test_central_directory_end() {
        const CENTRAL_DIRECTORY_END_RAW: [u8; 22] = [
            0x50, 0x4b, 0x05, 0x06, // End of central directory signature
            0x00, 0x00, // Number of this disk
            0x00, 0x00, // Disk where central directory starts
            0x01, 0x00, // Number of central directory records on this disk
            0x01, 0x00, // Total number of central directory records
            0x2d, 0x00, 0x00, 0x00, // Size of central directory (bytes)
            0xff, 0x00, 0x00, 0x00, // Offset of start of directory
            0x00, 0x00, // Comment length
        ];
        const CENTRAL_DIRECTORY_END: CentralDirectoryEnd = CentralDirectoryEnd {
            disk_number: 0,
            disk_with_central_directory: 0,
            disk_number_of_records: 1,
            total_number_of_records: 1,
            central_directory_size: 0x2d,
            central_directory_offset: 0xff,
            comment: vec![],
        };
        assert_eq!(
            CENTRAL_DIRECTORY_END_RAW,
            CENTRAL_DIRECTORY_END.build().as_slice()
        );
        assert_eq!(
            CENTRAL_DIRECTORY_END,
            CentralDirectoryEnd::parse(&mut Cursor::new(CENTRAL_DIRECTORY_END_RAW)).unwrap()
        );
    }

    #[test]
    fn test_zip64_central_directory_end() {
        const ZIP64_CENTRAL_DIRECTORY_END_RAW: [u8; 56] = [
            0x50, 0x4b, 0x06, 0x06, // Zip64 end of central directory signature
            0x2c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Size of this record
            0x2d, 0x03, // Version made by
            0x2d, 0x00, // Version needed to extract
            0x00, 0x00, 0x00, 0x00, // Number of this disk
            0x00, 0x00, 0x00, 0x00, // Disk where central directory starts
            // Number of central directory records on this disk
            0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            // Total number of central directory records
            0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            // Size of central directory (bytes)
            0x2d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Offset of start of directory
            0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        ];
        const ZIP64_CENTRAL_DIRECTORY_END: Zip64CentralDirectoryEnd = Zip64CentralDirectoryEnd {
            disk_number_of_records: 1,
            total_number_of_records: 1,
            central_directory_size: 0x2d,
            central_directory_offset: 0xff,
            version_made_by: VERSION_MADE_BY,
            version_needed_to_extract: DEFAULT_VERSION,
            disk_number: 0,
            disk_with_central_directory: 0,
            record_size: 44,
        };
        assert_eq!(
            ZIP64_CENTRAL_DIRECTORY_END_RAW,
            ZIP64_CENTRAL_DIRECTORY_END.build().as_slice()
        );
        assert_eq!(
            ZIP64_CENTRAL_DIRECTORY_END,
            Zip64CentralDirectoryEnd::parse(&mut Cursor::new(ZIP64_CENTRAL_DIRECTORY_END_RAW))
                .unwrap()
        );
    }

    #[test]
    fn test_zip64_central_directory_end_locator() {
        const ZIP64_CENTRAL_DIRECTORY_END_LOCATOR: Zip64CentralDirectoryEndLocator =
            Zip64CentralDirectoryEndLocator {
                disk_with_zip64_central_directory_end: 0,
                zip64_central_directory_end_offset: u32::MAX as u64 * 2,
                total_number_of_disks: 1,
            };
        const ZIP64_CENTRAL_DIRECTORY_END_LOCATOR_RAW: [u8; 20] = [
            0x50, 0x4b, 0x06, 0x07, // Zip64 end of central dir locator signature
            // Number of the disk with the start of the zip64 end of central directory
            0x00, 0x00, 0x00, 0x00,
            // Relative offset of the zip64 end of central directory record
            0xfe, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, //
            // Total number of disks
            0x01, 0x00, 0x00, 0x00,
        ];
        assert_eq!(
            ZIP64_CENTRAL_DIRECTORY_END_LOCATOR_RAW,
            ZIP64_CENTRAL_DIRECTORY_END_LOCATOR.build().as_slice()
        );
        assert_eq!(
            Some(ZIP64_CENTRAL_DIRECTORY_END_LOCATOR),
            Zip64CentralDirectoryEndLocator::parse(&mut Cursor::new(
                ZIP64_CENTRAL_DIRECTORY_END_LOCATOR_RAW
            ))
            .unwrap()
        );
    }
}