stuffr-cli 0.16.1

The stuffr command line interface
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
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
//! `fileio.c`'s archive input and strings: `open_input_file()`, `readbuf()`,
//! `seek_zipf()`, `do_string()`, `makeword()`/`makelong()`/`makeint64()`,
//! `dos_to_unix_time()`; `extract.c`'s `fnfilter()`; the `localtime()` the
//! listings call; the pager's pause (`UzpMorePause()`) and the password
//! prompt (`UzpPassword()`).
//!
//! The archive is read as the C reads it: `read(2)` of `INBUFSIZ` blocks
//! into `G.inbuf`, `lseek(2)` to block boundaries, with `G.incnt`,
//! `G.inptr` and `G.cur_zipfile_bufstart` kept as the C keeps them, so a
//! short read, a seek past the end or a seek that fails leaves the same
//! state behind. Every allocation is bounded by a field's width (a name, an
//! extra field or a comment is at most 64 KiB) or by a constant.

use std::io::{Read, Seek, SeekFrom};

use super::messages as m;
use super::unix::charset;
use super::{PK_COOL, PK_EOF, PK_ERR, PK_OK, PK_WARN, Uz, flavour};
use crate::compat::host::{Host, InFile};

/// unzpriv.h's `INBUFSIZ` ("larger buffers for real OSes").
pub(crate) const INBUFSIZ: usize = 8192;
/// unzpriv.h's `OUTBUFSIZ` (`lenEOL*WSIZE`).
pub(crate) const OUTBUFSIZ: usize = stuffr::infozip::WSIZE;
/// unzpriv.h's `WSIZE`.
pub(crate) const WSIZE: usize = stuffr::infozip::WSIZE;

/// unzpriv.h's `CR`.
const CR: u8 = 13;
/// unzpriv.h's `LF`.
const LF: u8 = 10;

/// unzpriv.h's version-made-by host numbers this file reads.
pub(crate) const FS_FAT_: u8 = 0;
pub(crate) const FS_HPFS_: u8 = 6;
pub(crate) const FS_NTFS_: u8 = 11;

/// `do_string()`'s options (unzpriv.h `SKIP` .. `DS_FN_L`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum DoString {
    /// `SKIP`: step over the string.
    Skip,
    /// `DISPLAY`: print it (the archive comment).
    Display,
    /// `DISPL_8`: print it after the host's code page conversion (an
    /// entry's comment).
    Displ8,
}

/// `G.pInfo`'s fields that `do_string()` reads (list.c's `min_info info`):
/// set by `process_cdir_file_hdr()`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct PInfo {
    /// `hostver`: the version-made-by's low byte.
    pub hostver: u8,
    /// `hostnum`: the version-made-by's high byte, at most `NUM_HOSTS`.
    pub hostnum: u8,
    /// `lcflag`: lowercase the name (`-L`, `-LL`).
    pub lcflag: bool,
    /// `vollabel`: the entry is an MS-DOS volume label.
    pub vollabel: bool,
    /// `HasUxAtt`: the external attributes' high 16 bits are set.
    pub has_ux_att: bool,
    /// `GPFIsUTF8` (ubuntu: -DUNICODE_SUPPORT): the central header's
    /// general-purpose bit 11, "the name and comment are UTF-8".
    pub gpf_is_utf8: bool,
}

/// The archive input: `G.zipfd` and `readbuf()`'s buffer state.
pub(crate) struct ZipIn {
    /// `G.zipfd`: the open archive.
    pub(crate) fd: Option<InFile>,
    /// `G.inbuf`, `INBUFSIZ + 4` bytes (the last 4 are `G.hold`, for a
    /// signature that spans two blocks of `rec_find()`'s backward search).
    /// ruling: process_zipfiles' `malloc(INBUFSIZ + 4)` leaves it
    /// uninitialised, and `rec_find()` can compare `G.hold` before writing
    /// it (a tail shorter than a record); a fresh buffer reads as zeros
    /// here. It lives across archives, as the C's does.
    pub(crate) inbuf: Box<[u8]>,
    /// `G.incnt`: bytes left in `inbuf` from `inptr` (a C `int`; negative
    /// after a failed `read()`).
    pub(crate) incnt: i64,
    /// `G.inptr`, as an index into `inbuf`.
    pub(crate) inptr: usize,
    /// `G.cur_zipfile_bufstart`: the file offset `inbuf` was read from.
    pub(crate) cur_zipfile_bufstart: i64,
    /// `G.extra_bytes`: bytes before the archive proper (a preamble).
    pub(crate) extra_bytes: i64,
    /// `G.ziplen`: the archive's size by `stat()`.
    pub(crate) ziplen: i64,
    /// `G.inptr_leftover`, `G.incnt_leftover`: the buffer's bytes past the
    /// entry being decoded (`defer_leftover_input()`).
    pub(crate) inptr_leftover: usize,
    pub(crate) incnt_leftover: i64,
}

impl Default for ZipIn {
    /// A stand-in while the extraction holds the real one (no buffer, no
    /// archive).
    fn default() -> ZipIn {
        ZipIn {
            fd: None,
            inbuf: Box::default(),
            incnt: 0,
            inptr: 0,
            cur_zipfile_bufstart: 0,
            extra_bytes: 0,
            ziplen: 0,
            inptr_leftover: 0,
            incnt_leftover: 0,
        }
    }
}

impl ZipIn {
    pub(crate) fn new() -> ZipIn {
        ZipIn {
            fd: None,
            inbuf: vec![0u8; INBUFSIZ + 4].into_boxed_slice(),
            incnt: 0,
            inptr: 0,
            cur_zipfile_bufstart: 0,
            extra_bytes: 0,
            ziplen: 0,
            inptr_leftover: 0,
            incnt_leftover: 0,
        }
    }

    /// `read(G.zipfd, G.inbuf + at, n)`: the count, 0 at the end, -1 on an
    /// error (or with no archive open).
    pub(crate) fn read_at(&mut self, at: usize, n: usize) -> i64 {
        let Some(fd) = self.fd.as_mut() else {
            return -1;
        };
        loop {
            match fd.read(&mut self.inbuf[at..at + n]) {
                Ok(k) => return k as i64,
                Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
                Err(_) => return -1,
            }
        }
    }

