ctb_formats_detection/droid.rs
1/*
2$File: COPYING,v 1.2 2018/09/09 20:33:28 christos Exp $
3Copyright (c) Ian F. Darwin 1986, 1987, 1989, 1990, 1991, 1992, 1994, 1995.
4Software written by Ian F. Darwin and others;
5maintained 1994- Christos Zoulas.
6
7This software is not subject to any export provision of the United States
8Department of Commerce, and may be exported to any country or planet.
9
10Redistribution and use in source and binary forms, with or without
11modification, are permitted provided that the following conditions
12are met:
131. Redistributions of source code must retain the above copyright
14 notice immediately at the beginning of the file, without modification,
15 this list of conditions, and the following disclaimer.
162. Redistributions in binary form must reproduce the above copyright
17 notice, this list of conditions and the following disclaimer in the
18 documentation and/or other materials provided with the distribution.
19
20THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
24ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30SUCH DAMAGE.
31
32The preceding notice is from COPYING in `file`.
33
34
35
36/*
37 * Copyright (c) Ian F. Darwin 1986-1995.
38 * Software written by Ian F. Darwin and others;
39 * maintained 1995-present by Christos Zoulas and others.
40 *
41 * Redistribution and use in source and binary forms, with or without
42 * modification, are permitted provided that the following conditions
43 * are met:
44 * 1. Redistributions of source code must retain the above copyright
45 * notice immediately at the beginning of the file, without modification,
46 * this list of conditions, and the following disclaimer.
47 * 2. Redistributions in binary form must reproduce the above copyright
48 * notice, this list of conditions and the following disclaimer in the
49 * documentation and/or other materials provided with the distribution.
50 *
51 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
52 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
53 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
54 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
55 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
56 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
57 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
58 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
59 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
60 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
61 * SUCH DAMAGE.
62 */
63
64The preceding notice is from src/apprentice.c, src/ascmagic.c, src/compress.c, src/encoding.c, src/file.c, src/file.h, src/fsmagic.c, src/missing/asprintf.c, src/missing/dprintf.c, src/print.c, src/softmagic.c, src/swap.c, and src/swap.h in `file`.
65
66
67
68/*
69 * Copyright (c) Christos Zoulas 2017.
70 * All Rights Reserved.
71 *
72 * Redistribution and use in source and binary forms, with or without
73 * modification, are permitted provided that the following conditions
74 * are met:
75 * 1. Redistributions of source code must retain the above copyright
76 * notice immediately at the beginning of the file, without modification,
77 * this list of conditions, and the following disclaimer.
78 * 2. Redistributions in binary form must reproduce the above copyright
79 * notice, this list of conditions and the following disclaimer in the
80 * documentation and/or other materials provided with the distribution.
81 *
82 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
83 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
84 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
85 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
86 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
87 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
88 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
89 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
90 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
91 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
92 * SUCH DAMAGE.
93 */
94
95The preceding notice is from src/buffer.c in `file`.
96
97
98
99/*
100 * Copyright (c) Christos Zoulas 2008.
101 * All Rights Reserved.
102 *
103 * Redistribution and use in source and binary forms, with or without
104 * modification, are permitted provided that the following conditions
105 * are met:
106 * 1. Redistributions of source code must retain the above copyright
107 * notice immediately at the beginning of the file, without modification,
108 * this list of conditions, and the following disclaimer.
109 * 2. Redistributions in binary form must reproduce the above copyright
110 * notice, this list of conditions and the following disclaimer in the
111 * documentation and/or other materials provided with the distribution.
112 *
113 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
114 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
115 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
116 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
117 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
118 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
119 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
120 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
121 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
122 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
123 * SUCH DAMAGE.
124 */
125
126The preceding notice is from src/elfclass.h in `file`.
127
128
129
130/*
131 * Copyright (c) Christos Zoulas 2003.
132 * All Rights Reserved.
133 *
134 * Redistribution and use in source and binary forms, with or without
135 * modification, are permitted provided that the following conditions
136 * are met:
137 * 1. Redistributions of source code must retain the above copyright
138 * notice immediately at the beginning of the file, without modification,
139 * this list of conditions, and the following disclaimer.
140 * 2. Redistributions in binary form must reproduce the above copyright
141 * notice, this list of conditions and the following disclaimer in the
142 * documentation and/or other materials provided with the distribution.
143 *
144 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
145 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
146 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
147 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
148 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
149 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
150 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
151 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
152 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
153 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
154 * SUCH DAMAGE.
155 */
156
157The preceding notice is from src/funcs.c, src/magic.c, src/magic.h.in, src/readelf.c, and src/readelf.h in `file`.
158
159
160
161/*
162 * Copyright (c) Ian F. Darwin 1986-1995.
163 * Software written by Ian F. Darwin and others;
164 * maintained 1995-present by Christos Zoulas and others.
165 *
166 * Redistribution and use in source and binary forms, with or without
167 * modification, are permitted provided that the following conditions
168 * are met:
169 * 1. Redistributions of source code must retain the above copyright
170 * notice immediately at the beginning of the file, without modification,
171 * this list of conditions, and the following disclaimer.
172 * 2. Redistributions in binary form must reproduce the above copyright
173 * notice, this list of conditions and the following disclaimer in the
174 * documentation and/or other materials provided with the distribution.
175 *
176 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
177 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
178 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
179 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
180 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
181 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
182 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
183 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
184 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
185 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
186 * SUCH DAMAGE.
187 */
188
189/*
190 * is_tar() -- figure out whether file is a tar archive.
191 *
192 * Stolen (by the author!) from the file_public domain tar program:
193 * Public Domain version written 26 Aug 1985 John Gilmore (ihnp4!hoptoad!gnu).
194 *
195 * @(#)list.c 1.18 9/23/86 Public Domain - gnu
196 *
197 * Comments changed and some code/comments reformatted
198 * for file command by Ian Darwin.
199 */
200
201The preceding notice is from src/is_tar.c in `file`.
202
203
204
205/*
206 * Redistribution and use in source and binary forms, with or without
207 * modification, are permitted provided that the following conditions
208 * are met:
209 * 1. Redistributions of source code must retain the above copyright
210 * notice immediately at the beginning of the file, without modification,
211 * this list of conditions, and the following disclaimer.
212 * 2. Redistributions in binary form must reproduce the above copyright
213 * notice, this list of conditions and the following disclaimer in the
214 * documentation and/or other materials provided with the distribution.
215 *
216 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
217 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
218 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
219 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
220 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
221 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
222 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
223 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
224 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
225 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
226 * SUCH DAMAGE.
227 */
228
229The preceding notice is from src/landlock.c and src/seccomp.c in `file`.
230
231
232
233/*
234 * Copyright (c) Christos Zoulas 2021.
235 * All Rights Reserved.
236 *
237 * Redistribution and use in source and binary forms, with or without
238 * modification, are permitted provided that the following conditions
239 * are met:
240 * 1. Redistributions of source code must retain the above copyright
241 * notice immediately at the beginning of the file, without modification,
242 * this list of conditions, and the following disclaimer.
243 * 2. Redistributions in binary form must reproduce the above copyright
244 * notice, this list of conditions and the following disclaimer in the
245 * documentation and/or other materials provided with the distribution.
246 *
247 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
248 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
249 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
250 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
251 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
252 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
253 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
254 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
255 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
256 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
257 * SUCH DAMAGE.
258 */
259
260The preceding notice is from src/memtest.c in `file`.
261
262
263
264/*
265 * Copyright (c) Ian F. Darwin 1986-1995.
266 * Software written by Ian F. Darwin and others;
267 * maintained 1995-present by Christos Zoulas and others.
268 *
269 * Redistribution and use in source and binary forms, with or without
270 * modification, are permitted provided that the following conditions
271 * are met:
272 * 1. Redistributions of source code must retain the above copyright
273 * notice immediately at the beginning of the file, without modification,
274 * this list of conditions, and the following disclaimer.
275 * 2. Redistributions in binary form must reproduce the above copyright
276 * notice, this list of conditions and the following disclaimer in the
277 * documentation and/or other materials provided with the distribution.
278 *
279 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
280 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
281 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
282 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
283 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
284 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
285 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
286 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
287 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
288 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
289 * SUCH DAMAGE.
290 */
291
292/*###########################################################################
293 # #
294 # vasprintf #
295 # #
296 # Copyright (c) 2002-2005 David TAILLANDIER #
297 # #
298 ###########################################################################*/
299
300/*
301
302This software is distributed under the "modified BSD licence".
303
304This software is also released with GNU license (GPL) in another file (same
305source-code, only license differ).
306
307
308
309Redistribution and use in source and binary forms, with or without
310modification, are permitted provided that the following conditions are met:
311
312Redistributions of source code must retain the above copyright notice, this
313list of conditions and the following disclaimer. Redistributions in binary
314form must reproduce the above copyright notice, this list of conditions and
315the following disclaimer in the documentation and/or other materials
316provided with the distribution. The name of the author may not be used to
317endorse or promote products derived from this software without specific
318prior written permission.
319
320THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
321WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
322MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
323EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
324SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
325PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
326OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
327WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
328OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
329ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
330
331====================
332
333Hacked from xnprintf version of 26th February 2005 to provide only
334vasprintf by Reuben Thomas <rrt@sc3d.org>.
335
336====================
337
338
339'printf' function family use the following format string:
340
341%[flag][width][.prec][modifier]type
342
343%% is the escape sequence to print a '%'
344% followed by an unknown format will print the characters without
345trying to do any interpretation
346
347flag: none + - # (blank)
348width: n 0n *
349prec: none .0 .n .*
350modifier: F N L h l ll z t ('F' and 'N' are ms-dos/16-bit specific)
351type: d i o u x X f e g E G c s p n
352
353
354The function needs to allocate memory to store the full text before to
355actually writing it. i.e if you want to fnprintf() 1000 characters, the
356functions will allocate 1000 bytes.
357This behaviour can be modified: you have to customise the code to flush the
358internal buffer (writing to screen or file) when it reach a given size. Then
359the buffer can have a shorter length. But what? If you really need to write
360HUGE string, don't use printf!
361During the process, some other memory is allocated (1024 bytes minimum)
362to handle the output of partial sprintf() calls. If you have only 10000 bytes
363free in memory, you *may* not be able to nprintf() an 8000 bytes-long text.
364
365note: if a buffer overflow occurs, exit() is called. This situation should
366never appear ... but if you want to be *really* sure, you have to modify the
367code to handle those situations (only one place to modify).
368A buffer overflow can only occur if your sprintf() do strange things or when
369you use strange formats.
370
371*/
372
373The preceding notice is from src/missing/vasprintf.c in `file`.
374
375
376
377/*
378 * Copyright (c) Ian F. Darwin 1986-1995.
379 * Software written by Ian F. Darwin and others;
380 * maintained 1995-present by Christos Zoulas and others.
381 *
382 * Redistribution and use in source and binary forms, with or without
383 * modification, are permitted provided that the following conditions
384 * are met:
385 * 1. Redistributions of source code must retain the above copyright
386 * notice immediately at the beginning of the file, without modification,
387 * this list of conditions, and the following disclaimer.
388 * 2. Redistributions in binary form must reproduce the above copyright
389 * notice, this list of conditions and the following disclaimer in the
390 * documentation and/or other materials provided with the distribution.
391 *
392 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
393 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
394 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
395 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
396 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
397 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
398 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
399 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
400 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
401 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
402 * SUCH DAMAGE.
403 */
404
405/*
406 * Header file for file_public domain tar (tape archive) program.
407 *
408 * @(#)tar.h 1.20 86/10/29 Public Domain.
409 *
410 * Created 25 August 1985 by John Gilmore, ihnp4!hoptoad!gnu.
411 *
412 * $File: tar.h,v 1.16 2022/12/26 17:31:14 christos Exp $ # checkin only
413 */
414
415The preceding notice is from src/tar.h in `file`.
416*/
417
418// SPDX-License-Identifier: AGPL-3.0-or-later AND BSD-2-Clause-Darwin AND Apache-2.0 AND MIT AND BSD-3-Clause
419// SPDX-License-Identifier for parts derived from `file` (libmagic): BSD-2-Clause-Darwin AND BSD-3-Clause
420// SPDX-License-Identifier for parts derived from polyfile: Apache-2.0
421// SPDX-License-Identifier for parts derived from fileid and binwalk: MIT
422// SPDX-License-Identifier for parts derived from DROID: BSD-3-Clause
423/*
424This file is part of Collective Toolbox, a database and document workspace and utilities.
425Copyright (C) 2026 Collective Toolbox Developers
426Contact: info@collectivetoolbox.com
427
428This program is free software: you can redistribute it and/or modify it under
429the terms of the GNU Affero General Public License as published by the Free
430Software Foundation, either version 3 of the License, or (at your option) any
431later version.
432
433This program is distributed in the hope that it will be useful, but WITHOUT ANY
434WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
435A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
436
437You should have received a copy of the GNU Affero General Public License along
438with this program. If not, see <https://www.gnu.org/licenses/>.
439*/
440
441// The Collective Toolbox file detection tools, of which this file is a part, combine elements from several other similar tools: `file`, polyfile, binwalk, fileid, and DROID.
442// See license texts at the beginning and end of this file for full license details for parts derived from `file` <https://www.darwinsys.com/file/>.
443// See the full license details for parts derived from polyfile <https://github.com/trailofbits/polyfile>, binwalk <https://github.com/ReFirmLabs/binwalk>, fileid <https://github.com/DBHeise/fileid>, and DROID <https://github.com/digital-preservation/droid> at the end of this file.
444
445//! DROID and PRONOM signature evaluation and container inspection subsystem.
446//!
447//! Implements:
448//! - Dual-anchored BOF (Beginning of File) and EOF (End of File) signatures
449//! with variable offset windows ported from DROID / PRONOM.
450//! - Declarative container signature model for ZIP-based formats (DOCX, XLSX,
451//! PPTX, EPUB, APK, JAR, ODF) via Central Directory inspection without
452//! eager in-memory decompression or unpacking.
453
454#[allow(
455 unused_imports,
456 clippy::wildcard_imports,
457 reason = "Standard workspace module prelude"
458)]
459use crate::utilities::*;
460
461use std::collections::HashMap;
462use std::sync::LazyLock;
463
464use crate::detection::source::DetectionSource;
465use crate::detection::types::{
466 ConfidenceTier, DetectionCandidate, DetectionEvidence, DetectionHint,
467};
468use crate::format_id::FormatId;
469
470// ---------------------------------------------------------------------------
471// 1. Dual-Anchored BOF / EOF Signatures (DROID / PRONOM)
472// ---------------------------------------------------------------------------
473
474/// Dual-anchored format signature requiring byte patterns at both the start
475/// (BOF) and optionally end (EOF) of a file within bounded offset windows.
476#[derive(Debug, Clone, Copy)]
477pub struct DualAnchoredSignature {
478 pub format_id: Option<FormatId>,
479 pub dc_id: Option<u128>,
480 pub mime: &'static str,
481 pub description: &'static str,
482 pub bof_pattern: &'static [u8],
483 pub bof_min_offset: u64,
484 pub bof_max_offset: u64,
485 pub eof_pattern: Option<&'static [u8]>,
486 pub eof_min_offset: u64,
487 pub eof_max_offset: u64,
488 pub priority: u32,
489}
490
491/// Authoritative DROID dual-anchored signature registry.
492pub static DROID_DUAL_ANCHORED_SIGNATURES: &[DualAnchoredSignature] = &[
493 // PDF: %PDF- at BOF 0..1024, %%EOF at EOF 0..1024
494 DualAnchoredSignature {
495 format_id: None,
496 dc_id: None,
497 mime: "application/pdf",
498 description: "PDF document",
499 bof_pattern: b"%PDF-",
500 bof_min_offset: 0,
501 bof_max_offset: 1024,
502 eof_pattern: Some(b"%%EOF"),
503 eof_min_offset: 0,
504 eof_max_offset: 1024,
505 priority: 95,
506 },
507 // PNG: \x89PNG\r\n\x1a\n at BOF 0, IEND\xaeB`\x82 at EOF 0..12
508 DualAnchoredSignature {
509 format_id: None,
510 dc_id: None,
511 mime: "image/png",
512 description: "PNG image data",
513 bof_pattern: b"\x89PNG\r\n\x1a\n",
514 bof_min_offset: 0,
515 bof_max_offset: 0,
516 eof_pattern: Some(b"IEND"),
517 eof_min_offset: 0,
518 eof_max_offset: 12,
519 priority: 95,
520 },
521 // JPEG: \xFF\xD8\xFF at BOF 0, \xFF\xD9 at EOF 0..4
522 DualAnchoredSignature {
523 format_id: None,
524 dc_id: None,
525 mime: "image/jpeg",
526 description: "JPEG image data",
527 bof_pattern: b"\xFF\xD8\xFF",
528 bof_min_offset: 0,
529 bof_max_offset: 0,
530 eof_pattern: Some(b"\xFF\xD9"),
531 eof_min_offset: 0,
532 eof_max_offset: 4,
533 priority: 95,
534 },
535 // GIF87a: GIF87a at BOF 0, trailer ';' at EOF 0..2
536 DualAnchoredSignature {
537 format_id: None,
538 dc_id: None,
539 mime: "image/gif",
540 description: "GIF image data, version 87a",
541 bof_pattern: b"GIF87a",
542 bof_min_offset: 0,
543 bof_max_offset: 0,
544 eof_pattern: Some(b";"),
545 eof_min_offset: 0,
546 eof_max_offset: 2,
547 priority: 95,
548 },
549 // GIF89a: GIF89a at BOF 0, trailer ';' at EOF 0..2
550 DualAnchoredSignature {
551 format_id: None,
552 dc_id: None,
553 mime: "image/gif",
554 description: "GIF image data, version 89a",
555 bof_pattern: b"GIF89a",
556 bof_min_offset: 0,
557 bof_max_offset: 0,
558 eof_pattern: Some(b";"),
559 eof_min_offset: 0,
560 eof_max_offset: 2,
561 priority: 95,
562 },
563 // ZIP: PK\x03\x04 at BOF 0..65536, PK\x05\x06 at EOF 0..65558
564 DualAnchoredSignature {
565 format_id: Some(FormatId::Zip),
566 dc_id: None,
567 mime: "application/zip",
568 description: "Zip archive data",
569 bof_pattern: b"\x50\x4B\x03\x04",
570 bof_min_offset: 0,
571 bof_max_offset: 65536,
572 eof_pattern: Some(b"\x50\x4B\x05\x06"),
573 eof_min_offset: 0,
574 eof_max_offset: 65558,
575 priority: 85,
576 },
577 // PostScript: %!PS at BOF 0, %%EOF at EOF 0..1024
578 DualAnchoredSignature {
579 format_id: None,
580 dc_id: None,
581 mime: "application/postscript",
582 description: "PostScript document",
583 bof_pattern: b"%!PS",
584 bof_min_offset: 0,
585 bof_max_offset: 0,
586 eof_pattern: Some(b"%%EOF"),
587 eof_min_offset: 0,
588 eof_max_offset: 1024,
589 priority: 90,
590 },
591 // WebP: RIFF at BOF 0, WEBP at BOF 8
592 DualAnchoredSignature {
593 format_id: None,
594 dc_id: None,
595 mime: "image/webp",
596 description: "RIFF (little-endian) data, Web/P image",
597 bof_pattern: b"RIFF",
598 bof_min_offset: 0,
599 bof_max_offset: 0,
600 eof_pattern: None,
601 eof_min_offset: 0,
602 eof_max_offset: 0,
603 priority: 90,
604 },
605 // WebAssembly binary: \0asm at BOF 0
606 DualAnchoredSignature {
607 format_id: None,
608 dc_id: None,
609 mime: "application/wasm",
610 description: "WebAssembly (wasm) binary",
611 bof_pattern: b"\x00asm",
612 bof_min_offset: 0,
613 bof_max_offset: 0,
614 eof_pattern: None,
615 eof_min_offset: 0,
616 eof_max_offset: 0,
617 priority: 95,
618 },
619 // Java class: \xCA\xFE\xBA\xBE at BOF 0
620 DualAnchoredSignature {
621 format_id: None,
622 dc_id: None,
623 mime: "application/java-vm",
624 description: "compiled Java class data",
625 bof_pattern: b"\xCA\xFE\xBA\xBE",
626 bof_min_offset: 0,
627 bof_max_offset: 0,
628 eof_pattern: None,
629 eof_min_offset: 0,
630 eof_max_offset: 0,
631 priority: 95,
632 },
633 // TIFF Little-Endian: II*\0 at BOF 0
634 DualAnchoredSignature {
635 format_id: None,
636 dc_id: None,
637 mime: "image/tiff",
638 description: "TIFF image data, little-endian",
639 bof_pattern: b"II\x2A\x00",
640 bof_min_offset: 0,
641 bof_max_offset: 0,
642 eof_pattern: None,
643 eof_min_offset: 0,
644 eof_max_offset: 0,
645 priority: 90,
646 },
647 // TIFF Big-Endian: MM\0* at BOF 0
648 DualAnchoredSignature {
649 format_id: None,
650 dc_id: None,
651 mime: "image/tiff",
652 description: "TIFF image data, big-endian",
653 bof_pattern: b"MM\x00\x2A",
654 bof_min_offset: 0,
655 bof_max_offset: 0,
656 eof_pattern: None,
657 eof_min_offset: 0,
658 eof_max_offset: 0,
659 priority: 90,
660 },
661 // 7-Zip: 7z\xBC\xAF\x27\x1C at BOF 0
662 DualAnchoredSignature {
663 format_id: None,
664 dc_id: None,
665 mime: "application/x-7z-compressed",
666 description: "7-zip archive data",
667 bof_pattern: b"7z\xBC\xAF\x27\x1C",
668 bof_min_offset: 0,
669 bof_max_offset: 0,
670 eof_pattern: None,
671 eof_min_offset: 0,
672 eof_max_offset: 0,
673 priority: 95,
674 },
675 // RAR: Rar!\x1A\x07 at BOF 0
676 DualAnchoredSignature {
677 format_id: None,
678 dc_id: None,
679 mime: "application/x-rar",
680 description: "RAR archive data",
681 bof_pattern: b"Rar!\x1A\x07",
682 bof_min_offset: 0,
683 bof_max_offset: 0,
684 eof_pattern: None,
685 eof_min_offset: 0,
686 eof_max_offset: 0,
687 priority: 95,
688 },
689 // Ogg stream: OggS at BOF 0
690 DualAnchoredSignature {
691 format_id: None,
692 dc_id: None,
693 mime: "application/ogg",
694 description: "Ogg data",
695 bof_pattern: b"OggS",
696 bof_min_offset: 0,
697 bof_max_offset: 0,
698 eof_pattern: None,
699 eof_min_offset: 0,
700 eof_max_offset: 0,
701 priority: 90,
702 },
703 // FLAC: fLaC at BOF 0
704 DualAnchoredSignature {
705 format_id: None,
706 dc_id: None,
707 mime: "audio/flac",
708 description: "FLAC audio bitstream data",
709 bof_pattern: b"fLaC",
710 bof_min_offset: 0,
711 bof_max_offset: 0,
712 eof_pattern: None,
713 eof_min_offset: 0,
714 eof_max_offset: 0,
715 priority: 90,
716 },
717];
718
719/// Evaluates dual-anchored BOF / EOF signatures on source.
720pub fn evaluate_dual_anchored_signatures<S: DetectionSource + ?Sized>(
721 source: &mut S,
722) -> Result<Vec<DetectionCandidate>> {
723 let mut candidates = Vec::new();
724 let bof_sample = source.read_bof(65536_usize.saturating_add(1024))?;
725 let eof_sample = source.read_eof(65558)?;
726
727 for sig in DROID_DUAL_ANCHORED_SIGNATURES {
728 let bof_max = match usize::try_from(sig.bof_max_offset) {
729 Ok(m) => m,
730 Err(_) => continue,
731 };
732 let bof_min = match usize::try_from(sig.bof_min_offset) {
733 Ok(m) => m,
734 Err(_) => continue,
735 };
736
737 // Match BOF pattern within window
738 let mut bof_matched_offset: Option<u64> = None;
739 let pat_len = sig.bof_pattern.len();
740 let scan_limit = bof_max.saturating_add(pat_len).min(bof_sample.len());
741
742 let mut offset = bof_min;
743 while offset.saturating_add(pat_len) <= scan_limit {
744 if bof_sample.get(offset..offset.saturating_add(pat_len))
745 == Some(sig.bof_pattern)
746 {
747 // Special check for WebP: offset 8..12 must be b"WEBP"
748 if sig.mime == "image/webp" {
749 if bof_sample.get(8..12) != Some(b"WEBP".as_slice()) {
750 offset = offset.saturating_add(1);
751 continue;
752 }
753 }
754 if let Ok(u_off) = u64::try_from(offset) {
755 bof_matched_offset = Some(u_off);
756 break;
757 }
758 }
759 offset = offset.saturating_add(1);
760 }
761
762 let Some(bof_off) = bof_matched_offset else {
763 continue;
764 };
765
766 // Match EOF pattern if defined
767 let mut eof_matched_offset: Option<u64> = None;
768 if let Some(eof_pat) = sig.eof_pattern {
769 if eof_sample.is_empty() {
770 // If EOF sample cannot be read, do not match dual-anchored requirement
771 continue;
772 }
773 let eof_pat_len = eof_pat.len();
774 let eof_max = match usize::try_from(sig.eof_max_offset) {
775 Ok(m) => m,
776 Err(_) => continue,
777 };
778 let eof_min = match usize::try_from(sig.eof_min_offset) {
779 Ok(m) => m,
780 Err(_) => continue,
781 };
782
783 let mut matched = false;
784 // EOF scanning looks backwards from end of eof_sample
785 let sample_len = eof_sample.len();
786 let mut dist = eof_min;
787 while dist.saturating_add(eof_pat_len) <= eof_max.min(sample_len) {
788 let start_idx =
789 sample_len.saturating_sub(dist.saturating_add(eof_pat_len));
790 let end_idx = start_idx.saturating_add(eof_pat_len);
791 if eof_sample.get(start_idx..end_idx) == Some(eof_pat) {
792 matched = true;
793 if let Ok(u_dist) = u64::try_from(dist) {
794 eof_matched_offset = Some(u_dist);
795 }
796 break;
797 }
798 dist = dist.saturating_add(1);
799 }
800 if !matched {
801 continue;
802 }
803 }
804
805 let mut evidence = vec![
806 DetectionEvidence::DualAnchored {
807 bof_offset: bof_off,
808 eof_offset: eof_matched_offset,
809 score: sig.priority,
810 },
811 DetectionEvidence::ByteRange {
812 start: bof_off,
813 end: bof_off.saturating_add(
814 match u64::try_from(sig.bof_pattern.len()) {
815 Ok(l) => l,
816 Err(_) => 0,
817 },
818 ),
819 label: format!("{}: BOF Anchor", sig.description),
820 score: sig.priority,
821 },
822 ];
823
824 if let Some(eof_dist) = eof_matched_offset {
825 if let Some(total) = source.total_len() {
826 let eof_len = match sig.eof_pattern {
827 Some(p) => match u64::try_from(p.len()) {
828 Ok(l) => l,
829 Err(_) => 0,
830 },
831 None => 0,
832 };
833 evidence.push(DetectionEvidence::ByteRange {
834 start: total
835 .saturating_sub(eof_dist.saturating_add(eof_len)),
836 end: total.saturating_sub(eof_dist),
837 label: format!("{}: EOF Anchor", sig.description),
838 score: sig.priority,
839 });
840 }
841 }
842
843 candidates.push(DetectionCandidate {
844 format_id: sig.format_id,
845 dc_id: sig.dc_id,
846 mime: Some(sig.mime.to_string()),
847 description: sig.description.to_string(),
848 confidence: if sig.priority >= 90 {
849 ConfidenceTier::HighestConfidence
850 } else {
851 ConfidenceTier::Strong
852 },
853 score: sig.priority,
854 evidence,
855 chain_layers: None,
856 });
857 }
858
859 Ok(candidates)
860}
861
862// ---------------------------------------------------------------------------
863// 2. PRONOM Signature Database and Streaming XML Parser
864// ---------------------------------------------------------------------------
865
866/// Reference anchor for PRONOM byte sequences (BOF or EOF).
867#[derive(Debug, Clone, Copy, PartialEq, Eq)]
868pub enum PronomByteSequenceRef {
869 Bof,
870 Eof,
871}
872
873/// Bounded byte pattern subsequence within a PRONOM signature.
874#[derive(Debug, Clone, PartialEq, Eq)]
875pub struct PronomSubSequence {
876 pub min_offset: u64,
877 pub max_offset: u64,
878 pub sequence: Vec<u8>,
879}
880
881/// Sequence of PRONOM subsequences anchored at BOF or EOF.
882#[derive(Debug, Clone, PartialEq, Eq)]
883pub struct PronomByteSequence {
884 pub reference: PronomByteSequenceRef,
885 pub subsequences: Vec<PronomSubSequence>,
886}
887
888/// Internal PRONOM binary signature composed of byte sequences.
889#[derive(Debug, Clone, PartialEq, Eq)]
890pub struct PronomInternalSignature {
891 pub id: u32,
892 pub byte_sequences: Vec<PronomByteSequence>,
893}
894
895/// Format definition in the PRONOM database.
896#[derive(Debug, Clone, PartialEq, Eq)]
897pub struct PronomFormat {
898 pub id: u32,
899 pub puid: String,
900 pub name: String,
901 pub mime_type: Option<String>,
902 pub version: Option<String>,
903 pub extensions: Vec<String>,
904 pub signature_ids: Vec<u32>,
905}
906
907/// Full PRONOM signature database loaded from DROID XML.
908#[derive(Debug, Clone, Default)]
909pub struct PronomDatabase {
910 pub formats: HashMap<String, PronomFormat>,
911 pub signatures: HashMap<u32, PronomInternalSignature>,
912 pub puid_by_sig_id: HashMap<u32, Vec<String>>,
913 pub formats_by_ext: HashMap<String, Vec<String>>,
914}
915
916/// Container type discriminator for DROID container signatures.
917#[derive(Debug, Clone, Copy, PartialEq, Eq)]
918pub enum ContainerKind {
919 Zip,
920 Ole2,
921}
922
923/// File matching rule within a container signature.
924#[derive(Debug, Clone, PartialEq, Eq)]
925pub struct ContainerFileRule {
926 pub path: String,
927 pub text_signature: Option<String>,
928 pub binary_signature: Option<Vec<u8>>,
929}
930
931/// Container signature mapping a set of files/streams to a PUID format.
932#[derive(Debug, Clone, PartialEq, Eq)]
933pub struct ContainerSignature {
934 pub id: u32,
935 pub container_kind: ContainerKind,
936 pub description: String,
937 pub files: Vec<ContainerFileRule>,
938 pub puid: Option<String>,
939}
940
941/// Full DROID container signature database.
942#[derive(Debug, Clone, Default)]
943pub struct ContainerSignatureDatabase {
944 pub signatures: Vec<ContainerSignature>,
945 pub zip_signatures: Vec<ContainerSignature>,
946 pub ole2_signatures: Vec<ContainerSignature>,
947 pub sig_by_puid: HashMap<String, Vec<usize>>,
948}
949
950fn extract_attr<'a>(tag: &'a str, attr_name: &str) -> Option<&'a str> {
951 let needle = format!("{attr_name}=\"");
952 let start_idx = tag.find(&needle)?.checked_add(needle.len())?;
953 let rest = tag.get(start_idx..)?;
954 let end_idx = rest.find('"')?;
955 rest.get(..end_idx)
956}
957
958fn hex_nibble(b: u8) -> Option<u8> {
959 match b {
960 b'0'..=b'9' => b.checked_sub(b'0'),
961 b'a'..=b'f' => b.checked_sub(b'a')?.checked_add(10),
962 b'A'..=b'F' => b.checked_sub(b'A')?.checked_add(10),
963 _ => None,
964 }
965}
966
967fn decode_hex_bytes(hex_str: &str) -> Option<Vec<u8>> {
968 let clean: Vec<u8> = hex_str
969 .bytes()
970 .filter(|&b| !b.is_ascii_whitespace())
971 .collect();
972 let rem = clean.len().checked_rem(2)?;
973 if rem != 0 {
974 return None;
975 }
976 let half_len = clean.len().checked_div(2)?;
977 let mut out = Vec::with_capacity(half_len);
978 let mut i = 0usize;
979 while i < clean.len() {
980 let hi = hex_nibble(*clean.get(i)?)?;
981 let next_i = i.checked_add(1)?;
982 let lo = hex_nibble(*clean.get(next_i)?)?;
983 out.push(hi.checked_shl(4)?.checked_add(lo)?);
984 i = i.checked_add(2)?;
985 }
986 Some(out)
987}
988
989/// Decodes a PRONOM byte sequence string that may contain hex pairs, quoted
990/// text literals, or mixed tokens.
991fn decode_pronom_sequence(seq_str: &str) -> Option<Vec<u8>> {
992 let mut bytes = Vec::new();
993 let chars: Vec<char> = seq_str.trim().chars().collect();
994 let mut i = 0usize;
995 while i < chars.len() {
996 let Some(&ch) = chars.get(i) else {
997 break;
998 };
999 if ch.is_whitespace() {
1000 i = i.checked_add(1)?;
1001 continue;
1002 }
1003 if ch == '\'' {
1004 i = i.checked_add(1)?;
1005 let start = i;
1006 while i < chars.len() && chars.get(i) != Some(&'\'') {
1007 i = i.checked_add(1)?;
1008 }
1009 let sub_chars = chars.get(start..i)?;
1010 for &sc in sub_chars {
1011 let mut b = [0u8; 4];
1012 let enc = sc.encode_utf8(&mut b);
1013 bytes.extend_from_slice(enc.as_bytes());
1014 }
1015 if i < chars.len() {
1016 i = i.checked_add(1)?;
1017 }
1018 } else if ch == '[' {
1019 // Mask or character range like ['6'-'7'] or [&01] - not a static byte sequence
1020 return None;
1021 } else if ch.is_ascii_hexdigit() {
1022 let next_i = i.checked_add(1)?;
1023 let Some(&ch2) = chars.get(next_i) else {
1024 return None;
1025 };
1026 if ch2.is_ascii_hexdigit() {
1027 let hi = hex_nibble(u8::try_from(ch).ok()?)?;
1028 let lo = hex_nibble(u8::try_from(ch2).ok()?)?;
1029 bytes.push(hi.checked_shl(4)?.checked_add(lo)?);
1030 i = i.checked_add(2)?;
1031 } else {
1032 return None;
1033 }
1034 } else {
1035 i = i.checked_add(1)?;
1036 }
1037 }
1038
1039 if bytes.is_empty() { None } else { Some(bytes) }
1040}
1041
1042/// Parses the DROID PRONOM binary signature XML file into a `PronomDatabase`.
1043pub fn parse_pronom_signature_xml(xml: &str) -> Option<PronomDatabase> {
1044 let mut db = PronomDatabase::default();
1045
1046 let sig_col_start = xml.find("<InternalSignatureCollection>")?;
1047 let sig_col_end = xml.find("</InternalSignatureCollection>")?;
1048 let sig_xml = xml.get(sig_col_start..sig_col_end)?;
1049
1050 let mut cursor = 0usize;
1051 while let Some(slice) = sig_xml.get(cursor..) {
1052 let Some(start) = slice.find("<InternalSignature ") else {
1053 break;
1054 };
1055 let pos = cursor.checked_add(start)?;
1056 let Some(end_rel) = sig_xml.get(pos..)?.find("</InternalSignature>")
1057 else {
1058 break;
1059 };
1060 let end = pos
1061 .checked_add(end_rel)?
1062 .checked_add("</InternalSignature>".len())?;
1063 let block = sig_xml.get(pos..end)?;
1064 cursor = end;
1065
1066 let Some(tag_end) = block.find('>') else {
1067 continue;
1068 };
1069 let open_tag = block.get(..tag_end)?;
1070 let Some(id_str) = extract_attr(open_tag, "ID") else {
1071 continue;
1072 };
1073 let Ok(id) = id_str.parse::<u32>() else {
1074 continue;
1075 };
1076
1077 // Signatures containing LeftFragment or RightFragment rely on variable
1078 // regex fragments rather than exact literal sequences. Skip to prevent false positives.
1079 if block.contains("<LeftFragment") || block.contains("<RightFragment") {
1080 continue;
1081 }
1082
1083 let mut byte_sequences = Vec::new();
1084 let mut bcursor = 0usize;
1085 while let Some(bslice) = block.get(bcursor..) {
1086 let Some(bstart) = bslice.find("<ByteSequence ") else {
1087 break;
1088 };
1089 let bpos = bcursor.checked_add(bstart)?;
1090 let Some(bend_rel) = block.get(bpos..)?.find("</ByteSequence>")
1091 else {
1092 break;
1093 };
1094 let bend = bpos
1095 .checked_add(bend_rel)?
1096 .checked_add("</ByteSequence>".len())?;
1097 let bblock = block.get(bpos..bend)?;
1098 bcursor = bend;
1099
1100 let Some(btag_end) = bblock.find('>') else {
1101 continue;
1102 };
1103 let bopen_tag = bblock.get(..btag_end)?;
1104 let reference = match extract_attr(bopen_tag, "Reference") {
1105 Some("EOFoffset") => PronomByteSequenceRef::Eof,
1106 _ => PronomByteSequenceRef::Bof,
1107 };
1108
1109 let mut subsequences = Vec::new();
1110 let mut scursor = 0usize;
1111 while let Some(sslice) = bblock.get(scursor..) {
1112 let Some(sstart) = sslice.find("<SubSequence ") else {
1113 break;
1114 };
1115 let spos = scursor.checked_add(sstart)?;
1116 let Some(send_rel) = bblock.get(spos..)?.find("</SubSequence>")
1117 else {
1118 break;
1119 };
1120 let send = spos
1121 .checked_add(send_rel)?
1122 .checked_add("</SubSequence>".len())?;
1123 let sblock = bblock.get(spos..send)?;
1124 scursor = send;
1125
1126 let Some(stag_end) = sblock.find('>') else {
1127 continue;
1128 };
1129 let sopen_tag = sblock.get(..stag_end)?;
1130 let min_off = match extract_attr(sopen_tag, "SubSeqMinOffset") {
1131 Some(s) => match s.parse::<u64>() {
1132 Ok(v) => v,
1133 Err(_) => 0,
1134 },
1135 None => 0,
1136 };
1137 let max_off = match extract_attr(sopen_tag, "SubSeqMaxOffset") {
1138 Some(s) => match s.parse::<u64>() {
1139 Ok(v) => v,
1140 Err(_) => 0,
1141 },
1142 None => 0,
1143 };
1144
1145 if let Some(seq_start) = sblock.find("<Sequence>") {
1146 if let Some(seq_val_start) =
1147 seq_start.checked_add("<Sequence>".len())
1148 {
1149 if let Some(seq_val_end_rel) =
1150 sblock.get(seq_val_start..)?.find("</Sequence>")
1151 {
1152 let seq_val_end =
1153 seq_val_start.checked_add(seq_val_end_rel)?;
1154 if let Some(seq_hex) =
1155 sblock.get(seq_val_start..seq_val_end)
1156 {
1157 if let Some(seq_bytes) =
1158 decode_hex_bytes(seq_hex)
1159 {
1160 subsequences.push(PronomSubSequence {
1161 min_offset: min_off,
1162 max_offset: max_off,
1163 sequence: seq_bytes,
1164 });
1165 }
1166 }
1167 }
1168 }
1169 }
1170 }
1171
1172 if !subsequences.is_empty() {
1173 byte_sequences.push(PronomByteSequence {
1174 reference,
1175 subsequences,
1176 });
1177 }
1178 }
1179
1180 db.signatures
1181 .insert(id, PronomInternalSignature { id, byte_sequences });
1182 }
1183
1184 let fmt_col_start = xml.find("<FileFormatCollection>")?;
1185 let fmt_col_end = xml.find("</FileFormatCollection>")?;
1186 let fmt_xml = xml.get(fmt_col_start..fmt_col_end)?;
1187
1188 cursor = 0usize;
1189 while let Some(slice) = fmt_xml.get(cursor..) {
1190 let Some(start) = slice.find("<FileFormat ") else {
1191 break;
1192 };
1193 let pos = cursor.checked_add(start)?;
1194 let Some(tag_close) = fmt_xml.get(pos..)?.find('>') else {
1195 break;
1196 };
1197 let tag_close_abs = pos.checked_add(tag_close)?;
1198 let is_self_closing = fmt_xml.get(pos..tag_close_abs)?.ends_with('/');
1199 let end = if is_self_closing {
1200 tag_close_abs.checked_add(1)?
1201 } else {
1202 let Some(rel_end) = fmt_xml.get(pos..)?.find("</FileFormat>")
1203 else {
1204 break;
1205 };
1206 pos.checked_add(rel_end)?
1207 .checked_add("</FileFormat>".len())?
1208 };
1209 let block = fmt_xml.get(pos..end)?;
1210 cursor = end;
1211
1212 let open_tag = block.get(..tag_close)?;
1213 let Some(id_str) = extract_attr(open_tag, "ID") else {
1214 continue;
1215 };
1216 let Ok(id) = id_str.parse::<u32>() else {
1217 continue;
1218 };
1219 let Some(puid) =
1220 extract_attr(open_tag, "PUID").map(ToString::to_string)
1221 else {
1222 continue;
1223 };
1224 let name = match extract_attr(open_tag, "Name") {
1225 Some(n) => n.to_string(),
1226 None => String::new(),
1227 };
1228 let mime_type =
1229 extract_attr(open_tag, "MIMEType").map(ToString::to_string);
1230 let version =
1231 extract_attr(open_tag, "Version").map(ToString::to_string);
1232
1233 let mut signature_ids = Vec::new();
1234 let mut icursor = 0usize;
1235 while let Some(islice) = block.get(icursor..) {
1236 let Some(istart) = islice.find("<InternalSignatureID>") else {
1237 break;
1238 };
1239 let Some(ipos) = icursor
1240 .checked_add(istart)?
1241 .checked_add("<InternalSignatureID>".len())
1242 else {
1243 break;
1244 };
1245 let Some(iend_rel) =
1246 block.get(ipos..)?.find("</InternalSignatureID>")
1247 else {
1248 break;
1249 };
1250 let iend = ipos.checked_add(iend_rel)?;
1251 let sig_id_str = block.get(ipos..iend)?;
1252 icursor = iend.checked_add("</InternalSignatureID>".len())?;
1253 if let Ok(sig_id) = sig_id_str.parse::<u32>() {
1254 signature_ids.push(sig_id);
1255 db.puid_by_sig_id
1256 .entry(sig_id)
1257 .or_default()
1258 .push(puid.clone());
1259 }
1260 }
1261
1262 let mut extensions = Vec::new();
1263 let mut ecursor = 0usize;
1264 while let Some(eslice) = block.get(ecursor..) {
1265 let Some(estart) = eslice.find("<Extension>") else {
1266 break;
1267 };
1268 let Some(epos) = ecursor
1269 .checked_add(estart)?
1270 .checked_add("<Extension>".len())
1271 else {
1272 break;
1273 };
1274 let Some(eend_rel) = block.get(epos..)?.find("</Extension>") else {
1275 break;
1276 };
1277 let eend = epos.checked_add(eend_rel)?;
1278 let ext = block.get(epos..eend)?.trim().to_ascii_lowercase();
1279 ecursor = eend.checked_add("</Extension>".len())?;
1280 if !ext.is_empty() {
1281 extensions.push(ext.clone());
1282 db.formats_by_ext.entry(ext).or_default().push(puid.clone());
1283 }
1284 }
1285
1286 db.formats.insert(
1287 puid.clone(),
1288 PronomFormat {
1289 id,
1290 puid,
1291 name,
1292 mime_type,
1293 version,
1294 extensions,
1295 signature_ids,
1296 },
1297 );
1298 }
1299
1300 Some(db)
1301}
1302
1303/// Parses the DROID container signature XML into a `ContainerSignatureDatabase`.
1304pub fn parse_droid_container_signatures_xml(
1305 xml: &str,
1306) -> Option<ContainerSignatureDatabase> {
1307 let mut db = ContainerSignatureDatabase::default();
1308 let mut sig_by_id = HashMap::new();
1309
1310 let sig_col_start = xml.find("<ContainerSignatures>")?;
1311 let sig_col_end = xml.find("</ContainerSignatures>")?;
1312 let sig_xml = xml.get(sig_col_start..sig_col_end)?;
1313
1314 let mut cursor = 0usize;
1315 while let Some(slice) = sig_xml.get(cursor..) {
1316 let Some(start) = slice.find("<ContainerSignature ") else {
1317 break;
1318 };
1319 let pos = cursor.checked_add(start)?;
1320 let Some(end_rel) = sig_xml.get(pos..)?.find("</ContainerSignature>")
1321 else {
1322 break;
1323 };
1324 let end = pos
1325 .checked_add(end_rel)?
1326 .checked_add("</ContainerSignature>".len())?;
1327 let block = sig_xml.get(pos..end)?;
1328 cursor = end;
1329
1330 let Some(tag_end) = block.find('>') else {
1331 continue;
1332 };
1333 let open_tag = block.get(..tag_end)?;
1334 let Some(id_str) = extract_attr(open_tag, "Id") else {
1335 continue;
1336 };
1337 let Ok(id) = id_str.parse::<u32>() else {
1338 continue;
1339 };
1340 let container_kind = match extract_attr(open_tag, "ContainerType") {
1341 Some("OLE2") => ContainerKind::Ole2,
1342 _ => ContainerKind::Zip,
1343 };
1344
1345 let description = if let Some(desc_start) = block.find("<Description>")
1346 {
1347 if let Some(desc_val_start) =
1348 desc_start.checked_add("<Description>".len())
1349 {
1350 if let Some(desc_rel_end) =
1351 block.get(desc_val_start..)?.find("</Description>")
1352 {
1353 let desc_end = desc_val_start.checked_add(desc_rel_end)?;
1354 match block.get(desc_val_start..desc_end) {
1355 Some(d) => d.trim().to_string(),
1356 None => String::new(),
1357 }
1358 } else {
1359 String::new()
1360 }
1361 } else {
1362 String::new()
1363 }
1364 } else {
1365 String::new()
1366 };
1367
1368 let mut files = Vec::new();
1369 let mut fcursor = 0usize;
1370 while let Some(fslice) = block.get(fcursor..) {
1371 let Some(fstart) = fslice.find("<File") else {
1372 break;
1373 };
1374 let fpos = fcursor.checked_add(fstart)?;
1375 let Some(fend_rel) = block.get(fpos..)?.find("</File>") else {
1376 break;
1377 };
1378 let fend =
1379 fpos.checked_add(fend_rel)?.checked_add("</File>".len())?;
1380 let fblock = block.get(fpos..fend)?;
1381 fcursor = fend;
1382
1383 let path = if let Some(pstart) = fblock.find("<Path>") {
1384 if let Some(pval_start) = pstart.checked_add("<Path>".len()) {
1385 if let Some(pend_rel) =
1386 fblock.get(pval_start..)?.find("</Path>")
1387 {
1388 let pend = pval_start.checked_add(pend_rel)?;
1389 match fblock.get(pval_start..pend) {
1390 Some(p) => p.trim().to_string(),
1391 None => String::new(),
1392 }
1393 } else {
1394 String::new()
1395 }
1396 } else {
1397 String::new()
1398 }
1399 } else {
1400 String::new()
1401 };
1402
1403 if path.is_empty() {
1404 continue;
1405 }
1406
1407 let mut text_signature = None;
1408 let mut binary_signature = None;
1409 if let Some(sstart) = fblock.find("<Sequence>") {
1410 if let Some(sval_start) = sstart.checked_add("<Sequence>".len())
1411 {
1412 if let Some(send_rel) =
1413 fblock.get(sval_start..)?.find("</Sequence>")
1414 {
1415 let send = sval_start.checked_add(send_rel)?;
1416 // Reason for fallback: empty string used when sequence tag is empty
1417 let seq_raw =
1418 fblock.get(sval_start..send).unwrap_or("").trim();
1419 if let Some(bytes) = decode_pronom_sequence(seq_raw) {
1420 if let Ok(text) = std::str::from_utf8(&bytes) {
1421 if !text.contains('\0') {
1422 text_signature = Some(text.to_string());
1423 }
1424 }
1425 binary_signature = Some(bytes);
1426 }
1427 }
1428 }
1429 }
1430
1431 files.push(ContainerFileRule {
1432 path,
1433 text_signature,
1434 binary_signature,
1435 });
1436 }
1437
1438 let sig = ContainerSignature {
1439 id,
1440 container_kind,
1441 description,
1442 files,
1443 puid: None,
1444 };
1445 sig_by_id.insert(id, sig);
1446 }
1447
1448 if let Some(map_start) = xml.find("<FileFormatMappings>") {
1449 if let Some(map_end) = xml.find("</FileFormatMappings>") {
1450 if let Some(map_xml) = xml.get(map_start..map_end) {
1451 let mut cursor = 0usize;
1452 while let Some(slice) = map_xml.get(cursor..) {
1453 let Some(start) = slice.find("<FileFormatMapping ") else {
1454 break;
1455 };
1456 let pos = cursor.checked_add(start)?;
1457 let Some(tag_close) = map_xml.get(pos..)?.find('>') else {
1458 break;
1459 };
1460 let tag_close_pos = pos.checked_add(tag_close)?;
1461 let tag = map_xml.get(pos..tag_close_pos)?;
1462 cursor = tag_close_pos.checked_add(1)?;
1463
1464 let Some(id_str) = extract_attr(tag, "signatureId") else {
1465 continue;
1466 };
1467 let Ok(sig_id) = id_str.parse::<u32>() else {
1468 continue;
1469 };
1470 let Some(puid) = extract_attr(tag, "Puid") else {
1471 continue;
1472 };
1473
1474 if let Some(sig) = sig_by_id.get_mut(&sig_id) {
1475 sig.puid = Some(puid.to_string());
1476 }
1477 }
1478 }
1479 }
1480 }
1481
1482 for (_, sig) in sig_by_id {
1483 match sig.container_kind {
1484 ContainerKind::Zip => db.zip_signatures.push(sig.clone()),
1485 ContainerKind::Ole2 => db.ole2_signatures.push(sig.clone()),
1486 }
1487 if let Some(ref puid) = sig.puid {
1488 let idx = db.signatures.len();
1489 db.sig_by_puid.entry(puid.clone()).or_default().push(idx);
1490 }
1491 db.signatures.push(sig);
1492 }
1493
1494 Some(db)
1495}
1496
1497static DROID_SIGNATURE_XML: LazyLock<Option<Vec<u8>>> = LazyLock::new(|| {
1498 let key = "data/detection/droid/signatures/DROID_SignatureFile_V125.xml";
1499 if let Some(bytes) = ctb_storage_asset_bundle::get_asset(key) {
1500 return Some(bytes);
1501 }
1502 // Reason for fallback: when running tests or before asset bundle repack, load from repository assets directory
1503 let disk_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1504 .join("../../../assets")
1505 .join(key);
1506 std::fs::read(disk_path).ok()
1507});
1508
1509static DROID_CONTAINER_SIGNATURE_XML: LazyLock<Option<Vec<u8>>> =
1510 LazyLock::new(|| {
1511 let key =
1512 "data/detection/droid/signatures/container-signature-20260119.xml";
1513 if let Some(bytes) = ctb_storage_asset_bundle::get_asset(key) {
1514 return Some(bytes);
1515 }
1516 // Reason for fallback: when running tests or before asset bundle repack, load from repository assets directory
1517 let disk_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1518 .join("../../../assets")
1519 .join(key);
1520 std::fs::read(disk_path).ok()
1521 });
1522
1523/// Returns the canonical DROID PRONOM binary signature file (V125) as raw bytes.
1524pub fn get_droid_signature_xml() -> Option<&'static [u8]> {
1525 DROID_SIGNATURE_XML.as_deref()
1526}
1527
1528/// Returns the canonical DROID container signature file as raw bytes.
1529pub fn get_droid_container_signature_xml() -> Option<&'static [u8]> {
1530 DROID_CONTAINER_SIGNATURE_XML.as_deref()
1531}
1532
1533/// Authoritative DROID PRONOM binary signature database loaded from embedded XML.
1534pub static DROID_PRONOM_DB: LazyLock<PronomDatabase> = LazyLock::new(|| {
1535 // Reason for fallback: default empty database used if embedded asset fails to parse
1536 get_droid_signature_xml()
1537 .and_then(|bytes| std::str::from_utf8(bytes).ok())
1538 .and_then(parse_pronom_signature_xml)
1539 .unwrap_or_default()
1540});
1541
1542/// Authoritative DROID container signature database loaded from embedded XML.
1543pub static DROID_CONTAINER_DB: LazyLock<ContainerSignatureDatabase> =
1544 LazyLock::new(|| {
1545 // Reason for fallback: default empty database used if embedded asset fails to parse
1546 get_droid_container_signature_xml()
1547 .and_then(|bytes| std::str::from_utf8(bytes).ok())
1548 .and_then(parse_droid_container_signatures_xml)
1549 .unwrap_or_default()
1550 });
1551
1552/// Evaluates PRONOM signatures from DROID database on source.
1553pub fn evaluate_pronom_signatures<S: DetectionSource + ?Sized>(
1554 source: &mut S,
1555 hint: Option<&DetectionHint>,
1556) -> Result<Vec<DetectionCandidate>> {
1557 let mut candidates = Vec::new();
1558 let bof_sample = source.read_bof(65536)?;
1559 let eof_sample = source.read_eof(65536)?;
1560
1561 let hint_ext = hint.and_then(|h| {
1562 h.extension.as_deref().or_else(|| {
1563 h.filename.as_deref().and_then(|f| {
1564 f.rsplit(['/', '\\'])
1565 .next()?
1566 .rsplit_once('.')
1567 .map(|(_, ext)| ext)
1568 })
1569 })
1570 });
1571
1572 let db = &*DROID_PRONOM_DB;
1573 if db.signatures.is_empty() {
1574 return Ok(candidates);
1575 }
1576
1577 for sig in db.signatures.values() {
1578 if sig.byte_sequences.is_empty() {
1579 continue;
1580 }
1581
1582 let mut sig_matched = true;
1583 let mut bof_matched = false;
1584 let mut eof_matched = false;
1585 let mut first_bof_off: Option<u64> = None;
1586 let mut first_eof_off: Option<u64> = None;
1587
1588 for bs in &sig.byte_sequences {
1589 match bs.reference {
1590 PronomByteSequenceRef::Bof => {
1591 if bof_sample.is_empty() {
1592 sig_matched = false;
1593 break;
1594 }
1595 let mut bof_ok = true;
1596 for sub in &bs.subsequences {
1597 let min_off =
1598 if let Ok(m) = usize::try_from(sub.min_offset) {
1599 m
1600 } else {
1601 bof_ok = false;
1602 break;
1603 };
1604 let max_off =
1605 if let Ok(m) = usize::try_from(sub.max_offset) {
1606 m
1607 } else {
1608 bof_ok = false;
1609 break;
1610 };
1611 let pat = &sub.sequence;
1612 if pat.len() < 2 {
1613 bof_ok = false;
1614 break;
1615 }
1616 // Fast rejection for exact offset
1617 if min_off == max_off {
1618 if let Some(first_byte) = pat.first() {
1619 if bof_sample.get(min_off) != Some(first_byte) {
1620 bof_ok = false;
1621 break;
1622 }
1623 }
1624 }
1625 let limit = max_off
1626 .saturating_add(pat.len())
1627 .min(bof_sample.len());
1628 let mut found = false;
1629 let mut off = min_off;
1630 while off.saturating_add(pat.len()) <= limit {
1631 if bof_sample
1632 .get(off..off.saturating_add(pat.len()))
1633 == Some(pat.as_slice())
1634 {
1635 found = true;
1636 if first_bof_off.is_none() {
1637 first_bof_off = u64::try_from(off).ok();
1638 }
1639 break;
1640 }
1641 off = off.saturating_add(1);
1642 }
1643 if !found {
1644 bof_ok = false;
1645 break;
1646 }
1647 }
1648 if bof_ok {
1649 bof_matched = true;
1650 } else {
1651 sig_matched = false;
1652 break;
1653 }
1654 }
1655 PronomByteSequenceRef::Eof => {
1656 if eof_sample.is_empty() {
1657 sig_matched = false;
1658 break;
1659 }
1660 let mut eof_ok = true;
1661 let sample_len = eof_sample.len();
1662 for sub in &bs.subsequences {
1663 let min_off =
1664 if let Ok(m) = usize::try_from(sub.min_offset) {
1665 m
1666 } else {
1667 eof_ok = false;
1668 break;
1669 };
1670 let max_off =
1671 if let Ok(m) = usize::try_from(sub.max_offset) {
1672 m
1673 } else {
1674 eof_ok = false;
1675 break;
1676 };
1677 let pat = &sub.sequence;
1678 if pat.len() < 2 {
1679 eof_ok = false;
1680 break;
1681 }
1682 let limit = max_off.min(sample_len);
1683 let mut found = false;
1684 let mut dist = min_off;
1685 while dist.saturating_add(pat.len()) <= limit {
1686 let start_idx = sample_len
1687 .saturating_sub(dist.saturating_add(pat.len()));
1688 let end_idx = start_idx.saturating_add(pat.len());
1689 if eof_sample.get(start_idx..end_idx)
1690 == Some(pat.as_slice())
1691 {
1692 found = true;
1693 if first_eof_off.is_none() {
1694 first_eof_off = u64::try_from(dist).ok();
1695 }
1696 break;
1697 }
1698 dist = dist.saturating_add(1);
1699 }
1700 if !found {
1701 eof_ok = false;
1702 break;
1703 }
1704 }
1705 if eof_ok {
1706 eof_matched = true;
1707 } else {
1708 sig_matched = false;
1709 break;
1710 }
1711 }
1712 }
1713 }
1714
1715 if sig_matched && (bof_matched || eof_matched) {
1716 if let Some(puids) = db.puid_by_sig_id.get(&sig.id) {
1717 for puid in puids {
1718 if let Some(fmt) = db.formats.get(puid) {
1719 let mut score = if bof_matched && eof_matched {
1720 95u32
1721 } else {
1722 90u32
1723 };
1724 let mut evidence = vec![DetectionEvidence::Pronom {
1725 puid: puid.clone(),
1726 score,
1727 }];
1728 if let Some(bof_off) = first_bof_off {
1729 evidence.push(DetectionEvidence::DualAnchored {
1730 bof_offset: bof_off,
1731 eof_offset: first_eof_off,
1732 score,
1733 });
1734 }
1735
1736 if let Some(ext) = hint_ext {
1737 if fmt
1738 .extensions
1739 .iter()
1740 .any(|e| e.eq_ignore_ascii_case(ext))
1741 {
1742 score = score.saturating_add(5).min(100);
1743 evidence.push(DetectionEvidence::Extension {
1744 ext: ext.to_string(),
1745 is_primary: true,
1746 score: 25,
1747 });
1748 }
1749 }
1750
1751 let is_elf_puid = puid == "fmt/689"
1752 || puid == "fmt/690"
1753 || fmt.name.eq_ignore_ascii_case(
1754 "Executable and Linkable Format",
1755 );
1756 let mapping = fmt
1757 .mime_type
1758 .as_deref()
1759 .and_then(|m| {
1760 crate::mime_derivation::FORMAT_CATALOG
1761 .lookup_mime(m)
1762 })
1763 .or_else(|| {
1764 crate::mime_derivation::FORMAT_CATALOG
1765 .lookup_description_or_ident(&fmt.name)
1766 });
1767 let format_id = mapping.and_then(|m| m.format_id).or({
1768 if is_elf_puid {
1769 Some(FormatId::Elf)
1770 } else {
1771 None
1772 }
1773 });
1774 let dc_id = mapping.map(|m| m.dc_id).or_else(|| {
1775 if is_elf_puid {
1776 FormatId::Elf.dc_id()
1777 } else {
1778 None
1779 }
1780 });
1781
1782 candidates.push(DetectionCandidate {
1783 format_id,
1784 dc_id,
1785 mime: fmt.mime_type.clone(),
1786 description: fmt.name.clone(),
1787 confidence: if score >= 90 {
1788 ConfidenceTier::HighestConfidence
1789 } else {
1790 ConfidenceTier::Strong
1791 },
1792 score,
1793 evidence,
1794 chain_layers: None,
1795 });
1796 }
1797 }
1798 }
1799 }
1800 }
1801
1802 Ok(candidates)
1803}
1804
1805// ---------------------------------------------------------------------------
1806// 3. ZIP Central Directory Inspector & Container Signatures
1807// ---------------------------------------------------------------------------
1808
1809const ZIP_LOCAL_HEADER_MAGIC: [u8; 4] = [0x50, 0x4B, 0x03, 0x04];
1810const ZIP_CENTRAL_HEADER_MAGIC: [u8; 4] = [0x50, 0x4B, 0x01, 0x02];
1811const ZIP_EOCD_MAGIC: [u8; 4] = [0x50, 0x4B, 0x05, 0x06];
1812const ZIP64_EOCD_LOCATOR_MAGIC: [u8; 4] = [0x50, 0x4B, 0x06, 0x07];
1813
1814/// Summary of an individual file or directory entry in a ZIP container.
1815#[derive(Debug, Clone, PartialEq, Eq)]
1816pub struct ZipEntrySummary {
1817 pub name: String,
1818 pub compressed_size: u32,
1819 pub uncompressed_size: u32,
1820 pub compression_method: u16,
1821 pub local_header_offset: u32,
1822}
1823
1824/// Parses the ZIP Central Directory from the end of the file (EOCD).
1825///
1826/// Returns `Ok(Some(entries))` when a valid End of Central Directory record
1827/// and Central Directory headers are successfully identified and traversed.
1828/// Falls back to returning `Ok(None)` if no EOCD signature is found within
1829/// the standard 65KB EOF window.
1830pub fn parse_zip_central_directory<S: DetectionSource + ?Sized>(
1831 source: &mut S,
1832) -> Result<Option<Vec<ZipEntrySummary>>> {
1833 let Some(total) = source.total_len() else {
1834 return Ok(None);
1835 };
1836 if total < 22 {
1837 return Ok(None);
1838 }
1839
1840 // Read up to 65557 bytes from EOF (maximum ZIP comment size is 65535 + 22 byte EOCD)
1841 // Reason for fallback: cap maximum EOF read to 65557 bytes if integer conversion overflows
1842 let max_read = usize::try_from(total.min(65557)).unwrap_or(65557);
1843 let eof_buf = source.read_eof(max_read)?;
1844 if eof_buf.len() < 22 {
1845 return Ok(None);
1846 }
1847
1848 // Scan backwards for EOCD signature PK\x05\x06
1849 let mut eocd_pos: Option<usize> = None;
1850 let len = eof_buf.len();
1851 let mut i = len.saturating_sub(22);
1852 loop {
1853 if eof_buf.get(i..i.saturating_add(4)) == Some(ZIP_EOCD_MAGIC.as_slice()) {
1854 eocd_pos = Some(i);
1855 break;
1856 }
1857 if i == 0 {
1858 break;
1859 }
1860 i = i.saturating_sub(1);
1861 }
1862
1863 let Some(pos) = eocd_pos else {
1864 return Ok(None);
1865 };
1866
1867 let Some(eocd_slice) = eof_buf.get(pos..) else {
1868 return Ok(None);
1869 };
1870 if eocd_slice.len() < 22 {
1871 return Ok(None);
1872 }
1873
1874 let total_entries = match eocd_slice.get(10..12) {
1875 Some(&[b0, b1]) => u16::from_le_bytes([b0, b1]),
1876 _ => return Ok(None),
1877 };
1878 let cd_size = match eocd_slice.get(12..16) {
1879 Some(&[b0, b1, b2, b3]) => u32::from_le_bytes([b0, b1, b2, b3]),
1880 _ => return Ok(None),
1881 };
1882 let cd_offset = match eocd_slice.get(16..20) {
1883 Some(&[b0, b1, b2, b3]) => u32::from_le_bytes([b0, b1, b2, b3]),
1884 _ => return Ok(None),
1885 };
1886
1887 // Safety checks against overflow or corrupt offsets
1888 let u_cd_offset = u64::from(cd_offset);
1889 let u_cd_size = u64::from(cd_size);
1890 if u_cd_offset.saturating_add(u_cd_size) > total {
1891 return Ok(None);
1892 }
1893
1894 // Cap maximum directory entries to prevent DoS attacks
1895 let max_entries = usize::from(total_entries.min(5000));
1896 // Reason for fallback: bounded central directory buffer allocation if integer conversion overflows
1897 let cd_bytes_len = usize::try_from(u_cd_size.min(524288)).unwrap_or(524288);
1898 let mut cd_buf = vec![0u8; cd_bytes_len];
1899 let n = source.read_at(u_cd_offset, &mut cd_buf)?;
1900 let cd_sample = match cd_buf.get(..n) {
1901 Some(s) => s,
1902 None => return Ok(None),
1903 };
1904
1905 let mut entries = Vec::with_capacity(max_entries);
1906 let mut cd_pos: usize = 0;
1907 while cd_pos.saturating_add(46) <= cd_sample.len()
1908 && entries.len() < max_entries
1909 {
1910 if cd_sample.get(cd_pos..cd_pos.saturating_add(4))
1911 != Some(ZIP_CENTRAL_HEADER_MAGIC.as_slice())
1912 {
1913 break;
1914 }
1915
1916 let header = match cd_sample.get(cd_pos..cd_pos.saturating_add(46)) {
1917 Some(h) => h,
1918 None => break,
1919 };
1920
1921 let method = match header.get(10..12) {
1922 Some(&[b0, b1]) => u16::from_le_bytes([b0, b1]),
1923 _ => break,
1924 };
1925 let comp_sz = match header.get(20..24) {
1926 Some(&[b0, b1, b2, b3]) => u32::from_le_bytes([b0, b1, b2, b3]),
1927 _ => break,
1928 };
1929 let uncomp_sz = match header.get(24..28) {
1930 Some(&[b0, b1, b2, b3]) => u32::from_le_bytes([b0, b1, b2, b3]),
1931 _ => break,
1932 };
1933 let flen = match header.get(28..30) {
1934 Some(&[b0, b1]) => u16::from_le_bytes([b0, b1]),
1935 _ => break,
1936 };
1937 let elen = match header.get(30..32) {
1938 Some(&[b0, b1]) => u16::from_le_bytes([b0, b1]),
1939 _ => break,
1940 };
1941 let clen = match header.get(32..34) {
1942 Some(&[b0, b1]) => u16::from_le_bytes([b0, b1]),
1943 _ => break,
1944 };
1945 let local_off = match header.get(42..46) {
1946 Some(&[b0, b1, b2, b3]) => u32::from_le_bytes([b0, b1, b2, b3]),
1947 _ => break,
1948 };
1949
1950 let name_start = cd_pos.saturating_add(46);
1951 let name_end = name_start.saturating_add(usize::from(flen));
1952 if let Some(name_bytes) = cd_sample.get(name_start..name_end) {
1953 let name = String::from_utf8_lossy(name_bytes).to_string();
1954 entries.push(ZipEntrySummary {
1955 name,
1956 compressed_size: comp_sz,
1957 uncompressed_size: uncomp_sz,
1958 compression_method: method,
1959 local_header_offset: local_off,
1960 });
1961 }
1962
1963 cd_pos = name_end
1964 .saturating_add(usize::from(elen))
1965 .saturating_add(usize::from(clen));
1966 }
1967
1968 Ok(Some(entries))
1969}
1970
1971/// Fallback scanner for local file headers from the beginning of the file.
1972pub fn scan_zip_local_headers<S: DetectionSource + ?Sized>(
1973 source: &mut S,
1974) -> Result<Vec<ZipEntrySummary>> {
1975 let mut buf = vec![0u8; 65536];
1976 let n = source.read_at(0, &mut buf)?;
1977 if n < 30 || !buf.starts_with(&ZIP_LOCAL_HEADER_MAGIC) {
1978 return Ok(Vec::new());
1979 }
1980
1981 let sample = match buf.get(..n) {
1982 Some(s) => s,
1983 None => return Ok(Vec::new()),
1984 };
1985
1986 let mut entries = Vec::new();
1987 let mut pos: usize = 0;
1988 while pos.saturating_add(30) <= sample.len() && entries.len() < 500 {
1989 let header = match sample.get(pos..pos.saturating_add(30)) {
1990 Some(h) => h,
1991 None => break,
1992 };
1993 if header.get(..4) == Some(ZIP_LOCAL_HEADER_MAGIC.as_slice()) {
1994 let method = match header.get(8..10) {
1995 Some(&[b0, b1]) => u16::from_le_bytes([b0, b1]),
1996 _ => break,
1997 };
1998 let comp_sz = match header.get(18..22) {
1999 Some(&[b0, b1, b2, b3]) => u32::from_le_bytes([b0, b1, b2, b3]),
2000 _ => break,
2001 };
2002 let uncomp_sz = match header.get(22..26) {
2003 Some(&[b0, b1, b2, b3]) => u32::from_le_bytes([b0, b1, b2, b3]),
2004 _ => break,
2005 };
2006 let flen = match header.get(26..28) {
2007 Some(&[b0, b1]) => u16::from_le_bytes([b0, b1]),
2008 _ => break,
2009 };
2010 let elen = match header.get(28..30) {
2011 Some(&[b0, b1]) => u16::from_le_bytes([b0, b1]),
2012 _ => break,
2013 };
2014
2015 let name_start = pos.saturating_add(30);
2016 let name_end = name_start.saturating_add(usize::from(flen));
2017 if let Some(name_bytes) = sample.get(name_start..name_end) {
2018 let name = String::from_utf8_lossy(name_bytes).to_string();
2019 // Reason for fallback: default to zero offset if local position conversion overflows
2020 let local_off = u32::try_from(pos).unwrap_or(0);
2021 entries.push(ZipEntrySummary {
2022 name,
2023 compressed_size: comp_sz,
2024 uncompressed_size: uncomp_sz,
2025 compression_method: method,
2026 local_header_offset: local_off,
2027 });
2028 }
2029 pos = name_end
2030 .saturating_add(usize::from(elen))
2031 .max(pos.saturating_add(1));
2032 } else {
2033 pos = pos.saturating_add(1);
2034 }
2035 }
2036
2037 Ok(entries)
2038}
2039
2040/// Reads the uncompressed or Deflate-decompressed payload of a ZIP entry.
2041pub fn read_zip_entry_payload<S: DetectionSource + ?Sized>(
2042 source: &mut S,
2043 entry: &ZipEntrySummary,
2044 max_bytes: usize,
2045) -> Result<Option<Vec<u8>>> {
2046 let local_off = u64::from(entry.local_header_offset);
2047 let mut header = [0u8; 30];
2048 let n = source.read_at(local_off, &mut header)?;
2049 if n < 30 || header.get(..4) != Some(ZIP_LOCAL_HEADER_MAGIC.as_slice()) {
2050 return Ok(None);
2051 }
2052 let flen = match header.get(26..28) {
2053 Some(&[b0, b1]) => u16::from_le_bytes([b0, b1]),
2054 _ => return Ok(None),
2055 };
2056 let elen = match header.get(28..30) {
2057 Some(&[b0, b1]) => u16::from_le_bytes([b0, b1]),
2058 _ => return Ok(None),
2059 };
2060 let data_offset = local_off
2061 .saturating_add(30)
2062 .saturating_add(u64::from(flen))
2063 .saturating_add(u64::from(elen));
2064
2065 if entry.compression_method == 0 {
2066 // Reason for fallback: cap read size to max_bytes buffer limit if conversion overflows
2067 let to_read = usize::try_from(u64::from(entry.uncompressed_size))
2068 .unwrap_or(max_bytes)
2069 .min(max_bytes);
2070 let mut buf = vec![0u8; to_read];
2071 let read_n = source.read_at(data_offset, &mut buf)?;
2072 buf.truncate(read_n);
2073 return Ok(Some(buf));
2074 }
2075
2076 if entry.compression_method == 8 {
2077 // Reason for fallback: bounded buffer size for streaming compressed deflate payload
2078 let comp_size = usize::try_from(u64::from(entry.compressed_size))
2079 .unwrap_or(65536)
2080 .min(65536);
2081 let mut comp_buf = vec![0u8; comp_size];
2082 let read_n = source.read_at(data_offset, &mut comp_buf)?;
2083 comp_buf.truncate(read_n);
2084
2085 use std::io::Read;
2086 let mut decoder =
2087 flate2::read::DeflateDecoder::new(comp_buf.as_slice());
2088 let mut decomp_buf = vec![0u8; max_bytes];
2089 let mut total_read = 0usize;
2090 while total_read < max_bytes {
2091 let Some(chunk_slice) = decomp_buf.get_mut(total_read..) else {
2092 break;
2093 };
2094 if chunk_slice.is_empty() {
2095 break;
2096 }
2097 match decoder.read(chunk_slice) {
2098 Ok(0) => break,
2099 Ok(bytes) => {
2100 total_read = total_read.saturating_add(bytes);
2101 }
2102 Err(_) => break,
2103 }
2104 }
2105 decomp_buf.truncate(total_read);
2106 return Ok(Some(decomp_buf));
2107 }
2108
2109 Ok(None)
2110}
2111
2112/// Reads the uncompressed payload of an entry stored with compression method 0.
2113fn read_uncompressed_entry<S: DetectionSource + ?Sized>(
2114 source: &mut S,
2115 entry: &ZipEntrySummary,
2116 max_bytes: usize,
2117) -> Result<Option<Vec<u8>>> {
2118 read_zip_entry_payload(source, entry, max_bytes)
2119}
2120
2121/// Evaluates DROID container signatures against ZIP entry summaries.
2122pub fn evaluate_droid_zip_container<S: DetectionSource + ?Sized>(
2123 source: &mut S,
2124 entries: &[ZipEntrySummary],
2125 db: &ContainerSignatureDatabase,
2126) -> Result<Option<DetectionCandidate>> {
2127 if entries.is_empty() || db.zip_signatures.is_empty() {
2128 return Ok(None);
2129 }
2130
2131 for sig in &db.zip_signatures {
2132 if sig.files.is_empty() {
2133 continue;
2134 }
2135
2136 let mut all_files_matched = true;
2137 for file_rule in &sig.files {
2138 let rule_path = file_rule.path.trim_start_matches('/');
2139 let Some(entry) = entries.iter().find(|e| {
2140 let entry_path = e.name.trim_start_matches('/');
2141 entry_path.eq_ignore_ascii_case(rule_path)
2142 }) else {
2143 all_files_matched = false;
2144 break;
2145 };
2146
2147 if let Some(ref text_sig) = file_rule.text_signature {
2148 let payload = if let Some(p) =
2149 read_zip_entry_payload(source, entry, 65536)?
2150 {
2151 p
2152 } else {
2153 all_files_matched = false;
2154 break;
2155 };
2156 let text = String::from_utf8_lossy(&payload);
2157 if !text.contains(text_sig) {
2158 all_files_matched = false;
2159 break;
2160 }
2161 }
2162
2163 if let Some(ref bin_sig) = file_rule.binary_signature {
2164 let payload = if let Some(p) =
2165 read_zip_entry_payload(source, entry, 65536)?
2166 {
2167 p
2168 } else {
2169 all_files_matched = false;
2170 break;
2171 };
2172 if !payload
2173 .windows(bin_sig.len())
2174 .any(|w| w == bin_sig.as_slice())
2175 {
2176 all_files_matched = false;
2177 break;
2178 }
2179 }
2180 }
2181
2182 if all_files_matched {
2183 let puid_opt = sig.puid.clone();
2184 let mut mime = None;
2185 let mut desc = sig.description.clone();
2186
2187 if let Some(ref puid) = puid_opt {
2188 if let Some(fmt) = DROID_PRONOM_DB.formats.get(puid) {
2189 if let Some(ref m) = fmt.mime_type {
2190 mime = Some(m.clone());
2191 } else {
2192 for ext in &fmt.extensions {
2193 if let Some(m) = crate::detection::mime_derivation::FORMAT_CATALOG
2194 .lookup_extension(ext)
2195 .iter()
2196 .find_map(|m| m.mime_types.first().cloned())
2197 {
2198 mime = Some(m);
2199 break;
2200 }
2201 if ext == "apk" {
2202 mime = Some(
2203 "application/vnd.android.package-archive"
2204 .to_string(),
2205 );
2206 break;
2207 }
2208 }
2209 }
2210 if !fmt.name.is_empty() {
2211 desc = fmt.name.clone();
2212 }
2213 }
2214 }
2215
2216 let mut evidence = vec![DetectionEvidence::ContainerStructure {
2217 detail: format!(
2218 "Matched DROID ZIP container signature {}: {}",
2219 sig.id, sig.description
2220 ),
2221 score: 98,
2222 }];
2223
2224 if let Some(ref puid) = puid_opt {
2225 evidence.push(DetectionEvidence::Pronom {
2226 puid: puid.clone(),
2227 score: 98,
2228 });
2229 }
2230
2231 return Ok(Some(DetectionCandidate {
2232 format_id: None,
2233 dc_id: None,
2234 mime,
2235 description: desc,
2236 confidence: ConfidenceTier::HighestConfidence,
2237 score: 98,
2238 evidence,
2239 chain_layers: None,
2240 }));
2241 }
2242 }
2243
2244 Ok(None)
2245}
2246
2247/// Evaluates DROID container signatures against OLE2 stream names.
2248pub fn evaluate_droid_ole2_container<S: DetectionSource + ?Sized>(
2249 source: &mut S,
2250 stream_names: &[String],
2251 db: &ContainerSignatureDatabase,
2252) -> Result<Option<DetectionCandidate>> {
2253 if stream_names.is_empty() || db.ole2_signatures.is_empty() {
2254 return Ok(None);
2255 }
2256
2257 let mut sample_buf = vec![0u8; 262144];
2258 let n = source.read_at(0, &mut sample_buf)?;
2259 // Reason for fallback: empty slice used if read buffer length is zero
2260 let sample = sample_buf.get(..n).unwrap_or(&[]);
2261
2262 let mut candidate_matches = Vec::new();
2263
2264 for sig in &db.ole2_signatures {
2265 if sig.files.is_empty() {
2266 continue;
2267 }
2268
2269 let mut has_sequence = false;
2270 let mut all_streams_matched = true;
2271
2272 for file_rule in &sig.files {
2273 let rule_path = file_rule.path.trim_start_matches('/');
2274 let stream_found = stream_names.iter().any(|s| {
2275 let s_path = s.trim_start_matches('/');
2276 s_path.eq_ignore_ascii_case(rule_path)
2277 });
2278 if !stream_found {
2279 all_streams_matched = false;
2280 break;
2281 }
2282
2283 if let Some(ref text_sig) = file_rule.text_signature {
2284 has_sequence = true;
2285 if !sample
2286 .windows(text_sig.len())
2287 .any(|w| w == text_sig.as_bytes())
2288 {
2289 all_streams_matched = false;
2290 break;
2291 }
2292 }
2293
2294 if let Some(ref bin_sig) = file_rule.binary_signature {
2295 has_sequence = true;
2296 if !sample
2297 .windows(bin_sig.len())
2298 .any(|w| w == bin_sig.as_slice())
2299 {
2300 all_streams_matched = false;
2301 break;
2302 }
2303 }
2304 }
2305
2306 if all_streams_matched {
2307 let score = if has_sequence { 95 } else { 85 };
2308 candidate_matches.push((has_sequence, sig.files.len(), score, sig));
2309 }
2310 }
2311
2312 candidate_matches.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| b.1.cmp(&a.1)));
2313
2314 let Some((_has_seq, _files_len, score, sig)) = candidate_matches.first()
2315 else {
2316 return Ok(None);
2317 };
2318
2319 let puid_opt = sig.puid.clone();
2320 let mut mime = None;
2321 let mut desc = sig.description.clone();
2322
2323 if let Some(ref puid) = puid_opt {
2324 if let Some(fmt) = DROID_PRONOM_DB.formats.get(puid) {
2325 if let Some(ref m) = fmt.mime_type {
2326 mime = Some(m.clone());
2327 } else {
2328 for ext in &fmt.extensions {
2329 if ext == "hwp" {
2330 mime = Some("application/x-hwp".to_string());
2331 break;
2332 }
2333 if let Some(m) =
2334 crate::detection::mime_derivation::FORMAT_CATALOG
2335 .lookup_extension(ext)
2336 .iter()
2337 .find_map(|m| m.mime_types.first().cloned())
2338 {
2339 mime = Some(m);
2340 break;
2341 }
2342 }
2343 }
2344 if !fmt.name.is_empty() {
2345 desc = fmt.name.clone();
2346 }
2347 }
2348 }
2349
2350 let mut evidence = vec![DetectionEvidence::ContainerStructure {
2351 detail: format!(
2352 "Matched DROID OLE2 container signature {}: {}",
2353 sig.id, sig.description
2354 ),
2355 score: *score,
2356 }];
2357
2358 if let Some(ref puid) = puid_opt {
2359 evidence.push(DetectionEvidence::Pronom {
2360 puid: puid.clone(),
2361 score: *score,
2362 });
2363 }
2364
2365 Ok(Some(DetectionCandidate {
2366 format_id: None,
2367 dc_id: None,
2368 mime,
2369 description: desc,
2370 confidence: ConfidenceTier::HighestConfidence,
2371 score: *score,
2372 evidence,
2373 chain_layers: None,
2374 }))
2375}
2376
2377/// Classifies a ZIP container from its entry list and uncompressed metadata.
2378pub fn classify_zip_container<S: DetectionSource + ?Sized>(
2379 source: &mut S,
2380 entries: &[ZipEntrySummary],
2381) -> Result<Option<DetectionCandidate>> {
2382 if entries.is_empty() {
2383 return Ok(None);
2384 }
2385
2386 // 0. Check DROID declarative container signatures
2387 if let Ok(Some(cand)) =
2388 evaluate_droid_zip_container(source, entries, &DROID_CONTAINER_DB)
2389 {
2390 return Ok(Some(cand));
2391 }
2392
2393 // 1. Check for `mimetype` entry (ODF, EPUB, KRA, ORA)
2394 if let Some(mimetype_entry) = entries.iter().find(|e| e.name == "mimetype")
2395 {
2396 if let Ok(Some(bytes)) =
2397 read_uncompressed_entry(source, mimetype_entry, 128)
2398 {
2399 let mime_str = String::from_utf8_lossy(&bytes).trim().to_string();
2400
2401 // OpenDocument Formats (ODF)
2402 if mime_str == "application/vnd.oasis.opendocument.text" {
2403 return Ok(Some(DetectionCandidate {
2404 format_id: None,
2405 dc_id: None,
2406 mime: Some(mime_str),
2407 description: "OpenDocument Text (ODT)".to_string(),
2408 confidence: ConfidenceTier::HighestConfidence,
2409 score: 98,
2410 evidence: vec![DetectionEvidence::ContainerStructure {
2411 detail: "Verified ODF Text mimetype in ZIP container"
2412 .to_string(),
2413 score: 98,
2414 }],
2415 chain_layers: None,
2416 }));
2417 } else if mime_str
2418 == "application/vnd.oasis.opendocument.spreadsheet"
2419 {
2420 return Ok(Some(DetectionCandidate {
2421 format_id: None,
2422 dc_id: None,
2423 mime: Some(mime_str),
2424 description: "OpenDocument Spreadsheet (ODS)".to_string(),
2425 confidence: ConfidenceTier::HighestConfidence,
2426 score: 98,
2427 evidence: vec![DetectionEvidence::ContainerStructure {
2428 detail:
2429 "Verified ODF Spreadsheet mimetype in ZIP container"
2430 .to_string(),
2431 score: 98,
2432 }],
2433 chain_layers: None,
2434 }));
2435 } else if mime_str
2436 == "application/vnd.oasis.opendocument.presentation"
2437 {
2438 return Ok(Some(DetectionCandidate {
2439 format_id: None,
2440 dc_id: None,
2441 mime: Some(mime_str),
2442 description: "OpenDocument Presentation (ODP)".to_string(),
2443 confidence: ConfidenceTier::HighestConfidence,
2444 score: 98,
2445 evidence: vec![DetectionEvidence::ContainerStructure {
2446 detail: "Verified ODF Presentation mimetype in ZIP container".to_string(),
2447 score: 98,
2448 }],
2449 chain_layers: None,
2450 }));
2451 } else if mime_str == "application/vnd.oasis.opendocument.graphics"
2452 {
2453 return Ok(Some(DetectionCandidate {
2454 format_id: None,
2455 dc_id: None,
2456 mime: Some(mime_str),
2457 description: "OpenDocument Drawing (ODG)".to_string(),
2458 confidence: ConfidenceTier::HighestConfidence,
2459 score: 98,
2460 evidence: vec![DetectionEvidence::ContainerStructure {
2461 detail:
2462 "Verified ODF Drawing mimetype in ZIP container"
2463 .to_string(),
2464 score: 98,
2465 }],
2466 chain_layers: None,
2467 }));
2468 } else if mime_str == "application/vnd.oasis.opendocument.formula" {
2469 return Ok(Some(DetectionCandidate {
2470 format_id: None,
2471 dc_id: None,
2472 mime: Some(mime_str),
2473 description: "OpenDocument Formula (ODF)".to_string(),
2474 confidence: ConfidenceTier::HighestConfidence,
2475 score: 98,
2476 evidence: vec![DetectionEvidence::ContainerStructure {
2477 detail:
2478 "Verified ODF Formula mimetype in ZIP container"
2479 .to_string(),
2480 score: 98,
2481 }],
2482 chain_layers: None,
2483 }));
2484 } else if mime_str == "application/epub+zip" {
2485 return Ok(Some(DetectionCandidate {
2486 format_id: None,
2487 dc_id: None,
2488 mime: Some(mime_str),
2489 description: "EPUB document".to_string(),
2490 confidence: ConfidenceTier::HighestConfidence,
2491 score: 98,
2492 evidence: vec![DetectionEvidence::ContainerStructure {
2493 detail: "Verified EPUB mimetype in ZIP container"
2494 .to_string(),
2495 score: 98,
2496 }],
2497 chain_layers: None,
2498 }));
2499 } else if mime_str == "application/x-krita" {
2500 return Ok(Some(DetectionCandidate {
2501 format_id: None,
2502 dc_id: None,
2503 mime: Some(mime_str),
2504 description: "Krita Document Format".to_string(),
2505 confidence: ConfidenceTier::HighestConfidence,
2506 score: 95,
2507 evidence: vec![DetectionEvidence::ContainerStructure {
2508 detail: "Verified Krita mimetype in ZIP container"
2509 .to_string(),
2510 score: 95,
2511 }],
2512 chain_layers: None,
2513 }));
2514 } else if mime_str == "image/openraster" {
2515 return Ok(Some(DetectionCandidate {
2516 format_id: None,
2517 dc_id: None,
2518 mime: Some(mime_str),
2519 description: "OpenRaster Image Format".to_string(),
2520 confidence: ConfidenceTier::HighestConfidence,
2521 score: 95,
2522 evidence: vec![DetectionEvidence::ContainerStructure {
2523 detail: "Verified OpenRaster mimetype in ZIP container"
2524 .to_string(),
2525 score: 95,
2526 }],
2527 chain_layers: None,
2528 }));
2529 } else if mime_str == "application/hwp+zip" {
2530 return Ok(Some(DetectionCandidate {
2531 format_id: None,
2532 dc_id: None,
2533 mime: Some("application/x-hwpx".to_string()),
2534 description:
2535 "Hancom HWP (Hangul Word Processor) file, HWPX"
2536 .to_string(),
2537 confidence: ConfidenceTier::HighestConfidence,
2538 score: 98,
2539 evidence: vec![DetectionEvidence::ContainerStructure {
2540 detail: "Verified HWPX mimetype in ZIP container"
2541 .to_string(),
2542 score: 98,
2543 }],
2544 chain_layers: None,
2545 }));
2546 }
2547 }
2548 }
2549
2550 // 2. Check for Office Open XML (OOXML)
2551 let has_content_types =
2552 entries.iter().any(|e| e.name == "[Content_Types].xml");
2553 let has_rels = entries.iter().any(|e| e.name.starts_with("_rels/"));
2554
2555 if has_content_types || has_rels {
2556 if entries.iter().any(|e| e.name.starts_with("word/")) {
2557 let is_macro =
2558 entries.iter().any(|e| e.name == "word/vbaProject.bin");
2559 let is_template =
2560 entries.iter().any(|e| e.name.starts_with("word/glossary/"));
2561 let (mime, desc) = if is_macro {
2562 (
2563 "application/vnd.ms-word.document.macroEnabled.12",
2564 "Microsoft Word Macro-Enabled Document",
2565 )
2566 } else if is_template {
2567 (
2568 "application/vnd.openxmlformats-officedocument.wordprocessingml.template",
2569 "Microsoft Word 2007+ Template",
2570 )
2571 } else {
2572 (
2573 "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
2574 "Microsoft Word 2007+",
2575 )
2576 };
2577 return Ok(Some(DetectionCandidate {
2578 format_id: None,
2579 dc_id: None,
2580 mime: Some(mime.to_string()),
2581 description: desc.to_string(),
2582 confidence: ConfidenceTier::HighestConfidence,
2583 score: 95,
2584 evidence: vec![DetectionEvidence::ContainerStructure {
2585 detail: format!(
2586 "Identified OOXML Word structure with word/ entry: {desc}"
2587 ),
2588 score: 95,
2589 }],
2590 chain_layers: None,
2591 }));
2592 }
2593
2594 if entries.iter().any(|e| e.name.starts_with("xl/")) {
2595 let is_macro =
2596 entries.iter().any(|e| e.name == "xl/vbaProject.bin");
2597 let is_bin = entries.iter().any(|e| e.name == "xl/workbook.bin");
2598 let (mime, desc) = if is_bin {
2599 (
2600 "application/vnd.ms-excel.sheet.binary.macroEnabled.12",
2601 "Microsoft Excel 2007+ Binary Workbook",
2602 )
2603 } else if is_macro {
2604 (
2605 "application/vnd.ms-excel.sheet.macroEnabled.12",
2606 "Microsoft Excel Macro-Enabled Spreadsheet",
2607 )
2608 } else {
2609 (
2610 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
2611 "Microsoft Excel 2007+",
2612 )
2613 };
2614 return Ok(Some(DetectionCandidate {
2615 format_id: None,
2616 dc_id: None,
2617 mime: Some(mime.to_string()),
2618 description: desc.to_string(),
2619 confidence: ConfidenceTier::HighestConfidence,
2620 score: 95,
2621 evidence: vec![DetectionEvidence::ContainerStructure {
2622 detail: format!(
2623 "Identified OOXML Excel structure with xl/ entry: {desc}"
2624 ),
2625 score: 95,
2626 }],
2627 chain_layers: None,
2628 }));
2629 }
2630
2631 if entries.iter().any(|e| e.name.starts_with("ppt/")) {
2632 let is_macro =
2633 entries.iter().any(|e| e.name == "ppt/vbaProject.bin");
2634 let (mime, desc) = if is_macro {
2635 (
2636 "application/vnd.ms-powerpoint.presentation.macroEnabled.12",
2637 "Microsoft PowerPoint Macro-Enabled Presentation",
2638 )
2639 } else {
2640 (
2641 "application/vnd.openxmlformats-officedocument.presentationml.presentation",
2642 "Microsoft PowerPoint 2007+",
2643 )
2644 };
2645 return Ok(Some(DetectionCandidate {
2646 format_id: None,
2647 dc_id: None,
2648 mime: Some(mime.to_string()),
2649 description: desc.to_string(),
2650 confidence: ConfidenceTier::HighestConfidence,
2651 score: 95,
2652 evidence: vec![DetectionEvidence::ContainerStructure {
2653 detail: format!(
2654 "Identified OOXML PowerPoint structure: {desc}"
2655 ),
2656 score: 95,
2657 }],
2658 chain_layers: None,
2659 }));
2660 }
2661 }
2662
2663 // 3. Check for Hancom HWPX
2664 if entries.iter().any(|e| {
2665 e.name.starts_with("Contents/content.hwpml")
2666 || e.name.starts_with("Contents/header.xml")
2667 || e.name.starts_with("version.xml")
2668 }) {
2669 return Ok(Some(DetectionCandidate {
2670 format_id: None,
2671 dc_id: None,
2672 mime: Some("application/x-hwpx".to_string()),
2673 description: "Hancom HWP (Hangul Word Processor) file, HWPX"
2674 .to_string(),
2675 confidence: ConfidenceTier::HighestConfidence,
2676 score: 95,
2677 evidence: vec![DetectionEvidence::ContainerStructure {
2678 detail: "Identified HWPX structure with Contents/ entry"
2679 .to_string(),
2680 score: 95,
2681 }],
2682 chain_layers: None,
2683 }));
2684 }
2685
2686 // 4. Check for Android Packages (APK / AAB / AAR)
2687 if entries.iter().any(|e| e.name == "AndroidManifest.xml") {
2688 let is_aar = entries.iter().any(|e| e.name == "classes.jar");
2689 let (mime, desc) = if is_aar {
2690 (
2691 "application/x-android-archive",
2692 "Android Archive Library (AAR)",
2693 )
2694 } else {
2695 (
2696 "application/vnd.android.package-archive",
2697 "Android package (APK)",
2698 )
2699 };
2700 return Ok(Some(DetectionCandidate {
2701 format_id: None,
2702 dc_id: None,
2703 mime: Some(mime.to_string()),
2704 description: desc.to_string(),
2705 confidence: ConfidenceTier::HighestConfidence,
2706 score: 95,
2707 evidence: vec![DetectionEvidence::ContainerStructure {
2708 detail: format!(
2709 "Identified Android structure with AndroidManifest.xml: {desc}"
2710 ),
2711 score: 95,
2712 }],
2713 chain_layers: None,
2714 }));
2715 }
2716 if entries.iter().any(|e| {
2717 e.name == "BundleConfig.pb"
2718 || e.name == "base/manifest/AndroidManifest.xml"
2719 }) {
2720 return Ok(Some(DetectionCandidate {
2721 format_id: None,
2722 dc_id: None,
2723 mime: Some("application/x-android-bundle".to_string()),
2724 description: "Android App Bundle (AAB)".to_string(),
2725 confidence: ConfidenceTier::HighestConfidence,
2726 score: 95,
2727 evidence: vec![DetectionEvidence::ContainerStructure {
2728 detail: "Identified Android App Bundle with BundleConfig.pb"
2729 .to_string(),
2730 score: 95,
2731 }],
2732 chain_layers: None,
2733 }));
2734 }
2735
2736 // 5. Check for Java Archives (JAR / WAR / EAR)
2737 if entries
2738 .iter()
2739 .any(|e| e.name.starts_with("META-INF/MANIFEST.MF"))
2740 {
2741 let is_war = entries.iter().any(|e| e.name.starts_with("WEB-INF/"));
2742 let is_ear =
2743 entries.iter().any(|e| e.name == "META-INF/application.xml");
2744 let (mime, desc) = if is_war {
2745 (
2746 "application/x-web-archive",
2747 "Java Web Application Archive (WAR)",
2748 )
2749 } else if is_ear {
2750 (
2751 "application/x-enterprise-archive",
2752 "Java Enterprise Application Archive (EAR)",
2753 )
2754 } else {
2755 ("application/java-archive", "Java archive data (JAR)")
2756 };
2757 return Ok(Some(DetectionCandidate {
2758 format_id: None,
2759 dc_id: None,
2760 mime: Some(mime.to_string()),
2761 description: desc.to_string(),
2762 confidence: ConfidenceTier::Strong,
2763 score: 90,
2764 evidence: vec![DetectionEvidence::ContainerStructure {
2765 detail: format!(
2766 "Identified Java archive with META-INF: {desc}"
2767 ),
2768 score: 90,
2769 }],
2770 chain_layers: None,
2771 }));
2772 }
2773
2774 // 6. Check for Apple iWork (Pages / Keynote / Numbers)
2775 if entries
2776 .iter()
2777 .any(|e| e.name == "Index/Document.iwa" || e.name == "Document.iwab")
2778 {
2779 return Ok(Some(DetectionCandidate {
2780 format_id: None,
2781 dc_id: None,
2782 mime: Some("application/vnd.apple.pages".to_string()),
2783 description: "Apple iWork Document".to_string(),
2784 confidence: ConfidenceTier::HighestConfidence,
2785 score: 92,
2786 evidence: vec![DetectionEvidence::ContainerStructure {
2787 detail:
2788 "Identified Apple iWork container with Index/Document.iwa"
2789 .to_string(),
2790 score: 92,
2791 }],
2792 chain_layers: None,
2793 }));
2794 }
2795
2796 // 7. Check for Comic Book Archive (CBZ)
2797 let non_dir_entries: Vec<&ZipEntrySummary> =
2798 entries.iter().filter(|e| !e.name.ends_with('/')).collect();
2799 if !non_dir_entries.is_empty()
2800 && non_dir_entries.iter().all(|e| {
2801 let lower = e.name.to_ascii_lowercase();
2802 lower.ends_with(".jpg")
2803 || lower.ends_with(".jpeg")
2804 || lower.ends_with(".png")
2805 || lower.ends_with(".webp")
2806 || lower.ends_with(".gif")
2807 })
2808 {
2809 return Ok(Some(DetectionCandidate {
2810 format_id: None,
2811 dc_id: None,
2812 mime: Some("application/vnd.comicbook+zip".to_string()),
2813 description: "Comic Book Archive (CBZ)".to_string(),
2814 confidence: ConfidenceTier::Strong,
2815 score: 85,
2816 evidence: vec![DetectionEvidence::ContainerStructure {
2817 detail: format!(
2818 "Identified CBZ comic book archive containing {} images",
2819 non_dir_entries.len()
2820 ),
2821 score: 85,
2822 }],
2823 chain_layers: None,
2824 }));
2825 }
2826
2827 // 8. Check for Keyhole Markup Language Zipped (KMZ)
2828 if entries
2829 .iter()
2830 .any(|e| e.name == "doc.kml" || e.name.ends_with(".kml"))
2831 {
2832 return Ok(Some(DetectionCandidate {
2833 format_id: None,
2834 dc_id: None,
2835 mime: Some("application/vnd.google-earth.kmz".to_string()),
2836 description: "Google Earth KMZ archive".to_string(),
2837 confidence: ConfidenceTier::HighestConfidence,
2838 score: 95,
2839 evidence: vec![DetectionEvidence::ContainerStructure {
2840 detail: "Identified Google Earth KMZ with .kml entry"
2841 .to_string(),
2842 score: 95,
2843 }],
2844 chain_layers: None,
2845 }));
2846 }
2847
2848 // 9. Generic ZIP Archive
2849 Ok(Some(DetectionCandidate {
2850 format_id: Some(FormatId::Zip),
2851 dc_id: None,
2852 mime: Some("application/zip".to_string()),
2853 description: "Zip archive data".to_string(),
2854 confidence: ConfidenceTier::Strong,
2855 score: 85,
2856 evidence: vec![DetectionEvidence::ContainerStructure {
2857 detail: format!(
2858 "Identified ZIP archive containing {} entries",
2859 entries.len()
2860 ),
2861 score: 85,
2862 }],
2863 chain_layers: None,
2864 }))
2865}
2866
2867/// Comprehensive ZIP container inspection using Central Directory parsing
2868/// with streaming local header scanning fallback.
2869pub fn inspect_zip_container_comprehensive<S: DetectionSource + ?Sized>(
2870 source: &mut S,
2871) -> Result<Option<DetectionCandidate>> {
2872 // Attempt EOF Central Directory parsing first
2873 if let Ok(Some(entries)) = parse_zip_central_directory(source) {
2874 if let Ok(Some(cand)) = classify_zip_container(source, &entries) {
2875 return Ok(Some(cand));
2876 }
2877 }
2878
2879 // Fallback to local header scanning from BOF
2880 let local_entries = scan_zip_local_headers(source)?;
2881 if !local_entries.is_empty() {
2882 if let Ok(Some(cand)) = classify_zip_container(source, &local_entries) {
2883 return Ok(Some(cand));
2884 }
2885 }
2886
2887 Ok(None)
2888}
2889
2890#[cfg(test)]
2891#[allow(
2892 clippy::panic,
2893 clippy::expect_used,
2894 clippy::unwrap_used,
2895 clippy::unwrap_in_result,
2896 clippy::panic_in_result_fn,
2897 clippy::indexing_slicing,
2898 clippy::arithmetic_side_effects,
2899 reason = "Standard repository test boilerplate"
2900)]
2901mod tests {
2902 use super::*;
2903
2904 #[crate::ctb_test]
2905 fn test_dual_anchored_pdf() {
2906 let mut pdf_data = Vec::new();
2907 pdf_data.extend_from_slice(b"%PDF-1.4\n%test\n");
2908 pdf_data.resize(500, b'A');
2909 pdf_data.extend_from_slice(b"\nxref\ntrailer\nstartxref\n400\n%%EOF\n");
2910
2911 let mut source: &[u8] = &pdf_data;
2912 let cands = evaluate_dual_anchored_signatures(&mut source).unwrap();
2913 assert!(
2914 cands
2915 .iter()
2916 .any(|c| c.mime.as_deref() == Some("application/pdf"))
2917 );
2918 }
2919
2920 #[crate::ctb_test]
2921 fn test_dual_anchored_png() {
2922 let mut png_data = Vec::new();
2923 png_data.extend_from_slice(b"\x89PNG\r\n\x1a\n");
2924 png_data.resize(100, 0);
2925 png_data.extend_from_slice(b"IEND\xaeB`\x82");
2926
2927 let mut source: &[u8] = &png_data;
2928 let cands = evaluate_dual_anchored_signatures(&mut source).unwrap();
2929 assert!(cands.iter().any(|c| c.mime.as_deref() == Some("image/png")));
2930 }
2931
2932 #[crate::ctb_test]
2933 fn test_dual_anchored_jpeg() {
2934 let mut jpeg_data = Vec::new();
2935 jpeg_data.extend_from_slice(b"\xFF\xD8\xFF\xE0\x00\x10JFIF\x00");
2936 jpeg_data.resize(80, 0);
2937 jpeg_data.extend_from_slice(b"\xFF\xD9");
2938
2939 let mut source: &[u8] = &jpeg_data;
2940 let cands = evaluate_dual_anchored_signatures(&mut source).unwrap();
2941 assert!(
2942 cands
2943 .iter()
2944 .any(|c| c.mime.as_deref() == Some("image/jpeg"))
2945 );
2946 }
2947
2948 #[crate::ctb_test]
2949 fn test_zip_central_directory_parsing_opendocument() {
2950 // Construct minimal ZIP with central directory and uncompressed mimetype entry
2951 let mime_payload = b"application/vnd.oasis.opendocument.text";
2952 let flen = 8u16; // "mimetype"
2953 let elen = 0u16;
2954
2955 let mime_len = u32::try_from(mime_payload.len()).unwrap_or(0);
2956
2957 let mut zip = Vec::new();
2958 // Local header at offset 0
2959 zip.extend_from_slice(&ZIP_LOCAL_HEADER_MAGIC);
2960 zip.extend_from_slice(&[20, 0]); // version
2961 zip.extend_from_slice(&[0, 0]); // flags
2962 zip.extend_from_slice(&[0, 0]); // compression: 0 (stored)
2963 zip.extend_from_slice(&[0, 0, 0, 0]); // time/date
2964 zip.extend_from_slice(&[0, 0, 0, 0]); // crc
2965 zip.extend_from_slice(&mime_len.to_le_bytes()); // comp
2966 zip.extend_from_slice(&mime_len.to_le_bytes()); // uncomp
2967 zip.extend_from_slice(&flen.to_le_bytes());
2968 zip.extend_from_slice(&elen.to_le_bytes());
2969 zip.extend_from_slice(b"mimetype");
2970 zip.extend_from_slice(mime_payload);
2971
2972 let cd_offset = u32::try_from(zip.len()).unwrap_or(0);
2973
2974 // Central Directory header
2975 zip.extend_from_slice(&ZIP_CENTRAL_HEADER_MAGIC);
2976 zip.extend_from_slice(&[20, 0]); // version made by
2977 zip.extend_from_slice(&[20, 0]); // version needed
2978 zip.extend_from_slice(&[0, 0]); // flags
2979 zip.extend_from_slice(&[0, 0]); // compression: 0 (stored)
2980 zip.extend_from_slice(&[0, 0, 0, 0]); // time/date
2981 zip.extend_from_slice(&[0, 0, 0, 0]); // crc
2982 zip.extend_from_slice(&mime_len.to_le_bytes()); // comp
2983 zip.extend_from_slice(&mime_len.to_le_bytes()); // uncomp
2984 zip.extend_from_slice(&flen.to_le_bytes());
2985 zip.extend_from_slice(&0u16.to_le_bytes()); // extra len
2986 zip.extend_from_slice(&0u16.to_le_bytes()); // comment len
2987 zip.extend_from_slice(&[0, 0]); // disk
2988 zip.extend_from_slice(&[0, 0]); // internal attr
2989 zip.extend_from_slice(&[0, 0, 0, 0]); // external attr
2990 zip.extend_from_slice(&0u32.to_le_bytes()); // local header offset = 0
2991 zip.extend_from_slice(b"mimetype");
2992
2993 let zip_len = u32::try_from(zip.len()).unwrap_or(0);
2994 let cd_size = zip_len.saturating_sub(cd_offset);
2995
2996 // EOCD record
2997 zip.extend_from_slice(&ZIP_EOCD_MAGIC);
2998 zip.extend_from_slice(&[0, 0]); // disk
2999 zip.extend_from_slice(&[0, 0]); // disk cd
3000 zip.extend_from_slice(&1u16.to_le_bytes()); // entries disk
3001 zip.extend_from_slice(&1u16.to_le_bytes()); // total entries
3002 zip.extend_from_slice(&cd_size.to_le_bytes());
3003 zip.extend_from_slice(&cd_offset.to_le_bytes());
3004 zip.extend_from_slice(&0u16.to_le_bytes()); // comment len
3005
3006 let mut source: &[u8] = &zip;
3007 let cand = inspect_zip_container_comprehensive(&mut source)
3008 .unwrap()
3009 .unwrap();
3010 assert_eq!(
3011 cand.mime.as_deref(),
3012 Some("application/vnd.oasis.opendocument.text")
3013 );
3014 assert_eq!(cand.description, "OpenDocument Text (ODT)");
3015 assert_eq!(cand.confidence, ConfidenceTier::HighestConfidence);
3016 }
3017
3018 #[crate::ctb_test]
3019 fn test_zip_central_directory_docx() {
3020 let entries = vec![
3021 ZipEntrySummary {
3022 name: "[Content_Types].xml".to_string(),
3023 compressed_size: 100,
3024 uncompressed_size: 200,
3025 compression_method: 8,
3026 local_header_offset: 0,
3027 },
3028 ZipEntrySummary {
3029 name: "word/document.xml".to_string(),
3030 compressed_size: 500,
3031 uncompressed_size: 1500,
3032 compression_method: 8,
3033 local_header_offset: 200,
3034 },
3035 ];
3036 let mut empty: &[u8] = &[];
3037 let cand = classify_zip_container(&mut empty, &entries)
3038 .unwrap()
3039 .unwrap();
3040 assert_eq!(
3041 cand.mime.as_deref(),
3042 Some(
3043 "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
3044 )
3045 );
3046 assert_eq!(cand.description, "Microsoft Word 2007+");
3047 assert_eq!(cand.confidence, ConfidenceTier::HighestConfidence);
3048 }
3049
3050 #[crate::ctb_test]
3051 fn test_zip_container_xlsx() {
3052 let test_dir =
3053 crate::detection::file_upstream_suite::locate_upstream_tests_dir()
3054 .unwrap();
3055 let path = test_dir.join("issue359xlsx.testfile");
3056 let data = std::fs::read(path).unwrap();
3057 let mut source: &[u8] = &data;
3058 let cand = inspect_zip_container_comprehensive(&mut source)
3059 .unwrap()
3060 .unwrap();
3061 assert!(cand.description.contains("Microsoft Excel"));
3062 assert_eq!(
3063 cand.mime.as_deref(),
3064 Some(
3065 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
3066 )
3067 );
3068 }
3069
3070 #[crate::ctb_test]
3071 fn test_zip_central_directory_apk() {
3072 let entries = vec![
3073 ZipEntrySummary {
3074 name: "AndroidManifest.xml".to_string(),
3075 compressed_size: 200,
3076 uncompressed_size: 400,
3077 compression_method: 8,
3078 local_header_offset: 0,
3079 },
3080 ZipEntrySummary {
3081 name: "classes.dex".to_string(),
3082 compressed_size: 1000,
3083 uncompressed_size: 3000,
3084 compression_method: 8,
3085 local_header_offset: 300,
3086 },
3087 ];
3088 let mut empty: &[u8] = &[];
3089 let cand = classify_zip_container(&mut empty, &entries)
3090 .unwrap()
3091 .unwrap();
3092 assert_eq!(
3093 cand.mime.as_deref(),
3094 Some("application/vnd.android.package-archive")
3095 );
3096 assert_eq!(cand.description, "Android package (APK)");
3097 }
3098
3099 #[crate::ctb_test]
3100 fn test_zip_central_directory_cbz() {
3101 let entries = vec![
3102 ZipEntrySummary {
3103 name: "001.jpg".to_string(),
3104 compressed_size: 2000,
3105 uncompressed_size: 2000,
3106 compression_method: 0,
3107 local_header_offset: 0,
3108 },
3109 ZipEntrySummary {
3110 name: "002.png".to_string(),
3111 compressed_size: 3000,
3112 uncompressed_size: 3000,
3113 compression_method: 0,
3114 local_header_offset: 2100,
3115 },
3116 ];
3117 let mut empty: &[u8] = &[];
3118 let cand = classify_zip_container(&mut empty, &entries)
3119 .unwrap()
3120 .unwrap();
3121 assert_eq!(cand.mime.as_deref(), Some("application/vnd.comicbook+zip"));
3122 assert_eq!(cand.description, "Comic Book Archive (CBZ)");
3123 }
3124
3125 #[crate::ctb_test]
3126 fn test_dual_anchored_gif89a_trailer() {
3127 let mut gif_data = Vec::new();
3128 gif_data.extend_from_slice(
3129 b"GIF89a\x0A\x00\x0A\x00\x80\x00\x00\x00\x00\x00\xFF\xFF\xFF",
3130 );
3131 gif_data.resize(50, 0);
3132 gif_data.push(b';'); // Trailer byte ';'
3133
3134 let mut source: &[u8] = &gif_data;
3135 let cands = evaluate_dual_anchored_signatures(&mut source).unwrap();
3136 assert!(cands.iter().any(|c| c.mime.as_deref() == Some("image/gif")));
3137 }
3138
3139 #[crate::ctb_test]
3140 fn test_droid_pronom_db_loaded() {
3141 assert!(DROID_PRONOM_DB.formats.len() > 2000);
3142 assert!(DROID_PRONOM_DB.signatures.len() > 1000);
3143 let pdf_fmt = DROID_PRONOM_DB.formats.get("fmt/18");
3144 assert!(pdf_fmt.is_some());
3145 let pdf = pdf_fmt.unwrap();
3146 assert_eq!(pdf.mime_type.as_deref(), Some("application/pdf"));
3147 }
3148
3149 #[crate::ctb_test]
3150 fn test_droid_container_db_loaded() {
3151 assert!(DROID_CONTAINER_DB.zip_signatures.len() > 100);
3152 assert!(DROID_CONTAINER_DB.ole2_signatures.len() > 100);
3153 }
3154
3155 #[crate::ctb_test]
3156 fn test_droid_pronom_detection_pdf() {
3157 let pdf_bytes = ctb_utilities::load_manifest_fixture(
3158 env!("CARGO_MANIFEST_DIR"),
3159 "droid/signatures/sample.pdf",
3160 )
3161 .expect("missing droid/signatures/sample.pdf fixture");
3162 let mut source: &[u8] = &pdf_bytes;
3163 let cands = evaluate_pronom_signatures(&mut source, None).unwrap();
3164 assert!(
3165 cands
3166 .iter()
3167 .any(|c| c.mime.as_deref() == Some("application/pdf"))
3168 );
3169 assert!(cands.iter().any(|c| c.evidence.iter().any(
3170 |e| matches!(e, DetectionEvidence::Pronom { puid, .. } if puid == "fmt/18")
3171 )));
3172 }
3173
3174 #[crate::ctb_test]
3175 fn test_droid_pronom_detection_jpeg() {
3176 let jpeg_bytes = ctb_utilities::load_manifest_fixture(
3177 env!("CARGO_MANIFEST_DIR"),
3178 "droid/signatures/DROID.jpeg",
3179 )
3180 .expect("missing droid/signatures/DROID.jpeg fixture");
3181 let mut source: &[u8] = &jpeg_bytes;
3182 let cands = evaluate_pronom_signatures(&mut source, None).unwrap();
3183 assert!(
3184 cands
3185 .iter()
3186 .any(|c| c.mime.as_deref() == Some("image/jpeg"))
3187 );
3188 }
3189
3190 #[crate::ctb_test]
3191 fn test_droid_container_test_zip() {
3192 let zip_bytes = ctb_utilities::load_manifest_fixture(
3193 env!("CARGO_MANIFEST_DIR"),
3194 "droid/containers/test.zip",
3195 )
3196 .expect("missing droid/containers/test.zip fixture");
3197 let mut source: &[u8] = &zip_bytes;
3198 let _ = inspect_zip_container_comprehensive(&mut source);
3199 }
3200}
3201/*
3202/*
3203 * Adapted from: apptype.c, Written by Eberhard Mattes and put into the
3204 * file_public domain
3205 *
3206 * Notes: 1. Qualify the filename so that DosQueryAppType does not do extraneous
3207 * searches.
3208 *
3209 * 2. DosQueryAppType will return FAPPTYP_DOS on a file ending with ".com"
3210 * (other than an OS/2 exe or Win exe with this name). Eberhard Mattes
3211 * remarks Tue, 6 Apr 93: Moreover, it reports the type of the (new and very
3212 * bug ridden) Win Emacs as "OS/2 executable".
3213 *
3214 * 3. apptype() uses the filename if given, otherwise a tmp file is created with
3215 * the contents of buf. If buf is not the complete file, apptype can
3216 * incorrectly identify the exe type. The "-z" option of "file" is the reason
3217 * for this ugly code.
3218 */
3219
3220The preceding notice is from src/apptype.c in `file`.
3221
3222
3223
3224/*-
3225 * Copyright (c) 2008 Christos Zoulas
3226 * All rights reserved.
3227 *
3228 * Redistribution and use in source and binary forms, with or without
3229 * modification, are permitted provided that the following conditions
3230 * are met:
3231 * 1. Redistributions of source code must retain the above copyright
3232 * notice, this list of conditions and the following disclaimer.
3233 * 2. Redistributions in binary form must reproduce the above copyright
3234 * notice, this list of conditions and the following disclaimer in the
3235 * documentation and/or other materials provided with the distribution.
3236 *
3237 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
3238 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
3239 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
3240 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
3241 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
3242 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
3243 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
3244 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
3245 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
3246 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
3247 * POSSIBILITY OF SUCH DAMAGE.
3248 */
3249
3250The preceding notice is from src/cdf.c, src/cdf.h, and src/cdf_time.c in `file`.
3251
3252
3253
3254/*-
3255 * Copyright (c) 2016 Christos Zoulas
3256 * All rights reserved.
3257 *
3258 * Redistribution and use in source and binary forms, with or without
3259 * modification, are permitted provided that the following conditions
3260 * are met:
3261 * 1. Redistributions of source code must retain the above copyright
3262 * notice, this list of conditions and the following disclaimer.
3263 * 2. Redistributions in binary form must reproduce the above copyright
3264 * notice, this list of conditions and the following disclaimer in the
3265 * documentation and/or other materials provided with the distribution.
3266 *
3267 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
3268 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
3269 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
3270 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
3271 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
3272 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
3273 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
3274 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
3275 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
3276 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
3277 * POSSIBILITY OF SUCH DAMAGE.
3278 */
3279
3280The preceding notice is from src/der.c and src/der.h in `file`.
3281
3282
3283
3284/*-
3285 * Copyright (c) 2019 Christos Zoulas
3286 * All rights reserved.
3287 *
3288 * Redistribution and use in source and binary forms, with or without
3289 * modification, are permitted provided that the following conditions
3290 * are met:
3291 * 1. Redistributions of source code must retain the above copyright
3292 * notice, this list of conditions and the following disclaimer.
3293 * 2. Redistributions in binary form must reproduce the above copyright
3294 * notice, this list of conditions and the following disclaimer in the
3295 * documentation and/or other materials provided with the distribution.
3296 *
3297 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
3298 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
3299 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
3300 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
3301 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
3302 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
3303 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
3304 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
3305 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
3306 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
3307 * POSSIBILITY OF SUCH DAMAGE.
3308 */
3309
3310The preceding notice is from src/is_csv.c in `file`.
3311
3312
3313
3314/*-
3315 * Copyright (c) 2018 Christos Zoulas
3316 * All rights reserved.
3317 *
3318 * Redistribution and use in source and binary forms, with or without
3319 * modification, are permitted provided that the following conditions
3320 * are met:
3321 * 1. Redistributions of source code must retain the above copyright
3322 * notice, this list of conditions and the following disclaimer.
3323 * 2. Redistributions in binary form must reproduce the above copyright
3324 * notice, this list of conditions and the following disclaimer in the
3325 * documentation and/or other materials provided with the distribution.
3326 *
3327 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
3328 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
3329 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
3330 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
3331 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
3332 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
3333 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
3334 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
3335 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
3336 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
3337 * POSSIBILITY OF SUCH DAMAGE.
3338 */
3339
3340The preceding notice is from src/is_json.c in `file`.
3341
3342
3343
3344/*-
3345 * Copyright (c) 2023 Christos Zoulas
3346 * All rights reserved.
3347 *
3348 * Redistribution and use in source and binary forms, with or without
3349 * modification, are permitted provided that the following conditions
3350 * are met:
3351 * 1. Redistributions of source code must retain the above copyright
3352 * notice, this list of conditions and the following disclaimer.
3353 * 2. Redistributions in binary form must reproduce the above copyright
3354 * notice, this list of conditions and the following disclaimer in the
3355 * documentation and/or other materials provided with the distribution.
3356 *
3357 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
3358 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
3359 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
3360 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
3361 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
3362 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
3363 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
3364 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
3365 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
3366 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
3367 * POSSIBILITY OF SUCH DAMAGE.
3368 */
3369
3370The preceding notice is from src/is_simh.c in `file`.
3371
3372
3373
3374/*-
3375 * SPDX-License-Identifier: BSD-3-Clause
3376 *
3377 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
3378 * Copyright (c) 1992, 1993, 1994
3379 * The Regents of the University of California. All rights reserved.
3380 *
3381 * This code is derived from software contributed to Berkeley by
3382 * Henry Spencer.
3383 *
3384 * Redistribution and use in source and binary forms, with or without
3385 * modification, are permitted provided that the following conditions
3386 * are met:
3387 * 1. Redistributions of source code must retain the above copyright
3388 * notice, this list of conditions and the following disclaimer.
3389 * 2. Redistributions in binary form must reproduce the above copyright
3390 * notice, this list of conditions and the following disclaimer in the
3391 * documentation and/or other materials provided with the distribution.
3392 * 3. Neither the name of the University nor the names of its contributors
3393 * may be used to endorse or promote products derived from this software
3394 * without specific prior written permission.
3395 *
3396 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3397 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3398 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3399 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3400 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3401 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3402 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3403 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3404 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3405 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3406 * SUCH DAMAGE.
3407 *
3408 * @(#)cname.h 8.3 (Berkeley) 3/20/94
3409 * $FreeBSD: head/lib/libc/regex/cname.h 326025 2017-11-20 19:49:47Z pfg $
3410 */
3411
3412The preceding notice is from src/missing/cname.h in `file`.
3413
3414
3415
3416/*-
3417 * SPDX-License-Identifier: BSD-3-Clause
3418 *
3419 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
3420 * Copyright (c) 1992, 1993, 1994
3421 * The Regents of the University of California. All rights reserved.
3422 *
3423 * This code is derived from software contributed to Berkeley by
3424 * Henry Spencer.
3425 *
3426 * Redistribution and use in source and binary forms, with or without
3427 * modification, are permitted provided that the following conditions
3428 * are met:
3429 * 1. Redistributions of source code must retain the above copyright
3430 * notice, this list of conditions and the following disclaimer.
3431 * 2. Redistributions in binary form must reproduce the above copyright
3432 * notice, this list of conditions and the following disclaimer in the
3433 * documentation and/or other materials provided with the distribution.
3434 * 3. Neither the name of the University nor the names of its contributors
3435 * may be used to endorse or promote products derived from this software
3436 * without specific prior written permission.
3437 *
3438 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3439 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3440 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3441 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3442 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3443 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3444 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3445 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3446 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3447 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3448 * SUCH DAMAGE.
3449 *
3450 * @(#)engine.c 8.5 (Berkeley) 3/20/94
3451 */
3452
3453The preceding notice is from src/missing/engine.c in `file`.
3454
3455
3456
3457/*-
3458 * Copyright (c) 2000 The NetBSD Foundation, Inc.
3459 * All rights reserved.
3460 *
3461 * This code was contributed to The NetBSD Foundation by Allen Briggs.
3462 *
3463 * Redistribution and use in source and binary forms, with or without
3464 * modification, are permitted provided that the following conditions
3465 * are met:
3466 * 1. Redistributions of source code must retain the above copyright
3467 * notice, this list of conditions and the following disclaimer.
3468 * 2. Redistributions in binary form must reproduce the above copyright
3469 * notice, this list of conditions and the following disclaimer in the
3470 * documentation and/or other materials provided with the distribution.
3471 *
3472 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
3473 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
3474 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
3475 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
3476 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
3477 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
3478 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
3479 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
3480 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
3481 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
3482 * POSSIBILITY OF SUCH DAMAGE.
3483 */
3484
3485The preceding notice is from src/missing/fmtcheck.c in `file`.
3486
3487
3488
3489/*-
3490 * Copyright (c) 2011 The NetBSD Foundation, Inc.
3491 * All rights reserved.
3492 *
3493 * This code is derived from software contributed to The NetBSD Foundation
3494 * by Christos Zoulas.
3495 *
3496 * Redistribution and use in source and binary forms, with or without
3497 * modification, are permitted provided that the following conditions
3498 * are met:
3499 * 1. Redistributions of source code must retain the above copyright
3500 * notice, this list of conditions and the following disclaimer.
3501 * 2. Redistributions in binary form must reproduce the above copyright
3502 * notice, this list of conditions and the following disclaimer in the
3503 * documentation and/or other materials provided with the distribution.
3504 *
3505 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
3506 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
3507 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
3508 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
3509 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
3510 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
3511 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
3512 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
3513 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
3514 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
3515 * POSSIBILITY OF SUCH DAMAGE.
3516 */
3517
3518The preceding notice is from src/missing/getline.c in `file`.
3519
3520
3521
3522/*-
3523 * Copyright (c) 2000 The NetBSD Foundation, Inc.
3524 * All rights reserved.
3525 *
3526 * This code is derived from software contributed to The NetBSD Foundation
3527 * by Dieter Baron and Thomas Klausner.
3528 *
3529 * Redistribution and use in source and binary forms, with or without
3530 * modification, are permitted provided that the following conditions
3531 * are met:
3532 * 1. Redistributions of source code must retain the above copyright
3533 * notice, this list of conditions and the following disclaimer.
3534 * 2. Redistributions in binary form must reproduce the above copyright
3535 * notice, this list of conditions and the following disclaimer in the
3536 * documentation and/or other materials provided with the distribution.
3537 *
3538 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
3539 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
3540 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
3541 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
3542 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
3543 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
3544 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
3545 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
3546 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
3547 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
3548 * POSSIBILITY OF SUCH DAMAGE.
3549 */
3550
3551The preceding notice is from src/missing/getopt_long.c and src/mygetopt.h in `file`.
3552
3553
3554
3555/*
3556 * Public domain fallback for reallocarray(3), for platforms (e.g.
3557 * AmigaOS/libnix) whose C library declares it but does not implement it.
3558 */
3559
3560The preceding notice is from src/missing/reallocarray.c in `file`.
3561
3562
3563
3564/*-
3565 * SPDX-License-Identifier: BSD-3-Clause
3566 *
3567 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
3568 * Copyright (c) 1992, 1993, 1994
3569 * The Regents of the University of California. All rights reserved.
3570 *
3571 * Copyright (c) 2011 The FreeBSD Foundation
3572 * All rights reserved.
3573 * Portions of this software were developed by David Chisnall
3574 * under sponsorship from the FreeBSD Foundation.
3575 *
3576 * This code is derived from software contributed to Berkeley by
3577 * Henry Spencer.
3578 *
3579 * Redistribution and use in source and binary forms, with or without
3580 * modification, are permitted provided that the following conditions
3581 * are met:
3582 * 1. Redistributions of source code must retain the above copyright
3583 * notice, this list of conditions and the following disclaimer.
3584 * 2. Redistributions in binary form must reproduce the above copyright
3585 * notice, this list of conditions and the following disclaimer in the
3586 * documentation and/or other materials provided with the distribution.
3587 * 3. Neither the name of the University nor the names of its contributors
3588 * may be used to endorse or promote products derived from this software
3589 * without specific prior written permission.
3590 *
3591 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3592 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3593 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3594 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3595 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3596 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3597 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3598 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3599 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3600 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3601 * SUCH DAMAGE.
3602 *
3603 * @(#)regcomp.c 8.5 (Berkeley) 3/20/94
3604 */
3605
3606The preceding notice is from src/missing/regcomp.c in `file`.
3607
3608
3609
3610/*-
3611 * SPDX-License-Identifier: BSD-3-Clause
3612 *
3613 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
3614 * Copyright (c) 1992, 1993, 1994
3615 * The Regents of the University of California. All rights reserved.
3616 *
3617 * This code is derived from software contributed to Berkeley by
3618 * Henry Spencer.
3619 *
3620 * Redistribution and use in source and binary forms, with or without
3621 * modification, are permitted provided that the following conditions
3622 * are met:
3623 * 1. Redistributions of source code must retain the above copyright
3624 * notice, this list of conditions and the following disclaimer.
3625 * 2. Redistributions in binary form must reproduce the above copyright
3626 * notice, this list of conditions and the following disclaimer in the
3627 * documentation and/or other materials provided with the distribution.
3628 * 3. Neither the name of the University nor the names of its contributors
3629 * may be used to endorse or promote products derived from this software
3630 * without specific prior written permission.
3631 *
3632 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3633 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3634 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3635 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3636 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3637 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3638 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3639 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3640 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3641 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3642 * SUCH DAMAGE.
3643 *
3644 * @(#)regerror.c 8.4 (Berkeley) 3/20/94
3645 */
3646
3647The preceding notice is from src/missing/regerror.c in `file`.
3648
3649
3650
3651$NetBSD: COPYRIGHT,v 1.5 2003/08/07 16:43:19 agc Exp $
3652
3653Copyright 1992, 1993, 1994 Henry Spencer. All rights reserved.
3654This software is not subject to any license of the American Telephone
3655and Telegraph Company or of the Regents of the University of California.
3656
3657Permission is granted to anyone to use this software for any purpose on
3658any computer system, and to alter it and redistribute it, subject
3659to the following restrictions:
3660
36611. The author is not responsible for the consequences of use of this
3662 software, no matter how awful, even if they arise from flaws in it.
3663
36642. The origin of this software must not be misrepresented, either by
3665 explicit claim or by omission. Since few users ever read sources,
3666 credits must appear in the documentation.
3667
36683. Altered versions must be plainly marked as such, and must not be
3669 misrepresented as being the original software. Since few users
3670 ever read sources, credits must appear in the documentation.
3671
36724. This notice may not be removed or altered.
3673
3674=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
3675/*-
3676 * Copyright (c) 1994
3677 * The Regents of the University of California. All rights reserved.
3678 *
3679 * Redistribution and use in source and binary forms, with or without
3680 * modification, are permitted provided that the following conditions
3681 * are met:
3682 * 1. Redistributions of source code must retain the above copyright
3683 * notice, this list of conditions and the following disclaimer.
3684 * 2. Redistributions in binary form must reproduce the above copyright
3685 * notice, this list of conditions and the following disclaimer in the
3686 * documentation and/or other materials provided with the distribution.
3687 * 3. Neither the name of the University nor the names of its contributors
3688 * may be used to endorse or promote products derived from this software
3689 * without specific prior written permission.
3690 *
3691 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3692 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3693 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3694 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3695 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3696 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3697 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3698 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3699 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3700 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3701 * SUCH DAMAGE.
3702 *
3703 * @(#)COPYRIGHT 8.1 (Berkeley) 3/16/94
3704 */
3705
3706The preceding notice is from src/missing/REGEX-COPYRIGHT in `file`.
3707
3708
3709
3710/*-
3711 * SPDX-License-Identifier: BSD-3-Clause
3712 *
3713 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
3714 * Copyright (c) 1992, 1993, 1994
3715 * The Regents of the University of California. All rights reserved.
3716 *
3717 * This code is derived from software contributed to Berkeley by
3718 * Henry Spencer.
3719 *
3720 * Redistribution and use in source and binary forms, with or without
3721 * modification, are permitted provided that the following conditions
3722 * are met:
3723 * 1. Redistributions of source code must retain the above copyright
3724 * notice, this list of conditions and the following disclaimer.
3725 * 2. Redistributions in binary form must reproduce the above copyright
3726 * notice, this list of conditions and the following disclaimer in the
3727 * documentation and/or other materials provided with the distribution.
3728 * 3. Neither the name of the University nor the names of its contributors
3729 * may be used to endorse or promote products derived from this software
3730 * without specific prior written permission.
3731 *
3732 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3733 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3734 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3735 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3736 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3737 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3738 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3739 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3740 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3741 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3742 * SUCH DAMAGE.
3743 *
3744 * @(#)regex2.h 8.4 (Berkeley) 3/20/94
3745 * $FreeBSD: head/lib/libc/regex/regex2.h 368359 2020-12-05 03:18:48Z kevans $
3746 */
3747
3748The preceding notice is from src/missing/regex2.h in `file`.
3749
3750
3751
3752/*-
3753 * SPDX-License-Identifier: BSD-3-Clause
3754 *
3755 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
3756 * Copyright (c) 1992, 1993, 1994
3757 * The Regents of the University of California. All rights reserved.
3758 *
3759 * This code is derived from software contributed to Berkeley by
3760 * Henry Spencer.
3761 *
3762 * Redistribution and use in source and binary forms, with or without
3763 * modification, are permitted provided that the following conditions
3764 * are met:
3765 * 1. Redistributions of source code must retain the above copyright
3766 * notice, this list of conditions and the following disclaimer.
3767 * 2. Redistributions in binary form must reproduce the above copyright
3768 * notice, this list of conditions and the following disclaimer in the
3769 * documentation and/or other materials provided with the distribution.
3770 * 3. Neither the name of the University nor the names of its contributors
3771 * may be used to endorse or promote products derived from this software
3772 * without specific prior written permission.
3773 *
3774 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3775 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3776 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3777 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3778 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3779 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3780 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3781 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3782 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3783 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3784 * SUCH DAMAGE.
3785 *
3786 * @(#)regexec.c 8.3 (Berkeley) 3/20/94
3787 */
3788
3789The preceding notice is from src/missing/regexec.c in `file`.
3790
3791
3792
3793/*-
3794 * SPDX-License-Identifier: BSD-3-Clause
3795 *
3796 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
3797 * Copyright (c) 1992, 1993, 1994
3798 * The Regents of the University of California. All rights reserved.
3799 *
3800 * This code is derived from software contributed to Berkeley by
3801 * Henry Spencer.
3802 *
3803 * Redistribution and use in source and binary forms, with or without
3804 * modification, are permitted provided that the following conditions
3805 * are met:
3806 * 1. Redistributions of source code must retain the above copyright
3807 * notice, this list of conditions and the following disclaimer.
3808 * 2. Redistributions in binary form must reproduce the above copyright
3809 * notice, this list of conditions and the following disclaimer in the
3810 * documentation and/or other materials provided with the distribution.
3811 * 3. Neither the name of the University nor the names of its contributors
3812 * may be used to endorse or promote products derived from this software
3813 * without specific prior written permission.
3814 *
3815 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3816 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3817 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3818 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3819 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3820 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3821 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3822 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3823 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3824 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3825 * SUCH DAMAGE.
3826 *
3827 * @(#)regfree.c 8.3 (Berkeley) 3/20/94
3828 */
3829
3830The preceding notice is from src/missing/regfree.c in `file`.
3831
3832
3833
3834/*-
3835 * Copyright (c) 1990, 1993
3836 * The Regents of the University of California. All rights reserved.
3837 *
3838 * This code is derived from software contributed to Berkeley by
3839 * Chris Torek.
3840 *
3841 * Redistribution and use in source and binary forms, with or without
3842 * modification, are permitted provided that the following conditions
3843 * are met:
3844 * 1. Redistributions of source code must retain the above copyright
3845 * notice, this list of conditions and the following disclaimer.
3846 * 2. Redistributions in binary form must reproduce the above copyright
3847 * notice, this list of conditions and the following disclaimer in the
3848 * documentation and/or other materials provided with the distribution.
3849 * 3. Neither the name of the University nor the names of its contributors
3850 * may be used to endorse or promote products derived from this software
3851 * without specific prior written permission.
3852 *
3853 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3854 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3855 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3856 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3857 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3858 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3859 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3860 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3861 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3862 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3863 * SUCH DAMAGE.
3864 */
3865
3866The preceding notice is from src/missing/strcasestr.c in `file`.
3867
3868
3869
3870/*
3871 * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
3872 *
3873 * Permission to use, copy, modify, and distribute this software for any
3874 * purpose with or without fee is hereby granted, provided that the above
3875 * copyright notice and this permission notice appear in all copies.
3876 *
3877 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
3878 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
3879 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
3880 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
3881 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
3882 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
3883 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
3884 */
3885
3886The preceding notice is from src/missing/strlcat.c and src/missing/strlcpy.c in `file`.
3887
3888
3889
3890/*-
3891 * SPDX-License-Identifier: BSD-3-Clause
3892 *
3893 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
3894 * Copyright (c) 1992, 1993, 1994
3895 * The Regents of the University of California. All rights reserved.
3896 *
3897 * This code is derived from software contributed to Berkeley by
3898 * Henry Spencer.
3899 *
3900 * Redistribution and use in source and binary forms, with or without
3901 * modification, are permitted provided that the following conditions
3902 * are met:
3903 * 1. Redistributions of source code must retain the above copyright
3904 * notice, this list of conditions and the following disclaimer.
3905 * 2. Redistributions in binary form must reproduce the above copyright
3906 * notice, this list of conditions and the following disclaimer in the
3907 * documentation and/or other materials provided with the distribution.
3908 * 3. Neither the name of the University nor the names of its contributors
3909 * may be used to endorse or promote products derived from this software
3910 * without specific prior written permission.
3911 *
3912 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3913 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3914 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3915 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3916 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3917 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3918 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3919 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3920 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3921 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3922 * SUCH DAMAGE.
3923 *
3924 * @(#)utils.h 8.3 (Berkeley) 3/20/94
3925 * $FreeBSD: head/lib/libc/regex/utils.h 341838 2018-12-12 04:23:00Z yuripv $
3926 */
3927
3928The preceding notice is from src/missing/utils.h in `file`.
3929
3930
3931
3932/*-
3933 * Copyright (c) 2008, 2016 Christos Zoulas
3934 * All rights reserved.
3935 *
3936 * Redistribution and use in source and binary forms, with or without
3937 * modification, are permitted provided that the following conditions
3938 * are met:
3939 * 1. Redistributions of source code must retain the above copyright
3940 * notice, this list of conditions and the following disclaimer.
3941 * 2. Redistributions in binary form must reproduce the above copyright
3942 * notice, this list of conditions and the following disclaimer in the
3943 * documentation and/or other materials provided with the distribution.
3944 *
3945 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
3946 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
3947 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
3948 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
3949 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
3950 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
3951 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
3952 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
3953 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
3954 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
3955 * POSSIBILITY OF SUCH DAMAGE.
3956 */
3957
3958The preceding notice is from src/readcdf.c in `file`.
3959
3960
3961
3962/*-
3963 * Copyright (c) 1992 Henry Spencer.
3964 * Copyright (c) 1992, 1993
3965 * The Regents of the University of California. All rights reserved.
3966 *
3967 * This code is derived from software contributed to Berkeley by
3968 * Henry Spencer of the University of Toronto.
3969 *
3970 * Redistribution and use in source and binary forms, with or without
3971 * modification, are permitted provided that the following conditions
3972 * are met:
3973 * 1. Redistributions of source code must retain the above copyright
3974 * notice, this list of conditions and the following disclaimer.
3975 * 2. Redistributions in binary form must reproduce the above copyright
3976 * notice, this list of conditions and the following disclaimer in the
3977 * documentation and/or other materials provided with the distribution.
3978 * 3. Neither the name of the University nor the names of its contributors
3979 * may be used to endorse or promote products derived from this software
3980 * without specific prior written permission.
3981 *
3982 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3983 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3984 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3985 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3986 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3987 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3988 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3989 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3990 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3991 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3992 * SUCH DAMAGE.
3993 *
3994 * @(#)regex.h 8.2 (Berkeley) 1/3/94
3995 * $FreeBSD: src/include/regex.h,v 1.12 2010/02/16 19:39:50 imp Exp $
3996 */
3997
3998The preceding notice is from src/regex-bsd.h in `file`.
3999*/
4000/*
4001
4002Text of LICENSE from DROID:
4003
4004Copyright (c) 2016, The National Archives <pronom@nationalarchives.gov.uk>
4005All rights reserved.
4006
4007Redistribution and use in source and binary forms, with or without
4008modification, are permitted provided that the following
4009conditions are met:
4010
4011 * Redistributions of source code must retain the above copyright
4012 notice, this list of conditions and the following disclaimer.
4013
4014 * Redistributions in binary form must reproduce the above copyright
4015 notice, this list of conditions and the following disclaimer in the
4016 documentation and/or other materials provided with the distribution.
4017
4018 * Neither the name of the The National Archives nor the
4019 names of its contributors may be used to endorse or promote products
4020 derived from this software without specific prior written permission.
4021
4022THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
4023AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
4024IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
4025PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
4026CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
4027EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
4028PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
4029PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
4030LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
4031NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
4032SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
4033*/
4034
4035/*
4036
4037Text of LICENSE from fileid:
4038
4039The MIT License (MIT)
4040
4041Copyright (c) 2015 David B Heise
4042
4043Permission is hereby granted, free of charge, to any person obtaining a copy of
4044this software and associated documentation files (the "Software"), to deal in
4045the Software without restriction, including without limitation the rights to
4046use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
4047the Software, and to permit persons to whom the Software is furnished to do so,
4048subject to the following conditions:
4049
4050The above copyright notice and this permission notice shall be included in all
4051copies or substantial portions of the Software.
4052
4053THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
4054IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
4055FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
4056COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
4057IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
4058CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
4059
4060
4061*/
4062
4063/*
4064Text of LICENSE from binwalk:
4065
4066
4067MIT License
4068
4069Copyright (c) 2024 devttys0
4070
4071Permission is hereby granted, free of charge, to any person obtaining a copy
4072of this software and associated documentation files (the "Software"), to deal
4073in the Software without restriction, including without limitation the rights
4074to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
4075copies of the Software, and to permit persons to whom the Software is
4076furnished to do so, subject to the following conditions:
4077
4078The above copyright notice and this permission notice shall be included in all
4079copies or substantial portions of the Software.
4080
4081THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
4082IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
4083FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
4084AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
4085LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
4086OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
4087SOFTWARE.
4088
4089*/
4090
4091/*
4092Text of LICENSE from polyfile:
4093
4094
4095 Apache License
4096 Version 2.0, January 2004
4097 http://www.apache.org/licenses/
4098
4099 TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
4100
4101 1. Definitions.
4102
4103 "License" shall mean the terms and conditions for use, reproduction,
4104 and distribution as defined by Sections 1 through 9 of this document.
4105
4106 "Licensor" shall mean the copyright owner or entity authorized by
4107 the copyright owner that is granting the License.
4108
4109 "Legal Entity" shall mean the union of the acting entity and all
4110 other entities that control, are controlled by, or are under common
4111 control with that entity. For the purposes of this definition,
4112 "control" means (i) the power, direct or indirect, to cause the
4113 direction or management of such entity, whether by contract or
4114 otherwise, or (ii) ownership of fifty percent (50%) or more of the
4115 outstanding shares, or (iii) beneficial ownership of such entity.
4116
4117 "You" (or "Your") shall mean an individual or Legal Entity
4118 exercising permissions granted by this License.
4119
4120 "Source" form shall mean the preferred form for making modifications,
4121 including but not limited to software source code, documentation
4122 source, and configuration files.
4123
4124 "Object" form shall mean any form resulting from mechanical
4125 transformation or translation of a Source form, including but
4126 not limited to compiled object code, generated documentation,
4127 and conversions to other media types.
4128
4129 "Work" shall mean the work of authorship, whether in Source or
4130 Object form, made available under the License, as indicated by a
4131 copyright notice that is included in or attached to the work
4132 (an example is provided in the Appendix below).
4133
4134 "Derivative Works" shall mean any work, whether in Source or Object
4135 form, that is based on (or derived from) the Work and for which the
4136 editorial revisions, annotations, elaborations, or other modifications
4137 represent, as a whole, an original work of authorship. For the purposes
4138 of this License, Derivative Works shall not include works that remain
4139 separable from, or merely link (or bind by name) to the interfaces of,
4140 the Work and Derivative Works thereof.
4141
4142 "Contribution" shall mean any work of authorship, including
4143 the original version of the Work and any modifications or additions
4144 to that Work or Derivative Works thereof, that is intentionally
4145 submitted to Licensor for inclusion in the Work by the copyright owner
4146 or by an individual or Legal Entity authorized to submit on behalf of
4147 the copyright owner. For the purposes of this definition, "submitted"
4148 means any form of electronic, verbal, or written communication sent
4149 to the Licensor or its representatives, including but not limited to
4150 communication on electronic mailing lists, source code control systems,
4151 and issue tracking systems that are managed by, or on behalf of, the
4152 Licensor for the purpose of discussing and improving the Work, but
4153 excluding communication that is conspicuously marked or otherwise
4154 designated in writing by the copyright owner as "Not a Contribution."
4155
4156 "Contributor" shall mean Licensor and any individual or Legal Entity
4157 on behalf of whom a Contribution has been received by Licensor and
4158 subsequently incorporated within the Work.
4159
4160 2. Grant of Copyright License. Subject to the terms and conditions of
4161 this License, each Contributor hereby grants to You a perpetual,
4162 worldwide, non-exclusive, no-charge, royalty-free, irrevocable
4163 copyright license to reproduce, prepare Derivative Works of,
4164 publicly display, publicly perform, sublicense, and distribute the
4165 Work and such Derivative Works in Source or Object form.
4166
4167 3. Grant of Patent License. Subject to the terms and conditions of
4168 this License, each Contributor hereby grants to You a perpetual,
4169 worldwide, non-exclusive, no-charge, royalty-free, irrevocable
4170 (except as stated in this section) patent license to make, have made,
4171 use, offer to sell, sell, import, and otherwise transfer the Work,
4172 where such license applies only to those patent claims licensable
4173 by such Contributor that are necessarily infringed by their
4174 Contribution(s) alone or by combination of their Contribution(s)
4175 with the Work to which such Contribution(s) was submitted. If You
4176 institute patent litigation against any entity (including a
4177 cross-claim or counterclaim in a lawsuit) alleging that the Work
4178 or a Contribution incorporated within the Work constitutes direct
4179 or contributory patent infringement, then any patent licenses
4180 granted to You under this License for that Work shall terminate
4181 as of the date such litigation is filed.
4182
4183 4. Redistribution. You may reproduce and distribute copies of the
4184 Work or Derivative Works thereof in any medium, with or without
4185 modifications, and in Source or Object form, provided that You
4186 meet the following conditions:
4187
4188 (a) You must give any other recipients of the Work or
4189 Derivative Works a copy of this License; and
4190
4191 (b) You must cause any modified files to carry prominent notices
4192 stating that You changed the files; and
4193
4194 (c) You must retain, in the Source form of any Derivative Works
4195 that You distribute, all copyright, patent, trademark, and
4196 attribution notices from the Source form of the Work,
4197 excluding those notices that do not pertain to any part of
4198 the Derivative Works; and
4199
4200 (d) If the Work includes a "NOTICE" text file as part of its
4201 distribution, then any Derivative Works that You distribute must
4202 include a readable copy of the attribution notices contained
4203 within such NOTICE file, excluding those notices that do not
4204 pertain to any part of the Derivative Works, in at least one
4205 of the following places: within a NOTICE text file distributed
4206 as part of the Derivative Works; within the Source form or
4207 documentation, if provided along with the Derivative Works; or,
4208 within a display generated by the Derivative Works, if and
4209 wherever such third-party notices normally appear. The contents
4210 of the NOTICE file are for informational purposes only and
4211 do not modify the License. You may add Your own attribution
4212 notices within Derivative Works that You distribute, alongside
4213 or as an addendum to the NOTICE text from the Work, provided
4214 that such additional attribution notices cannot be construed
4215 as modifying the License.
4216
4217 You may add Your own copyright statement to Your modifications and
4218 may provide additional or different license terms and conditions
4219 for use, reproduction, or distribution of Your modifications, or
4220 for any such Derivative Works as a whole, provided Your use,
4221 reproduction, and distribution of the Work otherwise complies with
4222 the conditions stated in this License.
4223
4224 5. Submission of Contributions. Unless You explicitly state otherwise,
4225 any Contribution intentionally submitted for inclusion in the Work
4226 by You to the Licensor shall be under the terms and conditions of
4227 this License, without any additional terms or conditions.
4228 Notwithstanding the above, nothing herein shall supersede or modify
4229 the terms of any separate license agreement you may have executed
4230 with Licensor regarding such Contributions.
4231
4232 6. Trademarks. This License does not grant permission to use the trade
4233 names, trademarks, service marks, or product names of the Licensor,
4234 except as required for reasonable and customary use in describing the
4235 origin of the Work and reproducing the content of the NOTICE file.
4236
4237 7. Disclaimer of Warranty. Unless required by applicable law or
4238 agreed to in writing, Licensor provides the Work (and each
4239 Contributor provides its Contributions) on an "AS IS" BASIS,
4240 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
4241 implied, including, without limitation, any warranties or conditions
4242 of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
4243 PARTICULAR PURPOSE. You are solely responsible for determining the
4244 appropriateness of using or redistributing the Work and assume any
4245 risks associated with Your exercise of permissions under this License.
4246
4247 8. Limitation of Liability. In no event and under no legal theory,
4248 whether in tort (including negligence), contract, or otherwise,
4249 unless required by applicable law (such as deliberate and grossly
4250 negligent acts) or agreed to in writing, shall any Contributor be
4251 liable to You for damages, including any direct, indirect, special,
4252 incidental, or consequential damages of any character arising as a
4253 result of this License or out of the use or inability to use the
4254 Work (including but not limited to damages for loss of goodwill,
4255 work stoppage, computer failure or malfunction, or any and all
4256 other commercial damages or losses), even if such Contributor
4257 has been advised of the possibility of such damages.
4258
4259 9. Accepting Warranty or Additional Liability. While redistributing
4260 the Work or Derivative Works thereof, You may choose to offer,
4261 and charge a fee for, acceptance of support, warranty, indemnity,
4262 or other liability obligations and/or rights consistent with this
4263 License. However, in accepting such obligations, You may act only
4264 on Your own behalf and on Your sole responsibility, not on behalf
4265 of any other Contributor, and only if You agree to indemnify,
4266 defend, and hold each Contributor harmless for any liability
4267 incurred by, or claims asserted against, such Contributor by reason
4268 of your accepting any such warranty or additional liability.
4269
4270 END OF TERMS AND CONDITIONS
4271
4272 APPENDIX: How to apply the Apache License to your work.
4273
4274 To apply the Apache License to your work, attach the following
4275 boilerplate notice, with the fields enclosed by brackets "[]"
4276 replaced with your own identifying information. (Don't include
4277 the brackets!) The text should be enclosed in the appropriate
4278 comment syntax for the file format. We also recommend that a
4279 file or class name and description of purpose be included on the
4280 same "printed page" as the copyright notice for easier
4281 identification within third-party archives.
4282
4283 Copyright [yyyy] [name of copyright owner]
4284
4285 Licensed under the Apache License, Version 2.0 (the "License");
4286 you may not use this file except in compliance with the License.
4287 You may obtain a copy of the License at
4288
4289 http://www.apache.org/licenses/LICENSE-2.0
4290
4291 Unless required by applicable law or agreed to in writing, software
4292 distributed under the License is distributed on an "AS IS" BASIS,
4293 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4294 See the License for the specific language governing permissions and
4295 limitations under the License.
4296
4297*/