ctb_formats_detection/
detection.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//! Combined multi-signal format detection, hierarchical pattern matching,
446//! and multipart extension chain parsing.
447//!
448//! This crate (partial/incomplete but seems to be working for basic cases)
449//! provides file format guessing by synthesizing multiple orthogonal signals:
450//! - **Magic pattern matching**: Hierarchical, bitmask-aware rules compiled
451//!   from file signatures and fine-grained offsets.
452//! - **PRONOM / DROID signatures**: Dual-anchored header and trailer patterns
453//!   with variable-length gaps.
454//! - **Extension analysis**: Multipart extension chains (e.g. `.tar.gz`) with
455//!   case sensitivity rules and path classification.
456//! - **Structural inspection**: Container and polyglot detection for ZIP,
457//!   OLE2, AppleSingle/Double, and archive structures.
458//! - **Text encoding heuristics**: Multi-encoding validation (UTF-8, UTF-16,
459//!   ASCII, Latin-1) and XML/HTML markup pattern scoring.
460//! - **Platform knowledge**: Target operating system compatibility scoring
461//!   to resolve format ambiguities.
462//!
463//! # High-Level Convenience Functions
464//!
465//! For most use cases, convenience functions provide quick format guessing or
466//! full diagnostic reporting across common input types:
467//!
468//! - Filesystem paths: [`guess_path`] and [`guess_and_report_path`]
469//! - UTF-8 / String data: [`guess_string`] and [`guess_and_report_string`]
470//! - Document strings: [`guess_dcs`] and [`guess_and_report_dcs`]
471//! - Raw byte buffers: [`guess_vec`] and [`guess_and_report_vec`]
472//! - Structured `File` entities: [`guess_file`] and [`guess_and_report_file`]
473//!
474//! # Examples
475//!
476//! ### Inspecting a Filesystem Path
477//!
478//! Identify a format directly from an on-disk path or generate a report:
479//!
480//! ```rust,no_run
481//! use ctb_formats_detection::{
482//!     guess_and_report_path, guess_path, FormatId, OsPath,
483//! };
484//!
485//! # fn main() -> anyhow::Result<()> {
486//! let dir = tempfile::tempdir()?;
487//! let path: OsPath = dir.path().join("archive.tar.gz");
488//! let gz_header = [0x1F, 0x8B, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00];
489//! std::fs::write(&path, gz_header)?;
490//!
491//! // Fast authoritative format identification:
492//! let format = guess_path(&path)?;
493//! assert_eq!(format, FormatId::Gzip);
494//!
495//! // Comprehensive detection report with ranked candidates:
496//! let report = guess_and_report_path(&path)?;
497//! assert_eq!(report.candidates[0].format_id, Some(FormatId::Gzip));
498//! # Ok(())
499//! # }
500//! ```
501//!
502//! ### Inspecting a String
503//!
504//! Detect markup, source code, or text formats from a `String` or `&str`:
505//!
506//! ```
507//! use ctb_formats_detection::{
508//!     guess_and_report_string, guess_string, FormatId,
509//! };
510//!
511//! # fn main() -> anyhow::Result<()> {
512//! let html = String::from(
513//!     "<!DOCTYPE html><html><body><h1>Header</h1></body></html>",
514//! );
515//!
516//! let format = guess_string(html.clone())?;
517//! assert_eq!(format, FormatId::Html);
518//!
519//! let report = guess_and_report_string(html)?;
520//! assert_eq!(report.candidates[0].format_id, Some(FormatId::Html));
521//! # Ok(())
522//! # }
523//! ```
524//!
525//! ### Inspecting a Document Character String (`DcString`)
526//!
527//! Detect formats directly from a [`DcString`]:
528//!
529//! ```
530//! use ctb_formats_detection::{
531//!     guess_and_report_dcs, guess_dcs, DcString, FormatId,
532//! };
533//!
534//! # fn main() -> anyhow::Result<()> {
535//! let dcs = DcString::from_dcutf(
536//!     b"<!DOCTYPE html><html><body>Test</body></html>".to_vec(),
537//! )?;
538//!
539//! let format = guess_dcs(&dcs)?;
540//! assert_eq!(format, FormatId::Html);
541//!
542//! let report = guess_and_report_dcs(&dcs)?;
543//! assert_eq!(report.candidates[0].format_id, Some(FormatId::Html));
544//! # Ok(())
545//! # }
546//! ```
547//!
548//! ### Inspecting Raw Byte Vectors
549//!
550//! Detect binary or text formats from an in-memory `Vec<u8>`:
551//!
552//! ```
553//! use ctb_formats_detection::{guess_and_report_vec, guess_vec, FormatId};
554//!
555//! # fn main() -> anyhow::Result<()> {
556//! let gz_bytes: Vec<u8> =
557//!     vec![0x1F, 0x8B, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00];
558//!
559//! let format = guess_vec(gz_bytes.clone())?;
560//! assert_eq!(format, FormatId::Gzip);
561//!
562//! let report = guess_and_report_vec(gz_bytes)?;
563//! assert_eq!(report.candidates[0].format_id, Some(FormatId::Gzip));
564//! # Ok(())
565//! # }
566//! ```
567//!
568//! ### Inspecting an `io/file` `File` Entity
569//!
570//! Detect formats when working with structured [`File`] entities:
571//!
572//! ```rust,no_run
573//! use ctb_formats_detection::{
574//!     guess_and_report_file, guess_file, File, FormatId,
575//! };
576//!
577//! # fn main() -> anyhow::Result<()> {
578//! let dir = tempfile::tempdir()?;
579//! let path = dir.path().join("archive.tar.gz");
580//! let gz_header = [0x1F, 0x8B, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00];
581//! std::fs::write(&path, gz_header)?;
582//!
583//! let file = File::from_filesystem(&path, None)?;
584//!
585//! let format = guess_file(&file)?;
586//! assert_eq!(format, FormatId::Gzip);
587//!
588//! let report = guess_and_report_file(&file)?;
589//! assert_eq!(report.candidates[0].format_id, Some(FormatId::Gzip));
590//! # Ok(())
591//! # }
592//! ```
593
594#[allow(
595    unused_imports,
596    clippy::wildcard_imports,
597    reason = "Standard workspace crate prelude"
598)]
599pub(crate) use ctb_utilities::*;
600
601pub use crate as detection;
602pub use ctb_formats_dcstring::DcString;
603pub use ctb_formats_utilities::encoding;
604pub use ctb_formats_utilities::extension_rule::{
605    CaseSensitivity, ExtensionRule,
606};
607pub use ctb_io_file::{
608    DiskPayloadSource, Extent, File, FileEntity, FileEntityKind,
609    FileEntityType, FileOrigin, InodeKey, MemoryPayloadSource, PayloadSource,
610    ReaderPayloadSource,
611};
612pub use ctb_utilities::FormatId;
613pub use ctb_utilities::format_id;
614pub type OsPath = std::path::PathBuf;
615
616pub mod chain;
617pub mod cli;
618pub mod conflict;
619pub mod container;
620pub mod decompression;
621pub mod der;
622pub mod droid;
623pub mod extension;
624pub mod extra_rules;
625pub mod file_upstream_suite;
626pub mod magic;
627pub mod magic_data;
628pub mod magic_parser;
629pub mod mime_derivation;
630pub mod platform;
631pub mod polyfile;
632pub mod readelf;
633pub mod resource_fork;
634pub mod source;
635pub mod special;
636pub mod text;
637pub mod types;
638
639pub use platform::{current_platform_os, format_matches_platform, is_os_match};
640pub use source::{DetectionSource, EmptySource};
641pub use types::*;
642
643use self::conflict::resolve_candidate_conflicts;
644use self::container::detect_container_candidates;
645use self::decompression::probe_decompression_candidates;
646use self::droid::{
647    evaluate_dual_anchored_signatures, evaluate_pronom_signatures,
648};
649use self::extension::resolve_extension_candidates;
650use self::extra_rules::{
651    detect_custom_text_format_candidate, detect_small_format_candidates,
652};
653use self::magic::{evaluate_rule, evaluate_rule_with_mode};
654use self::magic_data::{COMPILED_CTB_MAGIC_RULES, COMPILED_FILE_MAGIC_RULES};
655use self::mime_derivation::FORMAT_CATALOG;
656use self::polyfile::detect_polyglots;
657use self::readelf::inspect_elf_details;
658use self::special::detect_special_entity;
659use self::text::{TEXT_ENCODING_MAX_BYTES, detect_text_candidate_and_encoding};
660
661/// Bonus score awarded when a format candidate matches the target platform OS.
662const PLATFORM_PRIOR_BONUS: u32 = 15;
663
664/// Text-encoding evidence gathered by the text-analysis phase, used to
665/// corroborate extension-only candidates whose format implies this encoding.
666struct TextEncodingEvidence {
667    /// Format ID of the detected character encoding itself.
668    detected: FormatId,
669    /// Encoding/TextProperties evidence items cloned from the text candidate.
670    items: Vec<DetectionEvidence>,
671    /// Total score the text candidate earned from these evidence items.
672    score: u32,
673}
674
675/// Text-encoding compatibility for entailment corroboration. The detected
676/// encoding corroborates an implied encoding format when they are identical or
677/// when the detected encoding format implies the required encoding format
678/// according to the format database's `@implies(...)` relationships.
679fn encoding_entailment_compatible(
680    detected: FormatId,
681    implied: FormatId,
682) -> bool {
683    detected == implied || detected.implies().contains(&implied)
684}
685
686/// Primary format detection function returning a comprehensive report.
687pub fn guess_format_report(
688    source: &mut dyn DetectionSource,
689    hint: Option<&DetectionHint>,
690) -> Result<DetectionReport> {
691    let mut candidates = Vec::new();
692    let mut bytes_evaluated = 0u64;
693    let read_error: Option<String> = None;
694
695    // 0. Evaluate special filesystem entity hints (special.rs)
696    if let Some(special_cand) = detect_special_entity(hint) {
697        candidates.push(special_cand);
698    }
699
700    if let Some(h) = hint {
701        if let Some(code) = h.apple_type_code {
702            if let Some(mapping) = FORMAT_CATALOG.lookup_apple_type_code(&code)
703            {
704                candidates.push(DetectionCandidate {
705                    format_id: mapping.format_id,
706                    dc_id: Some(mapping.dc_id),
707                    mime: mapping.mime_types.first().cloned(),
708                    description: mapping.label.clone(),
709                    confidence: ConfidenceTier::Strong,
710                    score: 90,
711                    evidence: vec![DetectionEvidence::AppleTypeCode {
712                        code,
713                        score: 90,
714                    }],
715                    chain_layers: None,
716                });
717            }
718        }
719        for sc in &h.stream_candidates {
720            candidates.push(sc.clone());
721        }
722    }
723
724    let hint_ext = hint.and_then(|h| {
725        h.extension.as_deref().or_else(|| {
726            h.filename.as_deref().and_then(|f| {
727                f.rsplit(['/', '\\'])
728                    .next()?
729                    .rsplit_once('.')
730                    .map(|(_, ext)| ext)
731            })
732        })
733    });
734
735    let platform = hint.and_then(|h| h.platform);
736    let expected_cat = hint.and_then(|h| h.expected_category);
737
738    // 1.5. Evaluate DROID PRONOM and dual-anchored BOF / EOF signatures (droid.rs)
739    if let Ok(pronom_cands) = evaluate_pronom_signatures(source, hint) {
740        for cand in pronom_cands {
741            let mut merged = false;
742            for existing in &mut candidates {
743                let matches_fmt = cand.format_id.is_some()
744                    && existing.format_id == cand.format_id;
745                let matches_desc = !cand.description.is_empty()
746                    && (existing
747                        .description
748                        .eq_ignore_ascii_case(&cand.description)
749                        || existing
750                            .description
751                            .to_ascii_lowercase()
752                            .contains(&cand.description.to_ascii_lowercase())
753                        || cand.description.to_ascii_lowercase().contains(
754                            &existing.description.to_ascii_lowercase(),
755                        ));
756                let matches_mime =
757                    cand.mime.is_some() && existing.mime == cand.mime;
758                if matches_fmt || matches_desc || matches_mime {
759                    if existing.format_id.is_none() && cand.format_id.is_some()
760                    {
761                        existing.format_id = cand.format_id;
762                    }
763                    if cand.score > existing.score {
764                        existing.score = cand.score;
765                        existing.confidence = cand.confidence;
766                        existing.description = cand.description.clone();
767                    }
768                    if existing.mime.is_none() && cand.mime.is_some() {
769                        existing.mime = cand.mime.clone();
770                    }
771                    existing.evidence.extend(cand.evidence.clone());
772                    merged = true;
773                    break;
774                }
775            }
776            if !merged {
777                candidates.push(cand);
778            }
779        }
780    }
781
782    if let Ok(dual_cands) = evaluate_dual_anchored_signatures(source) {
783        for cand in dual_cands {
784            let mut merged = false;
785            for existing in &mut candidates {
786                let matches_fmt = cand.format_id.is_some()
787                    && existing.format_id == cand.format_id;
788                let matches_desc = !cand.description.is_empty()
789                    && (existing
790                        .description
791                        .eq_ignore_ascii_case(&cand.description)
792                        || existing
793                            .description
794                            .to_ascii_lowercase()
795                            .contains(&cand.description.to_ascii_lowercase())
796                        || cand.description.to_ascii_lowercase().contains(
797                            &existing.description.to_ascii_lowercase(),
798                        ));
799                let matches_mime =
800                    cand.mime.is_some() && existing.mime == cand.mime;
801                if matches_fmt || matches_desc || matches_mime {
802                    if existing.format_id.is_none() && cand.format_id.is_some()
803                    {
804                        existing.format_id = cand.format_id;
805                    }
806                    if cand.score > existing.score {
807                        existing.score = cand.score;
808                        existing.confidence = cand.confidence;
809                        existing.description = cand.description.clone();
810                    }
811                    if existing.mime.is_none() && cand.mime.is_some() {
812                        existing.mime = cand.mime.clone();
813                    }
814                    existing.evidence.extend(cand.evidence.clone());
815                    merged = true;
816                    break;
817                }
818            }
819            if !merged {
820                candidates.push(cand);
821            }
822        }
823    }
824
825    // Pre-evaluate ELF inspection if payload starts with ELF magic
826    let mut elf_details = None;
827    let mut bof4 = [0u8; 4];
828    if source.read_at(0, &mut bof4).is_ok() && bof4 == *b"\x7fELF" {
829        elf_details =
830            inspect_elf_details(source, hint.and_then(|h| h.file_mode));
831    }
832    let eval_mode = if let Some(ref elf) = elf_details {
833        if elf.is_executable { 0o755 } else { 0o644 }
834    } else {
835        // Reason for fallback: When file mode hint is absent or unspecified, evaluate magic rules with 0 (no mode bits)
836        hint.and_then(|h| h.file_mode).unwrap_or(0)
837    };
838
839    // 2. Evaluate compiled hierarchical magic rules (ctoolbox.magic -> CtbMagic, Magdir -> FileMagic)
840    for (rule_set, is_ctb) in [
841        (&*COMPILED_CTB_MAGIC_RULES, true),
842        (&*COMPILED_FILE_MAGIC_RULES, false),
843    ] {
844        for rule in rule_set {
845            if let Some(mut match_res) =
846                evaluate_rule_with_mode(rule, source, eval_mode)
847            {
848                if let Some(ref elf) = elf_details {
849                    if match_res.description.starts_with("ELF ") {
850                        match_res.description.push_str(&elf.suffix);
851                        match_res.match_end =
852                            match_res.match_end.max(elf.bytes_evaluated);
853                    }
854                }
855                bytes_evaluated = bytes_evaluated.max(match_res.match_end);
856                if match_res.description.trim().is_empty()
857                    && match_res.mime.is_none()
858                {
859                    continue;
860                }
861                let mut score = if is_ctb {
862                    match_res.score.max(90)
863                } else {
864                    match_res.score
865                };
866                let mut evidence = Vec::new();
867                if is_ctb {
868                    evidence.push(DetectionEvidence::CtbMagic {
869                        description: match_res.description.clone(),
870                        score: match_res.score,
871                    });
872                } else {
873                    evidence.push(DetectionEvidence::FileMagic {
874                        description: match_res.description.clone(),
875                        score: match_res.score,
876                    });
877                }
878
879                // Map MIME or description to format catalog
880                let is_generic_mime =
881                    match_res.mime.as_deref().is_some_and(|m| {
882                        m.eq_ignore_ascii_case("application/octet-stream")
883                            || m.eq_ignore_ascii_case("application/x-empty")
884                    });
885
886                let is_elf_match = match_res.description.starts_with("ELF ");
887                let mapping = FORMAT_CATALOG
888                    .lookup_magic_name(&match_res.description)
889                    .or_else(|| {
890                        match_res
891                            .mime
892                            .as_deref()
893                            .filter(|_| !is_generic_mime)
894                            .and_then(|m| FORMAT_CATALOG.lookup_mime(m))
895                    })
896                    .or_else(|| {
897                        FORMAT_CATALOG
898                            .lookup_description_or_ident(&match_res.description)
899                    })
900                    .or_else(|| {
901                        match_res.ext.as_deref().and_then(|ext| {
902                            ext.split(['/', ',']).find_map(|e| {
903                                FORMAT_CATALOG
904                                    .lookup_extension(e.trim())
905                                    .first()
906                            })
907                        })
908                    });
909
910                let format_id = mapping.and_then(|m| m.format_id).or({
911                    if is_elf_match {
912                        Some(FormatId::Elf)
913                    } else {
914                        None
915                    }
916                });
917                let dc_id = mapping.map(|m| m.dc_id).or_else(|| {
918                    if is_elf_match {
919                        FormatId::Elf.dc_id()
920                    } else {
921                        None
922                    }
923                });
924                let mime = match_res.mime.or_else(|| {
925                    mapping.and_then(|m| m.mime_types.first().cloned())
926                });
927                // Reason for fallback: rule match without custom description falls back to format label or "Unknown Format"
928                let description = if match_res.description.is_empty() {
929                    mapping.map_or_else(
930                        || "Unknown Format".to_string(),
931                        |m| m.label.clone(),
932                    )
933                } else {
934                    match_res.description
935                };
936
937                // Concordance with extension hint
938                if let Some(ext) = hint_ext {
939                    let ext_normalized = ext.to_ascii_lowercase();
940                    // Reason for fallback: rule without extension declaration evaluates to false for concordance
941                    let rule_ext_match =
942                        match_res.ext.as_deref().is_some_and(|e| {
943                            e.split(['/', ',']).any(|p| {
944                                p.trim().eq_ignore_ascii_case(&ext_normalized)
945                            })
946                        });
947
948                    // Reason for fallback: unmapped format evaluates to false for extension concordance
949                    let mapping_ext_match = mapping.is_some_and(|m| {
950                        m.extensions
951                            .iter()
952                            .any(|e| e.eq_ignore_ascii_case(&ext_normalized))
953                    });
954
955                    if rule_ext_match || mapping_ext_match {
956                        score = score.saturating_add(25);
957                        evidence.push(DetectionEvidence::Extension {
958                            ext: ext.to_string(),
959                            is_primary: true,
960                            score: 25,
961                        });
962                    }
963                }
964
965                // Platform prior boost from format dataset OS associations
966                if let Some(target_os) = platform {
967                    let is_matched = format_id.is_some_and(|fid| {
968                        format_matches_platform(fid, target_os)
969                    });
970
971                    if is_matched {
972                        score = score.saturating_add(PLATFORM_PRIOR_BONUS);
973                        evidence.push(DetectionEvidence::PlatformPrior {
974                            platform: target_os,
975                            score: PLATFORM_PRIOR_BONUS,
976                        });
977                    }
978                }
979
980                // Expected category boost
981                if let (Some(exp_cat), Some(fid)) = (expected_cat, format_id) {
982                    if fid.category() == exp_cat {
983                        score = score.saturating_add(20);
984                        evidence.push(DetectionEvidence::CategoryMatch {
985                            category: exp_cat,
986                            score: 20,
987                        });
988                    }
989                }
990
991                let confidence = if score >= 85 {
992                    ConfidenceTier::HighestConfidence
993                } else if score >= 65 {
994                    ConfidenceTier::Strong
995                } else if score >= 40 {
996                    ConfidenceTier::Moderate
997                } else {
998                    ConfidenceTier::Weak
999                };
1000
1001                // Deduplicate and merge with any existing candidate for the same format or description
1002                let mut merged = false;
1003                for existing in &mut candidates {
1004                    let matches_fmt = format_id.is_some()
1005                        && (existing.format_id == format_id
1006                            || existing
1007                                .mime
1008                                .as_deref()
1009                                .and_then(|m| FORMAT_CATALOG.lookup_mime(m))
1010                                .and_then(|m| m.format_id)
1011                                == format_id);
1012                    let matches_desc = !description.is_empty()
1013                        && (existing
1014                            .description
1015                            .eq_ignore_ascii_case(&description)
1016                            || existing
1017                                .description
1018                                .to_ascii_lowercase()
1019                                .contains(&description.to_ascii_lowercase())
1020                            || description.to_ascii_lowercase().contains(
1021                                &existing.description.to_ascii_lowercase(),
1022                            ));
1023                    let matches_mime = mime.is_some() && existing.mime == mime;
1024                    if matches_fmt || matches_desc || matches_mime {
1025                        if existing.format_id.is_none() && format_id.is_some() {
1026                            existing.format_id = format_id;
1027                        }
1028                        if existing.dc_id.is_none() && dc_id.is_some() {
1029                            existing.dc_id = dc_id;
1030                        }
1031                        if existing.mime.is_none() && mime.is_some() {
1032                            existing.mime = mime.clone();
1033                        }
1034                        if score > existing.score {
1035                            existing.score = score;
1036                            existing.confidence = confidence;
1037                            existing.description = description.clone();
1038                            if mime.is_some() {
1039                                existing.mime = mime.clone();
1040                            }
1041                        } else if score == existing.score
1042                            && description.len() > existing.description.len()
1043                        {
1044                            existing.description = description.clone();
1045                        }
1046                        existing.evidence.extend(evidence.clone());
1047                        merged = true;
1048                        break;
1049                    }
1050                }
1051
1052                if !merged {
1053                    candidates.push(DetectionCandidate {
1054                        format_id,
1055                        dc_id,
1056                        mime,
1057                        description,
1058                        confidence,
1059                        score,
1060                        evidence,
1061                        chain_layers: None,
1062                    });
1063                }
1064            }
1065        }
1066    }
1067
1068    // 2.3. Evaluate specialized deep parsers and container inspection (container.rs)
1069    if let Ok(container_cands) = detect_container_candidates(source, hint) {
1070        for cand in container_cands {
1071            let mut merged = false;
1072            for existing in &mut candidates {
1073                let matches_fmt = cand.format_id.is_some()
1074                    && existing.format_id == cand.format_id;
1075                let matches_desc = !cand.description.is_empty()
1076                    && existing
1077                        .description
1078                        .eq_ignore_ascii_case(&cand.description);
1079                if matches_fmt || matches_desc {
1080                    if existing.format_id.is_none() && cand.format_id.is_some()
1081                    {
1082                        existing.format_id = cand.format_id;
1083                    }
1084                    if cand.score > existing.score {
1085                        existing.score = cand.score;
1086                        existing.confidence = cand.confidence;
1087                        existing.description = cand.description.clone();
1088                    }
1089                    if existing.mime.is_none() && cand.mime.is_some() {
1090                        existing.mime = cand.mime.clone();
1091                    }
1092                    existing.evidence.extend(cand.evidence.clone());
1093                    merged = true;
1094                    break;
1095                }
1096            }
1097            if !merged {
1098                candidates.push(cand);
1099            }
1100        }
1101    }
1102
1103    // 2.3b. Evaluate transparent and recursive decompression inspection (decompression.rs)
1104    if let Ok(decomp_cands) = probe_decompression_candidates(
1105        source,
1106        &candidates,
1107        hint,
1108        |inner_src, inner_h| guess_format_report(inner_src, inner_h),
1109    ) {
1110        // Reason for fallback: default to false if hint is not provided
1111        if hint.is_some_and(|h| {
1112            h.compat && (h.uncompress || h.uncompress_noreport)
1113        }) {
1114            if !decomp_cands.is_empty() {
1115                candidates = decomp_cands;
1116            }
1117        } else {
1118            for cand in decomp_cands.into_iter().rev() {
1119                candidates.insert(0, cand);
1120            }
1121        }
1122    }
1123
1124    // 2.4. Evaluate PolyFile polyglot container detection (polyfile.rs)
1125    if let Ok(Some(poly_cand)) = detect_polyglots(source, &candidates) {
1126        candidates.push(poly_cand);
1127    }
1128
1129    // 2.5. Evaluate text & character encoding detection if no high-confidence binary magic matched
1130    let mut text_encoding_evidence: Option<TextEncodingEvidence> = None;
1131    let has_strong_binary_magic = candidates.iter().any(|c| {
1132        (c.confidence >= ConfidenceTier::Strong || c.score >= 50)
1133            && !c.description.contains("text")
1134            && !c.description.contains("script")
1135            && !c.description.contains("source")
1136            && !c.mime.as_deref().is_some_and(|m| m.starts_with("text/"))
1137            && c.format_id != Some(FormatId::Ascii)
1138    });
1139    if !has_strong_binary_magic {
1140        if let Ok(Some((text_cand, encoding_fmt))) =
1141            detect_text_candidate_and_encoding(source, hint)
1142        {
1143            // Capture the encoding evidence so extension-only candidates
1144            // implying this encoding can be corroborated in step 3.
1145            if let Some(detected) = encoding_fmt {
1146                let mut items = Vec::new();
1147                let mut items_score = 0u32;
1148                for ev in &text_cand.evidence {
1149                    let ev_score = match ev {
1150                        DetectionEvidence::Encoding { score, .. }
1151                        | DetectionEvidence::TextProperties { score, .. } => {
1152                            *score
1153                        }
1154                        _ => continue,
1155                    };
1156                    items_score = items_score.saturating_add(ev_score);
1157                    items.push(ev.clone());
1158                }
1159                text_encoding_evidence = Some(TextEncodingEvidence {
1160                    detected,
1161                    items,
1162                    score: items_score,
1163                });
1164            }
1165
1166            // Reason for fallback: default to 4096 byte inspection limit if arithmetic conversion overflows
1167            let inspect_size = u64::try_from(TEXT_ENCODING_MAX_BYTES.min(4096))
1168                .unwrap_or(4096);
1169            bytes_evaluated = bytes_evaluated.max(inspect_size);
1170
1171            let mut merged = false;
1172            for existing in &mut candidates {
1173                let matches_fmt = text_cand.format_id.is_some()
1174                    && existing.format_id == text_cand.format_id;
1175                let matches_desc = (!existing.description.is_empty()
1176                    && !text_cand.description.is_empty()
1177                    && (existing.description.contains(&text_cand.description)
1178                        || text_cand
1179                            .description
1180                            .contains(&existing.description)))
1181                    || (existing.description.contains("Python")
1182                        && text_cand.description.contains("Python"))
1183                    || (existing.description.contains("script")
1184                        && text_cand.description.contains("script"));
1185
1186                if matches_fmt || matches_desc {
1187                    if text_cand.score > existing.score {
1188                        existing.score = text_cand.score;
1189                        existing.confidence = text_cand.confidence;
1190                        existing.description = text_cand.description.clone();
1191                    }
1192                    if existing.mime.is_none() && text_cand.mime.is_some() {
1193                        existing.mime = text_cand.mime.clone();
1194                    }
1195                    if existing.format_id.is_none()
1196                        && text_cand.format_id.is_some()
1197                    {
1198                        existing.format_id = text_cand.format_id;
1199                    }
1200                    existing.evidence.extend(text_cand.evidence.clone());
1201                    merged = true;
1202                    break;
1203                }
1204            }
1205            if !merged {
1206                candidates.push(text_cand);
1207            }
1208        }
1209    }
1210
1211    // 2.6. Evaluate small specialized textual formats (IP addresses, UUIDs, checksums, math expressions)
1212    if !has_strong_binary_magic {
1213        let mut sample_buf = vec![0u8; 4096];
1214        if let Ok(n) = source.read_at(0, &mut sample_buf) {
1215            if n > 0 {
1216                sample_buf.truncate(n);
1217                let small_cands = detect_small_format_candidates(
1218                    &sample_buf,
1219                    source.total_len(),
1220                    hint,
1221                );
1222                for sc in small_cands {
1223                    candidates.push(sc);
1224                }
1225                if let Some(custom_cand) =
1226                    detect_custom_text_format_candidate(&sample_buf, hint)
1227                {
1228                    candidates.push(custom_cand);
1229                }
1230            }
1231        }
1232    }
1233
1234    // 3. If extension hint is present, evaluate extension candidates
1235    if let Some(ext) = hint_ext {
1236        let ext_candidates = resolve_extension_candidates(ext, platform);
1237        for (fmt, ext_score) in ext_candidates {
1238            // Check if already found via magic
1239            if let Some(existing) =
1240                candidates.iter_mut().find(|c| c.format_id == Some(fmt))
1241            {
1242                let has_ext = existing
1243                    .evidence
1244                    .iter()
1245                    .any(|e| matches!(e, DetectionEvidence::Extension { .. }));
1246                if !has_ext {
1247                    existing.score = existing.score.saturating_add(25);
1248                    existing.evidence.push(DetectionEvidence::Extension {
1249                        ext: ext.to_string(),
1250                        is_primary: true,
1251                        score: 25,
1252                    });
1253                    if existing.score >= 85 {
1254                        existing.confidence = ConfidenceTier::HighestConfidence;
1255                    } else if existing.score >= 65 {
1256                        existing.confidence = ConfidenceTier::Strong;
1257                    }
1258                }
1259                continue;
1260            }
1261
1262            let mapping = FORMAT_CATALOG.lookup_ident(fmt.ident());
1263            let dc_id = mapping.map(|m| m.dc_id);
1264            // Reason for fallback: unmapped format identifier uses raw identifier name for candidate description
1265            let description = mapping
1266                .map_or_else(|| fmt.ident().to_string(), |m| m.label.clone());
1267            let mime = mapping.and_then(|m| m.mime_types.first().cloned());
1268
1269            let mut final_score = ext_score;
1270            let mut evidence = Vec::new();
1271            evidence.push(DetectionEvidence::Extension {
1272                ext: ext.to_string(),
1273                is_primary: true,
1274                score: ext_score,
1275            });
1276
1277            if let Some(exp_cat) = expected_cat {
1278                if fmt.category() == exp_cat {
1279                    final_score = final_score.saturating_add(20);
1280                    evidence.push(DetectionEvidence::CategoryMatch {
1281                        category: exp_cat,
1282                        score: 20,
1283                    });
1284                }
1285            }
1286
1287            // Corroborate extension-only candidates that imply a text encoding
1288            // with the encoding evidence gathered by the text-analysis phase,
1289            // so a specific format guaranteed to be, say, UTF-8 text outranks
1290            // the bare generic encoding candidate (the mechanism is general:
1291            // any format implying an encoding format is corroborated).
1292            if let Some(te) = &text_encoding_evidence {
1293                let implies_compatible_encoding =
1294                    fmt.implies().iter().any(|implied| {
1295                        implied.category() == FormatCategory::Encoding
1296                            && encoding_entailment_compatible(
1297                                te.detected,
1298                                *implied,
1299                            )
1300                    });
1301                if implies_compatible_encoding {
1302                    final_score = final_score.saturating_add(te.score);
1303                    evidence.extend(te.items.clone());
1304                }
1305            }
1306
1307            let confidence = if final_score >= 65 {
1308                ConfidenceTier::Moderate
1309            } else {
1310                ConfidenceTier::Weak
1311            };
1312
1313            candidates.push(DetectionCandidate {
1314                format_id: Some(fmt),
1315                dc_id,
1316                mime,
1317                description,
1318                confidence,
1319                score: final_score,
1320                evidence,
1321                chain_layers: None,
1322            });
1323        }
1324    }
1325
1326    // 4. Resolve candidate conflicts and subsumption hierarchies
1327    let mut resolved = resolve_candidate_conflicts(candidates);
1328    if let Some(h) = hint {
1329        if h.limit_to_categories {
1330            resolved.retain(|c| {
1331                // Reason for fallback: candidates lacking a format_id are excluded when restricting by category
1332                c.format_id
1333                    .is_some_and(|fid| h.allows_category(fid.category()))
1334            });
1335        }
1336    }
1337
1338    let stream_signals_used = hint.is_some_and(|h| {
1339        !h.stream_candidates.is_empty() || h.apple_type_code.is_some()
1340    });
1341
1342    let outcome = if let Some(err) = read_error {
1343        DetectionOutcome::ReadError {
1344            offset: 0,
1345            message: err,
1346        }
1347    } else if !resolved.is_empty() {
1348        DetectionOutcome::Matched(resolved.clone())
1349    } else if let Some(total) = source.total_len() {
1350        if total < 4 && hint.is_none() {
1351            DetectionOutcome::InsufficientData {
1352                available_bytes: total,
1353                required_bytes: 4,
1354            }
1355        } else {
1356            DetectionOutcome::TrueNegative {
1357                bytes_inspected: bytes_evaluated,
1358            }
1359        }
1360    } else {
1361        DetectionOutcome::TrueNegative {
1362            bytes_inspected: bytes_evaluated,
1363        }
1364    };
1365
1366    let file_origin = hint.and_then(|h| h.file_origin.clone());
1367
1368    Ok(DetectionReport {
1369        outcome,
1370        candidates: resolved,
1371        bytes_evaluated,
1372        stream_signals_used,
1373        file_origin,
1374    })
1375}
1376
1377/// Evaluates magic byte rules, extensions, and environment priors to produce
1378/// ranked format candidates.
1379pub fn guess_format_candidates(
1380    source: &mut dyn DetectionSource,
1381    hint: Option<&DetectionHint>,
1382) -> Vec<DetectionCandidate> {
1383    // Reason for fallback: best-effort format candidate discovery defaults to an empty candidate list if report generation fails
1384    guess_format_report(source, hint)
1385        .map(|rep| rep.candidates)
1386        .unwrap_or_default()
1387}
1388
1389/// Detects `FormatId` using magic byte signatures, extension matching, and category filtering.
1390pub fn guess_format_id(
1391    data: Option<&[u8]>,
1392    filename_or_ext: Option<&str>,
1393    expected_category: Option<FormatCategory>,
1394) -> Option<FormatId> {
1395    detect_format_id(data, filename_or_ext, expected_category)
1396}
1397
1398/// Backward-compatible detection function picking the top candidate's `FormatId`.
1399pub fn detect_format_id(
1400    data: Option<&[u8]>,
1401    filename_or_ext: Option<&str>,
1402    expected_category: Option<FormatCategory>,
1403) -> Option<FormatId> {
1404    let hint = filename_or_ext
1405        .map(|name| {
1406            let mut h = DetectionHint {
1407                filename: Some(name.to_string()),
1408                ..Default::default()
1409            };
1410            if let Some(cat) = expected_category {
1411                h = h.with_category(cat);
1412            }
1413            h
1414        })
1415        .or_else(|| expected_category.map(DetectionHint::for_category));
1416
1417    let candidates = if let Some(bytes) = data {
1418        let mut slice = bytes;
1419        guess_format_candidates(&mut slice, hint.as_ref())
1420    } else {
1421        let mut empty = EmptySource;
1422        guess_format_candidates(&mut empty, hint.as_ref())
1423    };
1424
1425    if let Some(cat) = expected_category {
1426        if let Some(fmt) = candidates
1427            .iter()
1428            .filter_map(|c| c.format_id)
1429            .find(|fmt| fmt.category() == cat)
1430        {
1431            return Some(fmt);
1432        }
1433    }
1434
1435    if let Some(non_enc) = candidates
1436        .iter()
1437        .filter_map(|c| c.format_id)
1438        .find(|fmt| fmt.category() != FormatCategory::Encoding)
1439    {
1440        return Some(non_enc);
1441    }
1442
1443    candidates.into_iter().find_map(|c| c.format_id)
1444}
1445
1446/// Detects `FormatId` restricting candidates strictly to the provided categories.
1447pub fn detect_format_id_in_categories(
1448    data: Option<&[u8]>,
1449    filename_or_ext: Option<&str>,
1450    categories: &[FormatCategory],
1451) -> Option<FormatId> {
1452    let hint = filename_or_ext
1453        .map(|name| {
1454            let h = DetectionHint {
1455                filename: Some(name.to_string()),
1456                ..Default::default()
1457            };
1458            h.with_categories(categories)
1459        })
1460        .or_else(|| Some(DetectionHint::for_categories(categories)));
1461
1462    let candidates = if let Some(bytes) = data {
1463        let mut slice = bytes;
1464        guess_format_candidates(&mut slice, hint.as_ref())
1465    } else {
1466        let mut empty = EmptySource;
1467        guess_format_candidates(&mut empty, hint.as_ref())
1468    };
1469
1470    if categories.contains(&FormatCategory::Document) {
1471        if let Some(doc_fmt) = candidates
1472            .iter()
1473            .filter_map(|c| c.format_id)
1474            .find(|fmt| fmt.category() == FormatCategory::Document)
1475        {
1476            return Some(doc_fmt);
1477        }
1478    }
1479
1480    candidates
1481        .into_iter()
1482        .filter_map(|c| c.format_id)
1483        .find(|fmt| categories.contains(&fmt.category()))
1484}
1485
1486struct PayloadSourceAdapter<'a>(&'a mut (dyn ctb_io_file::PayloadSource + 'a));
1487
1488impl DetectionSource for PayloadSourceAdapter<'_> {
1489    fn read_at(&mut self, offset: u64, buf: &mut [u8]) -> Result<usize> {
1490        use std::io::{Read, Seek, SeekFrom};
1491        self.0.seek(SeekFrom::Start(offset))?;
1492        let mut read_bytes = 0;
1493        while read_bytes < buf.len() {
1494            let Some(tail) = buf.get_mut(read_bytes..) else {
1495                break;
1496            };
1497            let n = self.0.read(tail)?;
1498            if n == 0 {
1499                break;
1500            }
1501            read_bytes = read_bytes.saturating_add(n);
1502        }
1503        Ok(read_bytes)
1504    }
1505
1506    fn total_len(&self) -> Option<u64> {
1507        Some(self.0.total_size())
1508    }
1509}
1510
1511/// Evaluates multiple detection signals for an `io/file` `File` (i.e.
1512/// `FileEntity`) and its payload, inspecting file identity, Apple Type codes,
1513pub fn detect_file_report(
1514    file: &File,
1515    payload: &mut dyn ctb_io_file::PayloadSource,
1516) -> Result<DetectionReport> {
1517    detect_file_report_with_hint(file, payload, None)
1518}
1519
1520/// Evaluates multiple detection signals for an `io/file` `File` with custom detection hint.
1521pub fn detect_file_report_with_hint(
1522    file: &File,
1523    payload: &mut dyn ctb_io_file::PayloadSource,
1524    user_hint: Option<&DetectionHint>,
1525) -> Result<DetectionReport> {
1526    let filename = file
1527        .identity
1528        .relative_path
1529        .as_deref()
1530        .and_then(|p| p.file_name())
1531        .and_then(|n| n.to_str());
1532
1533    // Infer platform prior from archive origin (strongest), Apple metadata,
1534    // or recorded environment.
1535    let origin_archive_os =
1536        if let FileOrigin::Archive { archive_format, .. } =
1537            &file.identity.origin
1538        {
1539            FORMAT_CATALOG
1540                .lookup_format_id(*archive_format)
1541                .and_then(|m| m.os_associations.first().copied())
1542        } else {
1543            None
1544        };
1545
1546    let env_platform = if file.metadata.apple.is_some() {
1547        Some(FormatId::MacOs)
1548    } else if let Some(env) = file.environment() {
1549        let lower_os = env.os.to_ascii_lowercase();
1550        if lower_os.contains("darwin")
1551            || lower_os.contains("macos")
1552            || env.looks_like_gnustep()
1553        {
1554            Some(FormatId::MacOs)
1555        } else if lower_os.contains("windows") {
1556            Some(FormatId::Windows)
1557        } else if lower_os.contains("linux") {
1558            Some(FormatId::GnuLinux)
1559        } else if lower_os.contains("bsd") || lower_os.contains("unix") {
1560            Some(FormatId::Unix)
1561        } else {
1562            current_platform_os()
1563        }
1564    } else {
1565        current_platform_os()
1566    };
1567
1568    let base_platform = origin_archive_os.or(env_platform);
1569
1570    // Extract Apple Type code from FinderInfo if present.
1571    let apple_type_code = file.metadata.apple.as_ref().and_then(|app| {
1572        app.finder_info.as_ref().and_then(|info| {
1573            let bytes = info.file_type.as_bytes();
1574            if bytes.len() == 4 && bytes != b"\0\0\0\0" && bytes != b"    " {
1575                let mut code = [0u8; 4];
1576                code.copy_from_slice(bytes);
1577                Some(code)
1578            } else {
1579                None
1580            }
1581        })
1582    });
1583
1584    // Inspect attached streams / forks as rich detection signals.
1585    let mut stream_candidates = Vec::new();
1586    let mut stream_platform = None;
1587    for stream in &file.streams {
1588        match stream.kind {
1589            ctb_io_file::StreamKind::MacOsResourceFork => {
1590                stream_platform = Some(FormatId::MacOs);
1591                if let Some(ref data) = stream.data {
1592                    let type_codes =
1593                        resource_fork::extract_resource_fork_type_codes(data);
1594                    for code in type_codes {
1595                        if let Some(mapping) =
1596                            FORMAT_CATALOG.lookup_apple_type_code(&code)
1597                        {
1598                            stream_candidates.push(DetectionCandidate {
1599                                format_id: mapping.format_id,
1600                                dc_id: Some(mapping.dc_id),
1601                                mime: mapping.mime_types.first().cloned(),
1602                                description: mapping.label.clone(),
1603                                confidence: ConfidenceTier::HighestConfidence,
1604                                score: 95,
1605                                evidence: vec![
1606                                    DetectionEvidence::AttachedStream {
1607                                        stream_kind_name: "MacOsResourceFork"
1608                                            .to_string(),
1609                                        detail: format!(
1610                                            "Resource fork type code '{}'",
1611                                            String::from_utf8_lossy(&code)
1612                                        ),
1613                                        score: 95,
1614                                    },
1615                                ],
1616                                chain_layers: None,
1617                            });
1618                        }
1619                    }
1620                }
1621            }
1622            ctb_io_file::StreamKind::NtfsAlternateDataStream => {
1623                stream_platform = Some(FormatId::Windows);
1624                if let Some(ref name) = stream.name {
1625                    let name_lossy = name.to_string_lossy();
1626                    if name_lossy.contains("Zone.Identifier") {
1627                        stream_candidates.push(DetectionCandidate {
1628                            format_id: None,
1629                            dc_id: None,
1630                            mime: None,
1631                            description:
1632                                "Windows Internet Zone Transfer Identifier"
1633                                    .to_string(),
1634                            confidence: ConfidenceTier::Moderate,
1635                            score: 40,
1636                            evidence: vec![DetectionEvidence::AttachedStream {
1637                                stream_kind_name: "NtfsAlternateDataStream"
1638                                    .to_string(),
1639                                detail: "Zone.Identifier".to_string(),
1640                                score: 40,
1641                            }],
1642                            chain_layers: None,
1643                        });
1644                    }
1645                }
1646            }
1647            ctb_io_file::StreamKind::ExtendedAttribute => {
1648                if let Some(ref name) = stream.name {
1649                    let name_lossy = name.to_string_lossy();
1650                    if name_lossy == "user.mime_type"
1651                        || name_lossy == "xdg.mime.type"
1652                    {
1653                        if let Some(ref data) = stream.data {
1654                            if let Ok(mime_str) = std::str::from_utf8(data) {
1655                                let clean_mime =
1656                                    mime_str.trim().trim_matches('\0');
1657                                if let Some(mapping) =
1658                                    FORMAT_CATALOG.lookup_mime(clean_mime)
1659                                {
1660                                    stream_candidates.push(DetectionCandidate {
1661                                        format_id: mapping.format_id,
1662                                        dc_id: Some(mapping.dc_id),
1663                                        mime: Some(clean_mime.to_string()),
1664                                        description: mapping.label.clone(),
1665                                        confidence: ConfidenceTier::Strong,
1666                                        score: 85,
1667                                        evidence: vec![DetectionEvidence::AttachedStream {
1668                                            stream_kind_name: "ExtendedAttribute".to_string(),
1669                                            detail: format!(
1670                                                "Explicit xattr MIME '{clean_mime}'"
1671                                            ),
1672                                            score: 85,
1673                                        }],
1674                                        chain_layers: None,
1675                                    });
1676                                }
1677                            }
1678                        }
1679                    }
1680                }
1681            }
1682            _ => {}
1683        }
1684    }
1685
1686    let effective_platform = stream_platform.or(base_platform);
1687
1688    let special_kind = match &file.kind {
1689        FileEntityKind::Directory => Some("directory".to_string()),
1690        FileEntityKind::Symlink { .. } => Some("symlink".to_string()),
1691        FileEntityKind::Fifo => Some("fifo".to_string()),
1692        FileEntityKind::CharDevice { .. } => Some("char".to_string()),
1693        FileEntityKind::BlockDevice { .. } => Some("block".to_string()),
1694        FileEntityKind::Socket => Some("socket".to_string()),
1695        _ => None,
1696    };
1697
1698    let mut hint = DetectionHint {
1699        filename: filename.map(std::string::ToString::to_string),
1700        extension: None,
1701        platform: effective_platform,
1702        expected_category: None,
1703        apple_type_code,
1704        stream_candidates,
1705        special_kind,
1706        file_origin: Some(file.identity.origin.clone()),
1707        file_mode: file
1708            .metadata
1709            .mode
1710            .or_else(|| user_hint.and_then(|h| h.file_mode)),
1711        ..Default::default()
1712    };
1713    if let Some(user_h) = user_hint {
1714        hint.compat = user_h.compat;
1715        hint.uncompress = user_h.uncompress;
1716        hint.uncompress_noreport = user_h.uncompress_noreport;
1717        hint.decompress_byte_limit = user_h.decompress_byte_limit;
1718        hint.max_decompression_depth = user_h.max_decompression_depth;
1719        hint.recursion_depth = user_h.recursion_depth;
1720        if user_h.expected_category.is_some() {
1721            hint.expected_category = user_h.expected_category;
1722            hint.expected_categories = user_h.expected_categories.clone();
1723            hint.limit_to_categories = user_h.limit_to_categories;
1724        }
1725    }
1726
1727    // For directory bundles (e.g. .app, .framework), bundle inspection hooks can probe interior payloads.
1728    if let FileEntityKind::Directory = file.kind {
1729        if let Some(name) = filename {
1730            if name.ends_with(".app")
1731                || name.ends_with(".framework")
1732                || name.ends_with(".bundle")
1733            {
1734                let candidate = DetectionCandidate {
1735                    format_id: None,
1736                    dc_id: None,
1737                    mime: Some("application/x-apple-application".to_string()),
1738                    description: "macOS Application Bundle".to_string(),
1739                    confidence: ConfidenceTier::Strong,
1740                    score: 75,
1741                    evidence: vec![DetectionEvidence::Extension {
1742                        ext: "app".to_string(),
1743                        is_primary: true,
1744                        score: 75,
1745                    }],
1746                    chain_layers: None,
1747                };
1748                return Ok(DetectionReport {
1749                    outcome: DetectionOutcome::Matched(vec![candidate.clone()]),
1750                    candidates: vec![candidate],
1751                    bytes_evaluated: 0,
1752                    stream_signals_used: false,
1753                    file_origin: Some(file.identity.origin.clone()),
1754                });
1755            }
1756        }
1757    }
1758
1759    let mut adapter = PayloadSourceAdapter(payload);
1760    guess_format_report(&mut adapter, Some(&hint))
1761}
1762
1763/// Evaluates multiple detection signals for an `io/file` `File` and produces
1764/// the top matching `FormatId`, optionally restricted to a specific category.
1765pub fn detect_file_format(
1766    file: &File,
1767    payload: &mut dyn ctb_io_file::PayloadSource,
1768    expected_category: Option<FormatCategory>,
1769) -> Option<FormatId> {
1770    let report = detect_file_report(file, payload).ok()?;
1771    if let Some(cat) = expected_category {
1772        report
1773            .candidates
1774            .into_iter()
1775            .find_map(|c| c.format_id.filter(|fid| fid.category() == cat))
1776    } else {
1777        report.candidates.into_iter().find_map(|c| c.format_id)
1778    }
1779}
1780
1781/// Guesses format candidates and generates a detection report for a filesystem
1782/// path.
1783///
1784/// # Examples
1785///
1786/// ```rust,no_run
1787/// use ctb_formats_detection::{guess_and_report_path, FormatId, OsPath};
1788///
1789/// # fn main() -> anyhow::Result<()> {
1790/// let dir = tempfile::tempdir()?;
1791/// let path: OsPath = dir.path().join("archive.tar.gz");
1792/// std::fs::write(&path, [0x1F, 0x8B, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00])?;
1793///
1794/// let report = guess_and_report_path(&path)?;
1795/// assert_eq!(report.candidates[0].format_id, Some(FormatId::Gzip));
1796/// # Ok(())
1797/// # }
1798/// ```
1799pub fn guess_and_report_path(
1800    path: impl AsRef<std::path::Path>,
1801) -> Result<DetectionReport> {
1802    guess_and_report_path_with_hint(path, None)
1803}
1804
1805/// Guesses format candidates and generates a detection report for a filesystem
1806/// path with custom detection hint.
1807pub fn guess_and_report_path_with_hint(
1808    path: impl AsRef<std::path::Path>,
1809    hint: Option<&DetectionHint>,
1810) -> Result<DetectionReport> {
1811    let p = path.as_ref();
1812    let file = File::from_filesystem(p, None)?;
1813    if file.kind.entity_type() == FileEntityType::Regular {
1814        let mut source = DiskPayloadSource::open(p)?;
1815        detect_file_report_with_hint(&file, &mut source, hint)
1816    } else {
1817        let mut source = MemoryPayloadSource::new(Vec::new())?;
1818        detect_file_report_with_hint(&file, &mut source, hint)
1819    }
1820}
1821
1822/// Guesses the authoritative format for a given filesystem path.
1823///
1824/// # Examples
1825///
1826/// ```rust,no_run
1827/// use ctb_formats_detection::{guess_path, FormatId, OsPath};
1828///
1829/// # fn main() -> anyhow::Result<()> {
1830/// let dir = tempfile::tempdir()?;
1831/// let path: OsPath = dir.path().join("archive.tar.gz");
1832/// std::fs::write(&path, [0x1F, 0x8B, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00])?;
1833///
1834/// let format = guess_path(&path)?;
1835/// assert_eq!(format, FormatId::Gzip);
1836/// # Ok(())
1837/// # }
1838/// ```
1839pub fn guess_path(path: impl AsRef<std::path::Path>) -> Result<FormatId> {
1840    let p = path.as_ref();
1841    let report = guess_and_report_path(p)?;
1842    report
1843        .candidates
1844        .into_iter()
1845        .find_map(|c| c.format_id)
1846        .ok_or_else(|| {
1847            anyhow::anyhow!(
1848                "No matching file format detected for path '{}'",
1849                p.display()
1850            )
1851        })
1852}
1853
1854/// Guesses format candidates and generates a detection report from a String.
1855/// The report populates `file_origin` as `FileOrigin::Synthetic`.
1856///
1857/// # Examples
1858///
1859/// ```
1860/// use ctb_formats_detection::{guess_and_report_string, FormatId};
1861///
1862/// # fn main() -> anyhow::Result<()> {
1863/// let html = "<!DOCTYPE html><html><body><h1>Header</h1></body></html>";
1864/// let report = guess_and_report_string(html)?;
1865/// assert_eq!(report.candidates[0].format_id, Some(FormatId::Html));
1866/// # Ok(())
1867/// # }
1868/// ```
1869pub fn guess_and_report_string(
1870    content: impl Into<String>,
1871) -> Result<DetectionReport> {
1872    let s = content.into();
1873    let bytes = s.into_bytes();
1874    let file = File::from_vec(bytes.clone());
1875    let mut source = MemoryPayloadSource::new(bytes)?;
1876    detect_file_report(&file, &mut source)
1877}
1878
1879/// Guesses the authoritative format for a given String content.
1880///
1881/// # Examples
1882///
1883/// ```
1884/// use ctb_formats_detection::{guess_string, FormatId};
1885///
1886/// # fn main() -> anyhow::Result<()> {
1887/// let html = "<!DOCTYPE html><html><body><h1>Header</h1></body></html>";
1888/// let format = guess_string(html)?;
1889/// assert_eq!(format, FormatId::Html);
1890/// # Ok(())
1891/// # }
1892/// ```
1893pub fn guess_string(content: impl Into<String>) -> Result<FormatId> {
1894    let report = guess_and_report_string(content)?;
1895    report
1896        .candidates
1897        .into_iter()
1898        .find_map(|c| c.format_id)
1899        .ok_or_else(|| {
1900            anyhow::anyhow!("No matching file format detected for string")
1901        })
1902}
1903
1904/// Guesses format candidates and generates a detection report from a
1905/// `DcString`.
1906/// The report populates `file_origin` as `FileOrigin::Synthetic`.
1907///
1908/// # Examples
1909///
1910/// ```
1911/// use ctb_formats_detection::{guess_and_report_dcs, DcString, FormatId};
1912///
1913/// # fn main() -> anyhow::Result<()> {
1914/// let dcs = DcString::from_dcutf(
1915///     b"<!DOCTYPE html><html><body>Test</body></html>".to_vec(),
1916/// )?;
1917/// let report = guess_and_report_dcs(&dcs)?;
1918/// assert_eq!(report.candidates[0].format_id, Some(FormatId::Html));
1919/// # Ok(())
1920/// # }
1921/// ```
1922pub fn guess_and_report_dcs(
1923    dcs: impl std::borrow::Borrow<ctb_formats_dcstring::DcString>,
1924) -> Result<DetectionReport> {
1925    let bytes = dcs.borrow().as_bytes().to_vec();
1926    let file = File::from_vec(bytes.clone());
1927    let mut source = MemoryPayloadSource::new(bytes)?;
1928    detect_file_report(&file, &mut source)
1929}
1930
1931/// Guesses the authoritative format for a given `DcString`.
1932///
1933/// # Examples
1934///
1935/// ```
1936/// use ctb_formats_detection::{guess_dcs, DcString, FormatId};
1937///
1938/// # fn main() -> anyhow::Result<()> {
1939/// let dcs = DcString::from_dcutf(
1940///     b"<!DOCTYPE html><html><body>Test</body></html>".to_vec(),
1941/// )?;
1942/// let format = guess_dcs(&dcs)?;
1943/// assert_eq!(format, FormatId::Html);
1944/// # Ok(())
1945/// # }
1946/// ```
1947pub fn guess_dcs(
1948    dcs: impl std::borrow::Borrow<ctb_formats_dcstring::DcString>,
1949) -> Result<FormatId> {
1950    let report = guess_and_report_dcs(dcs)?;
1951    report
1952        .candidates
1953        .into_iter()
1954        .find_map(|c| c.format_id)
1955        .ok_or_else(|| {
1956            anyhow::anyhow!("No matching file format detected for DcString")
1957        })
1958}
1959
1960/// Guesses format candidates and generates a detection report from raw bytes.
1961/// The report populates `file_origin` as `FileOrigin::Synthetic`.
1962///
1963/// # Examples
1964///
1965/// ```
1966/// use ctb_formats_detection::{guess_and_report_vec, FormatId};
1967///
1968/// # fn main() -> anyhow::Result<()> {
1969/// let gz_bytes = vec![0x1F, 0x8B, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00];
1970/// let report = guess_and_report_vec(gz_bytes)?;
1971/// assert_eq!(report.candidates[0].format_id, Some(FormatId::Gzip));
1972/// # Ok(())
1973/// # }
1974/// ```
1975pub fn guess_and_report_vec(bytes: Vec<u8>) -> Result<DetectionReport> {
1976    guess_and_report_vec_with_hint(bytes, None)
1977}
1978
1979/// Guesses format candidates and generates a detection report from raw bytes with custom hint.
1980pub fn guess_and_report_vec_with_hint(
1981    bytes: Vec<u8>,
1982    hint: Option<&DetectionHint>,
1983) -> Result<DetectionReport> {
1984    let file = File::from_vec(bytes.clone());
1985    let mut source = MemoryPayloadSource::new(bytes)?;
1986    detect_file_report_with_hint(&file, &mut source, hint)
1987}
1988
1989/// Guesses the authoritative format for raw bytes.
1990///
1991/// # Examples
1992///
1993/// ```
1994/// use ctb_formats_detection::{guess_vec, FormatId};
1995///
1996/// # fn main() -> anyhow::Result<()> {
1997/// let gz_bytes = vec![0x1F, 0x8B, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00];
1998/// let format = guess_vec(gz_bytes)?;
1999/// assert_eq!(format, FormatId::Gzip);
2000/// # Ok(())
2001/// # }
2002/// ```
2003pub fn guess_vec(bytes: Vec<u8>) -> Result<FormatId> {
2004    let report = guess_and_report_vec(bytes)?;
2005    report
2006        .candidates
2007        .into_iter()
2008        .find_map(|c| c.format_id)
2009        .ok_or_else(|| {
2010            anyhow::anyhow!("No matching file format detected for byte vector")
2011        })
2012}
2013
2014/// Guesses format candidates and generates a detection report directly from an
2015/// `io/file` `File`.
2016///
2017/// # Examples
2018///
2019/// ```rust,no_run
2020/// use ctb_formats_detection::{guess_and_report_file, File, FormatId};
2021///
2022/// # fn main() -> anyhow::Result<()> {
2023/// let dir = tempfile::tempdir()?;
2024/// let path = dir.path().join("archive.tar.gz");
2025/// let gz_header = [0x1F, 0x8B, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00];
2026/// std::fs::write(&path, gz_header)?;
2027///
2028/// let file = File::from_filesystem(&path, None)?;
2029/// let report = guess_and_report_file(&file)?;
2030/// assert_eq!(report.candidates[0].format_id, Some(FormatId::Gzip));
2031/// # Ok(())
2032/// # }
2033/// ```
2034pub fn guess_and_report_file(file: &File) -> Result<DetectionReport> {
2035    if let FileOrigin::Filesystem { canonical_path, .. } = &file.identity.origin
2036    {
2037        if file.kind.entity_type() == FileEntityType::Regular {
2038            let mut source = DiskPayloadSource::open(canonical_path)?;
2039            detect_file_report(file, &mut source)
2040        } else {
2041            let mut source = MemoryPayloadSource::new(Vec::new())?;
2042            detect_file_report(file, &mut source)
2043        }
2044    } else {
2045        let mut source = MemoryPayloadSource::new(Vec::new())?;
2046        detect_file_report(file, &mut source)
2047    }
2048}
2049
2050/// Guesses the authoritative format directly from an `io/file` `File`.
2051///
2052/// # Examples
2053///
2054/// ```rust,no_run
2055/// use ctb_formats_detection::{guess_file, File, FormatId};
2056///
2057/// # fn main() -> anyhow::Result<()> {
2058/// let dir = tempfile::tempdir()?;
2059/// let path = dir.path().join("archive.tar.gz");
2060/// let gz_header = [0x1F, 0x8B, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00];
2061/// std::fs::write(&path, gz_header)?;
2062///
2063/// let file = File::from_filesystem(&path, None)?;
2064/// let format = guess_file(&file)?;
2065/// assert_eq!(format, FormatId::Gzip);
2066/// # Ok(())
2067/// # }
2068/// ```
2069pub fn guess_file(file: &File) -> Result<FormatId> {
2070    let report = guess_and_report_file(file)?;
2071    report
2072        .candidates
2073        .into_iter()
2074        .find_map(|c| c.format_id)
2075        .ok_or_else(|| {
2076            anyhow::anyhow!("No matching file format detected for FileEntity")
2077        })
2078}
2079
2080#[cfg(test)]
2081#[allow(
2082    clippy::panic,
2083    clippy::expect_used,
2084    clippy::unwrap_used,
2085    clippy::unwrap_in_result,
2086    clippy::panic_in_result_fn,
2087    clippy::indexing_slicing,
2088    clippy::arithmetic_side_effects,
2089    reason = "Standard repository test boilerplate"
2090)]
2091mod tests {
2092    use super::*;
2093
2094    #[ctb_test]
2095    fn test_detection_assets_loading_from_asset_bundle() {
2096        let ctb_magic = magic_data::get_ctb_magic_content();
2097        assert!(
2098            ctb_magic.is_some(),
2099            "Expected magic/ctoolbox.magic to be accessible"
2100        );
2101
2102        let droid_sig = droid::get_droid_signature_xml();
2103        assert!(
2104            droid_sig.is_some(),
2105            "Expected DROID signature XML to be accessible"
2106        );
2107
2108        let container_sig = droid::get_droid_container_signature_xml();
2109        assert!(
2110            container_sig.is_some(),
2111            "Expected DROID container signature XML to be accessible"
2112        );
2113
2114        let magdir_files = magic_data::get_magdir_files();
2115        assert!(
2116            !magdir_files.is_empty(),
2117            "Expected Magdir files to be loaded from asset bundle"
2118        );
2119    }
2120
2121    #[ctb_test]
2122    fn test_detect_format_id() {
2123        let gzip_data = [0x1F, 0x8B, 0x08, 0x00];
2124        let fmt = detect_format_id(
2125            Some(&gzip_data),
2126            Some("doc.gz"),
2127            Some(FormatCategory::Compression),
2128        );
2129        assert_eq!(fmt, Some(FormatId::Gzip));
2130    }
2131
2132    #[ctb_test]
2133    fn test_guess_format_candidates() {
2134        let gzip_data = [0x1F, 0x8B, 0x08, 0x00];
2135        let mut slice: &[u8] = &gzip_data;
2136        let hint = DetectionHint {
2137            filename: Some("archive.gz".to_string()),
2138            ..Default::default()
2139        };
2140        let candidates = guess_format_candidates(&mut slice, Some(&hint));
2141        assert!(!candidates.is_empty());
2142        let top = &candidates[0];
2143        assert_eq!(top.format_id, Some(FormatId::Gzip));
2144        assert_eq!(top.confidence, ConfidenceTier::HighestConfidence);
2145    }
2146
2147    #[ctb_test]
2148    fn test_detect_brotli() {
2149        let brotli_data = [
2150            143, 5, 128, 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100,
2151            10, 3,
2152        ];
2153        let _slice: &[u8] = &brotli_data;
2154        let _hint = DetectionHint {
2155            filename: Some("/tmp/system_in.br".to_string()),
2156            expected_category: Some(FormatCategory::Compression),
2157            ..Default::default()
2158        };
2159        let fmt = detect_format_id(
2160            Some(&brotli_data),
2161            Some("/tmp/system_in.br"),
2162            Some(FormatCategory::Compression),
2163        );
2164        assert_eq!(fmt, Some(FormatId::Brotli));
2165    }
2166
2167    #[ctb_test]
2168    fn test_detection_report_outcomes() {
2169        // Insufficient data
2170        let empty_data: [u8; 0] = [];
2171        let mut empty_slice: &[u8] = &empty_data;
2172        let report_insufficient =
2173            guess_format_report(&mut empty_slice, None).unwrap();
2174        assert!(matches!(
2175            report_insufficient.outcome,
2176            DetectionOutcome::InsufficientData {
2177                available_bytes: 0,
2178                required_bytes: 4
2179            }
2180        ));
2181
2182        // True negative (random non-matching bytes with no hint)
2183        let random_data = [0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF];
2184        let mut rand_slice: &[u8] = &random_data;
2185        let report_neg = guess_format_report(&mut rand_slice, None).unwrap();
2186        assert!(
2187            matches!(report_neg.outcome, DetectionOutcome::TrueNegative { .. }),
2188            "Expected TrueNegative, got: {:?}",
2189            report_neg.outcome
2190        );
2191
2192        // Matched
2193        let gzip_data = [0x1F, 0x8B, 0x08, 0x00];
2194        let mut gz_slice: &[u8] = &gzip_data;
2195        let report_matched = guess_format_report(&mut gz_slice, None).unwrap();
2196        assert!(matches!(
2197            report_matched.outcome,
2198            DetectionOutcome::Matched(_)
2199        ));
2200        assert_eq!(
2201            report_matched.candidates[0].format_id,
2202            Some(FormatId::Gzip)
2203        );
2204    }
2205
2206    #[ctb_test]
2207    fn test_detection_with_stream_and_apple_type_hint() {
2208        let empty_data: [u8; 0] = [];
2209        let mut empty_slice: &[u8] = &empty_data;
2210        let hint = DetectionHint {
2211            apple_type_code: Some(*b"TEXT"),
2212            stream_candidates: vec![DetectionCandidate {
2213                format_id: Some(FormatId::Ascii),
2214                dc_id: None,
2215                mime: Some("text/plain".to_string()),
2216                description: "Mac resource fork plain text".to_string(),
2217                confidence: ConfidenceTier::Strong,
2218                score: 75,
2219                evidence: vec![DetectionEvidence::AttachedStream {
2220                    stream_kind_name: "MacResourceFork".to_string(),
2221                    detail: "Resource type TEXT".to_string(),
2222                    score: 75,
2223                }],
2224                chain_layers: None,
2225            }],
2226            ..Default::default()
2227        };
2228
2229        let report =
2230            guess_format_report(&mut empty_slice, Some(&hint)).unwrap();
2231        assert!(report.stream_signals_used);
2232        assert!(matches!(report.outcome, DetectionOutcome::Matched(_)));
2233        assert_eq!(report.candidates[0].format_id, Some(FormatId::Ascii));
2234    }
2235
2236    #[ctb_test]
2237    fn test_detect_plain_text_report() {
2238        let text_data = b"Hello, world! This is a plain ASCII text file.\nWith standard LF lines.\n";
2239        let mut slice: &[u8] = text_data;
2240        let report = guess_format_report(&mut slice, None).unwrap();
2241        assert!(matches!(report.outcome, DetectionOutcome::Matched(_)));
2242        assert!(!report.candidates.is_empty());
2243        let top = &report.candidates[0];
2244        assert_eq!(top.format_id, Some(FormatId::Ascii));
2245        assert!(
2246            top.evidence
2247                .iter()
2248                .any(|e| matches!(e, DetectionEvidence::Encoding { .. }))
2249        );
2250        assert!(
2251            top.evidence
2252                .iter()
2253                .any(|e| matches!(e, DetectionEvidence::TextProperties { .. }))
2254        );
2255    }
2256
2257    #[ctb_test]
2258    fn test_detect_c_source() {
2259        let c_data = b"#include <stdio.h>\n\nint main(void) {\n    printf(\"hello\\n\");\n    return 0;\n}\n";
2260        let mut slice: &[u8] = c_data;
2261        let report = guess_format_report(&mut slice, None).unwrap();
2262        assert!(matches!(report.outcome, DetectionOutcome::Matched(_)));
2263        let top = &report.candidates[0];
2264        assert_eq!(top.format_id, Some(FormatId::C));
2265        assert_eq!(top.mime.as_deref(), Some("text/x-c"));
2266    }
2267
2268    #[ctb_test]
2269    fn test_detect_python_shebang() {
2270        let py_data =
2271            b"#!/usr/bin/env python3\nimport os\nprint(os.getpid())\n";
2272        let mut slice: &[u8] = py_data;
2273        let report = guess_format_report(&mut slice, None).unwrap();
2274        assert!(matches!(report.outcome, DetectionOutcome::Matched(_)));
2275        let top = &report.candidates[0];
2276        assert_eq!(top.mime.as_deref(), Some("text/x-python"));
2277        assert!(top.description.contains("Python script"));
2278    }
2279
2280    #[ctb_test]
2281    fn test_detect_html_document() {
2282        let html_data = b"<!DOCTYPE html>\n<html><head><title>Test</title></head><body><h1>Hello</h1></body></html>";
2283        let mut slice: &[u8] = html_data;
2284        let report = guess_format_report(&mut slice, None).unwrap();
2285        assert!(matches!(report.outcome, DetectionOutcome::Matched(_)));
2286        let top = &report.candidates[0];
2287        assert_eq!(top.format_id, Some(FormatId::Html));
2288        assert_eq!(top.mime.as_deref(), Some("text/html"));
2289    }
2290
2291    #[ctb_test]
2292    fn test_detect_convenience_string() {
2293        let html = "<!DOCTYPE html>\n<html><head><title>Test</title></head><body><h1>Hello</h1></body></html>";
2294        let report = guess_and_report_string(html).unwrap();
2295        assert_eq!(report.file_origin, Some(FileOrigin::Synthetic));
2296        assert!(matches!(report.outcome, DetectionOutcome::Matched(_)));
2297        assert_eq!(report.candidates[0].format_id, Some(FormatId::Html));
2298
2299        let fmt = guess_string(html).unwrap();
2300        assert_eq!(fmt, FormatId::Html);
2301    }
2302
2303    #[ctb_test]
2304    fn test_detect_convenience_dcs() {
2305        let dcs = ctb_formats_dcstring::DcString::from_dcutf(
2306            b"<!DOCTYPE html>\n<html><body>test</body></html>".to_vec(),
2307        )
2308        .unwrap();
2309        let report = guess_and_report_dcs(&dcs).unwrap();
2310        assert_eq!(report.file_origin, Some(FileOrigin::Synthetic));
2311        assert_eq!(report.candidates[0].format_id, Some(FormatId::Html));
2312
2313        let fmt = guess_dcs(&dcs).unwrap();
2314        assert_eq!(fmt, FormatId::Html);
2315    }
2316
2317    #[ctb_test]
2318    fn test_detect_convenience_vec() {
2319        let gz_header = vec![0x1F, 0x8B, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00];
2320        let report = guess_and_report_vec(gz_header.clone()).unwrap();
2321        assert_eq!(report.file_origin, Some(FileOrigin::Synthetic));
2322        assert_eq!(report.candidates[0].format_id, Some(FormatId::Gzip));
2323
2324        let fmt = guess_vec(gz_header).unwrap();
2325        assert_eq!(fmt, FormatId::Gzip);
2326    }
2327
2328    #[ctb_test]
2329    fn test_detect_convenience_path() {
2330        let temp = tempfile::tempdir().unwrap();
2331        let gz_path = temp.path().join("archive.tar.gz");
2332        let gz_header = [0x1F, 0x8B, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00];
2333        std::fs::write(&gz_path, gz_header).unwrap();
2334
2335        let report = guess_and_report_path(&gz_path).unwrap();
2336        assert!(matches!(
2337            report.file_origin,
2338            Some(FileOrigin::Filesystem { .. })
2339        ));
2340        assert_eq!(report.candidates[0].format_id, Some(FormatId::Gzip));
2341
2342        let fmt = guess_path(&gz_path).unwrap();
2343        assert_eq!(fmt, FormatId::Gzip);
2344    }
2345
2346    #[ctb_test]
2347    fn test_detect_convenience_file() {
2348        let temp = tempfile::tempdir().unwrap();
2349        let gz_path = temp.path().join("archive.tar.gz");
2350        let gz_header = [0x1F, 0x8B, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00];
2351        std::fs::write(&gz_path, gz_header).unwrap();
2352
2353        let file = File::from_filesystem(&gz_path, None).unwrap();
2354        let report = guess_and_report_file(&file).unwrap();
2355        assert!(matches!(
2356            report.file_origin,
2357            Some(FileOrigin::Filesystem { .. })
2358        ));
2359        assert_eq!(report.candidates[0].format_id, Some(FormatId::Gzip));
2360
2361        let fmt = guess_file(&file).unwrap();
2362        assert_eq!(fmt, FormatId::Gzip);
2363
2364        // Also test synthetic file
2365        let syn_file = File::from_vec(gz_header.to_vec());
2366        let mut syn_source =
2367            MemoryPayloadSource::new(gz_header.to_vec()).unwrap();
2368        let syn_report =
2369            detect_file_report(&syn_file, &mut syn_source).unwrap();
2370        assert_eq!(syn_report.file_origin, Some(FileOrigin::Synthetic));
2371        assert_eq!(syn_report.candidates[0].format_id, Some(FormatId::Gzip));
2372    }
2373
2374    #[ctb_test]
2375    fn test_file_entity_detect_format_report_with_resource_fork() {
2376        let temp = tempfile::tempdir().unwrap();
2377        let empty_path = temp.path().join("mac_sound");
2378        std::fs::write(&empty_path, []).unwrap();
2379
2380        let mut entity = File::from_filesystem(&empty_path, None).unwrap();
2381
2382        // Construct mock resource fork with 'alis' OSType (MacAlias)
2383        let mut fork = vec![0u8; 100];
2384        fork[0..4].copy_from_slice(&256u32.to_be_bytes());
2385        fork[4..8].copy_from_slice(&16u32.to_be_bytes());
2386        fork[8..12].copy_from_slice(&0u32.to_be_bytes());
2387        fork[12..16].copy_from_slice(&60u32.to_be_bytes());
2388        fork[40..42].copy_from_slice(&28u16.to_be_bytes());
2389        fork[44..46].copy_from_slice(&0u16.to_be_bytes()); // 1 type
2390        fork[46..50].copy_from_slice(b"alis");
2391
2392        let stream_entity = entity.clone();
2393        entity.streams.push(ctb_io_file::AttachedStream {
2394            name: None,
2395            kind: ctb_io_file::StreamKind::MacOsResourceFork,
2396            entity: Box::new(stream_entity),
2397            data: Some(fork),
2398            payload: None,
2399        });
2400
2401        let mut source = DiskPayloadSource::open(&empty_path).unwrap();
2402        let report = detect_file_report(&entity, &mut source).unwrap();
2403
2404        assert!(report.stream_signals_used);
2405        assert!(!report.candidates.is_empty());
2406        assert_eq!(report.candidates[0].format_id, Some(FormatId::MacAlias));
2407    }
2408
2409    fn csc_journal_v4_bytes() -> Vec<u8> {
2410        let mut data = Vec::new();
2411        data.extend_from_slice(b"CTBCSCJ\x04");
2412        data.extend_from_slice(
2413            b"\x00\x01\x02\x03 synthetic journal payload for detection",
2414        );
2415        data
2416    }
2417
2418    #[crate::ctb_test]
2419    fn test_csc_archive_magic_is_distinct_from_journal() {
2420        for filename in ["backup.cscarchive", "backup.cscjournal", "backup"] {
2421            let mut data: &[u8] = b"CTBCSCA\x01 synthetic archive payload";
2422            let hint = DetectionHint {
2423                filename: Some(filename.to_owned()),
2424                ..Default::default()
2425            };
2426            let report = guess_format_report(&mut data, Some(&hint)).unwrap();
2427            assert_eq!(
2428                report.candidates[0].format_id,
2429                Some(FormatId::CscArchive1)
2430            );
2431        }
2432    }
2433
2434    #[ctb_test]
2435    fn test_csc_journal_v4_magic_resolves_version() {
2436        let data = csc_journal_v4_bytes();
2437        let mut slice: &[u8] = &data;
2438        let hint = DetectionHint {
2439            filename: Some("journal.cscjournal".to_string()),
2440            ..Default::default()
2441        };
2442        let report = guess_format_report(&mut slice, Some(&hint)).unwrap();
2443        assert_eq!(report.candidates[0].format_id, Some(FormatId::CscJournal4));
2444        assert_eq!(
2445            report.candidates[0].description,
2446            "Collective Toolbox csc journal, version 4"
2447        );
2448    }
2449
2450    #[ctb_test]
2451    fn test_csc_journal_v1_magic_resolves_generic() {
2452        let mut data = Vec::new();
2453        data.extend_from_slice(b"CTBCSCJ\x01");
2454        data.extend_from_slice(
2455            b"\x00\x01\x02\x03 synthetic journal payload for detection",
2456        );
2457        let mut slice: &[u8] = &data;
2458        let hint = DetectionHint {
2459            filename: Some("journal.cscjournal".to_string()),
2460            ..Default::default()
2461        };
2462        let report = guess_format_report(&mut slice, Some(&hint)).unwrap();
2463        assert_eq!(report.candidates[0].format_id, Some(FormatId::CscJournal));
2464    }
2465
2466    #[ctb_test]
2467    fn test_ctb_asset_bundle_and_packaged_node_magic_detection() {
2468        for (magic, expected_fmt) in [
2469            (
2470                &b"CTBRSRC\0\x01\0\0\0\0\0\0\0"[..],
2471                FormatId::CtbAssetBundleV1,
2472            ),
2473            (
2474                &b"CTBRSRC\0\x02\0\0\0\0\0\0\0"[..],
2475                FormatId::CtbAssetBundleV2,
2476            ),
2477            (
2478                &b"CTBRSRC\0\x03\0\0\0\0\0\0\0"[..],
2479                FormatId::CtbAssetBundleV3,
2480            ),
2481            (
2482                &b"CTBRSRC\0\x04\0\0\0\0\0\0\0"[..],
2483                FormatId::CtbAssetBundleV4,
2484            ),
2485            (&b"CTBNODE\0\x01\0\0\0\0"[..], FormatId::CtbNodeV1),
2486            (&b"CTBNODE\0\x02\0\0\0\0"[..], FormatId::CtbNodeV2),
2487            (&b"CTBNODE\0\x03\0\0\0\0"[..], FormatId::CtbNodeV3),
2488            (&b"BZ0123456789"[..], FormatId::Bzip),
2489            (&b"LRZI\x00\x06\x00\x00"[..], FormatId::Lrzip),
2490            (&b"BZ3v1\x00\x10\x00\x00"[..], FormatId::Bzip3),
2491            (&b"bvx2\x00\x00\x00\x00"[..], FormatId::Lzfse),
2492            (&b"zPQ\x01\x00\x00"[..], FormatId::Zpaq),
2493            (&b"WARC/1.1\r\n"[..], FormatId::Warc),
2494            (&b"\x00\x05\x16\x00\x00\x02\x00\x00"[..], FormatId::AppleSingle),
2495            (&b"\x00\x05\x16\x07\x00\x02\x00\x00"[..], FormatId::AppleDouble),
2496            (
2497                &b"\x89EDFe\r\n\x1a\n\xfe\xff|Format version:1"[..],
2498                FormatId::Edf_1_0_43,
2499            ),
2500            (
2501                &b"\x89EDFe\r\n\x1a\xfe\xff\n|Format version:1_0_44"[..],
2502                FormatId::Edf_1_0_44,
2503            ),
2504            (&b"\x89EDFe\r\n\x1a\x00\x00\x00"[..], FormatId::Edf),
2505        ] {
2506            let mut slice = magic;
2507            let report = guess_format_report(&mut slice, None).unwrap();
2508            assert!(
2509                report
2510                    .candidates
2511                    .iter()
2512                    .any(|c| c.format_id == Some(expected_fmt)),
2513                "Expected {expected_fmt:?} in candidates for magic {magic:?}, got: {:?}",
2514                report.candidates
2515            );
2516        }
2517
2518        // Extension-only .edf should boost the common implied ancestor FormatId::Edf
2519        // above specific versions Edf_1_0_43 and Edf_1_0_44.
2520        assert_eq!(
2521            detect_format_id(None, Some("sample.edf"), None),
2522            Some(FormatId::Edf)
2523        );
2524    }
2525
2526    #[ctb_test]
2527    fn test_edf_and_ember_formats_detection() {
2528        let edf_43 = b"\x89EDFe\r\n\x1a\n\xfe\xff|Format version:1\0Hello";
2529        assert_eq!(
2530            detect_format_id(Some(edf_43), None, None),
2531            Some(FormatId::Edf_1_0_43)
2532        );
2533        assert_eq!(
2534            detect_format_id(Some(edf_43), Some("doc.edf"), None),
2535            Some(FormatId::Edf_1_0_43)
2536        );
2537
2538        let edf_44 = b"\x89EDFe\r\n\x1a\xfe\xff\n|Format version:1_0_44\0Hello";
2539        assert_eq!(
2540            detect_format_id(Some(edf_44), None, None),
2541            Some(FormatId::Edf_1_0_44)
2542        );
2543        assert_eq!(
2544            detect_format_id(Some(edf_44), Some("doc.edf"), None),
2545            Some(FormatId::Edf_1_0_44)
2546        );
2547
2548        let edf_unknown_ver = b"\x89EDFe\r\n\x1a\x99\x99\0Hello";
2549        assert_eq!(
2550            detect_format_id(Some(edf_unknown_ver), None, None),
2551            Some(FormatId::Edf)
2552        );
2553
2554        assert_eq!(
2555            detect_format_id(None, Some("pivot.edc"), None),
2556            Some(FormatId::EdfDcList)
2557        );
2558        assert_eq!(
2559            detect_format_id(
2560                Some(b"Hello @1@ World!"),
2561                Some("doc.edceditable"),
2562                None
2563            ),
2564            Some(FormatId::EdfEditableDcList)
2565        );
2566        assert_eq!(
2567            detect_format_id(None, Some("records.erd"), None),
2568            Some(FormatId::Erd)
2569        );
2570    }
2571
2572    #[ctb_test]
2573    fn test_csc_desc_implied_encoding_corroborated() {
2574        // .cscdesc implies UTF-8 (f0); when content lacks a magic header but is
2575        // valid ASCII text, the implied-encoding compatibility from the database
2576        // strengthens the tentative extension candidate without confirming its structure.
2577        let data = b"Status: Completed\nFilesCommitted: 0\n".to_vec();
2578        let mut slice: &[u8] = &data;
2579        let hint = DetectionHint {
2580            filename: Some("x.cscdesc".to_string()),
2581            ..Default::default()
2582        };
2583        let report = guess_format_report(&mut slice, Some(&hint)).unwrap();
2584        let candidate = report
2585            .candidates
2586            .iter()
2587            .find(|candidate| candidate.format_id == Some(FormatId::CscDesc))
2588            .unwrap();
2589        assert_eq!(candidate.confidence, ConfidenceTier::Moderate);
2590        assert!(
2591            candidate
2592                .evidence
2593                .iter()
2594                .any(|e| matches!(e, DetectionEvidence::Encoding { .. }))
2595        );
2596        assert!(
2597            candidate
2598                .evidence
2599                .iter()
2600                .any(|e| matches!(e, DetectionEvidence::TextProperties { .. }))
2601        );
2602
2603        // Confirmed encoding evidence ranks ahead of an unverified format hint.
2604        let ascii_rank = report
2605            .candidates
2606            .iter()
2607            .position(|c| c.format_id == Some(FormatId::Ascii));
2608        assert_eq!(ascii_rank, Some(0));
2609    }
2610
2611    #[ctb_test]
2612    fn test_csc_desc_unrelated_text_is_not_structural_evidence() {
2613        let mut slice: &[u8] =
2614            b"The shopping list contains apples and bread.\n";
2615        let hint = DetectionHint {
2616            filename: Some("x.cscdesc".to_string()),
2617            ..Default::default()
2618        };
2619        let report = guess_format_report(&mut slice, Some(&hint)).unwrap();
2620        let candidate = report
2621            .candidates
2622            .iter()
2623            .find(|candidate| candidate.format_id == Some(FormatId::CscDesc))
2624            .unwrap();
2625        assert!(
2626            candidate.confidence <= ConfidenceTier::Moderate,
2627            "{candidate:?}"
2628        );
2629        assert!(!candidate.evidence.iter().any(|evidence| matches!(
2630            evidence,
2631            DetectionEvidence::FileMagic { .. }
2632                | DetectionEvidence::CtbMagic { .. }
2633        )));
2634        let ascii = report
2635            .candidates
2636            .iter()
2637            .find(|candidate| candidate.format_id == Some(FormatId::Ascii))
2638            .unwrap();
2639        assert!(candidate.score > ascii.score);
2640        assert_eq!(report.candidates[0].format_id, Some(FormatId::Ascii));
2641    }
2642
2643    #[ctb_test]
2644    fn test_csc_desc_magic_detection() {
2645        // "CSC State File\n" matches content magic directly, identifying
2646        // CscDesc even without any filename hint.
2647        let data =
2648            b"CSC State File\nStatus: Completed\nFilesCommitted: 0\n".to_vec();
2649        let mut slice: &[u8] = &data;
2650        let report = guess_format_report(&mut slice, None).unwrap();
2651        let top = &report.candidates[0];
2652        assert_eq!(top.format_id, Some(FormatId::CscDesc));
2653        assert_eq!(top.confidence, ConfidenceTier::HighestConfidence);
2654
2655        // With .cscdesc filename hint, it gains extension evidence.
2656        let mut slice: &[u8] = &data;
2657        let hint = DetectionHint {
2658            filename: Some("x.cscdesc".to_string()),
2659            ..Default::default()
2660        };
2661        let report_hinted =
2662            guess_format_report(&mut slice, Some(&hint)).unwrap();
2663        let top_hinted = &report_hinted.candidates[0];
2664        assert_eq!(top_hinted.format_id, Some(FormatId::CscDesc));
2665        assert_eq!(top_hinted.confidence, ConfidenceTier::HighestConfidence);
2666        assert!(
2667            top_hinted
2668                .evidence
2669                .iter()
2670                .any(|e| matches!(e, DetectionEvidence::Extension { .. }))
2671        );
2672        assert_eq!(top_hinted.score, 185);
2673    }
2674
2675    #[ctb_test]
2676    fn test_extension_candidate_without_encoding_implication_not_corroborated()
2677    {
2678        // CscJournal does not imply any encoding format, so its extension-only
2679        // candidate must not gain encoding evidence even though the content
2680        // is plain text.
2681        let data =
2682            b"CSC State File\nStatus: Completed\nFilesCommitted: 0\n".to_vec();
2683        let mut slice: &[u8] = &data;
2684        let hint = DetectionHint {
2685            filename: Some("x.cscjournal".to_string()),
2686            ..Default::default()
2687        };
2688        let report = guess_format_report(&mut slice, Some(&hint)).unwrap();
2689        let csc_journal = report
2690            .candidates
2691            .iter()
2692            .find(|c| c.format_id == Some(FormatId::CscJournal))
2693            .unwrap();
2694        assert!(
2695            !csc_journal
2696                .evidence
2697                .iter()
2698                .any(|e| matches!(e, DetectionEvidence::Encoding { .. }))
2699        );
2700        assert!(
2701            !csc_journal
2702                .evidence
2703                .iter()
2704                .any(|e| matches!(e, DetectionEvidence::TextProperties { .. }))
2705        );
2706    }
2707
2708    #[ctb_test]
2709    fn test_gzipped_csc_journal_v4_chain_identifies_version() {
2710        let compressed = ctb_formats_compression::compress(
2711            &csc_journal_v4_bytes(),
2712            crate::SupportedCompressionFormat::Gzip,
2713        )
2714        .unwrap();
2715        let mut slice: &[u8] = &compressed;
2716        let hint = DetectionHint {
2717            filename: Some("journal.cscjournal.gz".to_string()),
2718            ..Default::default()
2719        };
2720        let report = guess_format_report(&mut slice, Some(&hint)).unwrap();
2721        let top = &report.candidates[0];
2722        assert!(
2723            top.description.starts_with("@chain(f632 > f35)"),
2724            "Expected chain with CscJournal4 inner format, got: {}",
2725            top.description
2726        );
2727        assert!(top.description.contains("version 4"));
2728    }
2729
2730    #[ctb_test]
2731    fn test_compat_uncompress_identifies_csc_journal_v4() {
2732        let compressed = ctb_formats_compression::compress(
2733            &csc_journal_v4_bytes(),
2734            crate::SupportedCompressionFormat::Gzip,
2735        )
2736        .unwrap();
2737        let mut slice: &[u8] = &compressed;
2738        let hint = DetectionHint {
2739            filename: Some("journal.cscjournal.gz".to_string()),
2740            compat: true,
2741            uncompress: true,
2742            ..Default::default()
2743        };
2744        let report = guess_format_report(&mut slice, Some(&hint)).unwrap();
2745        let top = &report.candidates[0];
2746        assert_eq!(top.format_id, Some(FormatId::CscJournal4));
2747        assert!(top.description.contains("version 4"));
2748        assert!(top.description.contains("gzip"));
2749    }
2750}
2751/*
2752/*
2753 * Adapted from: apptype.c, Written by Eberhard Mattes and put into the
2754 * file_public domain
2755 *
2756 * Notes: 1. Qualify the filename so that DosQueryAppType does not do extraneous
2757 * searches.
2758 *
2759 * 2. DosQueryAppType will return FAPPTYP_DOS on a file ending with ".com"
2760 * (other than an OS/2 exe or Win exe with this name). Eberhard Mattes
2761 * remarks Tue, 6 Apr 93: Moreover, it reports the type of the (new and very
2762 * bug ridden) Win Emacs as "OS/2 executable".
2763 *
2764 * 3. apptype() uses the filename if given, otherwise a tmp file is created with
2765 * the contents of buf. If buf is not the complete file, apptype can
2766 * incorrectly identify the exe type. The "-z" option of "file" is the reason
2767 * for this ugly code.
2768 */
2769
2770The preceding notice is from src/apptype.c in `file`.
2771
2772
2773
2774/*-
2775 * Copyright (c) 2008 Christos Zoulas
2776 * All rights reserved.
2777 *
2778 * Redistribution and use in source and binary forms, with or without
2779 * modification, are permitted provided that the following conditions
2780 * are met:
2781 * 1. Redistributions of source code must retain the above copyright
2782 *    notice, this list of conditions and the following disclaimer.
2783 * 2. Redistributions in binary form must reproduce the above copyright
2784 *    notice, this list of conditions and the following disclaimer in the
2785 *    documentation and/or other materials provided with the distribution.
2786 *
2787 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
2788 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
2789 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
2790 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
2791 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
2792 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
2793 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
2794 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
2795 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
2796 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
2797 * POSSIBILITY OF SUCH DAMAGE.
2798 */
2799
2800The preceding notice is from src/cdf.c, src/cdf.h, and src/cdf_time.c in `file`.
2801
2802
2803
2804/*-
2805 * Copyright (c) 2016 Christos Zoulas
2806 * All rights reserved.
2807 *
2808 * Redistribution and use in source and binary forms, with or without
2809 * modification, are permitted provided that the following conditions
2810 * are met:
2811 * 1. Redistributions of source code must retain the above copyright
2812 *    notice, this list of conditions and the following disclaimer.
2813 * 2. Redistributions in binary form must reproduce the above copyright
2814 *    notice, this list of conditions and the following disclaimer in the
2815 *    documentation and/or other materials provided with the distribution.
2816 *
2817 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
2818 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
2819 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
2820 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
2821 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
2822 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
2823 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
2824 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
2825 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
2826 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
2827 * POSSIBILITY OF SUCH DAMAGE.
2828 */
2829
2830The preceding notice is from src/der.c and src/der.h in `file`.
2831
2832
2833
2834/*-
2835 * Copyright (c) 2019 Christos Zoulas
2836 * All rights reserved.
2837 *
2838 * Redistribution and use in source and binary forms, with or without
2839 * modification, are permitted provided that the following conditions
2840 * are met:
2841 * 1. Redistributions of source code must retain the above copyright
2842 *    notice, this list of conditions and the following disclaimer.
2843 * 2. Redistributions in binary form must reproduce the above copyright
2844 *    notice, this list of conditions and the following disclaimer in the
2845 *    documentation and/or other materials provided with the distribution.
2846 *
2847 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
2848 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
2849 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
2850 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
2851 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
2852 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
2853 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
2854 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
2855 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
2856 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
2857 * POSSIBILITY OF SUCH DAMAGE.
2858 */
2859
2860The preceding notice is from src/is_csv.c in `file`.
2861
2862
2863
2864/*-
2865 * Copyright (c) 2018 Christos Zoulas
2866 * All rights reserved.
2867 *
2868 * Redistribution and use in source and binary forms, with or without
2869 * modification, are permitted provided that the following conditions
2870 * are met:
2871 * 1. Redistributions of source code must retain the above copyright
2872 *    notice, this list of conditions and the following disclaimer.
2873 * 2. Redistributions in binary form must reproduce the above copyright
2874 *    notice, this list of conditions and the following disclaimer in the
2875 *    documentation and/or other materials provided with the distribution.
2876 *
2877 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
2878 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
2879 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
2880 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
2881 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
2882 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
2883 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
2884 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
2885 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
2886 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
2887 * POSSIBILITY OF SUCH DAMAGE.
2888 */
2889
2890The preceding notice is from src/is_json.c in `file`.
2891
2892
2893
2894/*-
2895 * Copyright (c) 2023 Christos Zoulas
2896 * All rights reserved.
2897 *
2898 * Redistribution and use in source and binary forms, with or without
2899 * modification, are permitted provided that the following conditions
2900 * are met:
2901 * 1. Redistributions of source code must retain the above copyright
2902 *    notice, this list of conditions and the following disclaimer.
2903 * 2. Redistributions in binary form must reproduce the above copyright
2904 *    notice, this list of conditions and the following disclaimer in the
2905 *    documentation and/or other materials provided with the distribution.
2906 *
2907 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
2908 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
2909 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
2910 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
2911 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
2912 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
2913 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
2914 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
2915 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
2916 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
2917 * POSSIBILITY OF SUCH DAMAGE.
2918 */
2919
2920The preceding notice is from src/is_simh.c in `file`.
2921
2922
2923
2924/*-
2925 * SPDX-License-Identifier: BSD-3-Clause
2926 *
2927 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
2928 * Copyright (c) 1992, 1993, 1994
2929 *      The Regents of the University of California.  All rights reserved.
2930 *
2931 * This code is derived from software contributed to Berkeley by
2932 * Henry Spencer.
2933 *
2934 * Redistribution and use in source and binary forms, with or without
2935 * modification, are permitted provided that the following conditions
2936 * are met:
2937 * 1. Redistributions of source code must retain the above copyright
2938 *    notice, this list of conditions and the following disclaimer.
2939 * 2. Redistributions in binary form must reproduce the above copyright
2940 *    notice, this list of conditions and the following disclaimer in the
2941 *    documentation and/or other materials provided with the distribution.
2942 * 3. Neither the name of the University nor the names of its contributors
2943 *    may be used to endorse or promote products derived from this software
2944 *    without specific prior written permission.
2945 *
2946 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2947 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2948 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2949 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2950 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2951 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2952 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2953 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2954 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2955 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2956 * SUCH DAMAGE.
2957 *
2958 *      @(#)cname.h     8.3 (Berkeley) 3/20/94
2959 * $FreeBSD: head/lib/libc/regex/cname.h 326025 2017-11-20 19:49:47Z pfg $
2960 */
2961
2962The preceding notice is from src/missing/cname.h in `file`.
2963
2964
2965
2966/*-
2967 * SPDX-License-Identifier: BSD-3-Clause
2968 *
2969 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
2970 * Copyright (c) 1992, 1993, 1994
2971 *      The Regents of the University of California.  All rights reserved.
2972 *
2973 * This code is derived from software contributed to Berkeley by
2974 * Henry Spencer.
2975 *
2976 * Redistribution and use in source and binary forms, with or without
2977 * modification, are permitted provided that the following conditions
2978 * are met:
2979 * 1. Redistributions of source code must retain the above copyright
2980 *    notice, this list of conditions and the following disclaimer.
2981 * 2. Redistributions in binary form must reproduce the above copyright
2982 *    notice, this list of conditions and the following disclaimer in the
2983 *    documentation and/or other materials provided with the distribution.
2984 * 3. Neither the name of the University nor the names of its contributors
2985 *    may be used to endorse or promote products derived from this software
2986 *    without specific prior written permission.
2987 *
2988 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2989 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2990 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2991 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2992 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2993 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2994 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2995 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2996 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2997 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2998 * SUCH DAMAGE.
2999 *
3000 *      @(#)engine.c    8.5 (Berkeley) 3/20/94
3001 */
3002
3003The preceding notice is from src/missing/engine.c in `file`.
3004
3005
3006
3007/*-
3008 * Copyright (c) 2000 The NetBSD Foundation, Inc.
3009 * All rights reserved.
3010 *
3011 * This code was contributed to The NetBSD Foundation by Allen Briggs.
3012 *
3013 * Redistribution and use in source and binary forms, with or without
3014 * modification, are permitted provided that the following conditions
3015 * are met:
3016 * 1. Redistributions of source code must retain the above copyright
3017 *    notice, this list of conditions and the following disclaimer.
3018 * 2. Redistributions in binary form must reproduce the above copyright
3019 *    notice, this list of conditions and the following disclaimer in the
3020 *    documentation and/or other materials provided with the distribution.
3021 *
3022 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
3023 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
3024 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
3025 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
3026 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
3027 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
3028 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
3029 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
3030 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
3031 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
3032 * POSSIBILITY OF SUCH DAMAGE.
3033 */
3034
3035The preceding notice is from src/missing/fmtcheck.c in `file`.
3036
3037
3038
3039/*-
3040 * Copyright (c) 2011 The NetBSD Foundation, Inc.
3041 * All rights reserved.
3042 *
3043 * This code is derived from software contributed to The NetBSD Foundation
3044 * by Christos Zoulas.
3045 *
3046 * Redistribution and use in source and binary forms, with or without
3047 * modification, are permitted provided that the following conditions
3048 * are met:
3049 * 1. Redistributions of source code must retain the above copyright
3050 *    notice, this list of conditions and the following disclaimer.
3051 * 2. Redistributions in binary form must reproduce the above copyright
3052 *    notice, this list of conditions and the following disclaimer in the
3053 *    documentation and/or other materials provided with the distribution.
3054 *
3055 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
3056 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
3057 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
3058 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
3059 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
3060 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
3061 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
3062 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
3063 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
3064 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
3065 * POSSIBILITY OF SUCH DAMAGE.
3066 */
3067
3068The preceding notice is from src/missing/getline.c in `file`.
3069
3070
3071
3072/*-
3073 * Copyright (c) 2000 The NetBSD Foundation, Inc.
3074 * All rights reserved.
3075 *
3076 * This code is derived from software contributed to The NetBSD Foundation
3077 * by Dieter Baron and Thomas Klausner.
3078 *
3079 * Redistribution and use in source and binary forms, with or without
3080 * modification, are permitted provided that the following conditions
3081 * are met:
3082 * 1. Redistributions of source code must retain the above copyright
3083 *    notice, this list of conditions and the following disclaimer.
3084 * 2. Redistributions in binary form must reproduce the above copyright
3085 *    notice, this list of conditions and the following disclaimer in the
3086 *    documentation and/or other materials provided with the distribution.
3087 *
3088 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
3089 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
3090 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
3091 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
3092 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
3093 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
3094 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
3095 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
3096 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
3097 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
3098 * POSSIBILITY OF SUCH DAMAGE.
3099 */
3100
3101The preceding notice is from src/missing/getopt_long.c and src/mygetopt.h in `file`.
3102
3103
3104
3105/*
3106 * Public domain fallback for reallocarray(3), for platforms (e.g.
3107 * AmigaOS/libnix) whose C library declares it but does not implement it.
3108 */
3109
3110The preceding notice is from src/missing/reallocarray.c in `file`.
3111
3112
3113
3114/*-
3115 * SPDX-License-Identifier: BSD-3-Clause
3116 *
3117 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
3118 * Copyright (c) 1992, 1993, 1994
3119 *      The Regents of the University of California.  All rights reserved.
3120 *
3121 * Copyright (c) 2011 The FreeBSD Foundation
3122 * All rights reserved.
3123 * Portions of this software were developed by David Chisnall
3124 * under sponsorship from the FreeBSD Foundation.
3125 *
3126 * This code is derived from software contributed to Berkeley by
3127 * Henry Spencer.
3128 *
3129 * Redistribution and use in source and binary forms, with or without
3130 * modification, are permitted provided that the following conditions
3131 * are met:
3132 * 1. Redistributions of source code must retain the above copyright
3133 *    notice, this list of conditions and the following disclaimer.
3134 * 2. Redistributions in binary form must reproduce the above copyright
3135 *    notice, this list of conditions and the following disclaimer in the
3136 *    documentation and/or other materials provided with the distribution.
3137 * 3. Neither the name of the University nor the names of its contributors
3138 *    may be used to endorse or promote products derived from this software
3139 *    without specific prior written permission.
3140 *
3141 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3142 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3143 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3144 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3145 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3146 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3147 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3148 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3149 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3150 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3151 * SUCH DAMAGE.
3152 *
3153 *      @(#)regcomp.c   8.5 (Berkeley) 3/20/94
3154 */
3155
3156The preceding notice is from src/missing/regcomp.c in `file`.
3157
3158
3159
3160/*-
3161 * SPDX-License-Identifier: BSD-3-Clause
3162 *
3163 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
3164 * Copyright (c) 1992, 1993, 1994
3165 *      The Regents of the University of California.  All rights reserved.
3166 *
3167 * This code is derived from software contributed to Berkeley by
3168 * Henry Spencer.
3169 *
3170 * Redistribution and use in source and binary forms, with or without
3171 * modification, are permitted provided that the following conditions
3172 * are met:
3173 * 1. Redistributions of source code must retain the above copyright
3174 *    notice, this list of conditions and the following disclaimer.
3175 * 2. Redistributions in binary form must reproduce the above copyright
3176 *    notice, this list of conditions and the following disclaimer in the
3177 *    documentation and/or other materials provided with the distribution.
3178 * 3. Neither the name of the University nor the names of its contributors
3179 *    may be used to endorse or promote products derived from this software
3180 *    without specific prior written permission.
3181 *
3182 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3183 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3184 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3185 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3186 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3187 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3188 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3189 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3190 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3191 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3192 * SUCH DAMAGE.
3193 *
3194 *      @(#)regerror.c  8.4 (Berkeley) 3/20/94
3195 */
3196
3197The preceding notice is from src/missing/regerror.c in `file`.
3198
3199
3200
3201$NetBSD: COPYRIGHT,v 1.5 2003/08/07 16:43:19 agc Exp $
3202
3203Copyright 1992, 1993, 1994 Henry Spencer.  All rights reserved.
3204This software is not subject to any license of the American Telephone
3205and Telegraph Company or of the Regents of the University of California.
3206
3207Permission is granted to anyone to use this software for any purpose on
3208any computer system, and to alter it and redistribute it, subject
3209to the following restrictions:
3210
32111. The author is not responsible for the consequences of use of this
3212   software, no matter how awful, even if they arise from flaws in it.
3213
32142. The origin of this software must not be misrepresented, either by
3215   explicit claim or by omission.  Since few users ever read sources,
3216   credits must appear in the documentation.
3217
32183. Altered versions must be plainly marked as such, and must not be
3219   misrepresented as being the original software.  Since few users
3220   ever read sources, credits must appear in the documentation.
3221
32224. This notice may not be removed or altered.
3223
3224=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
3225/*-
3226 * Copyright (c) 1994
3227 *      The Regents of the University of California.  All rights reserved.
3228 *
3229 * Redistribution and use in source and binary forms, with or without
3230 * modification, are permitted provided that the following conditions
3231 * are met:
3232 * 1. Redistributions of source code must retain the above copyright
3233 *    notice, this list of conditions and the following disclaimer.
3234 * 2. Redistributions in binary form must reproduce the above copyright
3235 *    notice, this list of conditions and the following disclaimer in the
3236 *    documentation and/or other materials provided with the distribution.
3237 * 3. Neither the name of the University nor the names of its contributors
3238 *    may be used to endorse or promote products derived from this software
3239 *    without specific prior written permission.
3240 *
3241 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3242 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3243 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3244 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3245 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3246 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3247 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3248 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3249 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3250 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3251 * SUCH DAMAGE.
3252 *
3253 *      @(#)COPYRIGHT   8.1 (Berkeley) 3/16/94
3254 */
3255
3256The preceding notice is from src/missing/REGEX-COPYRIGHT in `file`.
3257
3258
3259
3260/*-
3261 * SPDX-License-Identifier: BSD-3-Clause
3262 *
3263 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
3264 * Copyright (c) 1992, 1993, 1994
3265 *      The Regents of the University of California.  All rights reserved.
3266 *
3267 * This code is derived from software contributed to Berkeley by
3268 * Henry Spencer.
3269 *
3270 * Redistribution and use in source and binary forms, with or without
3271 * modification, are permitted provided that the following conditions
3272 * are met:
3273 * 1. Redistributions of source code must retain the above copyright
3274 *    notice, this list of conditions and the following disclaimer.
3275 * 2. Redistributions in binary form must reproduce the above copyright
3276 *    notice, this list of conditions and the following disclaimer in the
3277 *    documentation and/or other materials provided with the distribution.
3278 * 3. Neither the name of the University nor the names of its contributors
3279 *    may be used to endorse or promote products derived from this software
3280 *    without specific prior written permission.
3281 *
3282 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3283 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3284 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3285 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3286 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3287 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3288 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3289 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3290 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3291 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3292 * SUCH DAMAGE.
3293 *
3294 *      @(#)regex2.h    8.4 (Berkeley) 3/20/94
3295 * $FreeBSD: head/lib/libc/regex/regex2.h 368359 2020-12-05 03:18:48Z kevans $
3296 */
3297
3298The preceding notice is from src/missing/regex2.h in `file`.
3299
3300
3301
3302/*-
3303 * SPDX-License-Identifier: BSD-3-Clause
3304 *
3305 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
3306 * Copyright (c) 1992, 1993, 1994
3307 *      The Regents of the University of California.  All rights reserved.
3308 *
3309 * This code is derived from software contributed to Berkeley by
3310 * Henry Spencer.
3311 *
3312 * Redistribution and use in source and binary forms, with or without
3313 * modification, are permitted provided that the following conditions
3314 * are met:
3315 * 1. Redistributions of source code must retain the above copyright
3316 *    notice, this list of conditions and the following disclaimer.
3317 * 2. Redistributions in binary form must reproduce the above copyright
3318 *    notice, this list of conditions and the following disclaimer in the
3319 *    documentation and/or other materials provided with the distribution.
3320 * 3. Neither the name of the University nor the names of its contributors
3321 *    may be used to endorse or promote products derived from this software
3322 *    without specific prior written permission.
3323 *
3324 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3325 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3326 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3327 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3328 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3329 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3330 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3331 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3332 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3333 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3334 * SUCH DAMAGE.
3335 *
3336 *      @(#)regexec.c   8.3 (Berkeley) 3/20/94
3337 */
3338
3339The preceding notice is from src/missing/regexec.c in `file`.
3340
3341
3342
3343/*-
3344 * SPDX-License-Identifier: BSD-3-Clause
3345 *
3346 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
3347 * Copyright (c) 1992, 1993, 1994
3348 *      The Regents of the University of California.  All rights reserved.
3349 *
3350 * This code is derived from software contributed to Berkeley by
3351 * Henry Spencer.
3352 *
3353 * Redistribution and use in source and binary forms, with or without
3354 * modification, are permitted provided that the following conditions
3355 * are met:
3356 * 1. Redistributions of source code must retain the above copyright
3357 *    notice, this list of conditions and the following disclaimer.
3358 * 2. Redistributions in binary form must reproduce the above copyright
3359 *    notice, this list of conditions and the following disclaimer in the
3360 *    documentation and/or other materials provided with the distribution.
3361 * 3. Neither the name of the University nor the names of its contributors
3362 *    may be used to endorse or promote products derived from this software
3363 *    without specific prior written permission.
3364 *
3365 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3366 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3367 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3368 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3369 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3370 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3371 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3372 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3373 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3374 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3375 * SUCH DAMAGE.
3376 *
3377 *      @(#)regfree.c   8.3 (Berkeley) 3/20/94
3378 */
3379
3380The preceding notice is from src/missing/regfree.c in `file`.
3381
3382
3383
3384/*-
3385 * Copyright (c) 1990, 1993
3386 *      The Regents of the University of California.  All rights reserved.
3387 *
3388 * This code is derived from software contributed to Berkeley by
3389 * Chris Torek.
3390 *
3391 * Redistribution and use in source and binary forms, with or without
3392 * modification, are permitted provided that the following conditions
3393 * are met:
3394 * 1. Redistributions of source code must retain the above copyright
3395 *    notice, this list of conditions and the following disclaimer.
3396 * 2. Redistributions in binary form must reproduce the above copyright
3397 *    notice, this list of conditions and the following disclaimer in the
3398 *    documentation and/or other materials provided with the distribution.
3399 * 3. Neither the name of the University nor the names of its contributors
3400 *    may be used to endorse or promote products derived from this software
3401 *    without specific prior written permission.
3402 *
3403 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3404 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3405 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3406 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3407 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3408 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3409 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3410 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3411 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3412 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3413 * SUCH DAMAGE.
3414 */
3415
3416The preceding notice is from src/missing/strcasestr.c in `file`.
3417
3418
3419
3420/*
3421 * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
3422 *
3423 * Permission to use, copy, modify, and distribute this software for any
3424 * purpose with or without fee is hereby granted, provided that the above
3425 * copyright notice and this permission notice appear in all copies.
3426 *
3427 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
3428 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
3429 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
3430 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
3431 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
3432 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
3433 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
3434 */
3435
3436The preceding notice is from src/missing/strlcat.c and src/missing/strlcpy.c in `file`.
3437
3438
3439
3440/*-
3441 * SPDX-License-Identifier: BSD-3-Clause
3442 *
3443 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
3444 * Copyright (c) 1992, 1993, 1994
3445 *      The Regents of the University of California.  All rights reserved.
3446 *
3447 * This code is derived from software contributed to Berkeley by
3448 * Henry Spencer.
3449 *
3450 * Redistribution and use in source and binary forms, with or without
3451 * modification, are permitted provided that the following conditions
3452 * are met:
3453 * 1. Redistributions of source code must retain the above copyright
3454 *    notice, this list of conditions and the following disclaimer.
3455 * 2. Redistributions in binary form must reproduce the above copyright
3456 *    notice, this list of conditions and the following disclaimer in the
3457 *    documentation and/or other materials provided with the distribution.
3458 * 3. Neither the name of the University nor the names of its contributors
3459 *    may be used to endorse or promote products derived from this software
3460 *    without specific prior written permission.
3461 *
3462 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3463 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3464 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3465 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3466 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3467 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3468 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3469 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3470 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3471 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3472 * SUCH DAMAGE.
3473 *
3474 *      @(#)utils.h     8.3 (Berkeley) 3/20/94
3475 * $FreeBSD: head/lib/libc/regex/utils.h 341838 2018-12-12 04:23:00Z yuripv $
3476 */
3477
3478The preceding notice is from src/missing/utils.h in `file`.
3479
3480
3481
3482/*-
3483 * Copyright (c) 2008, 2016 Christos Zoulas
3484 * All rights reserved.
3485 *
3486 * Redistribution and use in source and binary forms, with or without
3487 * modification, are permitted provided that the following conditions
3488 * are met:
3489 * 1. Redistributions of source code must retain the above copyright
3490 *    notice, this list of conditions and the following disclaimer.
3491 * 2. Redistributions in binary form must reproduce the above copyright
3492 *    notice, this list of conditions and the following disclaimer in the
3493 *    documentation and/or other materials provided with the distribution.
3494 *
3495 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
3496 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
3497 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
3498 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
3499 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
3500 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
3501 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
3502 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
3503 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
3504 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
3505 * POSSIBILITY OF SUCH DAMAGE.
3506 */
3507
3508The preceding notice is from src/readcdf.c in `file`.
3509
3510
3511
3512/*-
3513 * Copyright (c) 1992 Henry Spencer.
3514 * Copyright (c) 1992, 1993
3515 *      The Regents of the University of California.  All rights reserved.
3516 *
3517 * This code is derived from software contributed to Berkeley by
3518 * Henry Spencer of the University of Toronto.
3519 *
3520 * Redistribution and use in source and binary forms, with or without
3521 * modification, are permitted provided that the following conditions
3522 * are met:
3523 * 1. Redistributions of source code must retain the above copyright
3524 *    notice, this list of conditions and the following disclaimer.
3525 * 2. Redistributions in binary form must reproduce the above copyright
3526 *    notice, this list of conditions and the following disclaimer in the
3527 *    documentation and/or other materials provided with the distribution.
3528 * 3. Neither the name of the University nor the names of its contributors
3529 *    may be used to endorse or promote products derived from this software
3530 *    without specific prior written permission.
3531 *
3532 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3533 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3534 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3535 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3536 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3537 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3538 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3539 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3540 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3541 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3542 * SUCH DAMAGE.
3543 *
3544 *      @(#)regex.h     8.2 (Berkeley) 1/3/94
3545 * $FreeBSD: src/include/regex.h,v 1.12 2010/02/16 19:39:50 imp Exp $
3546 */
3547
3548The preceding notice is from src/regex-bsd.h in `file`.
3549*/
3550/*
3551
3552Text of LICENSE from DROID:
3553
3554Copyright (c) 2016, The National Archives <pronom@nationalarchives.gov.uk>
3555All rights reserved.
3556
3557Redistribution and use in source and binary forms, with or without
3558modification, are permitted provided that the following
3559conditions are met:
3560
3561 * Redistributions of source code must retain the above copyright
3562   notice, this list of conditions and the following disclaimer.
3563
3564 * Redistributions in binary form must reproduce the above copyright
3565   notice, this list of conditions and the following disclaimer in the
3566   documentation and/or other materials provided with the distribution.
3567
3568 * Neither the name of the The National Archives nor the
3569   names of its contributors may be used to endorse or promote products
3570   derived from this software without specific prior written permission.
3571
3572THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
3573AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3574IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
3575PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
3576CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
3577EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
3578PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
3579PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
3580LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
3581NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
3582SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3583*/
3584
3585/*
3586
3587Text of LICENSE from fileid:
3588
3589The MIT License (MIT)
3590
3591Copyright (c) 2015 David B Heise
3592
3593Permission is hereby granted, free of charge, to any person obtaining a copy of
3594this software and associated documentation files (the "Software"), to deal in
3595the Software without restriction, including without limitation the rights to
3596use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
3597the Software, and to permit persons to whom the Software is furnished to do so,
3598subject to the following conditions:
3599
3600The above copyright notice and this permission notice shall be included in all
3601copies or substantial portions of the Software.
3602
3603THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
3604IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
3605FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
3606COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
3607IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
3608CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
3609
3610
3611*/
3612
3613/*
3614Text of LICENSE from binwalk:
3615
3616
3617MIT License
3618
3619Copyright (c) 2024 devttys0
3620
3621Permission is hereby granted, free of charge, to any person obtaining a copy
3622of this software and associated documentation files (the "Software"), to deal
3623in the Software without restriction, including without limitation the rights
3624to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
3625copies of the Software, and to permit persons to whom the Software is
3626furnished to do so, subject to the following conditions:
3627
3628The above copyright notice and this permission notice shall be included in all
3629copies or substantial portions of the Software.
3630
3631THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
3632IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
3633FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
3634AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
3635LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
3636OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
3637SOFTWARE.
3638
3639*/
3640
3641/*
3642Text of LICENSE from polyfile:
3643
3644
3645                                 Apache License
3646                           Version 2.0, January 2004
3647                        http://www.apache.org/licenses/
3648
3649   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
3650
3651   1. Definitions.
3652
3653      "License" shall mean the terms and conditions for use, reproduction,
3654      and distribution as defined by Sections 1 through 9 of this document.
3655
3656      "Licensor" shall mean the copyright owner or entity authorized by
3657      the copyright owner that is granting the License.
3658
3659      "Legal Entity" shall mean the union of the acting entity and all
3660      other entities that control, are controlled by, or are under common
3661      control with that entity. For the purposes of this definition,
3662      "control" means (i) the power, direct or indirect, to cause the
3663      direction or management of such entity, whether by contract or
3664      otherwise, or (ii) ownership of fifty percent (50%) or more of the
3665      outstanding shares, or (iii) beneficial ownership of such entity.
3666
3667      "You" (or "Your") shall mean an individual or Legal Entity
3668      exercising permissions granted by this License.
3669
3670      "Source" form shall mean the preferred form for making modifications,
3671      including but not limited to software source code, documentation
3672      source, and configuration files.
3673
3674      "Object" form shall mean any form resulting from mechanical
3675      transformation or translation of a Source form, including but
3676      not limited to compiled object code, generated documentation,
3677      and conversions to other media types.
3678
3679      "Work" shall mean the work of authorship, whether in Source or
3680      Object form, made available under the License, as indicated by a
3681      copyright notice that is included in or attached to the work
3682      (an example is provided in the Appendix below).
3683
3684      "Derivative Works" shall mean any work, whether in Source or Object
3685      form, that is based on (or derived from) the Work and for which the
3686      editorial revisions, annotations, elaborations, or other modifications
3687      represent, as a whole, an original work of authorship. For the purposes
3688      of this License, Derivative Works shall not include works that remain
3689      separable from, or merely link (or bind by name) to the interfaces of,
3690      the Work and Derivative Works thereof.
3691
3692      "Contribution" shall mean any work of authorship, including
3693      the original version of the Work and any modifications or additions
3694      to that Work or Derivative Works thereof, that is intentionally
3695      submitted to Licensor for inclusion in the Work by the copyright owner
3696      or by an individual or Legal Entity authorized to submit on behalf of
3697      the copyright owner. For the purposes of this definition, "submitted"
3698      means any form of electronic, verbal, or written communication sent
3699      to the Licensor or its representatives, including but not limited to
3700      communication on electronic mailing lists, source code control systems,
3701      and issue tracking systems that are managed by, or on behalf of, the
3702      Licensor for the purpose of discussing and improving the Work, but
3703      excluding communication that is conspicuously marked or otherwise
3704      designated in writing by the copyright owner as "Not a Contribution."
3705
3706      "Contributor" shall mean Licensor and any individual or Legal Entity
3707      on behalf of whom a Contribution has been received by Licensor and
3708      subsequently incorporated within the Work.
3709
3710   2. Grant of Copyright License. Subject to the terms and conditions of
3711      this License, each Contributor hereby grants to You a perpetual,
3712      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
3713      copyright license to reproduce, prepare Derivative Works of,
3714      publicly display, publicly perform, sublicense, and distribute the
3715      Work and such Derivative Works in Source or Object form.
3716
3717   3. Grant of Patent License. Subject to the terms and conditions of
3718      this License, each Contributor hereby grants to You a perpetual,
3719      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
3720      (except as stated in this section) patent license to make, have made,
3721      use, offer to sell, sell, import, and otherwise transfer the Work,
3722      where such license applies only to those patent claims licensable
3723      by such Contributor that are necessarily infringed by their
3724      Contribution(s) alone or by combination of their Contribution(s)
3725      with the Work to which such Contribution(s) was submitted. If You
3726      institute patent litigation against any entity (including a
3727      cross-claim or counterclaim in a lawsuit) alleging that the Work
3728      or a Contribution incorporated within the Work constitutes direct
3729      or contributory patent infringement, then any patent licenses
3730      granted to You under this License for that Work shall terminate
3731      as of the date such litigation is filed.
3732
3733   4. Redistribution. You may reproduce and distribute copies of the
3734      Work or Derivative Works thereof in any medium, with or without
3735      modifications, and in Source or Object form, provided that You
3736      meet the following conditions:
3737
3738      (a) You must give any other recipients of the Work or
3739          Derivative Works a copy of this License; and
3740
3741      (b) You must cause any modified files to carry prominent notices
3742          stating that You changed the files; and
3743
3744      (c) You must retain, in the Source form of any Derivative Works
3745          that You distribute, all copyright, patent, trademark, and
3746          attribution notices from the Source form of the Work,
3747          excluding those notices that do not pertain to any part of
3748          the Derivative Works; and
3749
3750      (d) If the Work includes a "NOTICE" text file as part of its
3751          distribution, then any Derivative Works that You distribute must
3752          include a readable copy of the attribution notices contained
3753          within such NOTICE file, excluding those notices that do not
3754          pertain to any part of the Derivative Works, in at least one
3755          of the following places: within a NOTICE text file distributed
3756          as part of the Derivative Works; within the Source form or
3757          documentation, if provided along with the Derivative Works; or,
3758          within a display generated by the Derivative Works, if and
3759          wherever such third-party notices normally appear. The contents
3760          of the NOTICE file are for informational purposes only and
3761          do not modify the License. You may add Your own attribution
3762          notices within Derivative Works that You distribute, alongside
3763          or as an addendum to the NOTICE text from the Work, provided
3764          that such additional attribution notices cannot be construed
3765          as modifying the License.
3766
3767      You may add Your own copyright statement to Your modifications and
3768      may provide additional or different license terms and conditions
3769      for use, reproduction, or distribution of Your modifications, or
3770      for any such Derivative Works as a whole, provided Your use,
3771      reproduction, and distribution of the Work otherwise complies with
3772      the conditions stated in this License.
3773
3774   5. Submission of Contributions. Unless You explicitly state otherwise,
3775      any Contribution intentionally submitted for inclusion in the Work
3776      by You to the Licensor shall be under the terms and conditions of
3777      this License, without any additional terms or conditions.
3778      Notwithstanding the above, nothing herein shall supersede or modify
3779      the terms of any separate license agreement you may have executed
3780      with Licensor regarding such Contributions.
3781
3782   6. Trademarks. This License does not grant permission to use the trade
3783      names, trademarks, service marks, or product names of the Licensor,
3784      except as required for reasonable and customary use in describing the
3785      origin of the Work and reproducing the content of the NOTICE file.
3786
3787   7. Disclaimer of Warranty. Unless required by applicable law or
3788      agreed to in writing, Licensor provides the Work (and each
3789      Contributor provides its Contributions) on an "AS IS" BASIS,
3790      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
3791      implied, including, without limitation, any warranties or conditions
3792      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
3793      PARTICULAR PURPOSE. You are solely responsible for determining the
3794      appropriateness of using or redistributing the Work and assume any
3795      risks associated with Your exercise of permissions under this License.
3796
3797   8. Limitation of Liability. In no event and under no legal theory,
3798      whether in tort (including negligence), contract, or otherwise,
3799      unless required by applicable law (such as deliberate and grossly
3800      negligent acts) or agreed to in writing, shall any Contributor be
3801      liable to You for damages, including any direct, indirect, special,
3802      incidental, or consequential damages of any character arising as a
3803      result of this License or out of the use or inability to use the
3804      Work (including but not limited to damages for loss of goodwill,
3805      work stoppage, computer failure or malfunction, or any and all
3806      other commercial damages or losses), even if such Contributor
3807      has been advised of the possibility of such damages.
3808
3809   9. Accepting Warranty or Additional Liability. While redistributing
3810      the Work or Derivative Works thereof, You may choose to offer,
3811      and charge a fee for, acceptance of support, warranty, indemnity,
3812      or other liability obligations and/or rights consistent with this
3813      License. However, in accepting such obligations, You may act only
3814      on Your own behalf and on Your sole responsibility, not on behalf
3815      of any other Contributor, and only if You agree to indemnify,
3816      defend, and hold each Contributor harmless for any liability
3817      incurred by, or claims asserted against, such Contributor by reason
3818      of your accepting any such warranty or additional liability.
3819
3820   END OF TERMS AND CONDITIONS
3821
3822   APPENDIX: How to apply the Apache License to your work.
3823
3824      To apply the Apache License to your work, attach the following
3825      boilerplate notice, with the fields enclosed by brackets "[]"
3826      replaced with your own identifying information. (Don't include
3827      the brackets!)  The text should be enclosed in the appropriate
3828      comment syntax for the file format. We also recommend that a
3829      file or class name and description of purpose be included on the
3830      same "printed page" as the copyright notice for easier
3831      identification within third-party archives.
3832
3833   Copyright [yyyy] [name of copyright owner]
3834
3835   Licensed under the Apache License, Version 2.0 (the "License");
3836   you may not use this file except in compliance with the License.
3837   You may obtain a copy of the License at
3838
3839       http://www.apache.org/licenses/LICENSE-2.0
3840
3841   Unless required by applicable law or agreed to in writing, software
3842   distributed under the License is distributed on an "AS IS" BASIS,
3843   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3844   See the License for the specific language governing permissions and
3845   limitations under the License.
3846
3847*/