    /// `read(G.zipfd, buf, buf.len())` into a caller's buffer.
    pub(crate) fn read_into(&mut self, buf: &mut [u8]) -> i64 {
        let Some(fd) = self.fd.as_mut() else {
            return -1;
        };
        loop {
            match fd.read(buf) {
                Ok(k) => return k as i64,
                Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
                Err(_) => return -1,
            }
        }
    }

    /// `lseek(G.zipfd, off, SEEK_SET)`: the new offset, or -1 (a negative
    /// offset, or the system's refusal), the position then unchanged.
    pub(crate) fn lseek(&mut self, off: i64) -> i64 {
        let Some(fd) = self.fd.as_mut() else {
            return -1;
        };
        if off < 0 {
            return -1;
        }
        fd.seek(SeekFrom::Start(off as u64))
            .map_or(-1, |p| p as i64)
    }
}

// port: fileio.c:makeword
/// A little-endian 16-bit field.
pub(crate) fn makeword(b: &[u8]) -> u16 {
    u16::from(b[0]) | (u16::from(b[1]) << 8)
}

// port: fileio.c:makelong
/// A little-endian 32-bit field.
pub(crate) fn makelong(b: &[u8]) -> u32 {
    u32::from_le_bytes([b[0], b[1], b[2], b[3]])
}

// port: fileio.c:makeint64
/// A little-endian 64-bit field, as `LARGE_FILE_SUPPORT`'s `makeint64()`
/// assembles it: upstream's leaves out byte 5 (bits 40..47), so Apple's
/// unzip reads `0x0000_ff00_0000_0000` as 0.
/// ubuntu: 21-fix-warning-messages-on-big-files.patch adds byte 5
/// (`flavour::makeint64_reads_byte_5`).
pub(crate) fn makeint64(f: flavour::Flavour, b: &[u8]) -> u64 {
    let mut v = (u64::from(b[7]) << 56)
        .wrapping_add(u64::from(b[6]) << 48)
        .wrapping_add(u64::from(b[4]) << 32)
        .wrapping_add(u64::from(makelong(b)));
    if flavour::makeint64_reads_byte_5(f) {
        v = v.wrapping_add(u64::from(b[5]) << 40);
    }
    v
}

// port: fileio.c:readbuf
/// Up to `buf.len()` bytes of the archive from the buffer, refilling it a
/// block at a time: the count read (short only at the end; 0 after a read
/// error, which `ReadError` reports).
pub(crate) fn readbuf(uz: &mut Uz, buf: &mut [u8]) -> usize {
    let n = buf.len();
    let mut size = n;
    let mut at = 0usize;
    while size > 0 {
        if uz.zin.incnt <= 0 {
            uz.zin.incnt = uz.zin.read_at(0, INBUFSIZ);
            if uz.zin.incnt == 0 {
                return n - size;
            } else if uz.zin.incnt < 0 {
                // another hack, but no real harm copying same thing twice
                uz.info(0x401, m::READ_ERROR.as_bytes());
                return 0; // discarding some data; better than lock-up
            }
            // buffer ALWAYS starts on a block boundary:
            uz.zin.cur_zipfile_bufstart = uz.zin.cur_zipfile_bufstart.wrapping_add(INBUFSIZ as i64);
            uz.zin.inptr = 0;
        }
        let count = size.min(uz.zin.incnt as usize);
        let from = uz.zin.inptr;
        // ruling: `find_ecrec64()` sets `G.incnt` to what it read into its
        // own buffer, and when the directory starts in the block it last
        // seeked to, `seek_zipf()` keeps `G.inbuf` and adds to that count:
        // `G.inptr + G.incnt` can then pass the buffer's end by up to 52
        // bytes, which the C reads from beyond its allocation (undefined
        // behaviour). Those bytes read as zeros here.
        for (k, b) in buf[at..at + count].iter_mut().enumerate() {
            *b = uz.zin.inbuf.get(from + k).copied().unwrap_or(0);
        }
        at += count;
        uz.zin.inptr += count;
        uz.zin.incnt -= count as i64;
        size -= count;
    }
    n
}

// port: fileio.c:seek_zipf
/// Position the buffer at `abs_offset` (an offset as if there were no
/// extra bytes): `PK_BADERR` before the start of the file, `PK_EOF` past
/// its end, else `PK_OK`.
pub(crate) fn seek_zipf(uz: &mut Uz, abs_offset: i64) -> i32 {
    let request = abs_offset.wrapping_add(uz.zin.extra_bytes);
    let inbuf_offset = request.wrapping_rem(INBUFSIZ as i64);
    let bufstart = request.wrapping_sub(inbuf_offset);

    if request < 0 {
        let msg = {
            let mut b = Vec::new();
            m::printf(
                &mut b,
                m::SEEK_MSG,
                &[&uz.zipfn.clone(), m::REPORT_MSG.as_bytes()],
            );
            b
        };
        uz.info(1, &msg);
        return super::PK_BADERR;
    } else if bufstart != uz.zin.cur_zipfile_bufstart {
        uz.zin.cur_zipfile_bufstart = uz.zin.lseek(bufstart);
        uz.zin.incnt = uz.zin.read_at(0, INBUFSIZ);
        if uz.zin.incnt <= 0 {
            return PK_EOF;
        }
        uz.zin.incnt -= inbuf_offset;
        uz.zin.inptr = inbuf_offset as usize;
    } else {
        uz.zin.incnt += uz.zin.inptr as i64 - inbuf_offset;
        uz.zin.inptr = inbuf_offset as usize;
    }
    PK_OK
}

/// The offset `seek_zipf()` takes for the byte at `G.inptr` plus `length`
/// (`G.cur_zipfile_bufstart - G.extra_bytes + (G.inptr-G.inbuf) + length`).
fn here_plus(uz: &Uz, length: usize) -> i64 {
    uz.zin
        .cur_zipfile_bufstart
        .wrapping_sub(uz.zin.extra_bytes)
        .wrapping_add(uz.zin.inptr as i64)
        .wrapping_add(length as i64)
}

