ctb_formats_detection/
container.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//! Specialized deep parsers and container inspection subsystem.
446//!
447//! Implements procedural format validators ported from `file`:
448//! - TAR archive checksum verification (`is_tar.c`)
449//! - Fast JSON state-machine scanner (`is_json.c`)
450//! - Tabular CSV/TSV consistency validator (`is_csv.c`)
451//! - ELF binary header inspector (`readelf.c`)
452//! - OLE2 Compound Document File (CDF) inspector (`readcdf.c`)
453//! - ZIP container signature inspector (DOCX, XLSX, PPTX, EPUB, APK, JAR, HWPX)
454//! - Transparent payload decompression probe (`compress.c`)
455
456#[allow(
457    unused_imports,
458    clippy::wildcard_imports,
459    reason = "Standard workspace module prelude"
460)]
461use crate::utilities::*;
462
463use std::io::Read;
464
465use crate::detection::source::DetectionSource;
466use crate::detection::types::{
467    ConfidenceTier, DetectionCandidate, DetectionEvidence, DetectionHint,
468};
469use crate::format_id::FormatId;
470
471/// Maximum bytes inspected for JSON state-machine parsing.
472const JSON_MAX_INSPECT_BYTES: usize = 65536;
473
474/// Maximum bytes inspected for CSV/TSV tabular consistency.
475const CSV_MAX_INSPECT_BYTES: usize = 8192;
476
477/// Maximum recursion depth allowed during JSON parsing to prevent stack
478/// overflow.
479const JSON_MAX_RECURSION_DEPTH: usize = 500;
480
481// ---------------------------------------------------------------------------
482// 1. TAR Archive Checksum Verification (`is_tar.c`)
483// ---------------------------------------------------------------------------
484
485/// Decodes an octal string field from a TAR header.
486fn decode_tar_octal(bytes: &[u8]) -> Option<u32> {
487    let mut val: u32 = 0;
488    let mut found = false;
489
490    for &b in bytes {
491        if b == b' ' || b == 0 {
492            if found {
493                break;
494            }
495            continue;
496        }
497        if (b'0'..=b'7').contains(&b) {
498            found = true;
499            let digit = u32::from(b.checked_sub(b'0')?);
500            val = val.checked_mul(8)?.checked_add(digit)?;
501        } else {
502            return None;
503        }
504    }
505
506    if found { Some(val) } else { None }
507}
508
509/// Inspects source for a valid 512-byte TAR header with matching checksum.
510pub fn inspect_tar<S: DetectionSource + ?Sized>(
511    source: &mut S,
512) -> Result<Option<DetectionCandidate>> {
513    let mut header = [0u8; 512];
514    let n = source.read_at(0, &mut header)?;
515    if n < 512 {
516        return Ok(None);
517    }
518
519    // Octal checksum is at bytes 148..156 (8 bytes)
520    let chksum_bytes = match header.get(148..156) {
521        Some(b) => b,
522        None => return Ok(None),
523    };
524
525    let expected_sum = match decode_tar_octal(chksum_bytes) {
526        Some(sum) => sum,
527        None => return Ok(None),
528    };
529
530    // Calculate sum across all 512 bytes with chksum treated as ASCII spaces
531    let mut calc_sum: u32 = 0;
532    for (i, &b) in header.iter().enumerate() {
533        if (148..156).contains(&i) {
534            calc_sum = calc_sum.saturating_add(u32::from(b' '));
535        } else {
536            calc_sum = calc_sum.saturating_add(u32::from(b));
537        }
538    }
539
540    if calc_sum != expected_sum {
541        return Ok(None);
542    }
543
544    // Reason for fallback: truncated header shorter than 265 bytes defaults to empty magic slice
545    let magic_slice = header.get(257..265).unwrap_or(&[]);
546    let (desc, mime) = if magic_slice.starts_with(b"ustar  \0")
547        || magic_slice.starts_with(b"ustar ")
548    {
549        ("POSIX tar archive (GNU)", "application/x-tar")
550    } else if magic_slice.starts_with(b"ustar\0") {
551        ("POSIX tar archive", "application/x-tar")
552    } else {
553        ("tar archive", "application/x-tar")
554    };
555
556    Ok(Some(DetectionCandidate {
557        format_id: Some(FormatId::Tar),
558        dc_id: None,
559        mime: Some(mime.to_string()),
560        description: desc.to_string(),
561        confidence: ConfidenceTier::HighestConfidence,
562        score: 95,
563        evidence: vec![DetectionEvidence::ContainerStructure {
564            detail: "Validated 512-byte TAR block checksum".to_string(),
565            score: 95,
566        }],
567        chain_layers: None,
568    }))
569}
570
571// ---------------------------------------------------------------------------
572// 2. Fast JSON State-Machine Scanner (`is_json.c`)
573// ---------------------------------------------------------------------------
574
575#[derive(Default)]
576struct JsonParseStats {
577    objects: usize,
578    arrays: usize,
579    strings: usize,
580    numbers: usize,
581    constants: usize,
582}
583
584fn json_skip_whitespace(bytes: &[u8], pos: &mut usize) {
585    while let Some(&b) = bytes.get(*pos) {
586        if b == b' ' || b == b'\t' || b == b'\n' || b == b'\r' {
587            *pos = pos.saturating_add(1);
588        } else {
589            break;
590        }
591    }
592}
593
594fn json_parse_string(bytes: &[u8], pos: &mut usize) -> bool {
595    // Consume opening quote
596    *pos = pos.saturating_add(1);
597
598    while *pos < bytes.len() {
599        let b = match bytes.get(*pos) {
600            Some(&val) => val,
601            None => return false,
602        };
603        *pos = pos.saturating_add(1);
604
605        match b {
606            0 => return false,
607            b'"' => return true,
608            b'\\' => {
609                let esc = match bytes.get(*pos) {
610                    Some(&val) => val,
611                    None => return false,
612                };
613                *pos = pos.saturating_add(1);
614                match esc {
615                    b'"' | b'\\' | b'/' | b'b' | b'f' | b'n' | b'r' | b't' => {}
616                    b'u' => {
617                        // 4 hexadecimal digits
618                        for _ in 0..4 {
619                            let hex = match bytes.get(*pos) {
620                                Some(&val) => val,
621                                None => return false,
622                            };
623                            if hex.is_ascii_hexdigit() {
624                                *pos = pos.saturating_add(1);
625                            } else {
626                                return false;
627                            }
628                        }
629                    }
630                    _ => return false,
631                }
632            }
633            _ => {}
634        }
635    }
636
637    false
638}
639
640fn json_parse_number(bytes: &[u8], pos: &mut usize) -> bool {
641    let mut got_digit = false;
642
643    if let Some(&b'-') = bytes.get(*pos) {
644        *pos = pos.saturating_add(1);
645    }
646
647    while let Some(&b) = bytes.get(*pos) {
648        if b.is_ascii_digit() {
649            got_digit = true;
650            *pos = pos.saturating_add(1);
651        } else {
652            break;
653        }
654    }
655
656    if !got_digit {
657        return false;
658    }
659
660    if let Some(&b'.') = bytes.get(*pos) {
661        *pos = pos.saturating_add(1);
662        let mut got_frac = false;
663        while let Some(&b) = bytes.get(*pos) {
664            if b.is_ascii_digit() {
665                got_frac = true;
666                *pos = pos.saturating_add(1);
667            } else {
668                break;
669            }
670        }
671        if !got_frac {
672            return false;
673        }
674    }
675
676    if let Some(&b'e' | &b'E') = bytes.get(*pos) {
677        *pos = pos.saturating_add(1);
678        if let Some(&b'+' | &b'-') = bytes.get(*pos) {
679            *pos = pos.saturating_add(1);
680        }
681        let mut got_exp = false;
682        while let Some(&b) = bytes.get(*pos) {
683            if b.is_ascii_digit() {
684                got_exp = true;
685                *pos = pos.saturating_add(1);
686            } else {
687                break;
688            }
689        }
690        if !got_exp {
691            return false;
692        }
693    }
694
695    true
696}
697
698fn json_parse_constant(bytes: &[u8], pos: &mut usize, expected: &[u8]) -> bool {
699    for &exp in expected {
700        let b = match bytes.get(*pos) {
701            Some(&val) => val,
702            None => return false,
703        };
704        if b != exp {
705            return false;
706        }
707        *pos = pos.saturating_add(1);
708    }
709    true
710}
711
712fn json_parse_array(
713    bytes: &[u8],
714    pos: &mut usize,
715    stats: &mut JsonParseStats,
716    depth: usize,
717) -> bool {
718    // Consume opening '['
719    *pos = pos.saturating_add(1);
720    json_skip_whitespace(bytes, pos);
721
722    if let Some(&b']') = bytes.get(*pos) {
723        *pos = pos.saturating_add(1);
724        stats.arrays = stats.arrays.saturating_add(1);
725        return true;
726    }
727
728    loop {
729        if !json_parse_value(bytes, pos, stats, depth.saturating_add(1)) {
730            return false;
731        }
732        json_skip_whitespace(bytes, pos);
733
734        match bytes.get(*pos) {
735            Some(&b',') => {
736                *pos = pos.saturating_add(1);
737                json_skip_whitespace(bytes, pos);
738            }
739            Some(&b']') => {
740                *pos = pos.saturating_add(1);
741                stats.arrays = stats.arrays.saturating_add(1);
742                return true;
743            }
744            _ => return false,
745        }
746    }
747}
748
749fn json_parse_object(
750    bytes: &[u8],
751    pos: &mut usize,
752    stats: &mut JsonParseStats,
753    depth: usize,
754) -> bool {
755    // Consume opening '{'
756    *pos = pos.saturating_add(1);
757    json_skip_whitespace(bytes, pos);
758
759    if let Some(&b'}') = bytes.get(*pos) {
760        *pos = pos.saturating_add(1);
761        stats.objects = stats.objects.saturating_add(1);
762        return true;
763    }
764
765    loop {
766        if let Some(&b'"') = bytes.get(*pos) {
767            if !json_parse_string(bytes, pos) {
768                return false;
769            }
770        } else {
771            return false;
772        }
773
774        json_skip_whitespace(bytes, pos);
775        if let Some(&b':') = bytes.get(*pos) {
776            *pos = pos.saturating_add(1);
777        } else {
778            return false;
779        }
780
781        if !json_parse_value(bytes, pos, stats, depth.saturating_add(1)) {
782            return false;
783        }
784
785        json_skip_whitespace(bytes, pos);
786        match bytes.get(*pos) {
787            Some(&b',') => {
788                *pos = pos.saturating_add(1);
789                json_skip_whitespace(bytes, pos);
790            }
791            Some(&b'}') => {
792                *pos = pos.saturating_add(1);
793                stats.objects = stats.objects.saturating_add(1);
794                return true;
795            }
796            _ => return false,
797        }
798    }
799}
800
801fn json_parse_value(
802    bytes: &[u8],
803    pos: &mut usize,
804    stats: &mut JsonParseStats,
805    depth: usize,
806) -> bool {
807    if depth > JSON_MAX_RECURSION_DEPTH {
808        return false;
809    }
810
811    json_skip_whitespace(bytes, pos);
812    let b = match bytes.get(*pos) {
813        Some(&val) => val,
814        None => return false,
815    };
816
817    match b {
818        b'"' => {
819            if json_parse_string(bytes, pos) {
820                stats.strings = stats.strings.saturating_add(1);
821                true
822            } else {
823                false
824            }
825        }
826        b'{' => json_parse_object(bytes, pos, stats, depth),
827        b'[' => json_parse_array(bytes, pos, stats, depth),
828        b't' => {
829            if json_parse_constant(bytes, pos, b"true") {
830                stats.constants = stats.constants.saturating_add(1);
831                true
832            } else {
833                false
834            }
835        }
836        b'f' => {
837            if json_parse_constant(bytes, pos, b"false") {
838                stats.constants = stats.constants.saturating_add(1);
839                true
840            } else {
841                false
842            }
843        }
844        b'n' => {
845            if json_parse_constant(bytes, pos, b"null") {
846                stats.constants = stats.constants.saturating_add(1);
847                true
848            } else {
849                false
850            }
851        }
852        _ => {
853            if json_parse_number(bytes, pos) {
854                stats.numbers = stats.numbers.saturating_add(1);
855                true
856            } else {
857                false
858            }
859        }
860    }
861}
862
863/// Evaluates buffer with JSON state machine scanner.
864/// Returns 1 for single JSON document, 2 for NDJSON / `JSONLines`, 0 for not JSON.
865pub fn scan_json(bytes: &[u8]) -> u8 {
866    let mut pos = 0;
867    let mut stats = JsonParseStats::default();
868
869    json_skip_whitespace(bytes, &mut pos);
870    if pos >= bytes.len() {
871        return 0;
872    }
873
874    // Top-level document must start with '{' or '[' to be recognized as JSON
875    match bytes.get(pos) {
876        Some(&b'{' | &b'[') => {}
877        _ => return 0,
878    }
879
880    let ok = json_parse_value(bytes, &mut pos, &mut stats, 0);
881    if !ok {
882        return 0;
883    }
884
885    json_skip_whitespace(bytes, &mut pos);
886    if pos >= bytes.len() {
887        if stats.objects > 0 || stats.arrays > 0 {
888            return 1;
889        }
890        return 0;
891    }
892
893    // Check if multiple JSON records appear on subsequent lines (NDJSON)
894    let mut count: usize = 1;
895    while pos < bytes.len() {
896        json_skip_whitespace(bytes, &mut pos);
897        if pos >= bytes.len() {
898            break;
899        }
900        match bytes.get(pos) {
901            Some(&b'{' | &b'[') => {
902                if json_parse_value(bytes, &mut pos, &mut stats, 0) {
903                    count = count.saturating_add(1);
904                } else {
905                    return 0;
906                }
907            }
908            _ => return 0,
909        }
910    }
911
912    if count > 1 { 2 } else { 0 }
913}
914
915/// Inspects source for JSON text data or NDJSON.
916pub fn inspect_json<S: DetectionSource + ?Sized>(
917    source: &mut S,
918) -> Result<Option<DetectionCandidate>> {
919    let mut buf = vec![0u8; JSON_MAX_INSPECT_BYTES];
920    let n = source.read_at(0, &mut buf)?;
921    if n == 0 {
922        return Ok(None);
923    }
924
925    let sample = match buf.get(..n) {
926        Some(s) => s,
927        None => return Ok(None),
928    };
929
930    match scan_json(sample) {
931        1 => Ok(Some(DetectionCandidate {
932            format_id: Some(FormatId::Json),
933            dc_id: None,
934            mime: Some("application/json".to_string()),
935            description: "JSON text data".to_string(),
936            confidence: ConfidenceTier::Strong,
937            score: 90,
938            evidence: vec![DetectionEvidence::ContainerStructure {
939                detail: "Validated JSON structure".to_string(),
940                score: 90,
941            }],
942            chain_layers: None,
943        })),
944        2 => Ok(Some(DetectionCandidate {
945            format_id: Some(FormatId::Json),
946            dc_id: None,
947            mime: Some("application/x-ndjson".to_string()),
948            description: "New Line Delimited JSON text data".to_string(),
949            confidence: ConfidenceTier::Strong,
950            score: 85,
951            evidence: vec![DetectionEvidence::ContainerStructure {
952                detail: "Validated New Line Delimited JSON lines".to_string(),
953                score: 85,
954            }],
955            chain_layers: None,
956        })),
957        _ => Ok(None),
958    }
959}
960
961// ---------------------------------------------------------------------------
962// 3. Tabular CSV/TSV Consistency Validator (`is_csv.c`)
963// ---------------------------------------------------------------------------
964
965/// Inspects source for tabular consistency (CSV or TSV).
966pub fn inspect_csv_tsv<S: DetectionSource + ?Sized>(
967    source: &mut S,
968) -> Result<Option<DetectionCandidate>> {
969    let mut buf = vec![0u8; CSV_MAX_INSPECT_BYTES];
970    let n = source.read_at(0, &mut buf)?;
971    if n < 4 {
972        return Ok(None);
973    }
974
975    let sample = match buf.get(..n) {
976        Some(s) => s,
977        None => return Ok(None),
978    };
979
980    // Ensure sample is valid text (ASCII or UTF-8)
981    if std::str::from_utf8(sample).is_err() {
982        return Ok(None);
983    }
984
985    // Try CSV with ','
986    if let Some(cand) = check_delimited_table(
987        sample,
988        b',',
989        FormatId::Csv,
990        "text/csv",
991        "CSV text",
992    ) {
993        return Ok(Some(cand));
994    }
995
996    // Try TSV with '\t'
997    if let Some(cand) = check_delimited_table(
998        sample,
999        b'\t',
1000        FormatId::Tsv,
1001        "text/tab-separated-values",
1002        "TSV text",
1003    ) {
1004        return Ok(Some(cand));
1005    }
1006
1007    Ok(None)
1008}
1009
1010fn check_delimited_table(
1011    bytes: &[u8],
1012    delim: u8,
1013    format_id: FormatId,
1014    mime: &str,
1015    desc: &str,
1016) -> Option<DetectionCandidate> {
1017    let mut line_count: usize = 0;
1018    let mut target_fields: Option<usize> = None;
1019    let mut pos: usize = 0;
1020
1021    while pos < bytes.len() && line_count < 15 {
1022        let mut field_count: usize = 1;
1023        let mut in_quotes = false;
1024        let mut line_has_content = false;
1025
1026        while let Some(&b) = bytes.get(pos) {
1027            pos = pos.saturating_add(1);
1028
1029            if b == b'"' {
1030                in_quotes = !in_quotes;
1031                line_has_content = true;
1032            } else if b == delim && !in_quotes {
1033                field_count = field_count.saturating_add(1);
1034                line_has_content = true;
1035            } else if b == b'\n' && !in_quotes {
1036                break;
1037            } else if b != b'\r' && !b.is_ascii_whitespace() {
1038                line_has_content = true;
1039            }
1040        }
1041
1042        if line_has_content {
1043            if let Some(target) = target_fields {
1044                if field_count != target {
1045                    return None;
1046                }
1047            } else {
1048                if field_count <= 1 {
1049                    return None;
1050                }
1051                target_fields = Some(field_count);
1052            }
1053            line_count = line_count.saturating_add(1);
1054        }
1055    }
1056
1057    if line_count >= 2 && target_fields.is_some_and(|f| f > 1) {
1058        Some(DetectionCandidate {
1059            format_id: Some(format_id),
1060            dc_id: None,
1061            mime: Some(mime.to_string()),
1062            description: desc.to_string(),
1063            confidence: ConfidenceTier::Moderate,
1064            score: 70,
1065            evidence: vec![DetectionEvidence::ContainerStructure {
1066                detail: format!(
1067                    "Consistent {line_count} rows with {target_fields:?} columns"
1068                ),
1069                score: 70,
1070            }],
1071            chain_layers: None,
1072        })
1073    } else {
1074        None
1075    }
1076}
1077
1078// ---------------------------------------------------------------------------
1079// 4. ELF Binary Header Inspector (`readelf.c`)
1080// ---------------------------------------------------------------------------
1081
1082/// Inspects source for ELF binary executable or library header.
1083pub fn inspect_elf<S: DetectionSource + ?Sized>(
1084    source: &mut S,
1085) -> Result<Option<DetectionCandidate>> {
1086    let Some(elf) = super::readelf::inspect_elf_details(source, None) else {
1087        return Ok(None);
1088    };
1089
1090    let class_str = if elf.is_64bit { "64-bit" } else { "32-bit" };
1091    let endian_str = if elf.is_le { "LSB" } else { "MSB" };
1092
1093    let (type_str, mime) = if elf.is_pie {
1094        ("pie executable", "application/x-pie-executable")
1095    } else {
1096        match elf.e_type {
1097            1 => ("relocatable", "application/x-object"),
1098            2 => ("executable", "application/x-executable"),
1099            3 => ("shared object", "application/x-sharedlib"),
1100            4 => ("core file", "application/x-coredump"),
1101            _ => ("executable", "application/x-executable"),
1102        }
1103    };
1104
1105    let desc = format!(
1106        "ELF {class_str} {endian_str} {type_str}, {}, version 1 ({}){}",
1107        elf.arch_str, elf.osabi_str, elf.suffix
1108    );
1109
1110    let mut evidence = vec![DetectionEvidence::ContainerStructure {
1111        detail: format!("Parsed ELF {class_str} {} header", elf.arch_str),
1112        score: 98,
1113    }];
1114    if !elf.x86_properties.is_empty() {
1115        evidence.push(DetectionEvidence::ContainerStructure {
1116            detail: format!(
1117                "x86 security properties: {}",
1118                elf.x86_properties.join(", ")
1119            ),
1120            score: 95,
1121        });
1122    }
1123    if !elf.aarch64_properties.is_empty() {
1124        evidence.push(DetectionEvidence::ContainerStructure {
1125            detail: format!(
1126                "AArch64 security properties: {}",
1127                elf.aarch64_properties.join(", ")
1128            ),
1129            score: 95,
1130        });
1131    }
1132    if let Some(ref pax) = elf.pax_flags {
1133        evidence.push(DetectionEvidence::ContainerStructure {
1134            detail: format!("PaX flags: {pax}"),
1135            score: 95,
1136        });
1137    }
1138    if let Some(ref memtag) = elf.android_memtag {
1139        evidence.push(DetectionEvidence::ContainerStructure {
1140            detail: format!("Android Memtag: {memtag}"),
1141            score: 95,
1142        });
1143    }
1144    if let Some(ref core) = elf.core_details {
1145        let mut parts = Vec::new();
1146        if let Some(style) = core.os_style {
1147            parts.push(format!("Style: {style}"));
1148        }
1149        if let Some(ref cmd) = core.command_line {
1150            parts.push(format!("Process: {cmd}"));
1151        }
1152        if let Some(pid) = core.pid {
1153            parts.push(format!("PID: {pid}"));
1154        }
1155        if let Some(sig) = core.signal {
1156            parts.push(format!("Signal: {sig}"));
1157        }
1158        if let Some(ip) = core.register_ip {
1159            parts.push(format!("Fault IP: 0x{ip:x}"));
1160        }
1161        if !parts.is_empty() {
1162            evidence.push(DetectionEvidence::ContainerStructure {
1163                detail: format!("Core dump: {}", parts.join(", ")),
1164                score: 98,
1165            });
1166        }
1167    }
1168
1169    Ok(Some(DetectionCandidate {
1170        format_id: Some(FormatId::Elf),
1171        dc_id: None,
1172        mime: Some(mime.to_string()),
1173        description: desc,
1174        confidence: ConfidenceTier::HighestConfidence,
1175        score: 98,
1176        evidence,
1177        chain_layers: None,
1178    }))
1179}
1180
1181// ---------------------------------------------------------------------------
1182// 5. OLE2 Compound Document File (CDF) Inspector (`readcdf.c`)
1183// ---------------------------------------------------------------------------
1184
1185const OLE2_MAGIC: [u8; 8] = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];
1186
1187/// Inspects source for OLE2 CDF containers (Word, Excel, `PowerPoint`, MSI, HWP).
1188pub fn inspect_ole2_cdf<S: DetectionSource + ?Sized>(
1189    source: &mut S,
1190) -> Result<Option<DetectionCandidate>> {
1191    let mut header = [0u8; 512];
1192    let n = source.read_at(0, &mut header)?;
1193    if n < 512 || !header.starts_with(&OLE2_MAGIC) {
1194        return Ok(None);
1195    }
1196
1197    let Some(&[s0, s1]) = header
1198        .get(30..32)
1199        .and_then(|s| <&[u8; 2]>::try_from(s).ok())
1200    else {
1201        return Ok(None);
1202    };
1203    let sector_shift = u16::from_le_bytes([s0, s1]);
1204    // OLE2 specification requires sector shift of 9 (512 bytes) or 12 (4096 bytes)
1205    if sector_shift != 9 && sector_shift != 12 {
1206        return Ok(None);
1207    }
1208    let sector_size: u64 = if sector_shift == 12 { 4096 } else { 512 };
1209
1210    let Some(&[f0, f1, f2, f3]) = header
1211        .get(48..52)
1212        .and_then(|s| <&[u8; 4]>::try_from(s).ok())
1213    else {
1214        return Ok(None);
1215    };
1216    let first_dir_sector = u32::from_le_bytes([f0, f1, f2, f3]);
1217
1218    // Directory sector offset is (first_dir_sector + 1) * sector_size
1219    let dir_offset = u64::from(first_dir_sector.saturating_add(1))
1220        .saturating_mul(sector_size);
1221
1222    let dir_buf_len = if sector_size == 4096 { 4096 } else { 512 };
1223    let mut dir_buf = vec![0u8; dir_buf_len];
1224    let dir_read = source.read_at(dir_offset, &mut dir_buf)?;
1225    if dir_read < 128 {
1226        return Ok(None);
1227    }
1228
1229    // Scan directory entries (128 bytes each)
1230    let mut stream_names = Vec::new();
1231    let valid_read = dir_read.min(dir_buf.len());
1232    if let Some(read_slice) = dir_buf.get(..valid_read) {
1233        for entry in read_slice.chunks_exact(128) {
1234            let name_len = if let Some(&[n0, n1]) =
1235                entry.get(64..66).and_then(|s| <&[u8; 2]>::try_from(s).ok())
1236            {
1237                u16::from_le_bytes([n0, n1])
1238            } else {
1239                0
1240            };
1241            let name_bytes_len = usize::from(name_len).min(64);
1242            if name_bytes_len >= 2 {
1243                if let Some(name_bytes) =
1244                    entry.get(..name_bytes_len.saturating_sub(2))
1245                {
1246                    let name_words: Vec<u16> = name_bytes
1247                        .chunks_exact(2)
1248                        .map(|c| {
1249                            if let &[b0, b1] = c {
1250                                u16::from_le_bytes([b0, b1])
1251                            } else {
1252                                0
1253                            }
1254                        })
1255                        .collect();
1256                    if let Ok(name) = String::from_utf16(&name_words) {
1257                        stream_names.push(name);
1258                    }
1259                }
1260            }
1261        }
1262    }
1263
1264    // Check DROID declarative OLE2 container signatures
1265    if let Ok(Some(cand)) =
1266        crate::detection::droid::evaluate_droid_ole2_container(
1267            source,
1268            &stream_names,
1269            &crate::detection::droid::DROID_CONTAINER_DB,
1270        )
1271    {
1272        return Ok(Some(cand));
1273    }
1274
1275    for name in &stream_names {
1276        if name == "WordDocument" {
1277            return Ok(Some(DetectionCandidate {
1278                format_id: None,
1279                dc_id: None,
1280                mime: Some("application/msword".to_string()),
1281                description: "Microsoft Word 97-2004 Document".to_string(),
1282                confidence: ConfidenceTier::HighestConfidence,
1283                score: 95,
1284                evidence: vec![DetectionEvidence::ContainerStructure {
1285                    detail: "Found OLE2 WordDocument stream".to_string(),
1286                    score: 95,
1287                }],
1288                chain_layers: None,
1289            }));
1290        } else if name == "Book" || name == "Workbook" {
1291            return Ok(Some(DetectionCandidate {
1292                format_id: None,
1293                dc_id: None,
1294                mime: Some("application/vnd.ms-excel".to_string()),
1295                description: "Microsoft Excel 97-2004 Worksheet".to_string(),
1296                confidence: ConfidenceTier::HighestConfidence,
1297                score: 95,
1298                evidence: vec![DetectionEvidence::ContainerStructure {
1299                    detail: "Found OLE2 Workbook stream".to_string(),
1300                    score: 95,
1301                }],
1302                chain_layers: None,
1303            }));
1304        } else if name == "PowerPoint Document" || name == "Current User" {
1305            return Ok(Some(DetectionCandidate {
1306                format_id: None,
1307                dc_id: None,
1308                mime: Some("application/vnd.ms-powerpoint".to_string()),
1309                description: "Microsoft PowerPoint 97-2004 Presentation"
1310                    .to_string(),
1311                confidence: ConfidenceTier::HighestConfidence,
1312                score: 95,
1313                evidence: vec![DetectionEvidence::ContainerStructure {
1314                    detail: "Found OLE2 PowerPoint stream".to_string(),
1315                    score: 95,
1316                }],
1317                chain_layers: None,
1318            }));
1319        } else if name == "DigitalSignature" {
1320            return Ok(Some(DetectionCandidate {
1321                format_id: None,
1322                dc_id: None,
1323                mime: Some("application/vnd.ms-msi".to_string()),
1324                description: "Microsoft Installer".to_string(),
1325                confidence: ConfidenceTier::HighestConfidence,
1326                score: 95,
1327                evidence: vec![DetectionEvidence::ContainerStructure {
1328                    detail: "Found OLE2 DigitalSignature stream".to_string(),
1329                    score: 95,
1330                }],
1331                chain_layers: None,
1332            }));
1333        } else if name == "FileHeader" || name == "HwpSummaryInformation" {
1334            // Check for Hancom HWP 5.0
1335            return Ok(Some(DetectionCandidate {
1336                format_id: None,
1337                dc_id: None,
1338                mime: Some("application/x-hwp".to_string()),
1339                description:
1340                    "Hancom HWP (Hangul Word Processor) file, version 5.0"
1341                        .to_string(),
1342                confidence: ConfidenceTier::HighestConfidence,
1343                score: 95,
1344                evidence: vec![DetectionEvidence::ContainerStructure {
1345                    detail: "Found OLE2 Hancom HWP streams".to_string(),
1346                    score: 95,
1347                }],
1348                chain_layers: None,
1349            }));
1350        }
1351    }
1352
1353    Ok(Some(DetectionCandidate {
1354        format_id: None,
1355        dc_id: None,
1356        mime: Some("application/x-ole-storage".to_string()),
1357        description: "Composite Document File V2 Document".to_string(),
1358        confidence: ConfidenceTier::Strong,
1359        score: 80,
1360        evidence: vec![DetectionEvidence::ContainerStructure {
1361            detail: "Identified OLE2 Compound Document File structure"
1362                .to_string(),
1363            score: 80,
1364        }],
1365        chain_layers: None,
1366    }))
1367}
1368
1369// ---------------------------------------------------------------------------
1370// 6. ZIP Container Inspection (DOCX, XLSX, PPTX, EPUB, APK, JAR, HWPX)
1371// ---------------------------------------------------------------------------
1372
1373const ZIP_LOCAL_HEADER_MAGIC: [u8; 4] = [0x50, 0x4B, 0x03, 0x04];
1374
1375/// Inspects source for ZIP archive containers and specialized package formats.
1376pub fn inspect_zip_container<S: DetectionSource + ?Sized>(
1377    source: &mut S,
1378) -> Result<Option<DetectionCandidate>> {
1379    if let Ok(Some(cand)) =
1380        crate::detection::droid::inspect_zip_container_comprehensive(source)
1381    {
1382        return Ok(Some(cand));
1383    }
1384
1385    let mut buf = vec![0u8; 8192];
1386    let n = source.read_at(0, &mut buf)?;
1387    if n < 30 || !buf.starts_with(&ZIP_LOCAL_HEADER_MAGIC) {
1388        return Ok(None);
1389    }
1390
1391    let sample = match buf.get(..n) {
1392        Some(s) => s,
1393        None => return Ok(None),
1394    };
1395
1396    // Scan initial local file headers
1397    let mut file_names = Vec::new();
1398    let mut pos: usize = 0;
1399    while pos.saturating_add(30) <= sample.len() {
1400        if sample.get(pos..pos.saturating_add(4))
1401            == Some(ZIP_LOCAL_HEADER_MAGIC.as_slice())
1402        {
1403            let Some(&[f0, f1, e0, e1]) = sample
1404                .get(pos.saturating_add(26)..pos.saturating_add(30))
1405                .and_then(|s| <&[u8; 4]>::try_from(s).ok())
1406            else {
1407                break;
1408            };
1409            let flen = u16::from_le_bytes([f0, f1]);
1410            let elen = u16::from_le_bytes([e0, e1]);
1411            let name_start = pos.saturating_add(30);
1412            let name_end = name_start.saturating_add(usize::from(flen));
1413            if let Some(name_bytes) = sample.get(name_start..name_end) {
1414                if let Ok(name) = std::str::from_utf8(name_bytes) {
1415                    file_names.push(name.to_string());
1416                }
1417            }
1418            pos = name_end
1419                .saturating_add(usize::from(elen))
1420                .max(pos.saturating_add(1));
1421        } else {
1422            pos = pos.saturating_add(1);
1423        }
1424    }
1425
1426    // Check for Office Open XML and specialized ZIP packages
1427    for name in &file_names {
1428        if name.starts_with("word/") {
1429            return Ok(Some(DetectionCandidate {
1430                format_id: None,
1431                dc_id: None,
1432                mime: Some(
1433                    "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
1434                        .to_string(),
1435                ),
1436                description: "Microsoft Word 2007+".to_string(),
1437                confidence: ConfidenceTier::HighestConfidence,
1438                score: 95,
1439                evidence: vec![DetectionEvidence::ContainerStructure {
1440                    detail: "Identified DOCX structure with word/ entry".to_string(),
1441                    score: 95,
1442                }],
1443                chain_layers: None,
1444            }));
1445        } else if name.starts_with("xl/") {
1446            return Ok(Some(DetectionCandidate {
1447                format_id: None,
1448                dc_id: None,
1449                mime: Some(
1450                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet".to_string(),
1451                ),
1452                description: "Microsoft Excel 2007+".to_string(),
1453                confidence: ConfidenceTier::HighestConfidence,
1454                score: 95,
1455                evidence: vec![DetectionEvidence::ContainerStructure {
1456                    detail: "Identified XLSX structure with xl/ entry".to_string(),
1457                    score: 95,
1458                }],
1459                chain_layers: None,
1460            }));
1461        } else if name.starts_with("ppt/") {
1462            return Ok(Some(DetectionCandidate {
1463                format_id: None,
1464                dc_id: None,
1465                mime: Some(
1466                    "application/vnd.openxmlformats-officedocument.presentationml.presentation"
1467                        .to_string(),
1468                ),
1469                description: "Microsoft PowerPoint 2007+".to_string(),
1470                confidence: ConfidenceTier::HighestConfidence,
1471                score: 95,
1472                evidence: vec![DetectionEvidence::ContainerStructure {
1473                    detail: "Identified PPTX structure with ppt/ entry".to_string(),
1474                    score: 95,
1475                }],
1476                chain_layers: None,
1477            }));
1478        } else if name.starts_with("Contents/content.hwpml")
1479            || name.starts_with("version.xml")
1480        {
1481            return Ok(Some(DetectionCandidate {
1482                format_id: None,
1483                dc_id: None,
1484                mime: Some("application/x-hwpx".to_string()),
1485                description: "Hancom HWP (Hangul Word Processor) file, HWPX"
1486                    .to_string(),
1487                confidence: ConfidenceTier::HighestConfidence,
1488                score: 95,
1489                evidence: vec![DetectionEvidence::ContainerStructure {
1490                    detail: "Identified HWPX structure with Contents/ entry"
1491                        .to_string(),
1492                    score: 95,
1493                }],
1494                chain_layers: None,
1495            }));
1496        } else if name == "AndroidManifest.xml" {
1497            return Ok(Some(DetectionCandidate {
1498                format_id: None,
1499                dc_id: None,
1500                mime: Some(
1501                    "application/vnd.android.package-archive".to_string(),
1502                ),
1503                description: "Android package (APK)".to_string(),
1504                confidence: ConfidenceTier::HighestConfidence,
1505                score: 95,
1506                evidence: vec![DetectionEvidence::ContainerStructure {
1507                    detail: "Identified APK with AndroidManifest.xml"
1508                        .to_string(),
1509                    score: 95,
1510                }],
1511                chain_layers: None,
1512            }));
1513        } else if name.starts_with("META-INF/MANIFEST.MF") {
1514            return Ok(Some(DetectionCandidate {
1515                format_id: None,
1516                dc_id: None,
1517                mime: Some("application/java-archive".to_string()),
1518                description: "Java archive data (JAR)".to_string(),
1519                confidence: ConfidenceTier::Strong,
1520                score: 90,
1521                evidence: vec![DetectionEvidence::ContainerStructure {
1522                    detail: "Identified JAR with META-INF/MANIFEST.MF"
1523                        .to_string(),
1524                    score: 90,
1525                }],
1526                chain_layers: None,
1527            }));
1528        } else if name == "mimetype"
1529            && sample.windows(20).any(|w| w == b"application/epub+zip")
1530        {
1531            return Ok(Some(DetectionCandidate {
1532                format_id: None,
1533                dc_id: None,
1534                mime: Some("application/epub+zip".to_string()),
1535                description: "EPUB document".to_string(),
1536                confidence: ConfidenceTier::HighestConfidence,
1537                score: 95,
1538                evidence: vec![DetectionEvidence::ContainerStructure {
1539                    detail: "Identified EPUB mimetype".to_string(),
1540                    score: 95,
1541                }],
1542                chain_layers: None,
1543            }));
1544        }
1545    }
1546
1547    Ok(Some(DetectionCandidate {
1548        format_id: Some(FormatId::Zip),
1549        dc_id: None,
1550        mime: Some("application/zip".to_string()),
1551        description: "Zip archive data".to_string(),
1552        confidence: ConfidenceTier::Strong,
1553        score: 85,
1554        evidence: vec![DetectionEvidence::ContainerStructure {
1555            detail: "Identified ZIP header entries".to_string(),
1556            score: 85,
1557        }],
1558        chain_layers: None,
1559    }))
1560}
1561
1562// ---------------------------------------------------------------------------
1563// 8. SIM-H Magnetic Tape Image Inspector (`is_simh.c`)
1564// ---------------------------------------------------------------------------
1565
1566#[derive(Copy, Clone, PartialEq, Eq)]
1567enum SimhEndianness {
1568    Little,
1569    Big,
1570}
1571
1572#[derive(Copy, Clone, PartialEq, Eq)]
1573struct SimhLen {
1574    raw: u32,
1575    padded: usize,
1576}
1577
1578fn get_simh_record_len(
1579    slice: &[u8],
1580    offset: &mut usize,
1581    endianness: SimhEndianness,
1582) -> Option<SimhLen> {
1583    if offset.saturating_add(4) > slice.len() {
1584        return None;
1585    }
1586    let b0 = *slice.get(*offset)?;
1587    let b1 = *slice.get(offset.saturating_add(1))?;
1588    let b2 = *slice.get(offset.saturating_add(2))?;
1589    let b3 = *slice.get(offset.saturating_add(3))?;
1590    let bytes = [b0, b1, b2, b3];
1591    *offset = offset.saturating_add(4);
1592
1593    let n = match endianness {
1594        SimhEndianness::Little => u32::from_le_bytes(bytes),
1595        SimhEndianness::Big => u32::from_be_bytes(bytes),
1596    };
1597
1598    if n == 0xFFFF_FFFF {
1599        return Some(SimhLen {
1600            raw: 0xFFFF_FFFF,
1601            padded: 0,
1602        });
1603    }
1604
1605    // Upstream check: Bits 24 to 27 are not used (must match).
1606    if (n & 0x00FF_FFFF) != (n & 0x0FFF_FFFF) {
1607        return None;
1608    }
1609
1610    let raw = n & 0x00FF_FFFF;
1611    let mut padded = raw;
1612    // Odd record lengths are padded to an even number of bytes on tape
1613    if (padded & 1) != 0 {
1614        padded = padded.saturating_add(1);
1615    }
1616    let padded_usize = usize::try_from(padded).ok()?;
1617    Some(SimhLen {
1618        raw,
1619        padded: padded_usize,
1620    })
1621}
1622
1623fn simh_parse_endian(data: &[u8], endianness: SimhEndianness) -> bool {
1624    let mut offset: usize = 0;
1625    let mut num_tapemarks: usize = 0;
1626    let mut num_records: usize = 0;
1627    let max_tapemarks = 10usize;
1628
1629    while data.len().saturating_sub(offset) >= 4 {
1630        let rec = match get_simh_record_len(data, &mut offset, endianness) {
1631            Some(r) => r,
1632            None => return false,
1633        };
1634
1635        if (num_tapemarks > 0 || num_records > 0) && rec.raw == 0xFFFF_FFFF {
1636            // End of medium after at least one record or tapemark
1637            break;
1638        }
1639
1640        if rec.raw == 0 {
1641            num_tapemarks = num_tapemarks.saturating_add(1);
1642            if num_tapemarks >= max_tapemarks {
1643                break;
1644            }
1645            continue;
1646        }
1647
1648        offset = match offset.checked_add(rec.padded) {
1649            Some(o) => o,
1650            None => return false,
1651        };
1652
1653        if data.len().saturating_sub(offset) < 4 {
1654            break;
1655        }
1656
1657        let trailer = match get_simh_record_len(data, &mut offset, endianness) {
1658            Some(t) => t,
1659            None => return false,
1660        };
1661
1662        if rec.raw != trailer.raw {
1663            return false;
1664        }
1665        num_records = num_records.saturating_add(1);
1666    }
1667
1668    let tapemark_bytes = num_tapemarks.saturating_mul(4);
1669    if tapemark_bytes == offset && num_records == 0 {
1670        return false;
1671    }
1672    if num_records == 0 {
1673        return false;
1674    }
1675
1676    true
1677}
1678
1679fn simh_parse(data: &[u8]) -> bool {
1680    // Try standard Little-Endian first; if that fails, try Big-Endian.
1681    // This provides robust support without host byte-order dependency.
1682    simh_parse_endian(data, SimhEndianness::Little)
1683        || simh_parse_endian(data, SimhEndianness::Big)
1684}
1685
1686/// Inspects source for SIM-H magnetic tape image format (`is_simh.c`).
1687pub fn inspect_simh<S: DetectionSource + ?Sized>(
1688    source: &mut S,
1689) -> Result<Option<DetectionCandidate>> {
1690    let inspect_bytes = 65536usize;
1691    let mut buf = vec![0u8; inspect_bytes];
1692    let n = match source.read_at(0, &mut buf) {
1693        Ok(read_len) => read_len,
1694        Err(_) => return Ok(None),
1695    };
1696    let Some(sample) = buf.get(..n) else {
1697        return Ok(None);
1698    };
1699
1700    if !simh_parse(sample) {
1701        return Ok(None);
1702    }
1703
1704    Ok(Some(DetectionCandidate {
1705        format_id: None,
1706        dc_id: None,
1707        mime: Some("application/SIMH-tape-data".to_string()),
1708        description: "SIMH tape data".to_string(),
1709        confidence: ConfidenceTier::Moderate,
1710        score: 80,
1711        evidence: vec![DetectionEvidence::ContainerStructure {
1712            detail: "SIMH magnetic tape image format with valid record framing"
1713                .to_string(),
1714            score: 80,
1715        }],
1716        chain_layers: None,
1717    }))
1718}
1719
1720// ---------------------------------------------------------------------------
1721// Public Subsystem Coordinator
1722// ---------------------------------------------------------------------------
1723
1724/// Evaluates all container, structured format, and decompression inspectors on
1725/// source.
1726pub fn detect_container_candidates<S: DetectionSource + ?Sized>(
1727    source: &mut S,
1728    _hint: Option<&DetectionHint>,
1729) -> Result<Vec<DetectionCandidate>> {
1730    let mut candidates = Vec::new();
1731
1732    // 1. ELF binary inspection
1733    if let Ok(Some(elf_cand)) = inspect_elf(source) {
1734        candidates.push(elf_cand);
1735        return Ok(candidates);
1736    }
1737
1738    // 3. OLE2 CDF inspection
1739    if let Ok(Some(ole_cand)) = inspect_ole2_cdf(source) {
1740        candidates.push(ole_cand);
1741        return Ok(candidates);
1742    }
1743
1744    // 4. ZIP container inspection
1745    if let Ok(Some(zip_cand)) = inspect_zip_container(source) {
1746        candidates.push(zip_cand);
1747        return Ok(candidates);
1748    }
1749
1750    // 5. TAR archive verification
1751    if let Ok(Some(tar_cand)) = inspect_tar(source) {
1752        candidates.push(tar_cand);
1753        return Ok(candidates);
1754    }
1755
1756    // 6. JSON state-machine scanner
1757    if let Ok(Some(json_cand)) = inspect_json(source) {
1758        candidates.push(json_cand);
1759        return Ok(candidates);
1760    }
1761
1762    // 7. CSV/TSV tabular consistency
1763    if let Ok(Some(csv_cand)) = inspect_csv_tsv(source) {
1764        candidates.push(csv_cand);
1765    }
1766
1767    // 8. SIM-H magnetic tape image inspection
1768    if let Ok(Some(simh_cand)) = inspect_simh(source) {
1769        candidates.push(simh_cand);
1770        return Ok(candidates);
1771    }
1772
1773    Ok(candidates)
1774}
1775
1776#[cfg(test)]
1777#[allow(
1778    clippy::panic,
1779    clippy::expect_used,
1780    clippy::unwrap_used,
1781    clippy::unwrap_in_result,
1782    clippy::panic_in_result_fn,
1783    clippy::indexing_slicing,
1784    clippy::arithmetic_side_effects,
1785    reason = "Standard repository test boilerplate"
1786)]
1787mod tests {
1788    use super::*;
1789
1790    #[ctb_test]
1791    fn test_inspect_json_valid_object() {
1792        let json_data = br#"{"key": "value", "count": 42, "enabled": true}"#;
1793        let mut source: &[u8] = json_data;
1794        let cand = inspect_json(&mut source).unwrap().unwrap();
1795        assert_eq!(cand.description, "JSON text data");
1796        assert_eq!(cand.mime.as_deref(), Some("application/json"));
1797        assert_eq!(cand.format_id, Some(FormatId::Json));
1798    }
1799
1800    #[ctb_test]
1801    fn test_inspect_json_ndjson() {
1802        let ndjson_data = b"{\"a\": 1}\n{\"b\": 2}\n";
1803        let mut source: &[u8] = ndjson_data;
1804        let cand = inspect_json(&mut source).unwrap().unwrap();
1805        assert_eq!(cand.description, "New Line Delimited JSON text data");
1806        assert_eq!(cand.mime.as_deref(), Some("application/x-ndjson"));
1807    }
1808
1809    #[ctb_test]
1810    fn test_inspect_csv_valid() {
1811        let csv_data = b"name,age,city\nAlice,30,New York\nBob,25,Chicago\n";
1812        let mut source: &[u8] = csv_data;
1813        let cand = inspect_csv_tsv(&mut source).unwrap().unwrap();
1814        assert_eq!(cand.description, "CSV text");
1815        assert_eq!(cand.mime.as_deref(), Some("text/csv"));
1816        assert_eq!(cand.format_id, Some(FormatId::Csv));
1817    }
1818
1819    #[ctb_test]
1820    fn test_inspect_simh_valid_tape_le() {
1821        // Record 1: 5 bytes "HELLO" (odd, padded to 6 bytes on tape)
1822        // Record 2: Tapemark (4 bytes of 0x00)
1823        // Record 3: 4 bytes "TAPE" (even, 4 bytes on tape)
1824        let mut tape = Vec::new();
1825        // Record 1: len 5 (LE)
1826        tape.extend_from_slice(&5u32.to_le_bytes());
1827        tape.extend_from_slice(b"HELLO\0"); // 5 data + 1 pad
1828        tape.extend_from_slice(&5u32.to_le_bytes());
1829        // Tapemark
1830        tape.extend_from_slice(&0u32.to_le_bytes());
1831        // Record 2: len 4 (LE)
1832        tape.extend_from_slice(&4u32.to_le_bytes());
1833        tape.extend_from_slice(b"TAPE");
1834        tape.extend_from_slice(&4u32.to_le_bytes());
1835
1836        let mut source: &[u8] = &tape;
1837        let cand = inspect_simh(&mut source).unwrap().unwrap();
1838        assert_eq!(cand.description, "SIMH tape data");
1839        assert_eq!(cand.mime.as_deref(), Some("application/SIMH-tape-data"));
1840    }
1841
1842    #[ctb_test]
1843    fn test_inspect_simh_valid_tape_be() {
1844        // Big-endian record len
1845        let mut tape = Vec::new();
1846        tape.extend_from_slice(&4u32.to_be_bytes());
1847        tape.extend_from_slice(b"DATA");
1848        tape.extend_from_slice(&4u32.to_be_bytes());
1849
1850        let mut source: &[u8] = &tape;
1851        let cand = inspect_simh(&mut source).unwrap().unwrap();
1852        assert_eq!(cand.description, "SIMH tape data");
1853    }
1854
1855    #[ctb_test]
1856    fn test_inspect_simh_eom_marker() {
1857        let mut tape = Vec::new();
1858        tape.extend_from_slice(&2u32.to_le_bytes());
1859        tape.extend_from_slice(b"OK");
1860        tape.extend_from_slice(&2u32.to_le_bytes());
1861        // End of Medium
1862        tape.extend_from_slice(&0xFFFF_FFFFu32.to_le_bytes());
1863
1864        let mut source: &[u8] = &tape;
1865        let cand = inspect_simh(&mut source).unwrap().unwrap();
1866        assert_eq!(cand.description, "SIMH tape data");
1867    }
1868
1869    #[ctb_test]
1870    fn test_inspect_simh_reject_all_tapemarks() {
1871        // All zeros (tapemarks only) must be rejected
1872        let zeros = vec![0u8; 64];
1873        let mut source: &[u8] = &zeros;
1874        assert!(inspect_simh(&mut source).unwrap().is_none());
1875    }
1876
1877    #[ctb_test]
1878    fn test_inspect_simh_reject_mismatched_lengths() {
1879        let mut tape = Vec::new();
1880        tape.extend_from_slice(&4u32.to_le_bytes());
1881        tape.extend_from_slice(b"DATA");
1882        tape.extend_from_slice(&3u32.to_le_bytes()); // Mismatched trailer length
1883
1884        let mut source: &[u8] = &tape;
1885        assert!(inspect_simh(&mut source).unwrap().is_none());
1886    }
1887
1888    #[ctb_test]
1889    fn test_inspect_elf_header() {
1890        let mut elf_bytes = vec![0u8; 64];
1891        elf_bytes[..4].copy_from_slice(b"\x7fELF");
1892        elf_bytes[4] = 2; // 64-bit
1893        elf_bytes[5] = 1; // LSB
1894        elf_bytes[6] = 1; // version
1895        elf_bytes[7] = 0; // SYSV
1896        elf_bytes[16] = 2; // executable
1897        elf_bytes[18] = 0x3E; // x86-64
1898
1899        let mut source: &[u8] = &elf_bytes;
1900        let cand = inspect_elf(&mut source).unwrap().unwrap();
1901        assert!(
1902            cand.description
1903                .contains("ELF 64-bit LSB executable, x86-64")
1904        );
1905        assert_eq!(cand.mime.as_deref(), Some("application/x-executable"));
1906        assert_eq!(cand.format_id, Some(FormatId::Elf));
1907    }
1908
1909    #[ctb_test]
1910    fn test_inspect_elf_rich_core_dump() {
1911        let mut elf = vec![0u8; 1024];
1912        elf[..4].copy_from_slice(b"\x7fELF");
1913        elf[4] = 2; // 64-bit
1914        elf[5] = 1; // LSB
1915        elf[6] = 1;
1916        elf[7] = 0; // SYSV
1917        elf[16] = 4; // e_type: ET_CORE
1918        elf[18] = 0x3E; // x86-64
1919
1920        // e_phoff = 64, phnum = 2
1921        elf[32..40].copy_from_slice(&64u64.to_le_bytes());
1922        elf[54..56].copy_from_slice(&56u16.to_le_bytes());
1923        elf[56..58].copy_from_slice(&2u16.to_le_bytes());
1924
1925        // Phdr 0: PT_LOAD at offset 512, filesz 256, vaddr 0x400000
1926        let ph0 = 64usize;
1927        elf[ph0..ph0 + 4].copy_from_slice(&1u32.to_le_bytes()); // PT_LOAD
1928        elf[ph0 + 8..ph0 + 16].copy_from_slice(&512u64.to_le_bytes());
1929        elf[ph0 + 16..ph0 + 24].copy_from_slice(&0x400000u64.to_le_bytes());
1930        elf[ph0 + 32..ph0 + 40].copy_from_slice(&256u64.to_le_bytes());
1931
1932        // Phdr 1: PT_NOTE at offset 200, size 512
1933        let ph1 = 64usize + 56;
1934        elf[ph1..ph1 + 4].copy_from_slice(&4u32.to_le_bytes()); // PT_NOTE
1935        elf[ph1 + 8..ph1 + 16].copy_from_slice(&200u64.to_le_bytes());
1936        elf[ph1 + 32..ph1 + 40].copy_from_slice(&512u64.to_le_bytes());
1937
1938        // Note 1: NT_PRPSINFO (3), name "CORE\0", size 128
1939        let n1 = 200usize;
1940        elf[n1..n1 + 4].copy_from_slice(&5u32.to_le_bytes());
1941        elf[n1 + 4..n1 + 8].copy_from_slice(&128u32.to_le_bytes());
1942        elf[n1 + 8..n1 + 12].copy_from_slice(&3u32.to_le_bytes()); // NT_PRPSINFO
1943        elf[n1 + 12..n1 + 17].copy_from_slice(b"CORE\0");
1944        // PRPSOFFSETS64[2] is 56 (Linux command line): write "myprog -v\0" at n1 + 20 + 56
1945        let cmd_bytes = b"myprog -v\0";
1946        elf[n1 + 20 + 56..n1 + 20 + 56 + cmd_bytes.len()]
1947            .copy_from_slice(cmd_bytes);
1948
1949        // Note 2: NT_PRSTATUS (1), size 256
1950        let n2 = n1 + 20 + 128;
1951        elf[n2..n2 + 4].copy_from_slice(&5u32.to_le_bytes());
1952        elf[n2 + 4..n2 + 8].copy_from_slice(&256u32.to_le_bytes());
1953        elf[n2 + 8..n2 + 12].copy_from_slice(&1u32.to_le_bytes()); // NT_PRSTATUS
1954        elf[n2 + 12..n2 + 17].copy_from_slice(b"CORE\0");
1955        // signal = 11 (SIGSEGV) at n2 + 20 + 0
1956        elf[n2 + 20..n2 + 20 + 4].copy_from_slice(&11u32.to_le_bytes());
1957        // pid = 4321 at n2 + 20 + 32
1958        elf[n2 + 20 + 32..n2 + 20 + 36].copy_from_slice(&4321u32.to_le_bytes());
1959        // rip = 0x401234 at n2 + 20 + 240
1960        elf[n2 + 20 + 240..n2 + 20 + 248]
1961            .copy_from_slice(&0x401234u64.to_le_bytes());
1962
1963        let mut source: &[u8] = &elf;
1964        let cand = inspect_elf(&mut source).unwrap().unwrap();
1965        assert_eq!(cand.format_id, Some(FormatId::Elf));
1966        assert_eq!(cand.mime.as_deref(), Some("application/x-coredump"));
1967        // Check compat description
1968        assert!(cand.description.contains(", SVR4-style, from 'myprog -v'"));
1969        // Check rich evidence
1970        let evidence_details: Vec<String> = cand
1971            .evidence
1972            .iter()
1973            .filter_map(|e| match e {
1974                DetectionEvidence::ContainerStructure { detail, .. } => {
1975                    Some(detail.clone())
1976                }
1977                _ => None,
1978            })
1979            .collect();
1980        assert!(evidence_details.iter().any(|d| {
1981            d.starts_with("Core dump:")
1982                && d.contains("Style: SVR4")
1983                && d.contains("Process: myprog -v")
1984                && d.contains("PID: 4321")
1985                && d.contains("Signal: 11")
1986                && d.contains("Fault IP: 0x401234")
1987        }));
1988    }
1989
1990    #[ctb_test]
1991    fn test_inspect_tar_header() {
1992        let mut tar_bytes = vec![0u8; 512];
1993        tar_bytes[..5].copy_from_slice(b"hello");
1994        tar_bytes[257..263].copy_from_slice(b"ustar\0");
1995
1996        // Calculate checksum
1997        let mut sum: u32 = 0;
1998        for (i, &b) in tar_bytes.iter().enumerate() {
1999            if (148..156).contains(&i) {
2000                sum = sum.saturating_add(u32::from(b' '));
2001            } else {
2002                sum = sum.saturating_add(u32::from(b));
2003            }
2004        }
2005        let chksum_str = format!("{sum:06o}\0 ");
2006        tar_bytes[148..156].copy_from_slice(chksum_str.as_bytes());
2007
2008        let mut source: &[u8] = &tar_bytes;
2009        let cand = inspect_tar(&mut source).unwrap().unwrap();
2010        assert_eq!(cand.description, "POSIX tar archive");
2011        assert_eq!(cand.mime.as_deref(), Some("application/x-tar"));
2012        assert_eq!(cand.format_id, Some(FormatId::Tar));
2013    }
2014
2015    #[ctb_test]
2016    fn test_inspect_ole2_cdf_malformed_and_valid() {
2017        // Truncated header (< 512 bytes)
2018        let mut malformed_short = [0u8; 100];
2019        malformed_short[..8].copy_from_slice(&OLE2_MAGIC);
2020        let mut src_short: &[u8] = &malformed_short;
2021        assert!(inspect_ole2_cdf(&mut src_short).unwrap().is_none());
2022
2023        // Corrupted sector shift / out of bounds directory sector
2024        let mut malformed_sectors = vec![0u8; 1024];
2025        malformed_sectors[..8].copy_from_slice(&OLE2_MAGIC);
2026        malformed_sectors[30..32].copy_from_slice(&60u16.to_le_bytes());
2027        malformed_sectors[48..52]
2028            .copy_from_slice(&0xFFFF_FFFFu32.to_le_bytes());
2029        let mut src_sectors: &[u8] = &malformed_sectors;
2030        assert!(inspect_ole2_cdf(&mut src_sectors).unwrap().is_none());
2031
2032        // Valid minimal OLE2 CDF with WordDocument stream entry
2033        let sector_size: usize = 512;
2034        let mut valid_cdf = vec![0u8; sector_size.saturating_mul(3)];
2035        valid_cdf[..8].copy_from_slice(&OLE2_MAGIC);
2036        valid_cdf[30..32].copy_from_slice(&9u16.to_le_bytes());
2037        valid_cdf[48..52].copy_from_slice(&0u32.to_le_bytes());
2038
2039        let dir_offset: usize = 512;
2040        let word_doc_utf16: Vec<u16> =
2041            "WordDocument\0".encode_utf16().collect();
2042        for (i, &w) in word_doc_utf16.iter().enumerate() {
2043            let byte_idx = dir_offset.saturating_add(i.saturating_mul(2));
2044            valid_cdf[byte_idx..byte_idx.saturating_add(2)]
2045                .copy_from_slice(&w.to_le_bytes());
2046        }
2047        let name_bytes_len =
2048            u16::try_from(word_doc_utf16.len().saturating_mul(2)).unwrap();
2049        valid_cdf[dir_offset.saturating_add(64)..dir_offset.saturating_add(66)]
2050            .copy_from_slice(&name_bytes_len.to_le_bytes());
2051
2052        let mut src_valid: &[u8] = &valid_cdf;
2053        let cand = inspect_ole2_cdf(&mut src_valid).unwrap().unwrap();
2054        assert!(cand.description.contains("Microsoft Word"));
2055    }
2056}
2057/*
2058/*
2059 * Adapted from: apptype.c, Written by Eberhard Mattes and put into the
2060 * file_public domain
2061 *
2062 * Notes: 1. Qualify the filename so that DosQueryAppType does not do extraneous
2063 * searches.
2064 *
2065 * 2. DosQueryAppType will return FAPPTYP_DOS on a file ending with ".com"
2066 * (other than an OS/2 exe or Win exe with this name). Eberhard Mattes
2067 * remarks Tue, 6 Apr 93: Moreover, it reports the type of the (new and very
2068 * bug ridden) Win Emacs as "OS/2 executable".
2069 *
2070 * 3. apptype() uses the filename if given, otherwise a tmp file is created with
2071 * the contents of buf. If buf is not the complete file, apptype can
2072 * incorrectly identify the exe type. The "-z" option of "file" is the reason
2073 * for this ugly code.
2074 */
2075
2076The preceding notice is from src/apptype.c in `file`.
2077
2078
2079
2080/*-
2081 * Copyright (c) 2008 Christos Zoulas
2082 * All rights reserved.
2083 *
2084 * Redistribution and use in source and binary forms, with or without
2085 * modification, are permitted provided that the following conditions
2086 * are met:
2087 * 1. Redistributions of source code must retain the above copyright
2088 *    notice, this list of conditions and the following disclaimer.
2089 * 2. Redistributions in binary form must reproduce the above copyright
2090 *    notice, this list of conditions and the following disclaimer in the
2091 *    documentation and/or other materials provided with the distribution.
2092 *
2093 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
2094 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
2095 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
2096 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
2097 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
2098 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
2099 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
2100 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
2101 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
2102 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
2103 * POSSIBILITY OF SUCH DAMAGE.
2104 */
2105
2106The preceding notice is from src/cdf.c, src/cdf.h, and src/cdf_time.c in `file`.
2107
2108
2109
2110/*-
2111 * Copyright (c) 2016 Christos Zoulas
2112 * All rights reserved.
2113 *
2114 * Redistribution and use in source and binary forms, with or without
2115 * modification, are permitted provided that the following conditions
2116 * are met:
2117 * 1. Redistributions of source code must retain the above copyright
2118 *    notice, this list of conditions and the following disclaimer.
2119 * 2. Redistributions in binary form must reproduce the above copyright
2120 *    notice, this list of conditions and the following disclaimer in the
2121 *    documentation and/or other materials provided with the distribution.
2122 *
2123 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
2124 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
2125 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
2126 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
2127 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
2128 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
2129 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
2130 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
2131 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
2132 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
2133 * POSSIBILITY OF SUCH DAMAGE.
2134 */
2135
2136The preceding notice is from src/der.c and src/der.h in `file`.
2137
2138
2139
2140/*-
2141 * Copyright (c) 2019 Christos Zoulas
2142 * All rights reserved.
2143 *
2144 * Redistribution and use in source and binary forms, with or without
2145 * modification, are permitted provided that the following conditions
2146 * are met:
2147 * 1. Redistributions of source code must retain the above copyright
2148 *    notice, this list of conditions and the following disclaimer.
2149 * 2. Redistributions in binary form must reproduce the above copyright
2150 *    notice, this list of conditions and the following disclaimer in the
2151 *    documentation and/or other materials provided with the distribution.
2152 *
2153 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
2154 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
2155 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
2156 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
2157 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
2158 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
2159 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
2160 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
2161 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
2162 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
2163 * POSSIBILITY OF SUCH DAMAGE.
2164 */
2165
2166The preceding notice is from src/is_csv.c in `file`.
2167
2168
2169
2170/*-
2171 * Copyright (c) 2018 Christos Zoulas
2172 * All rights reserved.
2173 *
2174 * Redistribution and use in source and binary forms, with or without
2175 * modification, are permitted provided that the following conditions
2176 * are met:
2177 * 1. Redistributions of source code must retain the above copyright
2178 *    notice, this list of conditions and the following disclaimer.
2179 * 2. Redistributions in binary form must reproduce the above copyright
2180 *    notice, this list of conditions and the following disclaimer in the
2181 *    documentation and/or other materials provided with the distribution.
2182 *
2183 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
2184 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
2185 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
2186 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
2187 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
2188 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
2189 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
2190 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
2191 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
2192 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
2193 * POSSIBILITY OF SUCH DAMAGE.
2194 */
2195
2196The preceding notice is from src/is_json.c in `file`.
2197
2198
2199
2200/*-
2201 * Copyright (c) 2023 Christos Zoulas
2202 * All rights reserved.
2203 *
2204 * Redistribution and use in source and binary forms, with or without
2205 * modification, are permitted provided that the following conditions
2206 * are met:
2207 * 1. Redistributions of source code must retain the above copyright
2208 *    notice, this list of conditions and the following disclaimer.
2209 * 2. Redistributions in binary form must reproduce the above copyright
2210 *    notice, this list of conditions and the following disclaimer in the
2211 *    documentation and/or other materials provided with the distribution.
2212 *
2213 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
2214 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
2215 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
2216 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
2217 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
2218 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
2219 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
2220 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
2221 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
2222 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
2223 * POSSIBILITY OF SUCH DAMAGE.
2224 */
2225
2226The preceding notice is from src/is_simh.c in `file`.
2227
2228
2229
2230/*-
2231 * SPDX-License-Identifier: BSD-3-Clause
2232 *
2233 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
2234 * Copyright (c) 1992, 1993, 1994
2235 *      The Regents of the University of California.  All rights reserved.
2236 *
2237 * This code is derived from software contributed to Berkeley by
2238 * Henry Spencer.
2239 *
2240 * Redistribution and use in source and binary forms, with or without
2241 * modification, are permitted provided that the following conditions
2242 * are met:
2243 * 1. Redistributions of source code must retain the above copyright
2244 *    notice, this list of conditions and the following disclaimer.
2245 * 2. Redistributions in binary form must reproduce the above copyright
2246 *    notice, this list of conditions and the following disclaimer in the
2247 *    documentation and/or other materials provided with the distribution.
2248 * 3. Neither the name of the University nor the names of its contributors
2249 *    may be used to endorse or promote products derived from this software
2250 *    without specific prior written permission.
2251 *
2252 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2253 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2254 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2255 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2256 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2257 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2258 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2259 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2260 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2261 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2262 * SUCH DAMAGE.
2263 *
2264 *      @(#)cname.h     8.3 (Berkeley) 3/20/94
2265 * $FreeBSD: head/lib/libc/regex/cname.h 326025 2017-11-20 19:49:47Z pfg $
2266 */
2267
2268The preceding notice is from src/missing/cname.h in `file`.
2269
2270
2271
2272/*-
2273 * SPDX-License-Identifier: BSD-3-Clause
2274 *
2275 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
2276 * Copyright (c) 1992, 1993, 1994
2277 *      The Regents of the University of California.  All rights reserved.
2278 *
2279 * This code is derived from software contributed to Berkeley by
2280 * Henry Spencer.
2281 *
2282 * Redistribution and use in source and binary forms, with or without
2283 * modification, are permitted provided that the following conditions
2284 * are met:
2285 * 1. Redistributions of source code must retain the above copyright
2286 *    notice, this list of conditions and the following disclaimer.
2287 * 2. Redistributions in binary form must reproduce the above copyright
2288 *    notice, this list of conditions and the following disclaimer in the
2289 *    documentation and/or other materials provided with the distribution.
2290 * 3. Neither the name of the University nor the names of its contributors
2291 *    may be used to endorse or promote products derived from this software
2292 *    without specific prior written permission.
2293 *
2294 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2295 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2296 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2297 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2298 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2299 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2300 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2301 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2302 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2303 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2304 * SUCH DAMAGE.
2305 *
2306 *      @(#)engine.c    8.5 (Berkeley) 3/20/94
2307 */
2308
2309The preceding notice is from src/missing/engine.c in `file`.
2310
2311
2312
2313/*-
2314 * Copyright (c) 2000 The NetBSD Foundation, Inc.
2315 * All rights reserved.
2316 *
2317 * This code was contributed to The NetBSD Foundation by Allen Briggs.
2318 *
2319 * Redistribution and use in source and binary forms, with or without
2320 * modification, are permitted provided that the following conditions
2321 * are met:
2322 * 1. Redistributions of source code must retain the above copyright
2323 *    notice, this list of conditions and the following disclaimer.
2324 * 2. Redistributions in binary form must reproduce the above copyright
2325 *    notice, this list of conditions and the following disclaimer in the
2326 *    documentation and/or other materials provided with the distribution.
2327 *
2328 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
2329 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
2330 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
2331 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
2332 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
2333 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
2334 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
2335 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
2336 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
2337 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
2338 * POSSIBILITY OF SUCH DAMAGE.
2339 */
2340
2341The preceding notice is from src/missing/fmtcheck.c in `file`.
2342
2343
2344
2345/*-
2346 * Copyright (c) 2011 The NetBSD Foundation, Inc.
2347 * All rights reserved.
2348 *
2349 * This code is derived from software contributed to The NetBSD Foundation
2350 * by Christos Zoulas.
2351 *
2352 * Redistribution and use in source and binary forms, with or without
2353 * modification, are permitted provided that the following conditions
2354 * are met:
2355 * 1. Redistributions of source code must retain the above copyright
2356 *    notice, this list of conditions and the following disclaimer.
2357 * 2. Redistributions in binary form must reproduce the above copyright
2358 *    notice, this list of conditions and the following disclaimer in the
2359 *    documentation and/or other materials provided with the distribution.
2360 *
2361 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
2362 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
2363 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
2364 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
2365 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
2366 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
2367 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
2368 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
2369 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
2370 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
2371 * POSSIBILITY OF SUCH DAMAGE.
2372 */
2373
2374The preceding notice is from src/missing/getline.c in `file`.
2375
2376
2377
2378/*-
2379 * Copyright (c) 2000 The NetBSD Foundation, Inc.
2380 * All rights reserved.
2381 *
2382 * This code is derived from software contributed to The NetBSD Foundation
2383 * by Dieter Baron and Thomas Klausner.
2384 *
2385 * Redistribution and use in source and binary forms, with or without
2386 * modification, are permitted provided that the following conditions
2387 * are met:
2388 * 1. Redistributions of source code must retain the above copyright
2389 *    notice, this list of conditions and the following disclaimer.
2390 * 2. Redistributions in binary form must reproduce the above copyright
2391 *    notice, this list of conditions and the following disclaimer in the
2392 *    documentation and/or other materials provided with the distribution.
2393 *
2394 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
2395 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
2396 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
2397 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
2398 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
2399 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
2400 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
2401 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
2402 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
2403 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
2404 * POSSIBILITY OF SUCH DAMAGE.
2405 */
2406
2407The preceding notice is from src/missing/getopt_long.c and src/mygetopt.h in `file`.
2408
2409
2410
2411/*
2412 * Public domain fallback for reallocarray(3), for platforms (e.g.
2413 * AmigaOS/libnix) whose C library declares it but does not implement it.
2414 */
2415
2416The preceding notice is from src/missing/reallocarray.c in `file`.
2417
2418
2419
2420/*-
2421 * SPDX-License-Identifier: BSD-3-Clause
2422 *
2423 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
2424 * Copyright (c) 1992, 1993, 1994
2425 *      The Regents of the University of California.  All rights reserved.
2426 *
2427 * Copyright (c) 2011 The FreeBSD Foundation
2428 * All rights reserved.
2429 * Portions of this software were developed by David Chisnall
2430 * under sponsorship from the FreeBSD Foundation.
2431 *
2432 * This code is derived from software contributed to Berkeley by
2433 * Henry Spencer.
2434 *
2435 * Redistribution and use in source and binary forms, with or without
2436 * modification, are permitted provided that the following conditions
2437 * are met:
2438 * 1. Redistributions of source code must retain the above copyright
2439 *    notice, this list of conditions and the following disclaimer.
2440 * 2. Redistributions in binary form must reproduce the above copyright
2441 *    notice, this list of conditions and the following disclaimer in the
2442 *    documentation and/or other materials provided with the distribution.
2443 * 3. Neither the name of the University nor the names of its contributors
2444 *    may be used to endorse or promote products derived from this software
2445 *    without specific prior written permission.
2446 *
2447 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2448 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2449 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2450 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2451 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2452 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2453 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2454 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2455 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2456 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2457 * SUCH DAMAGE.
2458 *
2459 *      @(#)regcomp.c   8.5 (Berkeley) 3/20/94
2460 */
2461
2462The preceding notice is from src/missing/regcomp.c in `file`.
2463
2464
2465
2466/*-
2467 * SPDX-License-Identifier: BSD-3-Clause
2468 *
2469 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
2470 * Copyright (c) 1992, 1993, 1994
2471 *      The Regents of the University of California.  All rights reserved.
2472 *
2473 * This code is derived from software contributed to Berkeley by
2474 * Henry Spencer.
2475 *
2476 * Redistribution and use in source and binary forms, with or without
2477 * modification, are permitted provided that the following conditions
2478 * are met:
2479 * 1. Redistributions of source code must retain the above copyright
2480 *    notice, this list of conditions and the following disclaimer.
2481 * 2. Redistributions in binary form must reproduce the above copyright
2482 *    notice, this list of conditions and the following disclaimer in the
2483 *    documentation and/or other materials provided with the distribution.
2484 * 3. Neither the name of the University nor the names of its contributors
2485 *    may be used to endorse or promote products derived from this software
2486 *    without specific prior written permission.
2487 *
2488 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2489 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2490 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2491 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2492 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2493 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2494 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2495 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2496 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2497 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2498 * SUCH DAMAGE.
2499 *
2500 *      @(#)regerror.c  8.4 (Berkeley) 3/20/94
2501 */
2502
2503The preceding notice is from src/missing/regerror.c in `file`.
2504
2505
2506
2507$NetBSD: COPYRIGHT,v 1.5 2003/08/07 16:43:19 agc Exp $
2508
2509Copyright 1992, 1993, 1994 Henry Spencer.  All rights reserved.
2510This software is not subject to any license of the American Telephone
2511and Telegraph Company or of the Regents of the University of California.
2512
2513Permission is granted to anyone to use this software for any purpose on
2514any computer system, and to alter it and redistribute it, subject
2515to the following restrictions:
2516
25171. The author is not responsible for the consequences of use of this
2518   software, no matter how awful, even if they arise from flaws in it.
2519
25202. The origin of this software must not be misrepresented, either by
2521   explicit claim or by omission.  Since few users ever read sources,
2522   credits must appear in the documentation.
2523
25243. Altered versions must be plainly marked as such, and must not be
2525   misrepresented as being the original software.  Since few users
2526   ever read sources, credits must appear in the documentation.
2527
25284. This notice may not be removed or altered.
2529
2530=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
2531/*-
2532 * Copyright (c) 1994
2533 *      The Regents of the University of California.  All rights reserved.
2534 *
2535 * Redistribution and use in source and binary forms, with or without
2536 * modification, are permitted provided that the following conditions
2537 * are met:
2538 * 1. Redistributions of source code must retain the above copyright
2539 *    notice, this list of conditions and the following disclaimer.
2540 * 2. Redistributions in binary form must reproduce the above copyright
2541 *    notice, this list of conditions and the following disclaimer in the
2542 *    documentation and/or other materials provided with the distribution.
2543 * 3. Neither the name of the University nor the names of its contributors
2544 *    may be used to endorse or promote products derived from this software
2545 *    without specific prior written permission.
2546 *
2547 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2548 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2549 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2550 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2551 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2552 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2553 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2554 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2555 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2556 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2557 * SUCH DAMAGE.
2558 *
2559 *      @(#)COPYRIGHT   8.1 (Berkeley) 3/16/94
2560 */
2561
2562The preceding notice is from src/missing/REGEX-COPYRIGHT in `file`.
2563
2564
2565
2566/*-
2567 * SPDX-License-Identifier: BSD-3-Clause
2568 *
2569 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
2570 * Copyright (c) 1992, 1993, 1994
2571 *      The Regents of the University of California.  All rights reserved.
2572 *
2573 * This code is derived from software contributed to Berkeley by
2574 * Henry Spencer.
2575 *
2576 * Redistribution and use in source and binary forms, with or without
2577 * modification, are permitted provided that the following conditions
2578 * are met:
2579 * 1. Redistributions of source code must retain the above copyright
2580 *    notice, this list of conditions and the following disclaimer.
2581 * 2. Redistributions in binary form must reproduce the above copyright
2582 *    notice, this list of conditions and the following disclaimer in the
2583 *    documentation and/or other materials provided with the distribution.
2584 * 3. Neither the name of the University nor the names of its contributors
2585 *    may be used to endorse or promote products derived from this software
2586 *    without specific prior written permission.
2587 *
2588 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2589 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2590 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2591 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2592 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2593 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2594 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2595 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2596 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2597 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2598 * SUCH DAMAGE.
2599 *
2600 *      @(#)regex2.h    8.4 (Berkeley) 3/20/94
2601 * $FreeBSD: head/lib/libc/regex/regex2.h 368359 2020-12-05 03:18:48Z kevans $
2602 */
2603
2604The preceding notice is from src/missing/regex2.h in `file`.
2605
2606
2607
2608/*-
2609 * SPDX-License-Identifier: BSD-3-Clause
2610 *
2611 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
2612 * Copyright (c) 1992, 1993, 1994
2613 *      The Regents of the University of California.  All rights reserved.
2614 *
2615 * This code is derived from software contributed to Berkeley by
2616 * Henry Spencer.
2617 *
2618 * Redistribution and use in source and binary forms, with or without
2619 * modification, are permitted provided that the following conditions
2620 * are met:
2621 * 1. Redistributions of source code must retain the above copyright
2622 *    notice, this list of conditions and the following disclaimer.
2623 * 2. Redistributions in binary form must reproduce the above copyright
2624 *    notice, this list of conditions and the following disclaimer in the
2625 *    documentation and/or other materials provided with the distribution.
2626 * 3. Neither the name of the University nor the names of its contributors
2627 *    may be used to endorse or promote products derived from this software
2628 *    without specific prior written permission.
2629 *
2630 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2631 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2632 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2633 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2634 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2635 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2636 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2637 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2638 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2639 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2640 * SUCH DAMAGE.
2641 *
2642 *      @(#)regexec.c   8.3 (Berkeley) 3/20/94
2643 */
2644
2645The preceding notice is from src/missing/regexec.c in `file`.
2646
2647
2648
2649/*-
2650 * SPDX-License-Identifier: BSD-3-Clause
2651 *
2652 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
2653 * Copyright (c) 1992, 1993, 1994
2654 *      The Regents of the University of California.  All rights reserved.
2655 *
2656 * This code is derived from software contributed to Berkeley by
2657 * Henry Spencer.
2658 *
2659 * Redistribution and use in source and binary forms, with or without
2660 * modification, are permitted provided that the following conditions
2661 * are met:
2662 * 1. Redistributions of source code must retain the above copyright
2663 *    notice, this list of conditions and the following disclaimer.
2664 * 2. Redistributions in binary form must reproduce the above copyright
2665 *    notice, this list of conditions and the following disclaimer in the
2666 *    documentation and/or other materials provided with the distribution.
2667 * 3. Neither the name of the University nor the names of its contributors
2668 *    may be used to endorse or promote products derived from this software
2669 *    without specific prior written permission.
2670 *
2671 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2672 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2673 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2674 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2675 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2676 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2677 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2678 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2679 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2680 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2681 * SUCH DAMAGE.
2682 *
2683 *      @(#)regfree.c   8.3 (Berkeley) 3/20/94
2684 */
2685
2686The preceding notice is from src/missing/regfree.c in `file`.
2687
2688
2689
2690/*-
2691 * Copyright (c) 1990, 1993
2692 *      The Regents of the University of California.  All rights reserved.
2693 *
2694 * This code is derived from software contributed to Berkeley by
2695 * Chris Torek.
2696 *
2697 * Redistribution and use in source and binary forms, with or without
2698 * modification, are permitted provided that the following conditions
2699 * are met:
2700 * 1. Redistributions of source code must retain the above copyright
2701 *    notice, this list of conditions and the following disclaimer.
2702 * 2. Redistributions in binary form must reproduce the above copyright
2703 *    notice, this list of conditions and the following disclaimer in the
2704 *    documentation and/or other materials provided with the distribution.
2705 * 3. Neither the name of the University nor the names of its contributors
2706 *    may be used to endorse or promote products derived from this software
2707 *    without specific prior written permission.
2708 *
2709 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2710 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2711 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2712 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2713 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2714 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2715 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2716 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2717 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2718 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2719 * SUCH DAMAGE.
2720 */
2721
2722The preceding notice is from src/missing/strcasestr.c in `file`.
2723
2724
2725
2726/*
2727 * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
2728 *
2729 * Permission to use, copy, modify, and distribute this software for any
2730 * purpose with or without fee is hereby granted, provided that the above
2731 * copyright notice and this permission notice appear in all copies.
2732 *
2733 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
2734 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
2735 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
2736 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
2737 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
2738 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
2739 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
2740 */
2741
2742The preceding notice is from src/missing/strlcat.c and src/missing/strlcpy.c in `file`.
2743
2744
2745
2746/*-
2747 * SPDX-License-Identifier: BSD-3-Clause
2748 *
2749 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
2750 * Copyright (c) 1992, 1993, 1994
2751 *      The Regents of the University of California.  All rights reserved.
2752 *
2753 * This code is derived from software contributed to Berkeley by
2754 * Henry Spencer.
2755 *
2756 * Redistribution and use in source and binary forms, with or without
2757 * modification, are permitted provided that the following conditions
2758 * are met:
2759 * 1. Redistributions of source code must retain the above copyright
2760 *    notice, this list of conditions and the following disclaimer.
2761 * 2. Redistributions in binary form must reproduce the above copyright
2762 *    notice, this list of conditions and the following disclaimer in the
2763 *    documentation and/or other materials provided with the distribution.
2764 * 3. Neither the name of the University nor the names of its contributors
2765 *    may be used to endorse or promote products derived from this software
2766 *    without specific prior written permission.
2767 *
2768 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2769 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2770 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2771 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2772 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2773 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2774 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2775 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2776 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2777 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2778 * SUCH DAMAGE.
2779 *
2780 *      @(#)utils.h     8.3 (Berkeley) 3/20/94
2781 * $FreeBSD: head/lib/libc/regex/utils.h 341838 2018-12-12 04:23:00Z yuripv $
2782 */
2783
2784The preceding notice is from src/missing/utils.h in `file`.
2785
2786
2787
2788/*-
2789 * Copyright (c) 2008, 2016 Christos Zoulas
2790 * All rights reserved.
2791 *
2792 * Redistribution and use in source and binary forms, with or without
2793 * modification, are permitted provided that the following conditions
2794 * are met:
2795 * 1. Redistributions of source code must retain the above copyright
2796 *    notice, this list of conditions and the following disclaimer.
2797 * 2. Redistributions in binary form must reproduce the above copyright
2798 *    notice, this list of conditions and the following disclaimer in the
2799 *    documentation and/or other materials provided with the distribution.
2800 *
2801 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
2802 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
2803 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
2804 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
2805 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
2806 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
2807 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
2808 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
2809 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
2810 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
2811 * POSSIBILITY OF SUCH DAMAGE.
2812 */
2813
2814The preceding notice is from src/readcdf.c in `file`.
2815
2816
2817
2818/*-
2819 * Copyright (c) 1992 Henry Spencer.
2820 * Copyright (c) 1992, 1993
2821 *      The Regents of the University of California.  All rights reserved.
2822 *
2823 * This code is derived from software contributed to Berkeley by
2824 * Henry Spencer of the University of Toronto.
2825 *
2826 * Redistribution and use in source and binary forms, with or without
2827 * modification, are permitted provided that the following conditions
2828 * are met:
2829 * 1. Redistributions of source code must retain the above copyright
2830 *    notice, this list of conditions and the following disclaimer.
2831 * 2. Redistributions in binary form must reproduce the above copyright
2832 *    notice, this list of conditions and the following disclaimer in the
2833 *    documentation and/or other materials provided with the distribution.
2834 * 3. Neither the name of the University nor the names of its contributors
2835 *    may be used to endorse or promote products derived from this software
2836 *    without specific prior written permission.
2837 *
2838 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2839 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2840 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2841 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2842 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2843 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2844 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2845 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2846 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2847 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2848 * SUCH DAMAGE.
2849 *
2850 *      @(#)regex.h     8.2 (Berkeley) 1/3/94
2851 * $FreeBSD: src/include/regex.h,v 1.12 2010/02/16 19:39:50 imp Exp $
2852 */
2853
2854The preceding notice is from src/regex-bsd.h in `file`.
2855*/
2856/*
2857
2858Text of LICENSE from DROID:
2859
2860Copyright (c) 2016, The National Archives <pronom@nationalarchives.gov.uk>
2861All rights reserved.
2862
2863Redistribution and use in source and binary forms, with or without
2864modification, are permitted provided that the following
2865conditions are met:
2866
2867 * Redistributions of source code must retain the above copyright
2868   notice, this list of conditions and the following disclaimer.
2869
2870 * Redistributions in binary form must reproduce the above copyright
2871   notice, this list of conditions and the following disclaimer in the
2872   documentation and/or other materials provided with the distribution.
2873
2874 * Neither the name of the The National Archives nor the
2875   names of its contributors may be used to endorse or promote products
2876   derived from this software without specific prior written permission.
2877
2878THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
2879AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2880IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
2881PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
2882CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
2883EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
2884PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
2885PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
2886LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
2887NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
2888SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2889*/
2890
2891/*
2892
2893Text of LICENSE from fileid:
2894
2895The MIT License (MIT)
2896
2897Copyright (c) 2015 David B Heise
2898
2899Permission is hereby granted, free of charge, to any person obtaining a copy of
2900this software and associated documentation files (the "Software"), to deal in
2901the Software without restriction, including without limitation the rights to
2902use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
2903the Software, and to permit persons to whom the Software is furnished to do so,
2904subject to the following conditions:
2905
2906The above copyright notice and this permission notice shall be included in all
2907copies or substantial portions of the Software.
2908
2909THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
2910IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
2911FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
2912COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
2913IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
2914CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
2915
2916
2917*/
2918
2919/*
2920Text of LICENSE from binwalk:
2921
2922
2923MIT License
2924
2925Copyright (c) 2024 devttys0
2926
2927Permission is hereby granted, free of charge, to any person obtaining a copy
2928of this software and associated documentation files (the "Software"), to deal
2929in the Software without restriction, including without limitation the rights
2930to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
2931copies of the Software, and to permit persons to whom the Software is
2932furnished to do so, subject to the following conditions:
2933
2934The above copyright notice and this permission notice shall be included in all
2935copies or substantial portions of the Software.
2936
2937THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
2938IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
2939FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
2940AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
2941LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
2942OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2943SOFTWARE.
2944
2945*/
2946
2947/*
2948Text of LICENSE from polyfile:
2949
2950
2951                                 Apache License
2952                           Version 2.0, January 2004
2953                        http://www.apache.org/licenses/
2954
2955   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
2956
2957   1. Definitions.
2958
2959      "License" shall mean the terms and conditions for use, reproduction,
2960      and distribution as defined by Sections 1 through 9 of this document.
2961
2962      "Licensor" shall mean the copyright owner or entity authorized by
2963      the copyright owner that is granting the License.
2964
2965      "Legal Entity" shall mean the union of the acting entity and all
2966      other entities that control, are controlled by, or are under common
2967      control with that entity. For the purposes of this definition,
2968      "control" means (i) the power, direct or indirect, to cause the
2969      direction or management of such entity, whether by contract or
2970      otherwise, or (ii) ownership of fifty percent (50%) or more of the
2971      outstanding shares, or (iii) beneficial ownership of such entity.
2972
2973      "You" (or "Your") shall mean an individual or Legal Entity
2974      exercising permissions granted by this License.
2975
2976      "Source" form shall mean the preferred form for making modifications,
2977      including but not limited to software source code, documentation
2978      source, and configuration files.
2979
2980      "Object" form shall mean any form resulting from mechanical
2981      transformation or translation of a Source form, including but
2982      not limited to compiled object code, generated documentation,
2983      and conversions to other media types.
2984
2985      "Work" shall mean the work of authorship, whether in Source or
2986      Object form, made available under the License, as indicated by a
2987      copyright notice that is included in or attached to the work
2988      (an example is provided in the Appendix below).
2989
2990      "Derivative Works" shall mean any work, whether in Source or Object
2991      form, that is based on (or derived from) the Work and for which the
2992      editorial revisions, annotations, elaborations, or other modifications
2993      represent, as a whole, an original work of authorship. For the purposes
2994      of this License, Derivative Works shall not include works that remain
2995      separable from, or merely link (or bind by name) to the interfaces of,
2996      the Work and Derivative Works thereof.
2997
2998      "Contribution" shall mean any work of authorship, including
2999      the original version of the Work and any modifications or additions
3000      to that Work or Derivative Works thereof, that is intentionally
3001      submitted to Licensor for inclusion in the Work by the copyright owner
3002      or by an individual or Legal Entity authorized to submit on behalf of
3003      the copyright owner. For the purposes of this definition, "submitted"
3004      means any form of electronic, verbal, or written communication sent
3005      to the Licensor or its representatives, including but not limited to
3006      communication on electronic mailing lists, source code control systems,
3007      and issue tracking systems that are managed by, or on behalf of, the
3008      Licensor for the purpose of discussing and improving the Work, but
3009      excluding communication that is conspicuously marked or otherwise
3010      designated in writing by the copyright owner as "Not a Contribution."
3011
3012      "Contributor" shall mean Licensor and any individual or Legal Entity
3013      on behalf of whom a Contribution has been received by Licensor and
3014      subsequently incorporated within the Work.
3015
3016   2. Grant of Copyright License. Subject to the terms and conditions of
3017      this License, each Contributor hereby grants to You a perpetual,
3018      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
3019      copyright license to reproduce, prepare Derivative Works of,
3020      publicly display, publicly perform, sublicense, and distribute the
3021      Work and such Derivative Works in Source or Object form.
3022
3023   3. Grant of Patent License. Subject to the terms and conditions of
3024      this License, each Contributor hereby grants to You a perpetual,
3025      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
3026      (except as stated in this section) patent license to make, have made,
3027      use, offer to sell, sell, import, and otherwise transfer the Work,
3028      where such license applies only to those patent claims licensable
3029      by such Contributor that are necessarily infringed by their
3030      Contribution(s) alone or by combination of their Contribution(s)
3031      with the Work to which such Contribution(s) was submitted. If You
3032      institute patent litigation against any entity (including a
3033      cross-claim or counterclaim in a lawsuit) alleging that the Work
3034      or a Contribution incorporated within the Work constitutes direct
3035      or contributory patent infringement, then any patent licenses
3036      granted to You under this License for that Work shall terminate
3037      as of the date such litigation is filed.
3038
3039   4. Redistribution. You may reproduce and distribute copies of the
3040      Work or Derivative Works thereof in any medium, with or without
3041      modifications, and in Source or Object form, provided that You
3042      meet the following conditions:
3043
3044      (a) You must give any other recipients of the Work or
3045          Derivative Works a copy of this License; and
3046
3047      (b) You must cause any modified files to carry prominent notices
3048          stating that You changed the files; and
3049
3050      (c) You must retain, in the Source form of any Derivative Works
3051          that You distribute, all copyright, patent, trademark, and
3052          attribution notices from the Source form of the Work,
3053          excluding those notices that do not pertain to any part of
3054          the Derivative Works; and
3055
3056      (d) If the Work includes a "NOTICE" text file as part of its
3057          distribution, then any Derivative Works that You distribute must
3058          include a readable copy of the attribution notices contained
3059          within such NOTICE file, excluding those notices that do not
3060          pertain to any part of the Derivative Works, in at least one
3061          of the following places: within a NOTICE text file distributed
3062          as part of the Derivative Works; within the Source form or
3063          documentation, if provided along with the Derivative Works; or,
3064          within a display generated by the Derivative Works, if and
3065          wherever such third-party notices normally appear. The contents
3066          of the NOTICE file are for informational purposes only and
3067          do not modify the License. You may add Your own attribution
3068          notices within Derivative Works that You distribute, alongside
3069          or as an addendum to the NOTICE text from the Work, provided
3070          that such additional attribution notices cannot be construed
3071          as modifying the License.
3072
3073      You may add Your own copyright statement to Your modifications and
3074      may provide additional or different license terms and conditions
3075      for use, reproduction, or distribution of Your modifications, or
3076      for any such Derivative Works as a whole, provided Your use,
3077      reproduction, and distribution of the Work otherwise complies with
3078      the conditions stated in this License.
3079
3080   5. Submission of Contributions. Unless You explicitly state otherwise,
3081      any Contribution intentionally submitted for inclusion in the Work
3082      by You to the Licensor shall be under the terms and conditions of
3083      this License, without any additional terms or conditions.
3084      Notwithstanding the above, nothing herein shall supersede or modify
3085      the terms of any separate license agreement you may have executed
3086      with Licensor regarding such Contributions.
3087
3088   6. Trademarks. This License does not grant permission to use the trade
3089      names, trademarks, service marks, or product names of the Licensor,
3090      except as required for reasonable and customary use in describing the
3091      origin of the Work and reproducing the content of the NOTICE file.
3092
3093   7. Disclaimer of Warranty. Unless required by applicable law or
3094      agreed to in writing, Licensor provides the Work (and each
3095      Contributor provides its Contributions) on an "AS IS" BASIS,
3096      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
3097      implied, including, without limitation, any warranties or conditions
3098      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
3099      PARTICULAR PURPOSE. You are solely responsible for determining the
3100      appropriateness of using or redistributing the Work and assume any
3101      risks associated with Your exercise of permissions under this License.
3102
3103   8. Limitation of Liability. In no event and under no legal theory,
3104      whether in tort (including negligence), contract, or otherwise,
3105      unless required by applicable law (such as deliberate and grossly
3106      negligent acts) or agreed to in writing, shall any Contributor be
3107      liable to You for damages, including any direct, indirect, special,
3108      incidental, or consequential damages of any character arising as a
3109      result of this License or out of the use or inability to use the
3110      Work (including but not limited to damages for loss of goodwill,
3111      work stoppage, computer failure or malfunction, or any and all
3112      other commercial damages or losses), even if such Contributor
3113      has been advised of the possibility of such damages.
3114
3115   9. Accepting Warranty or Additional Liability. While redistributing
3116      the Work or Derivative Works thereof, You may choose to offer,
3117      and charge a fee for, acceptance of support, warranty, indemnity,
3118      or other liability obligations and/or rights consistent with this
3119      License. However, in accepting such obligations, You may act only
3120      on Your own behalf and on Your sole responsibility, not on behalf
3121      of any other Contributor, and only if You agree to indemnify,
3122      defend, and hold each Contributor harmless for any liability
3123      incurred by, or claims asserted against, such Contributor by reason
3124      of your accepting any such warranty or additional liability.
3125
3126   END OF TERMS AND CONDITIONS
3127
3128   APPENDIX: How to apply the Apache License to your work.
3129
3130      To apply the Apache License to your work, attach the following
3131      boilerplate notice, with the fields enclosed by brackets "[]"
3132      replaced with your own identifying information. (Don't include
3133      the brackets!)  The text should be enclosed in the appropriate
3134      comment syntax for the file format. We also recommend that a
3135      file or class name and description of purpose be included on the
3136      same "printed page" as the copyright notice for easier
3137      identification within third-party archives.
3138
3139   Copyright [yyyy] [name of copyright owner]
3140
3141   Licensed under the Apache License, Version 2.0 (the "License");
3142   you may not use this file except in compliance with the License.
3143   You may obtain a copy of the License at
3144
3145       http://www.apache.org/licenses/LICENSE-2.0
3146
3147   Unless required by applicable law or agreed to in writing, software
3148   distributed under the License is distributed on an "AS IS" BASIS,
3149   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3150   See the License for the specific language governing permissions and
3151   limitations under the License.
3152
3153*/