/// unzpriv.h's `Ext_ASCII_TO_Native()` on unix (`CRTL_CP_IS_ISO`): names
/// and comments from MS-DOS FAT (except PKZIP 2.5, 2.6 and 4.0 with Unix
/// attributes or in a local header), OS/2 HPFS and Windows NT 5.0 are OEM
/// code page 850 (`_OEM_INTERN`, `oem2iso_850`); everything else is ISO
/// 8859-1 already (`_ISO_INTERN` is `A_TO_N`, nothing on ASCII). In
/// place, up to the string's NUL.
/// ubuntu: 20-unzip60-alt-iconv-utf8.patch makes `_OEM_INTERN` and
/// `_ISO_INTERN` `oem_intern()` and `iso_intern()`: the string converted
/// from `OEM_CP` or `ISO_CP` to the locale's character set through
/// `iconv(3)` (`unix::charset`), or left as it is (no table); and every
/// Windows NT archive is OEM, whatever its version. On success the
/// string's buffer is rewritten as `strncpy(string, buf, FILNAMSIZ)` does:
/// the converted text, then zeros up to `FILNAMSIZ` bytes.
pub(crate) fn ext_ascii_to_native(uz: &Uz, s: &mut [u8], p: &PInfo, islochdr: bool) {
    let ubuntu = flavour::iconv_charsets(uz.flavour);
    let oem = (p.hostnum == FS_FAT_
        && !((islochdr || p.has_ux_att)
            && (p.hostver == 25 || p.hostver == 26 || p.hostver == 40)))
        || p.hostnum == FS_HPFS_
        // ubuntu: 20-unzip60-alt-iconv-utf8.patch (`/* && (hostver) == 50 */`)
        || (p.hostnum == FS_NTFS_ && (ubuntu || p.hostver == 50));
    if ubuntu {
        // ubuntu: 20-unzip60-alt-iconv-utf8.patch
        let from = if oem { &uz.o.oem_cp } else { &uz.o.iso_cp };
        let buflen = flavour::filnamsiz(uz.flavour);
        if let Some(out) = charset::charset_to_intern(&uz.host, s, from, buflen) {
            let n = s.len().min(buflen);
            s[..n].fill(0);
            let k = out.len().min(n);
            s[..k].copy_from_slice(&out[..k]);
        }
        return;
    }
    if oem {
        for b in s.iter_mut() {
            if *b == 0 {
                break;
            }
            if *b & 0x80 != 0 {
                *b = m::OEM2ISO_850[usize::from(*b & 0x7f)];
            }
        }
    }
}

/// unzpriv.h's `STRLOWER` (unix `isupper`/`tolower`, ASCII in every locale
/// deviation 6 admits), in place up to the string's NUL.
pub(crate) fn strlower(s: &mut [u8]) {
    for b in s.iter_mut() {
        if *b == 0 {
            break;
        }
        b.make_ascii_lowercase();
    }
}

/// The C string in `buf`: up to its first NUL.
pub(crate) fn c_str(buf: &[u8]) -> &[u8] {
    match buf.iter().position(|&b| b == 0) {
        Some(n) => &buf[..n],
        None => buf,
    }
}

// port: fileio.c:do_string
/// `do_string(length, SKIP | DISPLAY | DISPL_8)`: step over the `length`
/// bytes at the archive's current position, or print them (CRs dropped,
/// `ESC` shown as `^[`, `^S` dropped, `DISPL_8` after the host's code page
/// conversion), then a newline if the text did not end one. `pinfo` is
/// `G.pInfo`, which `DISPL_8` reads. While extracting, a `^S` (with the
/// line end after it) flushes the text so far and pauses
/// ([`more_pause`]'s "Press `Q' to quit").
///
/// The text is formatted into `uz.slide`, as the C formats into `slide[]`.
/// ruling: the C strips CRs with `while (*p) { while (*p == CR) ++p; *q++ =
/// *p++; }`, which steps past the terminator when a block ends in CRs and
/// then scans bytes after it (past `G.outbuf`'s end for a full block);
/// what it prints is the block up to its first NUL with the CRs taken out
/// either way, and that is what is printed here, without reading further.
pub(crate) fn do_string(
    uz: &mut Uz,
    length: usize,
    option: DoString,
    pinfo: Option<&PInfo>,
) -> i32 {
    if length == 0 {
        return PK_COOL;
    }
    match option {
        DoString::Display | DoString::Displ8 => {
            let mut comment_bytes_left = length;
            let mut block_len = OUTBUFSIZ; // for the while statement, first time
            let mut outbuf = vec![0u8; OUTBUFSIZ.min(length)];
            while comment_bytes_left > 0 && block_len > 0 {
                let want = OUTBUFSIZ.min(comment_bytes_left);
                block_len = readbuf(uz, &mut outbuf[..want]);
                if block_len == 0 {
                    return PK_EOF;
                }
                comment_bytes_left -= block_len;

                // the block as a C string, with every CR removed
                let mut text: Vec<u8> = c_str(&outbuf[..block_len])
                    .iter()
                    .copied()
                    .filter(|&b| b != CR)
                    .collect();
                if option == DoString::Displ8
                    && let Some(p) = pinfo
                {
                    // `G.outbuf` is longer than `FILNAMSIZ`: the converted
                    // text is a C string in it
                    let mut buf = text.clone();
                    buf.resize((text.len() + 1).max(flavour::filnamsiz(uz.flavour)), 0);
                    ext_ascii_to_native(uz, &mut buf, p, false);
                    text = c_str(&buf).to_vec();
                }
                // ASCII, filter out ANSI escape sequences and handle ^S
                let mut q = 0usize;
                let mut i = 0usize;
                while i < text.len() {
                    let mut pause = false;
                    let c = text[i];
                    if c == 0x1b {
                        // ASCII escape char
                        uz.slide[q] = b'^';
                        uz.slide[q + 1] = b'[';
                        q += 2;
                    } else if c == 0x13 {
                        // ASCII ^S (pause)
                        pause = true;
                        let at = |k: usize| text.get(k).copied().unwrap_or(0);
                        if at(i + 1) == LF {
                            i += 1;
                            uz.slide[q] = text[i];
                            q += 1;
                        } else if at(i + 1) == CR && at(i + 2) == LF {
                            // (no CR is left in `text`: never taken)
                            i += 1;
                            uz.slide[q] = text[i];
                            i += 1;
                            uz.slide[q + 1] = text[i];
                            q += 2;
                        }
                    } else {
                        uz.slide[q] = c;
                        q += 1;
                    }
                    if q > WSIZE - 3 || pause {
                        // flush
                        let out = uz.slide[..q].to_vec();
                        uz.info(0, &out);
                        q = 0;
                        if pause && uz.extract_flag {
                            // don't pause for list/test
                            more_pause(uz, m::QUIT_PROMPT.as_bytes(), 0);
                            if uz.abort.is_some() {
                                // ruling: T11-7. `q` in a sandbox: the C
                                // has exited
                                return PK_COOL;
                            }
                        }
                    }
                    i += 1;
                }
                let out = uz.slide[..q].to_vec();
                uz.info(0, &out);
            }
            // add '\n' if not at start of line
            uz.info(super::MSG_TNEWLN, b"");
            PK_COOL
        }
        DoString::Skip => {
            // cur_zipfile_bufstart already takes account of extra_bytes, so
            // don't correct for it twice
            let to = here_plus(uz, length);
            seek_zipf(uz, to);
            PK_COOL
        }
    }
}

// port: fileio.c:do_string
/// `do_string(length, DS_FN)` (`islochdr` false) or `DS_FN_L`: read the
/// entry's name into `G.filename` (`uz.filename`, `FILNAMSIZ` bytes that
/// keep what an earlier name left past the new one's terminator, as the
/// C's array does), truncated to `FILNAMSIZ - 1` bytes with a warning,
/// converted from the host's code page, lowercased under `lcflag`, and a
/// volume label's dot after 8 characters removed. Returns the PK code
/// (`PK_WARN` for a truncated name, `PK_EOF` when nothing could be read).
pub(crate) fn read_filename(uz: &mut Uz, length: usize, pinfo: &PInfo, islochdr: bool) -> i32 {
    if length == 0 {
        return PK_COOL;
    }
    if flavour::unicode_support(uz.flavour) {
        return read_filename_full(uz, length, pinfo, islochdr);
    }
    let filnamsiz = uz.filename.len();
    let mut error = PK_OK;
    let mut length = length;
    let block_len = if length >= filnamsiz {
        uz.info(0x401, m::FILENAME_TOO_LONG_TRUNC.as_bytes());
        error = PK_WARN;
        // remember excess length in block_len
        let excess = length - (filnamsiz - 1);
        length = filnamsiz - 1;
        excess
    } else {
        0 // no excess size
    };
    let mut name = std::mem::take(&mut uz.filename);
    let got = readbuf(uz, &mut name[..length]);
    if got == 0 {
        uz.filename = name;
        return PK_EOF;
    }
    // A short read keeps the bytes past it from the earlier name.
    name[length] = 0; // terminate w/zero:  ASCIIZ

    native_name(uz, &mut name, length, pinfo, islochdr);
    uz.filename = name;

    if block_len == 0 {
        // no overflow, we're done here
        return error;
    }

    // We truncated the filename, so print what's left and then fall
    // through to the SKIP routine.
    let name = uz.filename.clone();
    let shown = fnfilter1(uz, c_str(&name));
    let mut msg = Vec::new();
    m::printf(&mut msg, m::TRUNCATED_NAME, &[&shown]);
    uz.info(0x401, &msg);
    let to = here_plus(uz, block_len);
    seek_zipf(uz, to);
    error
}

/// What `do_string(DS_FN)` does to a name once read: the host's code page
/// converted, lowercased under `lcflag`, a volume label's dot after 8
/// characters removed.
fn native_name(uz: &Uz, name: &mut [u8], length: usize, pinfo: &PInfo, islochdr: bool) {
    // translate the Zip entry filename coded in host-dependent "extended
    // ASCII" into the compiler's (system's) internal text code page
    ext_ascii_to_native(uz, name, pinfo, islochdr);

    if pinfo.lcflag {
        // replace with lowercase filename
        strlower(name);
    }

    if pinfo.vollabel && length > 8 && name[8] == b'.' {
        // disk label, and 8th char is dot:  remove dot
        let mut i = 8;
        while name[i] != 0 {
            name[i] = name[i + 1];
            i += 1;
        }
    }
}

// port: fileio.c:do_string
/// ubuntu: -DUNICODE_SUPPORT. `do_string(DS_FN)`'s Unicode build: the whole
/// name read into `G.filename_full` (grown to `length + 1` bytes when it is
/// too small, `FILNAMSIZ` at least), for the Unicode Path checksum, then
/// its first `FILNAMSIZ - 1` bytes into `G.filename` (`strncpy()`: to the
/// first NUL, zeros after), with the warning and `PK_WARN` when that cuts
/// it. Nothing is left to skip, so no `[ ... ]` line.
/// ruling: T13-7. A grown buffer is `malloc()`ed (its bytes past what a
/// short read gave are uninitialised); here they are zeros.
fn read_filename_full(uz: &mut Uz, length: usize, pinfo: &PInfo, islochdr: bool) -> i32 {
    let filnamsiz = uz.filename.len();
    let mut error = PK_OK;
    let mut full = uz.filename_full.take().unwrap_or_default();
    if full.len() <= length {
        full = vec![0u8; filnamsiz.max(length + 1)];
    }
    let got = readbuf(uz, &mut full[..length]);
    if got == 0 {
        uz.filename_full = Some(full);
        return PK_EOF;
    }
    full[length] = 0; // terminate w/zero:  ASCIIZ

    // if needed, chop off end so standard filename is a valid length
    let mut length = length;
    if length >= filnamsiz {
        uz.info(0x401, m::FILENAME_TOO_LONG_TRUNC.as_bytes());
        error = PK_WARN;
        length = filnamsiz - 1;
    }
    // no excess size
    let mut name = std::mem::take(&mut uz.filename);
    strncpy(&mut name, &full, length);
    name[length] = 0; // terminate w/zero:  ASCIIZ
    uz.filename_full = Some(full);
    native_name(uz, &mut name, length, pinfo, islochdr);
    uz.filename = name;
    error
}

/// `strncpy(dst, src, n)`: the C string `src`'s bytes, at most `n`, then
/// zeros up to `n`.
fn strncpy(dst: &mut [u8], src: &[u8], n: usize) {
    let s = c_str(src);
    let k = s.len().min(n);
    dst[..k].copy_from_slice(&s[..k]);
    dst[k..n].fill(0);
}

// port: fileio.c:do_string
/// ubuntu: -DUNICODE_SUPPORT. `do_string(EXTRA_FIELD)`'s tail, once the
/// field `ef` is read (and unless `-UU`): the entry's UTF-8 name, the
/// stored one when its general-purpose bit 11 is set (`pinfo`, the central
/// header's), else a Unicode Path block's, replaces `G.filename`: as it
/// is under a UTF-8 locale (and no `-U`), converted to the locale's
/// encoding otherwise (`utf8_to_local_string()`), each cut to `FILNAMSIZ -
/// 1` bytes with a warning (`PK_WARN`). A name that is not UTF-8 is
/// "Unicode filename corrupt", `PK_ERR`, and the name is left as it was.
/// Returns the code.
pub(crate) fn unicode_name(uz: &mut Uz, ef: &[u8], pinfo: &PInfo) -> i32 {
    use super::process::unicode::{self, UniPath};
    if uz.o.u_flag >= 2 {
        return PK_COOL;
    }
    let full = uz.filename_full.clone();
    // check if GPB11 (General Purpuse Bit 11) is set indicating the
    // standard path and comment are UTF-8
    let unipath: Option<Vec<u8>> = if pinfo.gpf_is_utf8 {
        // if GPB11 set then filename_full is untruncated UTF-8
        full.as_deref().map(|f| c_str(f).to_vec())
    } else {
        // Get the Unicode fields if exist
        match unicode::get_unicode_data(uz, ef, full.as_deref()).1 {
            UniPath::None => None,
            // the standard filename field is UTF-8
            UniPath::Standard => full.as_deref().map(|f| c_str(f).to_vec()),
            UniPath::Name(n) => Some(n),
        }
    };
    let Some(unipath) = unipath else {
        return PK_COOL;
    };
    let filnamsiz = uz.filename.len();
    let mut error = PK_COOL;
    // ubuntu: -DUTF8_MAYBE_NATIVE
    if uz.native_is_utf8 && !uz.unicode_escape_all {
        let mut name = std::mem::take(&mut uz.filename);
        strncpy(&mut name, &unipath, filnamsiz - 1);
        uz.filename = name;
        // make sure filename is short enough
        if unipath.len() >= filnamsiz {
            uz.filename[filnamsiz - 1] = 0;
            uz.info(0x401, m::UFILENAME_TOO_LONG_TRUNC.as_bytes());
            error = PK_WARN;
        }
    } else {
        // ubuntu: -DUNICODE_WCHAR: convert UTF-8 to local character set
        let escape_all = uz.unicode_escape_all;
        match unicode::utf8_to_local_string(uz, &unipath, escape_all) {
            // ubuntu: 28-cve-2022-0529-and-cve-2022-0530.patch: detect
            // conversion failure, emit message, continue with unconverted
            // name
            None => {
                uz.info(0x401, m::UFILENAME_CORRUPT.as_bytes());
                error = PK_ERR;
            }
            Some(mut fname) => {
                // make sure filename is short enough
                if fname.len() >= filnamsiz {
                    fname.truncate(filnamsiz - 1);
                    uz.info(0x401, m::UFILENAME_TOO_LONG_TRUNC.as_bytes());
                    error = PK_WARN;
                }
                // replace filename with converted UTF-8: strcpy()
                uz.filename[..fname.len()].copy_from_slice(&fname);
                uz.filename[fname.len()] = 0;
            }
        }
    }
    error
}

// port: unzip.c:unzip
/// unzip.c's `SETLOCALE(LC_CTYPE, "")` and its `UTF8_MAYBE_NATIVE` test
/// (`nl_langinfo(CODESET)` is `"UTF-8"`): whether the run's character type
/// locale is UTF-8 (`G.native_is_utf8`). Under `Host::Real` on unix this
/// sets the process's `LC_CTYPE` from the environment as unzip does, so
/// [`is_print`] then answers as the reference's `isprint()`; a sandbox, and
/// a build off unix, is the C locale (R7, R8).
/// probe: Apple's `unzip -l` of a name holding 0xe9 shows it raw under
/// `LC_CTYPE=UTF-8` (a macOS locale), `LANG=en_US.UTF-8`, `C.UTF-8` and
/// `LC_CTYPE=en_US.ISO8859-1`, and `?` under `LANG=C` and `LANG=xx_XX.UTF-8`
/// (no such locale: setlocale fails and C stays).
pub(crate) fn init_locale(host: &Host) -> bool {
    if !matches!(host, Host::Real) {
        return false;
    }
    real_locale_is_utf8()
}

#[cfg(unix)]
fn real_locale_is_utf8() -> bool {
    // SAFETY: called once, from the run's single thread, before anything
    // else reads the locale (unzip.c does it first thing too); the strings
    // passed are NUL-terminated, and the one `nl_langinfo` returns is valid
    // until the next locale call, read at once here.
    unsafe {
        libc::setlocale(libc::LC_CTYPE, c"".as_ptr());
        let codeset = libc::nl_langinfo(libc::CODESET);
        !codeset.is_null() && std::ffi::CStr::from_ptr(codeset).to_bytes() == b"UTF-8"
    }
}

#[cfg(not(unix))]
fn real_locale_is_utf8() -> bool {
    false
}

/// unix `isprint()` (`HAVE_WORKING_ISPRINT`) in the locale [`init_locale`]
/// set: the C library's answer under `Host::Real` on unix (Apple's counts
/// 0xa0..0xff but 0xad printable under a UTF-8 locale, and the Latin-1
/// letters under ISO8859-1; glibc's no byte above 0x7e under UTF-8), the C
/// locale's (printable ASCII) in a sandbox and off unix.
pub(crate) fn is_print(uz: &Uz, c: u8) -> bool {
    if matches!(uz.host, Host::Real) {
        return libc_isprint(c);
    }
    (0x20..0x7f).contains(&c)
}

#[cfg(unix)]
fn libc_isprint(c: u8) -> bool {
    // SAFETY: `isprint` takes any `unsigned char` value as an `int` and
    // reads only the locale's character table.
    unsafe { libc::isprint(libc::c_int::from(c)) != 0 }
}

#[cfg(not(unix))]
fn libc_isprint(c: u8) -> bool {
    (0x20..0x7f).contains(&c)
}

// port: extract.c:fnfilter
/// `fnfilter(raw, space, size)`: `raw` (a C string) in printable form,
/// written into `uz.slide[at..at + size]` as the C writes its `space`, and
/// returned. A control byte becomes `^` and its letter; another byte
/// `isprint()` refuses becomes `?`; past `size - 4` bytes the text ends in
/// `...`.
/// ubuntu: -DNO_WORKING_ISPRINT escapes control bytes only and leaves
/// every other byte (DEL and 0x80..0xff too) as it is
/// (`flavour::no_working_isprint`).
pub(crate) fn fnfilter_at(uz: &mut Uz, raw: &[u8], at: usize, size: usize) -> Vec<u8> {
    let raw = c_str(raw);
    let working_isprint = !flavour::no_working_isprint(uz.flavour);
    let mut out: Vec<u8> = Vec::with_capacity(raw.len().min(size));
    let slim = size.saturating_sub(4);
    let mut se: Option<usize> = None;
    let mut have_overflow = false;
    let mut r = 0usize;
    while r < raw.len() {
        let s = out.len();
        if size > 0 && s >= slim && se.is_none() {
            se = Some(s);
        }
        let c = raw[r];
        let printable = !working_isprint || is_print(uz, c);
        if c < 32 {
            // ASCII control codes are escaped as "^{letter}".
            if se.is_some() && s + 4 > size {
                have_overflow = true;
                break;
            }
            out.push(b'^');
            out.push(64 + c);
            r += 1;
        } else if !printable {
            // Other unprintable codes are replaced by the placeholder
            // character.
            if se.is_some() && s + 3 > size {
                have_overflow = true;
                break;
            }
            out.push(b'?');
            r += 1;
        } else {
            if se.is_some() && s + 3 > size {
                have_overflow = true;
                break;
            }
            out.push(c);
            r += 1;
        }
    }
    if have_overflow {
        let se = se.unwrap_or(out.len());
        out.truncate(se);
        out.extend_from_slice(b"...");
    }
    // The text never passes `size` bytes; its NUL can sit at `size`.
    let n = out.len().min(size);
    uz.put_slide_at(at, &out[..n], true);
    out
}

/// unzpriv.h's `FnFilter1(fname)`: `fnfilter()` into `slide + WSIZE/2`,
/// `WSIZE/4` bytes.
pub(crate) fn fnfilter1(uz: &mut Uz, raw: &[u8]) -> Vec<u8> {
    fnfilter_at(uz, raw, WSIZE >> 1, WSIZE >> 2)
}

/// unzpriv.h's `FnFilter2(fname)`: `fnfilter()` into `slide + WSIZE/2 +
/// WSIZE/4`, `WSIZE/4` bytes.
pub(crate) fn fnfilter2(uz: &mut Uz, raw: &[u8]) -> Vec<u8> {
    fnfilter_at(uz, raw, (WSIZE >> 1) + (WSIZE >> 2), WSIZE >> 2)
}

// port: extract.c:fnfilterp
/// apple: extract.c:2788, `fnfilterp(pfx, raw, slide + WSIZE/2, WSIZE/4)`:
/// `pfx` (when given and not empty) filtered, a `/`, then `raw` filtered
/// in the space left.
pub(crate) fn fnfilterp(uz: &mut Uz, pfx: Option<&[u8]>, raw: &[u8]) -> Vec<u8> {
    let (mut at, mut size) = (WSIZE >> 1, WSIZE >> 2);
    let mut out = Vec::new();
    if let Some(pfx) = pfx.filter(|p| !p.is_empty()) {
        let p = fnfilter_at(uz, pfx, at, size);
        let n = c_str(&p).len().min(size);
        at += n;
        size -= n;
        out.extend_from_slice(&p[..n]);
        uz.put_slide_at(at, b"/", false);
        out.push(b'/');
        at += 1;
        size = size.saturating_sub(1);
    }
    out.extend_from_slice(&fnfilter_at(uz, raw, at, size));
    out
}

// port: list.c:fnprint
/// `fnprint()`: the entry's name (`G.filename`) filtered into `slide`
/// (`WSIZE/2` bytes) and printed, then a newline.
pub(crate) fn fnprint(uz: &mut Uz) {
    let name = uz.filename.clone();
    let shown = fnfilter_at(uz, &name, 0, WSIZE >> 1);
    uz.info(0, &shown);
    uz.info(0, b"\n");
}

/// The fields of a `struct tm` the listings print.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Tm {
    /// `tm_year + 1900`.
    pub year: i64,
    /// `tm_mon + 1`.
    pub mon: u32,
    pub mday: u32,
    pub hour: u32,
    pub min: u32,
    /// `tm_sec` (zipinfo's long times show it).
    pub sec: u32,
    /// `tm_gmtoff`: seconds east of UTC.
    pub gmtoff: i64,
    /// `tm_isdst > 0`: summer time is in effect.
    pub isdst: bool,
}

/// `localtime(&t)`: the local time of `t` (`None` where the C gets
/// `NULL`). In a sandbox the zone is UTC (R7); off unix too (R8).
pub(crate) fn localtime(uz: &Uz, t: i64) -> Option<Tm> {
    if matches!(uz.host, crate::compat::host::Host::Real) {
        return localtime_real(t);
    }
    Some(utc(t))
}

#[cfg(unix)]
unsafe extern "C" {
    /// POSIX `tzset()`, which the `libc` crate does not declare on every
    /// unix.
    fn tzset();
}

#[cfg(unix)]
fn localtime_real(t: i64) -> Option<Tm> {
    let tt = t as libc::time_t;
    // SAFETY: `tm` is plain data that a successful `localtime_r` fills in
    // whole; both pointers are valid for the call. `tzset` has no
    // arguments (process_zipfiles() calls it first, as here).
    let mut tm: libc::tm = unsafe { std::mem::zeroed() };
    let ok = unsafe {
        tzset();
        !libc::localtime_r(&tt, &mut tm).is_null()
    };
    ok.then(|| Tm {
        year: i64::from(tm.tm_year) + 1900,
        mon: (tm.tm_mon + 1) as u32,
        mday: tm.tm_mday as u32,
        hour: tm.tm_hour as u32,
        min: tm.tm_min as u32,
        sec: tm.tm_sec as u32,
        gmtoff: tm.tm_gmtoff as i64,
        isdst: tm.tm_isdst > 0,
    })
}

#[cfg(not(unix))]
fn localtime_real(t: i64) -> Option<Tm> {
    Some(utc(t))
}

/// `gmtime(&t)`: `t` in UTC (zipinfo's `-v` shows both).
pub(crate) fn gmtime(t: i64) -> Tm {
    utc(t)
}

/// `t` in UTC (days from the civil calendar).
fn utc(t: i64) -> Tm {
    let days = t.div_euclid(86_400);
    let secs = t.rem_euclid(86_400);
    let z = days + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let mo = if mp < 10 { mp + 3 } else { mp - 9 };
    Tm {
        year: if mo <= 2 { y + 1 } else { y },
        mon: mo as u32,
        mday: d as u32,
        hour: (secs / 3600) as u32,
        min: (secs / 60 % 60) as u32,
        sec: (secs % 60) as u32,
        gmtoff: 0,
        isdst: false,
    }
}

/// unzpriv.h's `DOSTIME_2038_01_18`.
pub(crate) const DOSTIME_2038_01_18: u32 = 0x7432_0000;
/// unzpriv.h's `U_TIME_T_MAX` and `S_TIME_T_MAX` (as unzpriv.h defines
/// them for a 64-bit `time_t`: the 32-bit limits).
const U_TIME_T_MAX: i64 = 0xffff_ffff;
const S_TIME_T_MAX: i64 = 0x7fff_ffff;

/// fileio.c's `ydays[]`: days before each month (and the year's total).
const YDAYS: [u32; 13] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365];

// port: fileio.c:dos_to_unix_time
/// An MS-DOS date and time (local time) as a `time_t`, as the `BSD4_4`
/// build computes it (no `HAVE_MKTIME`): days and seconds from 1970, the
/// zone's offset (`tm_gmtoff` of the result) taken off, saturated at the
/// 32-bit limits.
/// ruling: `ydays[mo]` with a month field of 0, 14 or 15 reads outside the
/// 13-entry table (undefined behaviour: Apple's unzip `-T` gives month 0 ten
/// extra days and month 15 a date in 2090); here month 0 counts no days
/// before it and months 14 and 15 the whole year (`ydays[12]`, which month
/// 13 reads).
/// ubuntu: the Linux build (no `BSD4_4`: `flavour::dos_time_bsd4_4`)
/// adds `timezone` (the zone's standard offset, seconds west) and takes a
/// whole hour off when the result is in summer time; the two agree in UTC
/// and in whole-hour zones away from the changes. probe: extraction mtimes
/// under `TZ=EST5EDT,M3.2.0,M11.1.0` (a DOS time in the spring-forward
/// gap) and `TZ=LHST-10:30LHDT-11,M10.1.0,M4.1.0` (half-hour DST): Ubuntu's
/// 1583649000 and 1579048200, `BSD4_4`'s 1583652600 and 1579050000.
pub(crate) fn dos_to_unix_time(uz: &Uz, dosdatetime: u32) -> i64 {
    const YRBASE: i64 = 1970;
    let yr = i64::from((dosdatetime >> 25) & 0x7f) + (1980 - YRBASE);
    let mo = i64::from((dosdatetime >> 21) & 0x0f) - 1;
    let dy = i64::from((dosdatetime >> 16) & 0x1f) - 1;
    let hh = i64::from((dosdatetime >> 11) & 0x1f);
    let mm = i64::from((dosdatetime >> 5) & 0x3f);
    let ss = i64::from(dosdatetime & 0x1f) * 2;

    // leap = # of leap yrs from YRBASE up to but not including current year
    let leap = (yr + YRBASE - 1) / 4; // leap year base factor
    let ydays = if mo < 0 {
        0
    } else {
        i64::from(YDAYS[(mo as usize).min(12)])
    };
    // calculate days from BASE to this year and add expired days this year
    // (`unsigned days`: the sum is never negative here)
    let mut days = (yr * 365) + (leap - 492) + ydays;
    // if year is a leap year and month is after February, add another day
    if mo > 1 && (yr + YRBASE) % 4 == 0 && (yr + YRBASE) != 2100 {
        days += 1; // OK through 2199
    }
    // convert date & time to seconds relative to 00:00:00, 01/01/YRBASE
    let mut m_time = (days + dy) * 86_400 + hh * 3600 + (mm * 60 + ss);

    // Adjust for local standard timezone offset.
    let saturate = |t: i64| -> i64 {
        let mut t = t;
        if dosdatetime >= DOSTIME_2038_01_18 && t < 0x7000_0000 {
            t = U_TIME_T_MAX; // saturate in case of (unsigned) overflow
        }
        if t < 0 {
            t = S_TIME_T_MAX; // a converted DOS time cannot be negative
        }
        t
    };
    if flavour::dos_time_bsd4_4(uz.flavour) {
        m_time = saturate(m_time);
        if let Some(tm) = localtime(uz, m_time) {
            m_time -= tm.gmtoff; // sec. EAST of GMT: subtr.
        }
    } else {
        // ubuntu: !BSD4_4. tzset was already called at start of
        // process_zipfiles()
        m_time += timezone(uz); // seconds WEST of GMT:  add
        // Adjust for local daylight savings (summer) time.
        m_time = saturate(m_time);
        if localtime(uz, m_time).is_some_and(|tm| tm.isdst) {
            m_time -= 60 * 60; // adjust for daylight savings time
        }
    }
    saturate(m_time)
}

/// The C library's `timezone` once `tzset()` has run: the local standard
/// time's offset, seconds WEST of UTC. A sandbox's zone is UTC (R7).
fn timezone(uz: &Uz) -> i64 {
    if matches!(uz.host, crate::compat::host::Host::Real) {
        return timezone_real();
    }
    0
}

#[cfg(target_os = "linux")]
#[allow(clippy::useless_conversion)] // `c_long` is `i32` on 32-bit Linux
fn timezone_real() -> i64 {
    unsafe extern "C" {
        /// POSIX (XSI) `timezone`, which `tzset()` sets.
        #[link_name = "timezone"]
        static c_timezone: libc::c_long;
    }
    // SAFETY: `tzset()` takes no arguments and sets `timezone`, which is
    // then read; the run is single-threaded under `Host::Real`.
    unsafe {
        tzset();
        i64::from(c_timezone)
    }
}

/// Off Linux (the Ubuntu flavour elsewhere; nothing is promised there,
/// deviation 6) the standard offset is read from `localtime()`: the
/// offset of January 1st or July 1st of 2020 that is not summer time.
#[cfg(not(target_os = "linux"))]
fn timezone_real() -> i64 {
    [1_577_836_800i64, 1_593_561_600]
        .iter()
        .filter_map(|&t| localtime_real(t))
        .find(|tm| !tm.isdst)
        .map_or(0, |tm| -tm.gmtoff)
}

// port: fileio.c:UzpMorePause
/// `UzpMorePause(prompt, flag)`: `prompt` on standard error (after a
/// newline when the output is not at the start of a line), a key read
/// (`flag` 1: only Enter, space or `q`), the prompt covered. `q` ends the
/// run, exit 0; space under `flag` 1 starts a new screen.
///
/// ruling: T11-4. At the end of standard input (or a read error) the C's
/// `c` is uninitialised. With `flag` 0 (the `^S` pause in a comment) both
/// binaries go on, as for any key that is not `q` (probe: `unzip -o cs.zip
/// </dev/null`), and so does this. With `flag` 1 (`-M`) they wait for a key
/// that can never come, spinning for ever (probe: `unzip -M -l many.zip`,
/// stdout a terminal, stdin `/dev/null`); here the pager stops pausing for
/// the rest of the run, as if `-M` had not been given.
pub(crate) fn more_pause(uz: &mut Uz, prompt: &[u8], flag: u32) {
    if !uz.sol {
        let _ = uz.err.write_all(b"\n");
    }
    // numlines may or may not be used:
    let _ = uz.err.write_all(prompt);
    let _ = uz.err.flush();
    let c = if flag & 1 != 0 {
        loop {
            match super::ttyio::zgetch(uz) {
                Some(c @ (b'\r' | b'\n' | b' ' | b'q' | b'Q')) => break Some(c),
                Some(_) => {}
                None => break None,
            }
        }
    } else {
        super::ttyio::zgetch(uz)
    };

    // newline was not echoed, so cover up prompt line
    let _ = uz.err.write_all(m::HIDE_PROMPT.as_bytes());
    let _ = uz.err.flush();

    if c.is_some_and(|c| c.eq_ignore_ascii_case(&b'q')) {
        uz.exit_run(PK_COOL);
        return;
    }
    if c.is_none() && flag & 1 != 0 {
        // ruling: T11-4
        uz.o.m_flag = false;
    }

    uz.sol = true;

    // space for another screen, enter for another line.
    if flag & 1 != 0 && c == Some(b' ') {
        uz.lines = 0;
    }
}

/// crypt.h's `IZ_PW_*`: what a password fetch answered.
pub(crate) enum Pw {
    /// `IZ_PW_ENTERED`: a password was typed.
    Entered(super::ttyio::Password),
    /// `IZ_PW_CANCELALL`: an empty answer: skip, and ask no more.
    CancelAll,
    /// `IZ_PW_ERROR`: no password can be had.
    Error,
}

/// `UzpPassword()`'s first prompt: `[zipfile] entry password: ` with both
/// names filtered, or "Enter password: " when they exceed `2*FILNAMSIZ`
/// bytes together (ubuntu: 20-cve-2018-1000035; ruling T11-5 for Apple).
pub(crate) fn passw_prompt(uz: &mut Uz, zfn: &[u8], efn: &[u8]) -> Vec<u8> {
    let zfnf = fnfilter1(uz, zfn);
    let efnf = fnfilter2(uz, efn);
    let room = 2 * flavour::filnamsiz(uz.flavour);
    if zfnf.len() + efnf.len() <= room {
        let mut p = Vec::new();
        m::printf(&mut p, m::PASSW_PROMPT, &[&zfnf, &efnf]);
        p
    } else {
        m::PASSW_PROMPT2.as_bytes().to_vec()
    }
}

// port: fileio.c:UzpPassword
/// `UzpPassword(&G, rcnt, pwbuf, size, zfn, efn)`: the first call for an
/// entry (`*rcnt == 0`) asks with the archive's and the entry's names and
/// sets two retries; each later call asks "password incorrect--reenter"
/// and spends one. The names are `G.zipfn` and `G.filename`.
///
/// ubuntu: 20-cve-2018-1000035-unzip-buffer-overflow.patch: when the two
/// filtered names exceed `2*FILNAMSIZ` bytes the prompt is "Enter
/// password: ". ruling: T11-5. Apple's build `sprintf()`s them into its
/// `2*FILNAMSIZ + 15`-byte buffer unchecked, and `__sprintf_chk` kills it
/// (SIGTRAP, exit 133) one byte past that (probe: `lon3.zip` with an entry
/// of 1020 `^A` bytes, 2048 filtered bytes, prompts; `lon4.zip` with one
/// more byte traps); Apple's flavour gives Ubuntu's answer with its own
/// `FILNAMSIZ`, as the earlier buffer rulings (T8-1, T9) do.
pub(crate) fn uzp_password(uz: &mut Uz, rcnt: &mut i32) -> Pw {
    let prompt: Vec<u8> = if *rcnt == 0 {
        // First call for current entry
        *rcnt = 2;
        let zfn = uz.zipfn.clone();
        let efn = c_str(&uz.filename).to_vec();
        passw_prompt(uz, &zfn, &efn)
    } else {
        // Retry call, previous password was wrong
        *rcnt -= 1;
        m::PASSW_RETRY.as_bytes().to_vec()
    };

    match super::ttyio::getp(uz, &prompt) {
        Err(_) => Pw::Error,
        Ok(p) if p.is_empty_answer() => Pw::CancelAll,
        Ok(p) => Pw::Entered(p),
    }
}

#[cfg(test)]
mod tests;