ctb_formats_detection/magic.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//! Hierarchical magic byte pattern evaluation engine for format identification.
446
447#[allow(
448 unused_imports,
449 clippy::wildcard_imports,
450 reason = "Standard workspace module prelude"
451)]
452use std::collections::HashMap;
453
454use crate::utilities::*;
455
456use super::DetectionSource;
457use super::magic_parser::{
458 HierarchicalMagicRule, IndirectOp, IndirectType, MagicCond, MagicTest,
459 NumOp, Offset, PascalLengthSize, RelOp,
460};
461
462static COMPILED_MAGIC_REGEXES: std::sync::LazyLock<
463 std::sync::RwLock<HashMap<(String, bool), Option<regex::Regex>>>,
464> = std::sync::LazyLock::new(|| std::sync::RwLock::new(HashMap::new()));
465
466fn get_compiled_magic_regex(
467 pattern: &str,
468 case_insensitive: bool,
469) -> Option<regex::Regex> {
470 if let Ok(guard) = COMPILED_MAGIC_REGEXES.read()
471 && let Some(cached) =
472 guard.get(&(pattern.to_owned(), case_insensitive))
473 {
474 return cached.clone();
475 }
476 let compiled = regex::RegexBuilder::new(pattern)
477 .case_insensitive(case_insensitive)
478 .build()
479 .ok();
480 if let Ok(mut guard) = COMPILED_MAGIC_REGEXES.write() {
481 guard.insert((pattern.to_owned(), case_insensitive), compiled.clone());
482 }
483 compiled
484}
485
486fn bounded_source_read<S: DetectionSource + ?Sized>(
487 source: &mut S,
488 pos: u64,
489 max_bytes: usize,
490) -> Option<Vec<u8>> {
491 let alloc_len = if let Some(total) = source.total_len() {
492 if pos >= total {
493 return Some(Vec::new());
494 }
495 // Reason for fallback: remaining byte count exceeding usize::MAX clamps to max_bytes
496 let avail =
497 usize::try_from(total.saturating_sub(pos)).unwrap_or(max_bytes);
498 max_bytes.min(avail)
499 } else {
500 max_bytes
501 };
502 let mut buf = vec![0u8; alloc_len];
503 let n = source.read_at(pos, &mut buf).ok()?;
504 buf.truncate(n);
505 Some(buf)
506}
507
508/// Result of evaluating a hierarchical magic rule against a payload source.
509#[derive(Debug, Clone, PartialEq, Eq)]
510pub struct RuleMatchResult {
511 /// Specialized description formatted from matching root and child rules.
512 pub description: String,
513 /// MIME type associated with the match (child rule takes precedence).
514 pub mime: Option<String>,
515 /// File extension(s) associated with the match.
516 pub ext: Option<String>,
517 /// Apple type code if available.
518 pub apple: Option<String>,
519 /// Accumulated strength/confidence score.
520 pub score: u32,
521 /// End offset in payload of the matched sequence.
522 pub match_end: u64,
523 /// Next sibling starting offset for structured/DER sequential elements.
524 pub next_sibling_offset: u64,
525 /// Suppress space separator before appending to previous text.
526 pub nospace: bool,
527}
528
529/// Evaluates a relational comparison operator.
530fn eval_rel_op<T: Copy + Ord + Eq + std::ops::BitAnd<Output = T>>(
531 val: T,
532 op: RelOp,
533 target: T,
534) -> bool {
535 match op {
536 RelOp::Eq => val == target,
537 RelOp::Ne => val != target,
538 RelOp::Gt => val > target,
539 RelOp::Lt => val < target,
540 RelOp::BitAnd => (val & target) == target,
541 RelOp::BitClear => (val & target) != target,
542 RelOp::Any => true,
543 }
544}
545
546/// Applies arithmetic operation to a 64-bit integer before comparison/format.
547fn apply_num_op_u64(val: u64, op: NumOp) -> u64 {
548 match op {
549 NumOp::None => val,
550 // Reason for fallback: division by zero returns unmodified value
551 NumOp::Div(d) => val.checked_div(d).unwrap_or(val),
552 // Reason for fallback: modulo by zero returns 0
553 NumOp::Mod(m) => val.checked_rem(m).unwrap_or(0),
554 NumOp::Mul(m) => val.saturating_mul(m),
555 NumOp::Add(a) => val.saturating_add(a),
556 NumOp::Sub(s) => val.saturating_sub(s),
557 }
558}
559
560/// Extracted value used for printf-style format interpolation in descriptions.
561#[derive(Debug, Clone)]
562pub enum FormatValue {
563 None,
564 U64(u64),
565 I64(i64),
566 Str(String),
567 Date(i64),
568 F64(f64),
569}
570
571/// Evaluates IEEE-754 relational operator matching upstream softmagic.c.
572fn eval_float_op(val: f32, op: RelOp, target: f32) -> bool {
573 match op {
574 RelOp::Any => true,
575 RelOp::Eq => {
576 if val.is_nan() || target.is_nan() {
577 false
578 } else {
579 val == target
580 }
581 }
582 RelOp::Ne => {
583 if val.is_nan() || target.is_nan() {
584 true
585 } else {
586 val != target
587 }
588 }
589 RelOp::Gt => {
590 if val.is_nan() || target.is_nan() {
591 false
592 } else {
593 val > target
594 }
595 }
596 RelOp::Lt => {
597 if val.is_nan() || target.is_nan() {
598 false
599 } else {
600 val < target
601 }
602 }
603 RelOp::BitAnd | RelOp::BitClear => false,
604 }
605}
606
607/// Evaluates IEEE-754 64-bit relational operator matching upstream softmagic.c.
608fn eval_double_op(val: f64, op: RelOp, target: f64) -> bool {
609 match op {
610 RelOp::Any => true,
611 RelOp::Eq => {
612 if val.is_nan() || target.is_nan() {
613 false
614 } else {
615 val == target
616 }
617 }
618 RelOp::Ne => {
619 if val.is_nan() || target.is_nan() {
620 true
621 } else {
622 val != target
623 }
624 }
625 RelOp::Gt => {
626 if val.is_nan() || target.is_nan() {
627 false
628 } else {
629 val > target
630 }
631 }
632 RelOp::Lt => {
633 if val.is_nan() || target.is_nan() {
634 false
635 } else {
636 val < target
637 }
638 }
639 RelOp::BitAnd | RelOp::BitClear => false,
640 }
641}
642
643/// Formats 16 bytes as uppercase Microsoft mixed-endian GUID string.
644fn format_guid_le(b: &[u8; 16]) -> String {
645 let d1 = u32::from_le_bytes([b[0], b[1], b[2], b[3]]);
646 let d2 = u16::from_le_bytes([b[4], b[5]]);
647 let d3 = u16::from_le_bytes([b[6], b[7]]);
648 format!(
649 "{d1:08X}-{d2:04X}-{d3:04X}-{:02X}{:02X}-{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}",
650 b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]
651 )
652}
653
654/// Formats 16 bytes as uppercase big-endian RFC 4122 UUID string.
655fn format_guid_be(b: &[u8; 16]) -> String {
656 let d1 = u32::from_be_bytes([b[0], b[1], b[2], b[3]]);
657 let d2 = u16::from_be_bytes([b[4], b[5]]);
658 let d3 = u16::from_be_bytes([b[6], b[7]]);
659 format!(
660 "{d1:08X}-{d2:04X}-{d3:04X}-{:02X}{:02X}-{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}",
661 b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]
662 )
663}
664
665/// Extracts 16-bit wide character string collapsing into ASCII/UTF-8 string.
666fn extract_string16<S: DetectionSource + ?Sized>(
667 source: &mut S,
668 pos: u64,
669 is_be: bool,
670 max_chars: usize,
671) -> Option<(String, usize)> {
672 let mut raw_buf = vec![0u8; max_chars.saturating_mul(2)];
673 let n = source.read_at(pos, &mut raw_buf).ok()?;
674 if n < 2 {
675 return None;
676 }
677 let slice = raw_buf.get(..n)?;
678 let mut out = String::new();
679 let mut pairs_consumed = 0usize;
680 for chunk in slice.chunks_exact(2) {
681 let b0 = *chunk.first()?;
682 let b1 = *chunk.get(1)?;
683 let (lo, hi) = if is_be { (b1, b0) } else { (b0, b1) };
684 if lo == 0 && hi == 0 {
685 break;
686 }
687 pairs_consumed = pairs_consumed.saturating_add(1);
688 if hi == 0 {
689 out.push(char::from(lo));
690 } else {
691 let u = if is_be {
692 u16::from_be_bytes([b0, b1])
693 } else {
694 u16::from_le_bytes([b0, b1])
695 };
696 if let Some(ch) = char::from_u32(u32::from(u)) {
697 if ch.is_control() {
698 out.push(' ');
699 } else {
700 out.push(ch);
701 }
702 } else {
703 out.push(' ');
704 }
705 }
706 }
707 Some((out, pairs_consumed.saturating_mul(2)))
708}
709
710/// Formats a Unix timestamp as UTC `ctime`-compatible string:
711/// `%a %b %e %H:%M:%S %Y`.
712fn format_timestamp(secs: i64) -> String {
713 if let Ok(dt) = jiff::Timestamp::from_second(secs) {
714 dt.strftime("%a %b %e %H:%M:%S %Y").to_string()
715 } else {
716 format!("{secs}")
717 }
718}
719
720fn apply_padding(s: &str, width: usize, zero_pad: bool) -> String {
721 if s.len() >= width {
722 s.to_string()
723 } else {
724 let pad_char = if zero_pad { '0' } else { ' ' };
725 let diff = width.saturating_sub(s.len());
726 let mut out = String::with_capacity(width);
727 for _ in 0..diff {
728 out.push(pad_char);
729 }
730 out.push_str(s);
731 out
732 }
733}
734
735/// Formats a libmagic rule description interpolating `%s`, `%d`, `%x`, etc. specifiers.
736pub fn format_magic_description(desc: &str, val: &FormatValue) -> String {
737 if !desc.contains('%') {
738 return desc.to_string();
739 }
740
741 let mut result = String::with_capacity(desc.len().saturating_add(16));
742 let chars: Vec<char> = desc.chars().collect();
743 let mut i = 0;
744
745 while i < chars.len() {
746 if let Some(&c) = chars.get(i) {
747 if c != '%' {
748 result.push(c);
749 i = i.saturating_add(1);
750 continue;
751 }
752
753 i = i.saturating_add(1);
754 if let Some(&next) = chars.get(i) {
755 if next == '%' {
756 result.push('%');
757 i = i.saturating_add(1);
758 continue;
759 }
760 }
761
762 let mut zero_pad = false;
763 let mut width: usize = 0;
764 let mut alt_form = false;
765
766 while let Some(&f) = chars.get(i) {
767 if f == '0' {
768 zero_pad = true;
769 i = i.saturating_add(1);
770 } else if f == '#' {
771 alt_form = true;
772 i = i.saturating_add(1);
773 } else if f == '-' || f == '+' || f == ' ' {
774 i = i.saturating_add(1);
775 } else {
776 break;
777 }
778 }
779
780 while let Some(&w) = chars.get(i) {
781 if let Some(digit) = w.to_digit(10) {
782 // Reason for fallback: decimal digit 0..=9 conversion to usize defaults to 0
783 let d = usize::try_from(digit).unwrap_or(0);
784 width = width.saturating_mul(10).saturating_add(d);
785 i = i.saturating_add(1);
786 } else {
787 break;
788 }
789 }
790
791 let mut precision: Option<usize> = None;
792 if let Some(&'.') = chars.get(i) {
793 i = i.saturating_add(1);
794 let mut prec: usize = 0;
795 while let Some(&p) = chars.get(i) {
796 if let Some(digit) = p.to_digit(10) {
797 // Reason for fallback: decimal digit 0..=9 conversion to usize defaults to 0
798 let d = usize::try_from(digit).unwrap_or(0);
799 prec = prec.saturating_mul(10).saturating_add(d);
800 i = i.saturating_add(1);
801 } else {
802 break;
803 }
804 }
805 precision = Some(prec);
806 }
807
808 while let Some(&lm) = chars.get(i) {
809 if lm == 'l'
810 || lm == 'h'
811 || lm == 'z'
812 || lm == 'j'
813 || lm == 't'
814 || lm == 'L'
815 {
816 i = i.saturating_add(1);
817 } else {
818 break;
819 }
820 }
821
822 // Reason for fallback: format specifier truncated at end of format string defaults to string specifier 's'
823 let spec = chars.get(i).copied().unwrap_or('s');
824 i = i.saturating_add(1);
825
826 let formatted = match (spec, val) {
827 ('s', FormatValue::Str(s)) => {
828 let s_trimmed = if let Some(p) = precision {
829 s.chars().take(p).collect::<String>()
830 } else {
831 s.clone()
832 };
833 apply_padding(&s_trimmed, width, zero_pad)
834 }
835 ('s', FormatValue::Date(ts)) => format_timestamp(*ts),
836 ('s', FormatValue::U64(n)) => n.to_string(),
837 ('s', FormatValue::I64(n)) => n.to_string(),
838 ('d' | 'i', FormatValue::I64(n)) => {
839 let s = n.to_string();
840 apply_padding(&s, width, zero_pad)
841 }
842 ('d' | 'i', FormatValue::U64(n)) => {
843 let s = n.to_string();
844 apply_padding(&s, width, zero_pad)
845 }
846 ('u', FormatValue::U64(n)) => {
847 let s = n.to_string();
848 apply_padding(&s, width, zero_pad)
849 }
850 ('u', FormatValue::I64(n)) => {
851 let s = n.to_string();
852 apply_padding(&s, width, zero_pad)
853 }
854 ('x', FormatValue::U64(n)) => {
855 let s = if alt_form && *n != 0 {
856 format!("0x{n:x}")
857 } else {
858 format!("{n:x}")
859 };
860 apply_padding(&s, width, zero_pad)
861 }
862 ('x', FormatValue::I64(n)) => {
863 let s = if alt_form && *n != 0 {
864 format!("0x{n:x}")
865 } else {
866 format!("{n:x}")
867 };
868 apply_padding(&s, width, zero_pad)
869 }
870 ('X', FormatValue::U64(n)) => {
871 let s = if alt_form && *n != 0 {
872 format!("0X{n:X}")
873 } else {
874 format!("{n:X}")
875 };
876 apply_padding(&s, width, zero_pad)
877 }
878 ('X', FormatValue::I64(n)) => {
879 let s = if alt_form && *n != 0 {
880 format!("0X{n:X}")
881 } else {
882 format!("{n:X}")
883 };
884 apply_padding(&s, width, zero_pad)
885 }
886 ('o', FormatValue::U64(n)) => {
887 let s = if alt_form && *n != 0 {
888 format!("0{n:o}")
889 } else {
890 format!("{n:o}")
891 };
892 apply_padding(&s, width, zero_pad)
893 }
894 ('c', FormatValue::U64(n)) => {
895 if let Ok(b) = u8::try_from(*n) {
896 char::from(b).to_string()
897 } else {
898 "?".to_string()
899 }
900 }
901 ('f' | 'g' | 'e', FormatValue::F64(v)) => {
902 let s = if let Some(p) = precision {
903 if spec == 'g' {
904 format!("{v:.p$}")
905 } else if spec == 'e' {
906 format!("{v:.p$e}")
907 } else {
908 format!("{v:.p$}")
909 }
910 } else if spec == 'e' {
911 format!("{v:e}")
912 } else {
913 format!("{v}")
914 };
915 apply_padding(&s, width, zero_pad)
916 }
917 ('s', FormatValue::F64(v)) => {
918 let s = format!("{v}");
919 apply_padding(&s, width, zero_pad)
920 }
921 (_, FormatValue::Str(s)) => s.clone(),
922 (_, FormatValue::U64(n)) => n.to_string(),
923 (_, FormatValue::I64(n)) => n.to_string(),
924 (_, FormatValue::Date(ts)) => format_timestamp(*ts),
925 (_, FormatValue::F64(v)) => format!("{v}"),
926 (_, FormatValue::None) => String::new(),
927 };
928
929 result.push_str(&formatted);
930 } else {
931 break;
932 }
933 }
934
935 result
936}
937
938/// Expands `${x?then:else}` variable expressions according to mode execution bits,
939/// matching `varexpand` in `softmagic.c`.
940pub fn varexpand(s: &str, mode: u32) -> String {
941 if !s.contains("${") {
942 return s.to_string();
943 }
944 let is_exec = (mode & 0o111) != 0;
945 let mut result = String::with_capacity(s.len());
946 let mut rem = s;
947 while let Some(start_idx) = rem.find("${") {
948 let (prefix, after_start) = rem.split_at(start_idx);
949 result.push_str(prefix);
950 let Some(expr) = after_start.get(2..) else {
951 result.push_str(after_start);
952 rem = "";
953 break;
954 };
955 if let Some(end_idx) = expr.find('}') {
956 let Some(inner) = expr.get(..end_idx) else {
957 result.push_str(after_start);
958 rem = "";
959 break;
960 };
961 let Some(after_expr) = expr.get(end_idx.saturating_add(1)..) else {
962 result.push_str(after_start);
963 rem = "";
964 break;
965 };
966 rem = after_expr;
967 if let Some((var, branches)) = inner.split_once('?') {
968 if let Some((then_branch, else_branch)) =
969 branches.split_once(':')
970 {
971 if var == "x" {
972 if is_exec {
973 result.push_str(then_branch);
974 } else {
975 result.push_str(else_branch);
976 }
977 continue;
978 }
979 }
980 }
981 result.push_str("${");
982 result.push_str(inner);
983 result.push('}');
984 } else {
985 result.push_str(after_start);
986 rem = "";
987 break;
988 }
989 }
990 result.push_str(rem);
991 result
992}
993
994/// Returns true if the source is determined to be text (ASCII/UTF-8 with no null bytes).
995fn is_text_source<S: DetectionSource + ?Sized>(source: &mut S) -> bool {
996 let mut buf = [0u8; 512];
997 // Reason for fallback: read error defaults to 0 bytes read for text inspection
998 let n = source.read_at(0, &mut buf).unwrap_or(0);
999 if n == 0 {
1000 return true;
1001 }
1002 let slice = match buf.get(..n) {
1003 Some(s) => s,
1004 None => return false,
1005 };
1006 if slice.contains(&0) {
1007 return false;
1008 }
1009 crate::text::detect_text_encoding(slice).is_some()
1010}
1011
1012/// Reads raw integer value at dereference offset according to indirect type.
1013fn read_indirect_val<S: DetectionSource + ?Sized>(
1014 source: &mut S,
1015 deref_pos: u64,
1016 ind_type: IndirectType,
1017 is_signed: bool,
1018) -> Option<i64> {
1019 match ind_type {
1020 IndirectType::Byte => {
1021 let mut b = [0u8; 1];
1022 let n = source.read_at(deref_pos, &mut b).ok()?;
1023 if n < 1 {
1024 return None;
1025 }
1026 if is_signed {
1027 Some(i64::from(i8::from_le_bytes(b)))
1028 } else {
1029 Some(i64::from(b[0]))
1030 }
1031 }
1032 IndirectType::ShortLe => {
1033 let mut b = [0u8; 2];
1034 let n = source.read_at(deref_pos, &mut b).ok()?;
1035 if n < 2 {
1036 return None;
1037 }
1038 if is_signed {
1039 Some(i64::from(i16::from_le_bytes(b)))
1040 } else {
1041 Some(i64::from(u16::from_le_bytes(b)))
1042 }
1043 }
1044 IndirectType::ShortBe => {
1045 let mut b = [0u8; 2];
1046 let n = source.read_at(deref_pos, &mut b).ok()?;
1047 if n < 2 {
1048 return None;
1049 }
1050 if is_signed {
1051 Some(i64::from(i16::from_be_bytes(b)))
1052 } else {
1053 Some(i64::from(u16::from_be_bytes(b)))
1054 }
1055 }
1056 IndirectType::LongLe => {
1057 let mut b = [0u8; 4];
1058 let n = source.read_at(deref_pos, &mut b).ok()?;
1059 if n < 4 {
1060 return None;
1061 }
1062 if is_signed {
1063 Some(i64::from(i32::from_le_bytes(b)))
1064 } else {
1065 Some(i64::from(u32::from_le_bytes(b)))
1066 }
1067 }
1068 IndirectType::LongBe => {
1069 let mut b = [0u8; 4];
1070 let n = source.read_at(deref_pos, &mut b).ok()?;
1071 if n < 4 {
1072 return None;
1073 }
1074 if is_signed {
1075 Some(i64::from(i32::from_be_bytes(b)))
1076 } else {
1077 Some(i64::from(u32::from_be_bytes(b)))
1078 }
1079 }
1080 IndirectType::QuadLe => {
1081 let mut b = [0u8; 8];
1082 let n = source.read_at(deref_pos, &mut b).ok()?;
1083 if n < 8 {
1084 return None;
1085 }
1086 if is_signed {
1087 Some(i64::from_le_bytes(b))
1088 } else {
1089 i64::try_from(u64::from_le_bytes(b)).ok()
1090 }
1091 }
1092 IndirectType::QuadBe => {
1093 let mut b = [0u8; 8];
1094 let n = source.read_at(deref_pos, &mut b).ok()?;
1095 if n < 8 {
1096 return None;
1097 }
1098 if is_signed {
1099 Some(i64::from_be_bytes(b))
1100 } else {
1101 i64::try_from(u64::from_be_bytes(b)).ok()
1102 }
1103 }
1104 IndirectType::Id3Be => {
1105 let mut b = [0u8; 4];
1106 let n = source.read_at(deref_pos, &mut b).ok()?;
1107 if n < 4 {
1108 return None;
1109 }
1110 let val = ((u32::from(b[0]) & 0x7f) << 21)
1111 | ((u32::from(b[1]) & 0x7f) << 14)
1112 | ((u32::from(b[2]) & 0x7f) << 7)
1113 | (u32::from(b[3]) & 0x7f);
1114 if is_signed {
1115 Some(i64::from(i32::from_le_bytes(val.to_le_bytes())))
1116 } else {
1117 Some(i64::from(val))
1118 }
1119 }
1120 IndirectType::Id3Le => {
1121 let mut b = [0u8; 4];
1122 let n = source.read_at(deref_pos, &mut b).ok()?;
1123 if n < 4 {
1124 return None;
1125 }
1126 let val = (u32::from(b[0]) & 0x7f)
1127 | ((u32::from(b[1]) & 0x7f) << 7)
1128 | ((u32::from(b[2]) & 0x7f) << 14)
1129 | ((u32::from(b[3]) & 0x7f) << 21);
1130 if is_signed {
1131 Some(i64::from(i32::from_le_bytes(val.to_le_bytes())))
1132 } else {
1133 Some(i64::from(val))
1134 }
1135 }
1136 }
1137}
1138
1139/// Resolves an `Offset` to an absolute byte position within `source`.
1140fn resolve_offset<S: DetectionSource + ?Sized>(
1141 offset: &Offset,
1142 base_offset: u64,
1143 prev_match_end: u64,
1144 source: &mut S,
1145 depth: usize,
1146) -> Option<u64> {
1147 if depth > 16 {
1148 return None;
1149 }
1150 match offset {
1151 Offset::Bof(off) => base_offset.checked_add(*off),
1152 Offset::Eof(off) => {
1153 let total = source.total_len()?;
1154 total.checked_sub(*off)
1155 }
1156 Offset::Relative(rel) => {
1157 if *rel >= 0 {
1158 let add = u64::try_from(*rel).ok()?;
1159 prev_match_end.checked_add(add)
1160 } else {
1161 let sub = u64::try_from(rel.checked_neg()?).ok()?;
1162 prev_match_end.checked_sub(sub)
1163 }
1164 }
1165 Offset::Indirect {
1166 base,
1167 ind_type,
1168 is_signed,
1169 is_inverse,
1170 op,
1171 adjustment,
1172 } => {
1173 let deref_pos = resolve_offset(
1174 base,
1175 base_offset,
1176 prev_match_end,
1177 source,
1178 depth.saturating_add(1),
1179 )?;
1180 let mut val =
1181 read_indirect_val(source, deref_pos, *ind_type, *is_signed)?;
1182 if let Some(operation) = op {
1183 val = match operation {
1184 IndirectOp::Mul(factor) => val.checked_mul(*factor)?,
1185 IndirectOp::Div(denom) => {
1186 if *denom == 0 {
1187 return None;
1188 }
1189 val.checked_div(*denom)?
1190 }
1191 IndirectOp::Mod(denom) => {
1192 if *denom == 0 {
1193 return None;
1194 }
1195 val.checked_rem(*denom)?
1196 }
1197 IndirectOp::And(mask) => val & *mask,
1198 IndirectOp::Or(mask) => val | *mask,
1199 IndirectOp::Xor(mask) => val ^ *mask,
1200 IndirectOp::Add(add) => val.checked_add(*add)?,
1201 IndirectOp::Sub(sub) => val.checked_sub(*sub)?,
1202 };
1203 }
1204 if *is_inverse {
1205 val = !val;
1206 }
1207 let target_i64 = val.checked_add(*adjustment)?;
1208 let target_u64 = u64::try_from(target_i64).ok()?;
1209 base_offset.checked_add(target_u64)
1210 }
1211 Offset::RelativeIndirect {
1212 base,
1213 ind_type,
1214 is_signed,
1215 is_inverse,
1216 op,
1217 adjustment,
1218 } => {
1219 let deref_pos = resolve_offset(
1220 base,
1221 base_offset,
1222 prev_match_end,
1223 source,
1224 depth.saturating_add(1),
1225 )?;
1226 let mut val =
1227 read_indirect_val(source, deref_pos, *ind_type, *is_signed)?;
1228 if let Some(operation) = op {
1229 val = match operation {
1230 IndirectOp::Mul(factor) => val.checked_mul(*factor)?,
1231 IndirectOp::Div(denom) => {
1232 if *denom == 0 {
1233 return None;
1234 }
1235 val.checked_div(*denom)?
1236 }
1237 IndirectOp::Mod(denom) => {
1238 if *denom == 0 {
1239 return None;
1240 }
1241 val.checked_rem(*denom)?
1242 }
1243 IndirectOp::And(mask) => val & *mask,
1244 IndirectOp::Or(mask) => val | *mask,
1245 IndirectOp::Xor(mask) => val ^ *mask,
1246 IndirectOp::Add(add) => val.checked_add(*add)?,
1247 IndirectOp::Sub(sub) => val.checked_sub(*sub)?,
1248 };
1249 }
1250 if *is_inverse {
1251 val = !val;
1252 }
1253 let rel_val = val.checked_add(*adjustment)?;
1254 if rel_val >= 0 {
1255 let add = u64::try_from(rel_val).ok()?;
1256 prev_match_end.checked_add(add)
1257 } else {
1258 let sub = u64::try_from(rel_val.checked_neg()?).ok()?;
1259 prev_match_end.checked_sub(sub)
1260 }
1261 }
1262 Offset::Search { start, .. } => base_offset.checked_add(*start),
1263 }
1264}
1265
1266/// Returns true if the rule or any of its descendant rules have a description or annotation.
1267fn rule_tree_has_desc(r: &HierarchicalMagicRule) -> bool {
1268 if r.description.is_some()
1269 || r.mime.is_some()
1270 || r.ext.is_some()
1271 || r.apple.is_some()
1272 {
1273 return true;
1274 }
1275 r.children.iter().any(rule_tree_has_desc)
1276}
1277
1278/// Evaluates a hierarchical magic rule recursively with subroutine and relative match context.
1279fn evaluate_rule_internal<S: DetectionSource + ?Sized>(
1280 rule: &HierarchicalMagicRule,
1281 source: &mut S,
1282 base_offset: u64,
1283 prev_match_end: u64,
1284 templates: &HashMap<String, HierarchicalMagicRule>,
1285 depth: usize,
1286 mode: u32,
1287) -> Option<RuleMatchResult> {
1288 if depth > 32 {
1289 return None;
1290 }
1291
1292 let pos =
1293 resolve_offset(&rule.offset, base_offset, prev_match_end, source, 0)?;
1294
1295 let mut match_len: usize = 0;
1296 let mut der_match_info: Option<(usize, usize)> = None;
1297 let mut format_val = FormatValue::None;
1298 let mut use_subroutine_result: Option<RuleMatchResult> = None;
1299
1300 let matched = match &rule.test {
1301 MagicTest::ExactBytes(expected) => {
1302 let mut buf = vec![0u8; expected.len()];
1303 let n = source.read_at(pos, &mut buf).ok()?;
1304 if n >= expected.len() && buf == *expected {
1305 match_len = expected.len();
1306 format_val =
1307 FormatValue::Str(String::from_utf8_lossy(&buf).to_string());
1308 true
1309 } else {
1310 false
1311 }
1312 }
1313 MagicTest::MaskedBytes { bytes, mask } => {
1314 let mut buf = vec![0u8; bytes.len()];
1315 let n = source.read_at(pos, &mut buf).ok()?;
1316 if n < bytes.len() {
1317 false
1318 } else {
1319 let mut ok = true;
1320 for i in 0..bytes.len() {
1321 let actual = *buf.get(i)?;
1322 let m = *mask.get(i)?;
1323 let exp = *bytes.get(i)?;
1324 if (actual & m) != exp {
1325 ok = false;
1326 break;
1327 }
1328 }
1329 if ok {
1330 match_len = bytes.len();
1331 format_val = FormatValue::Str(
1332 String::from_utf8_lossy(&buf).to_string(),
1333 );
1334 }
1335 ok
1336 }
1337 }
1338 MagicTest::String { pattern, flags } => {
1339 if (flags.text_only && !is_text_source(source))
1340 || (flags.binary_only && is_text_source(source))
1341 {
1342 false
1343 } else if flags.compact_whitespace || flags.optional_whitespace {
1344 let max_read = pattern.len().saturating_add(512);
1345 let mut buf = vec![0u8; max_read];
1346 let n = source.read_at(pos, &mut buf).ok()?;
1347 let Some(slice) = buf.get(..n) else {
1348 return None;
1349 };
1350 let mut a_idx = 0;
1351 let mut b_idx = 0;
1352 let mut matched = true;
1353 while a_idx < pattern.len() {
1354 let Some(&pa) = pattern.get(a_idx) else {
1355 matched = false;
1356 break;
1357 };
1358 if pa.is_ascii_whitespace() {
1359 a_idx = a_idx.saturating_add(1);
1360 if flags.optional_whitespace {
1361 while let Some(&b) = slice.get(b_idx) {
1362 if !b.is_ascii_whitespace() {
1363 break;
1364 }
1365 b_idx = b_idx.saturating_add(1);
1366 }
1367 } else {
1368 if b_idx >= slice.len() {
1369 matched = false;
1370 break;
1371 }
1372 let Some(&pb) = slice.get(b_idx) else {
1373 matched = false;
1374 break;
1375 };
1376 if pb.is_ascii_whitespace() {
1377 b_idx = b_idx.saturating_add(1);
1378 while let Some(&b) = slice.get(b_idx) {
1379 if !b.is_ascii_whitespace() {
1380 break;
1381 }
1382 b_idx = b_idx.saturating_add(1);
1383 }
1384 } else {
1385 matched = false;
1386 break;
1387 }
1388 }
1389 } else {
1390 if b_idx >= slice.len() {
1391 matched = false;
1392 break;
1393 }
1394 let Some(&pb) = slice.get(b_idx) else {
1395 matched = false;
1396 break;
1397 };
1398 let eq = if flags.case_insensitive {
1399 pa.eq_ignore_ascii_case(&pb)
1400 } else {
1401 pa == pb
1402 };
1403 if eq {
1404 a_idx = a_idx.saturating_add(1);
1405 b_idx = b_idx.saturating_add(1);
1406 } else {
1407 matched = false;
1408 break;
1409 }
1410 }
1411 }
1412 if matched && flags.full_word {
1413 if let Some(&pb) = slice.get(b_idx) {
1414 if !pb.is_ascii_whitespace()
1415 && (pb.is_ascii_alphanumeric() || pb == b'_')
1416 {
1417 matched = false;
1418 }
1419 }
1420 }
1421 if matched {
1422 match_len = b_idx;
1423 // Reason for fallback: slice calculation beyond buffer bounds defaults to empty slice
1424 let matched_bytes = slice.get(..b_idx).unwrap_or(&[]);
1425 format_val = FormatValue::Str(
1426 String::from_utf8_lossy(matched_bytes).to_string(),
1427 );
1428 true
1429 } else {
1430 false
1431 }
1432 } else {
1433 let check_len =
1434 pattern.len().saturating_add(usize::from(flags.full_word));
1435 let mut buf = vec![0u8; check_len];
1436 let n = source.read_at(pos, &mut buf).ok()?;
1437 if n < pattern.len() {
1438 false
1439 } else {
1440 let pat_buf = buf.get(..pattern.len())?;
1441 let mut ok = if flags.case_insensitive {
1442 pat_buf.eq_ignore_ascii_case(pattern)
1443 } else {
1444 pat_buf == pattern.as_slice()
1445 };
1446 if ok && flags.full_word && n > pattern.len() {
1447 if let Some(&next_byte) = buf.get(pattern.len()) {
1448 if !next_byte.is_ascii_whitespace()
1449 && (next_byte.is_ascii_alphanumeric()
1450 || next_byte == b'_')
1451 {
1452 ok = false;
1453 }
1454 }
1455 }
1456 if ok {
1457 match_len = pattern.len();
1458 format_val = FormatValue::Str(
1459 String::from_utf8_lossy(pat_buf).to_string(),
1460 );
1461 }
1462 ok
1463 }
1464 }
1465 }
1466 MagicTest::StringAny(flags) => {
1467 if (flags.text_only && !is_text_source(source))
1468 || (flags.binary_only && is_text_source(source))
1469 {
1470 false
1471 } else {
1472 let mut buf = [0u8; 256];
1473 let n = source.read_at(pos, &mut buf).ok()?;
1474 if n == 0 {
1475 false
1476 } else {
1477 let Some(slice) = buf.get(..n) else {
1478 return None;
1479 };
1480 // Reason for fallback: if no null or newline delimiter is found, string spans to end of read slice
1481 let len = slice
1482 .iter()
1483 .position(|&b| b == 0 || b == b'\r' || b == b'\n')
1484 .unwrap_or(n);
1485 // Reason for fallback: subslice to delimiter defaults to empty slice
1486 let mut s = String::from_utf8_lossy(
1487 slice.get(..len).unwrap_or(&[]),
1488 )
1489 .to_string();
1490 if flags.trim {
1491 s = s.trim().to_string();
1492 }
1493 match_len = len;
1494 format_val = FormatValue::Str(s);
1495 true
1496 }
1497 }
1498 }
1499 MagicTest::StringRelOp { pattern, op, flags } => {
1500 if (flags.text_only && !is_text_source(source))
1501 || (flags.binary_only && is_text_source(source))
1502 {
1503 false
1504 } else {
1505 let mut buf = vec![0u8; pattern.len()];
1506 let n = source.read_at(pos, &mut buf).ok()?;
1507 if n < pattern.len() {
1508 false
1509 } else {
1510 let cmp = if flags.case_insensitive {
1511 buf.to_ascii_lowercase()
1512 .cmp(&pattern.to_ascii_lowercase())
1513 } else {
1514 buf.cmp(pattern)
1515 };
1516 let ok = match op {
1517 RelOp::Eq => cmp == std::cmp::Ordering::Equal,
1518 RelOp::Ne => cmp != std::cmp::Ordering::Equal,
1519 RelOp::Gt => cmp == std::cmp::Ordering::Greater,
1520 RelOp::Lt => cmp == std::cmp::Ordering::Less,
1521 RelOp::BitAnd | RelOp::BitClear | RelOp::Any => true,
1522 };
1523 if ok {
1524 let mut full_buf = [0u8; 256];
1525 // Reason for fallback: read error when fetching string format value defaults to 0 bytes read
1526 let fn_bytes =
1527 source.read_at(pos, &mut full_buf).unwrap_or(0);
1528 // Reason for fallback: slice defaults to empty slice if read length exceeds buffer
1529 let full_slice =
1530 full_buf.get(..fn_bytes).unwrap_or(&[]);
1531 // Reason for fallback: if no null or newline delimiter is found, string spans full buffer
1532 let str_len = full_slice
1533 .iter()
1534 .position(|&b| b == 0 || b == b'\r' || b == b'\n')
1535 .unwrap_or(fn_bytes);
1536 // Reason for fallback: subslice to delimiter defaults to original pattern buffer
1537 let mut s = String::from_utf8_lossy(
1538 full_slice.get(..str_len).unwrap_or(&buf),
1539 )
1540 .to_string();
1541 if flags.trim {
1542 s = s.trim().to_string();
1543 }
1544 match_len = pattern.len().max(str_len);
1545 format_val = FormatValue::Str(s);
1546 }
1547 ok
1548 }
1549 }
1550 }
1551 MagicTest::PascalString {
1552 pattern,
1553 length_size,
1554 length_includes_itself,
1555 } => {
1556 let prefix_len = match length_size {
1557 PascalLengthSize::Byte => 1,
1558 PascalLengthSize::ShortLe | PascalLengthSize::ShortBe => 2,
1559 PascalLengthSize::LongLe | PascalLengthSize::LongBe => 4,
1560 };
1561 let mut pfx = vec![0u8; prefix_len];
1562 let n = source.read_at(pos, &mut pfx).ok()?;
1563 if n < prefix_len {
1564 false
1565 } else {
1566 let raw_len = match length_size {
1567 PascalLengthSize::Byte => usize::from(*pfx.first()?),
1568 PascalLengthSize::ShortLe => {
1569 let b = <[u8; 2]>::try_from(pfx.get(..2)?).ok()?;
1570 usize::from(u16::from_le_bytes(b))
1571 }
1572 PascalLengthSize::ShortBe => {
1573 let b = <[u8; 2]>::try_from(pfx.get(..2)?).ok()?;
1574 usize::from(u16::from_be_bytes(b))
1575 }
1576 PascalLengthSize::LongLe => {
1577 let b = <[u8; 4]>::try_from(pfx.get(..4)?).ok()?;
1578 usize::try_from(u32::from_le_bytes(b)).ok()?
1579 }
1580 PascalLengthSize::LongBe => {
1581 let b = <[u8; 4]>::try_from(pfx.get(..4)?).ok()?;
1582 usize::try_from(u32::from_be_bytes(b)).ok()?
1583 }
1584 };
1585 let payload_len = if *length_includes_itself {
1586 raw_len.saturating_sub(prefix_len)
1587 } else {
1588 raw_len
1589 };
1590 let prefix_len_u64 = match length_size {
1591 PascalLengthSize::Byte => 1u64,
1592 PascalLengthSize::ShortLe | PascalLengthSize::ShortBe => {
1593 2u64
1594 }
1595 PascalLengthSize::LongLe | PascalLengthSize::LongBe => 4u64,
1596 };
1597 let read_len = payload_len.min(pattern.len());
1598 let mut content_buf = vec![0u8; read_len];
1599 let content_pos = pos.saturating_add(prefix_len_u64);
1600 let cn = source.read_at(content_pos, &mut content_buf).ok()?;
1601 if cn >= pattern.len() && content_buf == *pattern {
1602 match_len = prefix_len.saturating_add(payload_len);
1603 format_val = FormatValue::Str(
1604 String::from_utf8_lossy(&content_buf).to_string(),
1605 );
1606 true
1607 } else {
1608 false
1609 }
1610 }
1611 }
1612 MagicTest::PascalStringAny {
1613 length_size,
1614 length_includes_itself,
1615 } => {
1616 let prefix_len = match length_size {
1617 PascalLengthSize::Byte => 1,
1618 PascalLengthSize::ShortLe | PascalLengthSize::ShortBe => 2,
1619 PascalLengthSize::LongLe | PascalLengthSize::LongBe => 4,
1620 };
1621 let mut pfx = vec![0u8; prefix_len];
1622 let n = source.read_at(pos, &mut pfx).ok()?;
1623 if n < prefix_len {
1624 false
1625 } else {
1626 let raw_len = match length_size {
1627 PascalLengthSize::Byte => usize::from(*pfx.first()?),
1628 PascalLengthSize::ShortLe => {
1629 let b = <[u8; 2]>::try_from(pfx.get(..2)?).ok()?;
1630 usize::from(u16::from_le_bytes(b))
1631 }
1632 PascalLengthSize::ShortBe => {
1633 let b = <[u8; 2]>::try_from(pfx.get(..2)?).ok()?;
1634 usize::from(u16::from_be_bytes(b))
1635 }
1636 PascalLengthSize::LongLe => {
1637 let b = <[u8; 4]>::try_from(pfx.get(..4)?).ok()?;
1638 usize::try_from(u32::from_le_bytes(b)).ok()?
1639 }
1640 PascalLengthSize::LongBe => {
1641 let b = <[u8; 4]>::try_from(pfx.get(..4)?).ok()?;
1642 usize::try_from(u32::from_be_bytes(b)).ok()?
1643 }
1644 };
1645 let payload_len = if *length_includes_itself {
1646 raw_len.saturating_sub(prefix_len)
1647 } else {
1648 raw_len
1649 };
1650 let prefix_len_u64 = match length_size {
1651 PascalLengthSize::Byte => 1u64,
1652 PascalLengthSize::ShortLe | PascalLengthSize::ShortBe => {
1653 2u64
1654 }
1655 PascalLengthSize::LongLe | PascalLengthSize::LongBe => 4u64,
1656 };
1657 let read_len = payload_len.min(256);
1658 let mut content_buf = vec![0u8; read_len];
1659 let content_pos = pos.saturating_add(prefix_len_u64);
1660 let cn = source.read_at(content_pos, &mut content_buf).ok()?;
1661 let Some(content_slice) = content_buf.get(..cn) else {
1662 return None;
1663 };
1664 // Reason for fallback: if no null or newline delimiter is found, string spans full slice
1665 let str_len = content_slice
1666 .iter()
1667 .position(|&b| b == 0 || b == b'\r' || b == b'\n')
1668 .unwrap_or(cn);
1669 // Reason for fallback: subslice to delimiter defaults to full slice
1670 let s = String::from_utf8_lossy(
1671 content_slice.get(..str_len).unwrap_or(content_slice),
1672 )
1673 .to_string();
1674 match_len = prefix_len.saturating_add(str_len);
1675 format_val = FormatValue::Str(s);
1676 true
1677 }
1678 }
1679 MagicTest::Regex {
1680 pattern,
1681 case_insensitive,
1682 max_bytes,
1683 line_limit,
1684 offset_start,
1685 } => {
1686 let slice = bounded_source_read(source, pos, *max_bytes)?;
1687 if slice.is_empty() {
1688 false
1689 } else {
1690 let text = String::from_utf8_lossy(&slice);
1691 let re = get_compiled_magic_regex(pattern, *case_insensitive)?;
1692 // Reason for fallback: default regex search limit in libmagic is 80 lines when unconstrained
1693 let limit = line_limit.unwrap_or(80);
1694 let mut line_start_byte: usize = 0;
1695 let mut matched = false;
1696 let mut line_count: usize = 0;
1697
1698 for line in text.split_inclusive('\n') {
1699 line_count = line_count.saturating_add(1);
1700 if line_count > limit {
1701 break;
1702 }
1703 // Reason for fallback: line without trailing newline remains unchanged
1704 let trimmed_line = line.strip_suffix('\n').unwrap_or(line);
1705 // Reason for fallback: line without trailing carriage return remains unchanged
1706 let trimmed_line =
1707 trimmed_line.strip_suffix('\r').unwrap_or(trimmed_line);
1708
1709 if let Some(m) = re.find(trimmed_line) {
1710 let m_start = line_start_byte.saturating_add(m.start());
1711 let m_end = line_start_byte.saturating_add(m.end());
1712 match_len = if *offset_start { m_start } else { m_end };
1713 format_val = FormatValue::Str(m.as_str().to_string());
1714 matched = true;
1715 break;
1716 }
1717 line_start_byte =
1718 line_start_byte.saturating_add(line.len());
1719 }
1720
1721 if !matched
1722 && (pattern.contains(r"\n") || pattern.contains('\n'))
1723 {
1724 if let Some(m) = re.find(text.as_ref()) {
1725 match_len =
1726 if *offset_start { m.start() } else { m.end() };
1727 format_val = FormatValue::Str(m.as_str().to_string());
1728 matched = true;
1729 }
1730 }
1731
1732 matched
1733 }
1734 }
1735 MagicTest::U8 {
1736 value,
1737 op,
1738 mask,
1739 num_op,
1740 } => {
1741 let mut buf = [0u8; 1];
1742 let n = source.read_at(pos, &mut buf).ok()?;
1743 if n < 1 {
1744 false
1745 } else {
1746 let mut val = buf[0];
1747 if let Some(m) = mask {
1748 val &= m;
1749 }
1750 // Reason for fallback: arithmetic overflow when downcasting u64 num_op result back to u8 retains original value
1751 val = u8::try_from(apply_num_op_u64(u64::from(val), *num_op))
1752 .unwrap_or(val);
1753 let ok = eval_rel_op(val, *op, *value);
1754 if ok {
1755 match_len = 1;
1756 format_val = FormatValue::U64(u64::from(val));
1757 }
1758 ok
1759 }
1760 }
1761 MagicTest::U16Le {
1762 value,
1763 op,
1764 mask,
1765 num_op,
1766 } => {
1767 let mut buf = [0u8; 2];
1768 let n = source.read_at(pos, &mut buf).ok()?;
1769 if n < 2 {
1770 false
1771 } else {
1772 let mut val = u16::from_le_bytes(buf);
1773 if let Some(m) = mask {
1774 val &= m;
1775 }
1776 // Reason for fallback: arithmetic overflow when downcasting u64 num_op result back to u16 retains original value
1777 val = u16::try_from(apply_num_op_u64(u64::from(val), *num_op))
1778 .unwrap_or(val);
1779 let ok = eval_rel_op(val, *op, *value);
1780 if ok {
1781 match_len = 2;
1782 format_val = FormatValue::U64(u64::from(val));
1783 }
1784 ok
1785 }
1786 }
1787 MagicTest::U16Be {
1788 value,
1789 op,
1790 mask,
1791 num_op,
1792 } => {
1793 let mut buf = [0u8; 2];
1794 let n = source.read_at(pos, &mut buf).ok()?;
1795 if n < 2 {
1796 false
1797 } else {
1798 let mut val = u16::from_be_bytes(buf);
1799 if let Some(m) = mask {
1800 val &= m;
1801 }
1802 // Reason for fallback: arithmetic overflow when downcasting u64 num_op result back to u16 retains original value
1803 val = u16::try_from(apply_num_op_u64(u64::from(val), *num_op))
1804 .unwrap_or(val);
1805 let ok = eval_rel_op(val, *op, *value);
1806 if ok {
1807 match_len = 2;
1808 format_val = FormatValue::U64(u64::from(val));
1809 }
1810 ok
1811 }
1812 }
1813 MagicTest::U32Le {
1814 value,
1815 op,
1816 mask,
1817 num_op,
1818 } => {
1819 let mut buf = [0u8; 4];
1820 let n = source.read_at(pos, &mut buf).ok()?;
1821 if n < 4 {
1822 false
1823 } else {
1824 let mut val = u32::from_le_bytes(buf);
1825 if let Some(m) = mask {
1826 val &= m;
1827 }
1828 // Reason for fallback: arithmetic overflow when downcasting u64 num_op result back to u32 retains original value
1829 val = u32::try_from(apply_num_op_u64(u64::from(val), *num_op))
1830 .unwrap_or(val);
1831 let ok = eval_rel_op(val, *op, *value);
1832 if ok {
1833 match_len = 4;
1834 format_val = FormatValue::U64(u64::from(val));
1835 }
1836 ok
1837 }
1838 }
1839 MagicTest::U32Be {
1840 value,
1841 op,
1842 mask,
1843 num_op,
1844 } => {
1845 let mut buf = [0u8; 4];
1846 let n = source.read_at(pos, &mut buf).ok()?;
1847 if n < 4 {
1848 false
1849 } else {
1850 let mut val = u32::from_be_bytes(buf);
1851 if let Some(m) = mask {
1852 val &= m;
1853 }
1854 // Reason for fallback: arithmetic overflow when downcasting u64 num_op result back to u32 retains original value
1855 val = u32::try_from(apply_num_op_u64(u64::from(val), *num_op))
1856 .unwrap_or(val);
1857 let ok = eval_rel_op(val, *op, *value);
1858 if ok {
1859 match_len = 4;
1860 format_val = FormatValue::U64(u64::from(val));
1861 }
1862 ok
1863 }
1864 }
1865 MagicTest::U64Le {
1866 value,
1867 op,
1868 mask,
1869 num_op,
1870 } => {
1871 let mut buf = [0u8; 8];
1872 let n = source.read_at(pos, &mut buf).ok()?;
1873 if n < 8 {
1874 false
1875 } else {
1876 let mut val = u64::from_le_bytes(buf);
1877 if let Some(m) = mask {
1878 val &= m;
1879 }
1880 val = apply_num_op_u64(val, *num_op);
1881 let ok = eval_rel_op(val, *op, *value);
1882 if ok {
1883 match_len = 8;
1884 format_val = FormatValue::U64(val);
1885 }
1886 ok
1887 }
1888 }
1889 MagicTest::U64Be {
1890 value,
1891 op,
1892 mask,
1893 num_op,
1894 } => {
1895 let mut buf = [0u8; 8];
1896 let n = source.read_at(pos, &mut buf).ok()?;
1897 if n < 8 {
1898 false
1899 } else {
1900 let mut val = u64::from_be_bytes(buf);
1901 if let Some(m) = mask {
1902 val &= m;
1903 }
1904 val = apply_num_op_u64(val, *num_op);
1905 let ok = eval_rel_op(val, *op, *value);
1906 if ok {
1907 match_len = 8;
1908 format_val = FormatValue::U64(val);
1909 }
1910 ok
1911 }
1912 }
1913 MagicTest::Date32Le {
1914 value,
1915 op,
1916 adjustment,
1917 } => {
1918 let mut buf = [0u8; 4];
1919 let n = source.read_at(pos, &mut buf).ok()?;
1920 if n < 4 {
1921 false
1922 } else {
1923 let raw = u32::from_le_bytes(buf);
1924 let ok = eval_rel_op(raw, *op, *value);
1925 if ok {
1926 match_len = 4;
1927 let raw_i64 = i64::from(i32::from_le_bytes(buf));
1928 let adj = raw_i64.saturating_add(*adjustment);
1929 format_val = FormatValue::Date(adj);
1930 }
1931 ok
1932 }
1933 }
1934 MagicTest::Date32Be {
1935 value,
1936 op,
1937 adjustment,
1938 } => {
1939 let mut buf = [0u8; 4];
1940 let n = source.read_at(pos, &mut buf).ok()?;
1941 if n < 4 {
1942 false
1943 } else {
1944 let raw = u32::from_be_bytes(buf);
1945 let ok = eval_rel_op(raw, *op, *value);
1946 if ok {
1947 match_len = 4;
1948 let raw_i64 = i64::from(i32::from_be_bytes(buf));
1949 let adj = raw_i64.saturating_add(*adjustment);
1950 format_val = FormatValue::Date(adj);
1951 }
1952 ok
1953 }
1954 }
1955 MagicTest::Date64Le {
1956 value,
1957 op,
1958 adjustment,
1959 } => {
1960 let mut buf = [0u8; 8];
1961 let n = source.read_at(pos, &mut buf).ok()?;
1962 if n < 8 {
1963 false
1964 } else {
1965 let raw = u64::from_le_bytes(buf);
1966 let ok = eval_rel_op(raw, *op, *value);
1967 if ok {
1968 match_len = 8;
1969 let raw_i64 = i64::from_le_bytes(buf);
1970 let adj = raw_i64.saturating_add(*adjustment);
1971 format_val = FormatValue::Date(adj);
1972 }
1973 ok
1974 }
1975 }
1976 MagicTest::Date64Be {
1977 value,
1978 op,
1979 adjustment,
1980 } => {
1981 let mut buf = [0u8; 8];
1982 let n = source.read_at(pos, &mut buf).ok()?;
1983 if n < 8 {
1984 false
1985 } else {
1986 let raw = u64::from_be_bytes(buf);
1987 let ok = eval_rel_op(raw, *op, *value);
1988 if ok {
1989 match_len = 8;
1990 let raw_i64 = i64::from_be_bytes(buf);
1991 let adj = raw_i64.saturating_add(*adjustment);
1992 format_val = FormatValue::Date(adj);
1993 }
1994 ok
1995 }
1996 }
1997 MagicTest::MsDosDate => {
1998 let mut buf = [0u8; 2];
1999 let n = source.read_at(pos, &mut buf).ok()?;
2000 if n < 2 {
2001 false
2002 } else {
2003 let raw = u16::from_le_bytes(buf);
2004 let day = raw & 0x1F;
2005 let month_num = (raw >> 5) & 0x0F;
2006 let year_diff = u32::from((raw >> 9) & 0x7F);
2007 let year = 1980u32.saturating_add(year_diff);
2008 let months = [
2009 "Jan", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
2010 "Aug", "Sep", "Oct", "Nov", "Dec",
2011 ];
2012 // Reason for fallback: invalid MS-DOS month number defaults to Jan matching libmagic output
2013 let m_str = months
2014 .get(usize::from(month_num))
2015 .copied()
2016 .unwrap_or("Jan");
2017 let s = format!("{m_str} {day:02} {year}");
2018 match_len = 2;
2019 format_val = FormatValue::Str(s);
2020 true
2021 }
2022 }
2023 MagicTest::MsDosTime => {
2024 let mut buf = [0u8; 2];
2025 let n = source.read_at(pos, &mut buf).ok()?;
2026 if n < 2 {
2027 false
2028 } else {
2029 let raw = u16::from_le_bytes(buf);
2030 let sec = (raw & 0x1F).saturating_mul(2);
2031 let min = (raw >> 5) & 0x3F;
2032 let hour = (raw >> 11) & 0x1F;
2033 let s = format!("{hour:02}:{min:02}:{sec:02}");
2034 match_len = 2;
2035 format_val = FormatValue::Str(s);
2036 true
2037 }
2038 }
2039 MagicTest::Guid(expected) | MagicTest::GuidLe(expected) => {
2040 let mut buf = [0u8; 16];
2041 let n = source.read_at(pos, &mut buf).ok()?;
2042 if n >= 16 && buf == *expected {
2043 match_len = 16;
2044 format_val = FormatValue::Str(format_guid_le(&buf));
2045 true
2046 } else {
2047 false
2048 }
2049 }
2050 MagicTest::GuidBe(expected) => {
2051 let mut buf = [0u8; 16];
2052 let n = source.read_at(pos, &mut buf).ok()?;
2053 if n >= 16 && buf == *expected {
2054 match_len = 16;
2055 format_val = FormatValue::Str(format_guid_be(&buf));
2056 true
2057 } else {
2058 false
2059 }
2060 }
2061 MagicTest::GuidLeAny => {
2062 let mut buf = [0u8; 16];
2063 let n = source.read_at(pos, &mut buf).ok()?;
2064 if n >= 16 {
2065 match_len = 16;
2066 format_val = FormatValue::Str(format_guid_le(&buf));
2067 true
2068 } else {
2069 false
2070 }
2071 }
2072 MagicTest::GuidBeAny => {
2073 let mut buf = [0u8; 16];
2074 let n = source.read_at(pos, &mut buf).ok()?;
2075 if n >= 16 {
2076 match_len = 16;
2077 format_val = FormatValue::Str(format_guid_be(&buf));
2078 true
2079 } else {
2080 false
2081 }
2082 }
2083 MagicTest::FloatLe { value_bits, op } => {
2084 let mut buf = [0u8; 4];
2085 let n = source.read_at(pos, &mut buf).ok()?;
2086 if n < 4 {
2087 false
2088 } else {
2089 let val = f32::from_le_bytes(buf);
2090 let expected = f32::from_bits(*value_bits);
2091 let ok = eval_float_op(val, *op, expected);
2092 if ok {
2093 match_len = 4;
2094 format_val = FormatValue::F64(f64::from(val));
2095 }
2096 ok
2097 }
2098 }
2099 MagicTest::FloatBe { value_bits, op } => {
2100 let mut buf = [0u8; 4];
2101 let n = source.read_at(pos, &mut buf).ok()?;
2102 if n < 4 {
2103 false
2104 } else {
2105 let val = f32::from_be_bytes(buf);
2106 let expected = f32::from_bits(*value_bits);
2107 let ok = eval_float_op(val, *op, expected);
2108 if ok {
2109 match_len = 4;
2110 format_val = FormatValue::F64(f64::from(val));
2111 }
2112 ok
2113 }
2114 }
2115 MagicTest::DoubleLe { value_bits, op } => {
2116 let mut buf = [0u8; 8];
2117 let n = source.read_at(pos, &mut buf).ok()?;
2118 if n < 8 {
2119 false
2120 } else {
2121 let val = f64::from_le_bytes(buf);
2122 let expected = f64::from_bits(*value_bits);
2123 let ok = eval_double_op(val, *op, expected);
2124 if ok {
2125 match_len = 8;
2126 format_val = FormatValue::F64(val);
2127 }
2128 ok
2129 }
2130 }
2131 MagicTest::DoubleBe { value_bits, op } => {
2132 let mut buf = [0u8; 8];
2133 let n = source.read_at(pos, &mut buf).ok()?;
2134 if n < 8 {
2135 false
2136 } else {
2137 let val = f64::from_be_bytes(buf);
2138 let expected = f64::from_bits(*value_bits);
2139 let ok = eval_double_op(val, *op, expected);
2140 if ok {
2141 match_len = 8;
2142 format_val = FormatValue::F64(val);
2143 }
2144 ok
2145 }
2146 }
2147 MagicTest::String16Le { pattern, flags, op } => {
2148 let max_chars = pattern.len().max(32);
2149 if let Some((extracted, consumed_bytes)) =
2150 extract_string16(source, pos, false, max_chars)
2151 {
2152 let ok = match op {
2153 RelOp::Eq => {
2154 if flags.case_insensitive {
2155 extracted
2156 .to_ascii_lowercase()
2157 .as_bytes()
2158 .starts_with(&pattern.to_ascii_lowercase())
2159 } else {
2160 extracted.as_bytes().starts_with(pattern)
2161 }
2162 }
2163 RelOp::Ne => {
2164 if flags.case_insensitive {
2165 !extracted
2166 .to_ascii_lowercase()
2167 .as_bytes()
2168 .starts_with(&pattern.to_ascii_lowercase())
2169 } else {
2170 !extracted.as_bytes().starts_with(pattern)
2171 }
2172 }
2173 RelOp::Gt => extracted.as_bytes() > pattern.as_slice(),
2174 RelOp::Lt => extracted.as_bytes() < pattern.as_slice(),
2175 _ => true,
2176 };
2177 if ok {
2178 match_len =
2179 pattern.len().saturating_mul(2).min(consumed_bytes);
2180 format_val = FormatValue::Str(extracted);
2181 true
2182 } else {
2183 false
2184 }
2185 } else {
2186 false
2187 }
2188 }
2189 MagicTest::String16Be { pattern, flags, op } => {
2190 let max_chars = pattern.len().max(32);
2191 if let Some((extracted, consumed_bytes)) =
2192 extract_string16(source, pos, true, max_chars)
2193 {
2194 let ok = match op {
2195 RelOp::Eq => {
2196 if flags.case_insensitive {
2197 extracted
2198 .to_ascii_lowercase()
2199 .as_bytes()
2200 .starts_with(&pattern.to_ascii_lowercase())
2201 } else {
2202 extracted.as_bytes().starts_with(pattern)
2203 }
2204 }
2205 RelOp::Ne => {
2206 if flags.case_insensitive {
2207 !extracted
2208 .to_ascii_lowercase()
2209 .as_bytes()
2210 .starts_with(&pattern.to_ascii_lowercase())
2211 } else {
2212 !extracted.as_bytes().starts_with(pattern)
2213 }
2214 }
2215 RelOp::Gt => extracted.as_bytes() > pattern.as_slice(),
2216 RelOp::Lt => extracted.as_bytes() < pattern.as_slice(),
2217 _ => true,
2218 };
2219 if ok {
2220 match_len =
2221 pattern.len().saturating_mul(2).min(consumed_bytes);
2222 format_val = FormatValue::Str(extracted);
2223 true
2224 } else {
2225 false
2226 }
2227 } else {
2228 false
2229 }
2230 }
2231 MagicTest::String16LeAny(_) => {
2232 if let Some((extracted, consumed_bytes)) =
2233 extract_string16(source, pos, false, 512)
2234 {
2235 match_len = consumed_bytes;
2236 format_val = FormatValue::Str(extracted);
2237 true
2238 } else {
2239 false
2240 }
2241 }
2242 MagicTest::String16BeAny(_) => {
2243 if let Some((extracted, consumed_bytes)) =
2244 extract_string16(source, pos, true, 512)
2245 {
2246 match_len = consumed_bytes;
2247 format_val = FormatValue::Str(extracted);
2248 true
2249 } else {
2250 false
2251 }
2252 }
2253 MagicTest::VarintLe { value, op, mask } => {
2254 let mut buf = [0u8; 10];
2255 let n = source.read_at(pos, &mut buf).ok()?;
2256 if n == 0 {
2257 false
2258 } else {
2259 let slice = buf.get(..n)?;
2260 let mut val: u64 = 0;
2261 let mut shift: u32 = 0;
2262 let mut bytes_consumed = 0usize;
2263 let mut found_end = false;
2264 for (i, &b) in slice.iter().enumerate() {
2265 bytes_consumed = i.saturating_add(1);
2266 let chunk = u64::from(b & 0x7F);
2267 val |= chunk << shift;
2268 shift = shift.saturating_add(7);
2269 if (b & 0x80) == 0 {
2270 found_end = true;
2271 break;
2272 }
2273 if shift >= 64 {
2274 break;
2275 }
2276 }
2277 if !found_end && n < 10 {
2278 false
2279 } else {
2280 if let Some(m) = mask {
2281 val &= m;
2282 }
2283 let ok = eval_rel_op(val, *op, *value);
2284 if ok {
2285 match_len = bytes_consumed;
2286 format_val = FormatValue::U64(val);
2287 }
2288 ok
2289 }
2290 }
2291 }
2292 MagicTest::VarintBe { value, op, mask } => {
2293 let mut buf = [0u8; 10];
2294 let n = source.read_at(pos, &mut buf).ok()?;
2295 if n == 0 {
2296 false
2297 } else {
2298 let slice = buf.get(..n)?;
2299 let mut val: u64 = 0;
2300 let mut bytes_consumed = 0usize;
2301 let mut found_end = false;
2302 for (i, &b) in slice.iter().enumerate() {
2303 bytes_consumed = i.saturating_add(1);
2304 val = (val << 7) | u64::from(b & 0x7F);
2305 if (b & 0x80) == 0 {
2306 found_end = true;
2307 break;
2308 }
2309 if bytes_consumed >= 10 {
2310 break;
2311 }
2312 }
2313 if !found_end && n < 10 {
2314 false
2315 } else {
2316 if let Some(m) = mask {
2317 val &= m;
2318 }
2319 let ok = eval_rel_op(val, *op, *value);
2320 if ok {
2321 match_len = bytes_consumed;
2322 format_val = FormatValue::U64(val);
2323 }
2324 ok
2325 }
2326 }
2327 }
2328 MagicTest::DateWindows64Le {
2329 value,
2330 op,
2331 adjustment,
2332 } => {
2333 let mut buf = [0u8; 8];
2334 let n = source.read_at(pos, &mut buf).ok()?;
2335 if n < 8 {
2336 false
2337 } else {
2338 let raw = u64::from_le_bytes(buf);
2339 let ok = eval_rel_op(raw, *op, *value);
2340 if ok {
2341 match_len = 8;
2342 // Windows FILETIME is 100ns intervals since Jan 1, 1601.
2343 // 11644473600 seconds elapsed between Jan 1 1601 and Jan 1 1970 (Unix epoch).
2344 // Reason for fallback: Windows 100ns FILETIME units divided by 10^7 gives epoch seconds; divisor is non-zero so checked_div cannot fail.
2345 let total_secs_u64 =
2346 raw.checked_div(10_000_000).unwrap_or(0);
2347 // Reason for fallback: If FILETIME exceeds signed i64 range, clamp to i64::MAX before Unix epoch adjustment.
2348 let raw_secs = i64::try_from(total_secs_u64)
2349 .unwrap_or(i64::MAX)
2350 .saturating_sub(11_644_473_600);
2351 let adj = raw_secs.saturating_add(*adjustment);
2352 format_val = FormatValue::Date(adj);
2353 }
2354 ok
2355 }
2356 }
2357 MagicTest::DateWindows64Be {
2358 value,
2359 op,
2360 adjustment,
2361 } => {
2362 let mut buf = [0u8; 8];
2363 let n = source.read_at(pos, &mut buf).ok()?;
2364 if n < 8 {
2365 false
2366 } else {
2367 let raw = u64::from_be_bytes(buf);
2368 let ok = eval_rel_op(raw, *op, *value);
2369 if ok {
2370 match_len = 8;
2371 // Reason for fallback: Windows 100ns FILETIME units divided by 10^7 gives epoch seconds; divisor is non-zero so checked_div cannot fail.
2372 let total_secs_u64 =
2373 raw.checked_div(10_000_000).unwrap_or(0);
2374 // Reason for fallback: If FILETIME exceeds signed i64 range, clamp to i64::MAX before Unix epoch adjustment.
2375 let raw_secs = i64::try_from(total_secs_u64)
2376 .unwrap_or(i64::MAX)
2377 .saturating_sub(11_644_473_600);
2378 let adj = raw_secs.saturating_add(*adjustment);
2379 format_val = FormatValue::Date(adj);
2380 }
2381 ok
2382 }
2383 }
2384 MagicTest::Octal { pattern, is_any } => {
2385 if *is_any {
2386 let mut buf = [0u8; 32];
2387 let n = source.read_at(pos, &mut buf).ok()?;
2388 let slice = buf.get(..n)?;
2389 let mut digits = Vec::new();
2390 for &b in slice {
2391 if (b'0'..=b'7').contains(&b) {
2392 digits.push(b);
2393 } else {
2394 break;
2395 }
2396 }
2397 if digits.is_empty() {
2398 false
2399 } else {
2400 let s = std::str::from_utf8(&digits).ok()?;
2401 let val = u64::from_str_radix(s, 8).ok()?;
2402 match_len = digits.len();
2403 format_val = FormatValue::U64(val);
2404 true
2405 }
2406 } else {
2407 let mut buf = vec![0u8; pattern.len()];
2408 let n = source.read_at(pos, &mut buf).ok()?;
2409 if n >= pattern.len() && &buf == pattern {
2410 match_len = pattern.len();
2411 let s = std::str::from_utf8(pattern).ok()?;
2412 if let Ok(val) = u64::from_str_radix(s.trim(), 8) {
2413 format_val = FormatValue::U64(val);
2414 } else {
2415 format_val = FormatValue::Str(s.to_string());
2416 }
2417 true
2418 } else {
2419 false
2420 }
2421 }
2422 }
2423 MagicTest::OffsetVal => {
2424 match_len = 0;
2425 format_val = FormatValue::U64(pos);
2426 true
2427 }
2428 MagicTest::Default => {
2429 match_len = 0;
2430 true
2431 }
2432 MagicTest::Clear => {
2433 match_len = 0;
2434 true
2435 }
2436 MagicTest::Search {
2437 pattern,
2438 max_bytes,
2439 flags,
2440 negated,
2441 } => {
2442 if (flags.text_only && !is_text_source(source))
2443 || (flags.binary_only && is_text_source(source))
2444 {
2445 false
2446 } else {
2447 let slice_buf = bounded_source_read(source, pos, *max_bytes)?;
2448 let slice = slice_buf.as_slice();
2449 {
2450 if pattern.is_empty() {
2451 !negated
2452 } else {
2453 let match_pos = if flags.full_word {
2454 if flags.case_insensitive {
2455 let pat_lower = pattern.to_ascii_lowercase();
2456 let slice_lower = slice.to_ascii_lowercase();
2457 slice_lower.windows(pat_lower.len()).enumerate().find_map(|(idx, w)| {
2458 if w == pat_lower.as_slice() {
2459 let before_ok = if idx > 0 {
2460 // Reason for fallback: invalid index defaults to valid boundary
2461 slice.get(idx.saturating_sub(1)).is_none_or(|&b| !b.is_ascii_alphanumeric() && b != b'_')
2462 } else {
2463 true
2464 };
2465 let after_idx = idx.saturating_add(pattern.len());
2466 // Reason for fallback: invalid index defaults to valid boundary
2467 let after_ok = slice.get(after_idx).is_none_or(|&b| !b.is_ascii_alphanumeric() && b != b'_');
2468 if before_ok && after_ok {
2469 Some(idx)
2470 } else {
2471 None
2472 }
2473 } else {
2474 None
2475 }
2476 })
2477 } else {
2478 slice.windows(pattern.len()).enumerate().find_map(|(idx, w)| {
2479 if w == pattern.as_slice() {
2480 let before_ok = if idx > 0 {
2481 // Reason for fallback: invalid index defaults to valid boundary
2482 slice.get(idx.saturating_sub(1)).is_none_or(|&b| !b.is_ascii_alphanumeric() && b != b'_')
2483 } else {
2484 true
2485 };
2486 let after_idx = idx.saturating_add(pattern.len());
2487 // Reason for fallback: invalid index defaults to valid boundary
2488 let after_ok = slice.get(after_idx).is_none_or(|&b| !b.is_ascii_alphanumeric() && b != b'_');
2489 if before_ok && after_ok {
2490 Some(idx)
2491 } else {
2492 None
2493 }
2494 } else {
2495 None
2496 }
2497 })
2498 }
2499 } else if flags.case_insensitive {
2500 let pat_lower = pattern.to_ascii_lowercase();
2501 let slice_lower = slice.to_ascii_lowercase();
2502 slice_lower
2503 .windows(pat_lower.len())
2504 .position(|w| w == pat_lower.as_slice())
2505 } else {
2506 slice
2507 .windows(pattern.len())
2508 .position(|w| w == pattern.as_slice())
2509 };
2510
2511 if let Some(found_idx) = match_pos {
2512 if *negated {
2513 false
2514 } else {
2515 match_len =
2516 found_idx.saturating_add(pattern.len());
2517 if let Some(sub) = slice.get(
2518 found_idx
2519 ..found_idx
2520 .saturating_add(pattern.len()),
2521 ) {
2522 format_val = FormatValue::Str(
2523 String::from_utf8_lossy(sub)
2524 .to_string(),
2525 );
2526 }
2527 true
2528 }
2529 } else {
2530 *negated
2531 }
2532 }
2533 }
2534 }
2535 }
2536 MagicTest::Der(pattern) => {
2537 let slice = bounded_source_read(source, pos, 8192)?;
2538 if let Some(res) = crate::der::match_der(pattern, &slice) {
2539 match_len = res.header_len;
2540 der_match_info = Some((res.header_len, res.payload_len));
2541 format_val = FormatValue::Str(res.formatted_val);
2542 true
2543 } else {
2544 false
2545 }
2546 }
2547 MagicTest::Use(template_name) => {
2548 if let Some(tpl) = templates.get(template_name) {
2549 // Reason for fallback: template without top-level description defaults to empty description string
2550 let mut sub_desc = tpl
2551 .description
2552 .as_deref()
2553 .map(|d| varexpand(d, mode))
2554 .unwrap_or_default();
2555 let mut sub_mime =
2556 tpl.mime.as_deref().map(|m| varexpand(m, mode));
2557 let mut sub_ext = tpl.ext.clone();
2558 let mut sub_apple = tpl.apple.clone();
2559 let mut sub_score = tpl.strength;
2560 let mut sub_end = pos;
2561 let mut sub_sibling = pos;
2562 let mut sub_nospace = sub_desc.starts_with('\u{8}');
2563
2564 let mut matched_any_in_sub = false;
2565 let mut last_cond_matched = false;
2566 for child in &tpl.children {
2567 if child.test == MagicTest::Clear {
2568 matched_any_in_sub = false;
2569 last_cond_matched = false;
2570 }
2571 if child.test == MagicTest::Default && matched_any_in_sub {
2572 continue;
2573 }
2574 match child.cond {
2575 MagicCond::Elif | MagicCond::Else => {
2576 if last_cond_matched {
2577 continue;
2578 }
2579 }
2580 MagicCond::If | MagicCond::None => {}
2581 }
2582 if let Some(cm) = evaluate_rule_internal(
2583 child,
2584 source,
2585 pos,
2586 sub_sibling,
2587 templates,
2588 depth.saturating_add(1),
2589 mode,
2590 ) {
2591 matched_any_in_sub = true;
2592 if child.cond != MagicCond::None {
2593 last_cond_matched = true;
2594 }
2595 sub_end = sub_end.max(cm.match_end);
2596 if matches!(child.test, MagicTest::Der(_)) {
2597 sub_sibling = cm.next_sibling_offset;
2598 }
2599 if !cm.description.is_empty() {
2600 if cm.nospace || cm.description.starts_with('\u{8}')
2601 {
2602 let stripped =
2603 cm.description.trim_start_matches('\u{8}');
2604 if sub_desc.ends_with(' ') {
2605 sub_desc.pop();
2606 }
2607 if sub_desc.is_empty() {
2608 sub_nospace = true;
2609 }
2610 sub_desc.push_str(stripped);
2611 } else {
2612 if !sub_desc.is_empty()
2613 && !sub_desc.ends_with(' ')
2614 {
2615 let starts_with_punct =
2616 cm.description.starts_with(',')
2617 || cm.description.starts_with(';')
2618 || cm.description.starts_with(':');
2619 if !starts_with_punct {
2620 sub_desc.push(' ');
2621 }
2622 }
2623 sub_desc.push_str(&cm.description);
2624 }
2625 }
2626 if cm.mime.is_some() {
2627 sub_mime = cm.mime;
2628 }
2629 if cm.ext.is_some() {
2630 sub_ext = cm.ext;
2631 }
2632 if cm.apple.is_some() {
2633 sub_apple = cm.apple;
2634 }
2635 sub_score = sub_score.saturating_add(15).max(cm.score);
2636 } else if child.cond == MagicCond::If
2637 || child.cond == MagicCond::Elif
2638 {
2639 last_cond_matched = false;
2640 }
2641 }
2642 let has_output = !sub_desc.is_empty()
2643 || sub_mime.is_some()
2644 || sub_ext.is_some()
2645 || sub_apple.is_some();
2646 let tpl_has_desc = tpl.description.is_some()
2647 || tpl.children.iter().any(rule_tree_has_desc);
2648 if matched_any_in_sub && (has_output || !tpl_has_desc) {
2649 use_subroutine_result = Some(RuleMatchResult {
2650 description: sub_desc,
2651 mime: sub_mime,
2652 ext: sub_ext,
2653 apple: sub_apple,
2654 score: sub_score,
2655 match_end: sub_end,
2656 next_sibling_offset: sub_sibling,
2657 nospace: sub_nospace,
2658 });
2659 true
2660 } else {
2661 false
2662 }
2663 } else {
2664 false
2665 }
2666 }
2667 MagicTest::Name(_) => false,
2668 MagicTest::Indirect => {
2669 let mut best_match: Option<RuleMatchResult> = None;
2670 for r in super::magic_data::COMPILED_MAGIC_RULES.iter() {
2671 if let Some(res) = evaluate_rule_internal(
2672 r,
2673 source,
2674 pos,
2675 pos,
2676 templates,
2677 depth.saturating_add(1),
2678 mode,
2679 ) {
2680 if let Some(ref current_best) = best_match {
2681 if res.score > current_best.score {
2682 best_match = Some(res);
2683 }
2684 } else {
2685 best_match = Some(res);
2686 }
2687 }
2688 }
2689 if let Some(bm) = best_match {
2690 let mut full_desc = String::new();
2691 if let Some(raw) = &rule.description {
2692 full_desc.push_str(&varexpand(raw, mode));
2693 }
2694 if !bm.description.is_empty() {
2695 if !full_desc.is_empty() && !full_desc.ends_with(' ') {
2696 let starts_with_punct = bm.description.starts_with(',')
2697 || bm.description.starts_with(';')
2698 || bm.description.starts_with(':');
2699 if !starts_with_punct {
2700 full_desc.push(' ');
2701 }
2702 }
2703 full_desc.push_str(&bm.description);
2704 }
2705 use_subroutine_result = Some(RuleMatchResult {
2706 description: full_desc,
2707 mime: bm.mime.or_else(|| {
2708 rule.mime.as_deref().map(|m| varexpand(m, mode))
2709 }),
2710 ext: bm.ext.or_else(|| rule.ext.clone()),
2711 apple: bm.apple.or_else(|| rule.apple.clone()),
2712 score: rule.strength.saturating_add(bm.score),
2713 match_end: bm.match_end,
2714 next_sibling_offset: bm.next_sibling_offset,
2715 nospace: false,
2716 });
2717 true
2718 } else {
2719 false
2720 }
2721 }
2722 };
2723
2724 if !matched {
2725 return None;
2726 }
2727
2728 let (
2729 mut description,
2730 mut mime,
2731 mut ext,
2732 mut apple,
2733 mut score,
2734 this_match_end,
2735 mut nospace,
2736 mut overall_match_end,
2737 this_sibling_end,
2738 ) = if let Some(sub_res) = use_subroutine_result {
2739 (
2740 sub_res.description,
2741 sub_res.mime,
2742 sub_res.ext,
2743 sub_res.apple,
2744 sub_res.score,
2745 pos,
2746 sub_res.nospace,
2747 sub_res.match_end,
2748 sub_res.next_sibling_offset,
2749 )
2750 } else {
2751 let desc = if let Some(raw) = &rule.description {
2752 let formatted = format_magic_description(raw, &format_val);
2753 varexpand(&formatted, mode)
2754 } else {
2755 String::new()
2756 };
2757 // Reason for fallback: match_len exceeding u64 limit defaults to 0 offset addition
2758 let m_end = pos.saturating_add(u64::try_from(match_len).unwrap_or(0));
2759 let sib_end = if let Some((hdr, pay)) = der_match_info {
2760 let offset_delta = match u64::try_from(hdr.saturating_add(pay)) {
2761 Ok(total) => total,
2762 Err(_) => 0,
2763 };
2764 pos.saturating_add(offset_delta)
2765 } else {
2766 m_end
2767 };
2768 let starts_with_bs = desc.starts_with('\u{8}');
2769 let expanded_mime = rule.mime.as_deref().map(|m| varexpand(m, mode));
2770 (
2771 desc,
2772 expanded_mime,
2773 rule.ext.clone(),
2774 rule.apple.clone(),
2775 rule.strength,
2776 m_end,
2777 starts_with_bs,
2778 m_end,
2779 sib_end,
2780 )
2781 };
2782 let mut matched_any_in_level = false;
2783 let mut last_cond_matched = false;
2784
2785 // Recursively evaluate children to specialize description and boost score
2786 let mut current_child_offset = this_match_end;
2787 for child in &rule.children {
2788 if child.test == MagicTest::Clear {
2789 matched_any_in_level = false;
2790 last_cond_matched = false;
2791 }
2792 if child.test == MagicTest::Default && matched_any_in_level {
2793 continue;
2794 }
2795 match child.cond {
2796 MagicCond::Elif | MagicCond::Else => {
2797 if last_cond_matched {
2798 continue;
2799 }
2800 }
2801 MagicCond::If | MagicCond::None => {}
2802 }
2803 if let Some(child_match) = evaluate_rule_internal(
2804 child,
2805 source,
2806 base_offset,
2807 current_child_offset,
2808 templates,
2809 depth.saturating_add(1),
2810 mode,
2811 ) {
2812 matched_any_in_level = true;
2813 if child.cond != MagicCond::None {
2814 last_cond_matched = true;
2815 }
2816 overall_match_end = overall_match_end.max(child_match.match_end);
2817 if matches!(child.test, MagicTest::Der(_)) {
2818 current_child_offset = child_match.next_sibling_offset;
2819 }
2820 if !child_match.description.is_empty() {
2821 if child_match.nospace
2822 || child_match.description.starts_with('\u{8}')
2823 {
2824 let stripped =
2825 child_match.description.trim_start_matches('\u{8}');
2826 if description.ends_with(' ') {
2827 description.pop();
2828 }
2829 if description.is_empty() {
2830 nospace = true;
2831 }
2832 description.push_str(stripped);
2833 } else {
2834 if !description.is_empty() && !description.ends_with(' ') {
2835 let starts_with_punct =
2836 child_match.description.starts_with(',')
2837 || child_match.description.starts_with(';')
2838 || child_match.description.starts_with(':');
2839 if !starts_with_punct {
2840 description.push(' ');
2841 }
2842 }
2843 description.push_str(&child_match.description);
2844 }
2845 }
2846 if child_match.mime.is_some() {
2847 mime = child_match.mime;
2848 }
2849 if child_match.ext.is_some() {
2850 ext = child_match.ext;
2851 }
2852 if child_match.apple.is_some() {
2853 apple = child_match.apple;
2854 }
2855 if child.test == MagicTest::Indirect {
2856 score = score.saturating_add(child_match.score);
2857 } else {
2858 score = score.saturating_add(15).max(child_match.score);
2859 }
2860 } else if child.cond == MagicCond::If || child.cond == MagicCond::Elif {
2861 last_cond_matched = false;
2862 }
2863 }
2864
2865 if rule.cont_level == 0
2866 && description.trim().is_empty()
2867 && mime.is_none()
2868 && ext.is_none()
2869 && apple.is_none()
2870 {
2871 return None;
2872 }
2873
2874 Some(RuleMatchResult {
2875 description,
2876 mime,
2877 ext,
2878 apple,
2879 score,
2880 match_end: overall_match_end,
2881 next_sibling_offset: this_sibling_end,
2882 nospace,
2883 })
2884}
2885
2886/// Evaluates a hierarchical magic rule against a payload source using provided subroutines and file mode.
2887pub fn evaluate_rule_with_templates_and_mode<S: DetectionSource + ?Sized>(
2888 rule: &HierarchicalMagicRule,
2889 source: &mut S,
2890 templates: &HashMap<String, HierarchicalMagicRule>,
2891 mode: u32,
2892) -> Option<RuleMatchResult> {
2893 evaluate_rule_internal(rule, source, 0, 0, templates, 0, mode)
2894}
2895
2896/// Evaluates a hierarchical magic rule against a payload source using provided subroutines.
2897pub fn evaluate_rule_with_templates<S: DetectionSource + ?Sized>(
2898 rule: &HierarchicalMagicRule,
2899 source: &mut S,
2900 templates: &HashMap<String, HierarchicalMagicRule>,
2901) -> Option<RuleMatchResult> {
2902 evaluate_rule_with_templates_and_mode(rule, source, templates, 0)
2903}
2904
2905/// Evaluates a single `HierarchicalMagicRule` and its child tree against a `DetectionSource` with file mode.
2906pub fn evaluate_rule_with_mode<S: DetectionSource + ?Sized>(
2907 rule: &HierarchicalMagicRule,
2908 source: &mut S,
2909 mode: u32,
2910) -> Option<RuleMatchResult> {
2911 evaluate_rule_with_templates_and_mode(
2912 rule,
2913 source,
2914 &super::magic_data::COMPILED_MAGIC_TEMPLATES,
2915 mode,
2916 )
2917}
2918
2919/// Evaluates a single `HierarchicalMagicRule` and its child tree against a `DetectionSource`.
2920pub fn evaluate_rule<S: DetectionSource + ?Sized>(
2921 rule: &HierarchicalMagicRule,
2922 source: &mut S,
2923) -> Option<RuleMatchResult> {
2924 evaluate_rule_with_mode(rule, source, 0)
2925}
2926
2927/// A signature rule defining magic bytes to inspect in a file header (legacy compatibility).
2928#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2929pub struct MagicPattern {
2930 /// Byte offset where signature starts in file header (typically 0).
2931 pub offset: usize,
2932 /// Byte pattern expected at offset.
2933 pub bytes: &'static [u8],
2934 /// Optional byte mask (same length as bytes).
2935 pub mask: Option<&'static [u8]>,
2936 /// Confidence or priority score when pattern matches (default: 100).
2937 pub priority: u32,
2938}
2939
2940impl MagicPattern {
2941 /// Constructs an exact byte sequence magic pattern at offset 0.
2942 pub const fn exact(bytes: &'static [u8]) -> Self {
2943 Self {
2944 offset: 0,
2945 bytes,
2946 mask: None,
2947 priority: 100,
2948 }
2949 }
2950
2951 /// Constructs an exact byte sequence magic pattern at a specific offset and priority.
2952 pub const fn exact_at(
2953 offset: usize,
2954 bytes: &'static [u8],
2955 priority: u32,
2956 ) -> Self {
2957 Self {
2958 offset,
2959 bytes,
2960 mask: None,
2961 priority,
2962 }
2963 }
2964
2965 /// Constructs a masked byte magic pattern at offset 0.
2966 pub const fn masked(
2967 bytes: &'static [u8],
2968 mask: &'static [u8],
2969 priority: u32,
2970 ) -> Self {
2971 Self {
2972 offset: 0,
2973 bytes,
2974 mask: Some(mask),
2975 priority,
2976 }
2977 }
2978
2979 /// Checks if a byte slice matches this magic pattern.
2980 pub fn matches(&self, data: &[u8]) -> bool {
2981 let end = self.offset.saturating_add(self.bytes.len());
2982 if data.len() < end {
2983 return false;
2984 }
2985 let slice = match data.get(self.offset..end) {
2986 Some(s) => s,
2987 None => return false,
2988 };
2989
2990 match self.mask {
2991 Some(mask) => {
2992 if mask.len() != self.bytes.len() {
2993 return false;
2994 }
2995 for ((&byte, &m), &expected) in
2996 slice.iter().zip(mask).zip(self.bytes)
2997 {
2998 if (byte & m) != expected {
2999 return false;
3000 }
3001 }
3002 true
3003 }
3004 None => slice == self.bytes,
3005 }
3006 }
3007}
3008
3009#[cfg(test)]
3010#[allow(
3011 clippy::panic,
3012 clippy::expect_used,
3013 clippy::unwrap_used,
3014 clippy::unwrap_in_result,
3015 clippy::panic_in_result_fn,
3016 clippy::indexing_slicing,
3017 clippy::arithmetic_side_effects,
3018 reason = "Standard repository test boilerplate"
3019)]
3020mod tests {
3021 use super::super::magic_parser::parse_magic_content;
3022 use super::*;
3023
3024 #[ctb_test]
3025 fn test_magic_pattern_matching() {
3026 let gzip_magic = MagicPattern::exact(&[0x1F, 0x8B]);
3027 assert!(gzip_magic.matches(&[0x1F, 0x8B, 0x08, 0x00]));
3028 assert!(!gzip_magic.matches(&[0x1F, 0xA0, 0x08, 0x00]));
3029
3030 let lzw_block_magic =
3031 MagicPattern::masked(&[0x1F, 0x9D, 0x80], &[0xFF, 0xFF, 0x80], 110);
3032 assert!(lzw_block_magic.matches(&[0x1F, 0x9D, 0x90]));
3033 assert!(!lzw_block_magic.matches(&[0x1F, 0x9D, 0x10]));
3034 }
3035
3036 #[ctb_test]
3037 fn test_hierarchical_evaluation() {
3038 let content = r"
30390 belong 0x00051600 AppleSingle encoded Macintosh file
3040!:mime application/x-apple-single
3041!:ext as
3042>4 belong 0x00020000 \b, version 2.0
3043>4 belong 0x00010000 \b, version 1.0
3044";
3045 let rules = parse_magic_content(content);
3046 assert_eq!(rules.len(), 1);
3047
3048 let apple_single_v2 = [
3049 0x00, 0x05, 0x16, 0x00, // Magic
3050 0x00, 0x02, 0x00, 0x00, // Version 2.0
3051 0x00, 0x00, 0x00, 0x00,
3052 ];
3053
3054 let mut slice: &[u8] = &apple_single_v2;
3055 let result = evaluate_rule(&rules[0], &mut slice).unwrap();
3056 assert_eq!(result.mime, Some("application/x-apple-single".to_string()));
3057 assert_eq!(result.ext, Some("as".to_string()));
3058 assert!(result.description.contains("version 2.0"));
3059 assert!(result.score > 50);
3060 }
3061
3062 #[ctb_test]
3063 fn test_relative_offset_evaluation() {
3064 let content = r"
30650 string \x1f\x8b gzip
3066>&0 byte 8 \b, deflated
3067>>&0 byte x \b, flags %02x
3068";
3069 let rules = parse_magic_content(content);
3070 let sample = [0x1f, 0x8b, 0x08, 0x04];
3071 let mut slice: &[u8] = &sample;
3072 let res = evaluate_rule(&rules[0], &mut slice).unwrap();
3073 assert!(res.description.contains("gzip, deflated, flags 04"));
3074 }
3075
3076 #[ctb_test]
3077 fn test_indirect_offset_evaluation() {
3078 let content = r"
30790 string MZ DOS executable
3080>(0x10.l) string PE\0\0 \b, PE header
3081";
3082 let rules = parse_magic_content(content);
3083 let mut file_data = vec![0u8; 64];
3084 file_data[0] = b'M';
3085 file_data[1] = b'Z';
3086 // Put pointer at 0x10 pointing to 0x20
3087 file_data[0x10] = 0x20;
3088 file_data[0x20] = b'P';
3089 file_data[0x21] = b'E';
3090 file_data[0x22] = 0;
3091 file_data[0x23] = 0;
3092
3093 let mut slice: &[u8] = &file_data;
3094 let res = evaluate_rule(&rules[0], &mut slice).unwrap();
3095 assert!(res.description.contains("DOS executable, PE header"));
3096 }
3097
3098 #[ctb_test]
3099 fn test_formatted_descriptions_and_dates() {
3100 let content = r"
31010 lequad 0x0102030405060708 Header %016llx
3102>8 ledate x \b, created %s
3103";
3104 let rules = parse_magic_content(content);
3105 let mut data = vec![0u8; 16];
3106 data[0..8].copy_from_slice(&0x0102030405060708u64.to_le_bytes());
3107 // 1609459200 = 2021-01-01 00:00:00 UTC
3108 data[8..12].copy_from_slice(&1609459200u32.to_le_bytes());
3109
3110 let mut slice: &[u8] = &data;
3111 let res = evaluate_rule(&rules[0], &mut slice).unwrap();
3112 assert!(res.description.contains("0102030405060708"));
3113 assert!(
3114 res.description.contains("Jan") && res.description.contains("2021")
3115 );
3116 }
3117
3118 #[ctb_test]
3119 fn test_negative_date_stamps() {
3120 let content = r"
31210 string HIST Historical record
3122>4 ledate x \b, date %s
3123";
3124 let rules = parse_magic_content(content);
3125 let mut data = vec![0u8; 16];
3126 data[0..4].copy_from_slice(b"HIST");
3127 // -86400 = 1969-12-31 00:00:00 UTC
3128 data[4..8].copy_from_slice(&(-86400i32).to_le_bytes());
3129
3130 let mut slice: &[u8] = &data;
3131 let res = evaluate_rule(&rules[0], &mut slice).unwrap();
3132 assert!(res.description.contains("Historical record"));
3133 assert!(
3134 res.description.contains("Dec") && res.description.contains("1969")
3135 );
3136 }
3137
3138 #[ctb_test]
3139 fn test_subroutine_use_evaluation() {
3140 let content = r"
31410 name common-arch
3142>4 byte 1 \b, 32-bit
3143>4 byte 2 \b, 64-bit
3144
31450 string \177ELF ELF
3146>0 use common-arch
3147";
3148 let (rules, templates) =
3149 super::super::magic_parser::parse_magic_content_with_templates(
3150 content,
3151 );
3152 let sample = [0x7f, b'E', b'L', b'F', 0x02];
3153 let mut slice: &[u8] = &sample;
3154 let res =
3155 evaluate_rule_with_templates(&rules[0], &mut slice, &templates)
3156 .unwrap();
3157 assert_eq!(res.description, "ELF, 64-bit");
3158 }
3159
3160 #[ctb_test]
3161 fn test_regex_matching() {
3162 let content = r"
31630 regex/c/128 ^<!doctype\s+html HTML document
3164";
3165 let rules = parse_magic_content(content);
3166 let sample = b"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">";
3167 let mut slice: &[u8] = &sample[..];
3168 let res = evaluate_rule(&rules[0], &mut slice).unwrap();
3169 assert_eq!(res.description, "HTML document");
3170 }
3171
3172 #[ctb_test]
3173 fn test_pascal_string_matching() {
3174 let content = r"
31750 pstring/B Hello Pascal Greeting
3176";
3177 let rules = parse_magic_content(content);
3178 let sample = [5, b'H', b'e', b'l', b'l', b'o', b'!'];
3179 let mut slice: &[u8] = &sample;
3180 let res = evaluate_rule(&rules[0], &mut slice).unwrap();
3181 assert_eq!(res.description, "Pascal Greeting");
3182 }
3183
3184 #[ctb_test]
3185 fn test_evaluate_indirect_multiplier_and_synchsafe() {
3186 let content = r"
31870 string TEST Test
3188>(4.l*2+2) string HIT \b, multiplier hit
3189>(12.I+2) string TAG \b, synchsafe hit
3190";
3191 let rules = parse_magic_content(content);
3192 let mut synch_sample = vec![0u8; 150];
3193 synch_sample[0..4].copy_from_slice(b"TEST");
3194 synch_sample[4..8].copy_from_slice(&10u32.to_le_bytes()); // mult: 10*2+2 = 22
3195 synch_sample[22..25].copy_from_slice(b"HIT");
3196 // At offset 12: ID3 synchsafe bytes: [0, 0, 0, 0x1A] -> 26. 26 + 2 = 28.
3197 synch_sample[12..16].copy_from_slice(&[0x00, 0x00, 0x00, 0x1A]);
3198 synch_sample[28..31].copy_from_slice(b"TAG");
3199
3200 let mut slice: &[u8] = &synch_sample;
3201 let res = evaluate_rule(&rules[0], &mut slice).unwrap();
3202 assert!(res.description.contains("multiplier hit"));
3203 assert!(res.description.contains("synchsafe hit"));
3204 }
3205
3206 #[ctb_test]
3207 fn test_evaluate_search_negation() {
3208 let content_pass = r"
32090 string TEST Test
3210>0 search/64 !FORBIDDEN \b, cleanly negated
3211";
3212 let rules_pass = parse_magic_content(content_pass);
3213 let sample = b"TEST This is a clean test without forbidden word";
3214 let mut slice: &[u8] = sample;
3215 let res = evaluate_rule(&rules_pass[0], &mut slice).unwrap();
3216 assert!(res.description.contains("cleanly negated"));
3217
3218 let sample_fail = b"TEST This has FORBIDDEN keyword inside";
3219 let mut slice_fail: &[u8] = sample_fail;
3220 let res_fail = evaluate_rule(&rules_pass[0], &mut slice_fail).unwrap();
3221 assert!(!res_fail.description.contains("cleanly negated"));
3222 }
3223
3224 #[ctb_test]
3225 fn test_evaluate_recursive_indirect_magic() {
3226 let content = r"
32270 string WRAP Wrapper
3228>4 indirect x \b:
3229";
3230 let rules = parse_magic_content(content);
3231 let mut sample = vec![0u8; 32];
3232 sample[0..4].copy_from_slice(b"WRAP");
3233 sample[4..8].copy_from_slice(&[0x1F, 0x8B, 0x08, 0x00]);
3234 let mut slice: &[u8] = &sample;
3235 let res = evaluate_rule(&rules[0], &mut slice).unwrap();
3236 assert!(res.description.contains("Wrapper"));
3237 assert!(res.description.contains("gzip compressed data"));
3238 }
3239
3240 #[ctb_test]
3241 fn test_evaluate_der_rules() {
3242 let content = r"
32430 der seq
3244>&0 der int1=00
3245>&0 der int3=010001 DER Encoded Key Pair, 512 bits
3246";
3247 let rules = parse_magic_content(content);
3248 // Sequence (tag 0x30, len 8) containing:
3249 // - INTEGER (tag 0x02, len 1, val 0x00)
3250 // - INTEGER (tag 0x02, len 3, val 0x01, 0x00, 0x01)
3251 let sample =
3252 [0x30, 0x08, 0x02, 0x01, 0x00, 0x02, 0x03, 0x01, 0x00, 0x01];
3253 let mut slice: &[u8] = &sample;
3254 let res = evaluate_rule(&rules[0], &mut slice).unwrap();
3255 assert!(res.description.contains("DER Encoded Key Pair, 512 bits"));
3256 }
3257
3258 #[ctb_test]
3259 fn test_evaluate_der_hierarchical_certificate_info() {
3260 let content = r"
32610 name certinfo
3262>0 der seq
3263>>&0 der set
3264>>>&0 der seq
3265>>>>&0 der obj_id3=550406
3266>>>>&0 der prt_str=x \b, countryName=%s
3267
32680 der seq
3269>&0 der seq
3270>>&0 der int1=00 DER Encoded Certificate request
3271>>&0 use certinfo
3272";
3273 let (rules, tpls) =
3274 crate::magic_parser::parse_magic_content_with_templates(content);
3275 // Outer SEQUENCE (0x30, len 20)
3276 // -> Inner SEQUENCE (0x30, len 18)
3277 // -> INTEGER (0x02, len 1, val 0x00) (3 bytes)
3278 // -> SEQUENCE (0x30, len 13) (certinfo)
3279 // -> SET (0x31, len 11)
3280 // -> SEQUENCE (0x30, len 9)
3281 // -> OID (0x06, len 3, val 55 04 06) (5 bytes)
3282 // -> PRINTABLE_STRING (0x13, len 2, val "US") (4 bytes)
3283 let sample = [
3284 0x30, 0x14, // Outer seq
3285 0x30, 0x12, // Inner seq
3286 0x02, 0x01, 0x00, // int1=00
3287 0x30, 0x0D, // seq (start of certinfo)
3288 0x31, 0x0B, // set
3289 0x30, 0x09, // seq
3290 0x06, 0x03, 0x55, 0x04, 0x06, // obj_id3=550406
3291 0x13, 0x02, b'U', b'S', // prt_str="US"
3292 ];
3293 let mut slice: &[u8] = &sample;
3294 let res =
3295 evaluate_rule_with_templates(&rules[0], &mut slice, &tpls).unwrap();
3296 assert!(res.description.contains("DER Encoded Certificate request"));
3297 assert!(res.description.contains("countryName=US"));
3298 }
3299
3300 #[ctb_test]
3301 fn test_evaluate_float_and_double() {
3302 let content = r"
33030 lefloat >10.0 lefloat: %f
3304>4 befloat !0.0 \b, befloat: %g
3305>8 ledouble 2.75 \b, ledouble: %.2f
3306>16 bedouble x \b, bedouble: %g
3307";
3308 let rules = parse_magic_content(content);
3309 assert_eq!(rules.len(), 1);
3310
3311 let mut buf = Vec::new();
3312 // lefloat 12.5f32
3313 buf.extend_from_slice(&12.5f32.to_le_bytes());
3314 // befloat -2.5f32
3315 buf.extend_from_slice(&(-2.5f32).to_be_bytes());
3316 // ledouble 2.75f64
3317 buf.extend_from_slice(&2.75f64.to_le_bytes());
3318 // bedouble 123.456f64
3319 buf.extend_from_slice(&123.456f64.to_be_bytes());
3320
3321 let mut slice: &[u8] = &buf;
3322 let res = evaluate_rule(&rules[0], &mut slice).unwrap();
3323 assert!(res.description.contains("lefloat: 12.5"));
3324 assert!(res.description.contains("befloat: -2.5"));
3325 assert!(res.description.contains("ledouble: 2.75"));
3326 assert!(res.description.contains("bedouble: 123.456"));
3327 }
3328
3329 #[ctb_test]
3330 fn test_evaluate_string16() {
3331 let content = r"
33320 lestring16 Workbook Excel Workbook
3333>16 lestring16 x \b, title: %.10s
3334";
3335 let rules = parse_magic_content(content);
3336 assert_eq!(rules.len(), 1);
3337
3338 let mut buf = Vec::new();
3339 // "Workbook" in UTF-16LE (16 bytes)
3340 for b in b"Workbook" {
3341 buf.push(*b);
3342 buf.push(0x00);
3343 }
3344 // "Quarterly Report" in UTF-16LE followed by null terminator
3345 for b in b"Quarterly Report" {
3346 buf.push(*b);
3347 buf.push(0x00);
3348 }
3349 buf.push(0x00);
3350 buf.push(0x00);
3351
3352 let mut slice: &[u8] = &buf;
3353 let res = evaluate_rule(&rules[0], &mut slice).unwrap();
3354 assert!(res.description.contains("Excel Workbook"));
3355 // %.10s trims to 10 characters "Quarterly "
3356 assert!(res.description.contains("title: Quarterly "));
3357 }
3358
3359 #[ctb_test]
3360 fn test_evaluate_varints() {
3361 let content = r"
33620 levarint 300 LEB128 val: %u
3363";
3364 let rules = parse_magic_content(content);
3365 assert_eq!(rules.len(), 1);
3366
3367 // 300 in LEB128: 300 = 0x12C = 0b00000010_0101100.
3368 // Byte 0: 0x2C | 0x80 = 0xAC.
3369 // Byte 1: 0x02.
3370 let buf = [0xAC, 0x02];
3371 let mut slice: &[u8] = &buf;
3372 let res = evaluate_rule(&rules[0], &mut slice).unwrap();
3373 assert!(res.description.contains("LEB128 val: 300"));
3374
3375 // 300 in 7-bit big-endian:
3376 // Byte 0: 0x02 | 0x80 = 0x82.
3377 // Byte 1: 0x2C.
3378 // 300 & 0xFF = 44.
3379 let be_rules =
3380 parse_magic_content("0\tbevarint&0xFF\t44\tBE varint val: %u\n");
3381 let be_buf = [0x82, 0x2C];
3382 let mut be_slice: &[u8] = &be_buf;
3383 let be_res = evaluate_rule(&be_rules[0], &mut be_slice).unwrap();
3384 assert!(be_res.description.contains("BE varint val: 44"));
3385 }
3386
3387 #[ctb_test]
3388 fn test_evaluate_qwdate() {
3389 // Windows FILETIME 133801824000000000 = Jan 1 2025
3390 let raw_filetime: u64 = 133801824000000000;
3391 let content = "0\tleqwdate\tx\tCreated %s\n";
3392 let rules = parse_magic_content(content);
3393
3394 let buf = raw_filetime.to_le_bytes();
3395 let mut slice: &[u8] = &buf;
3396 let res = evaluate_rule(&rules[0], &mut slice).unwrap();
3397 assert!(res.description.contains("Created "));
3398 assert!(res.description.contains("2025"));
3399 }
3400
3401 #[ctb_test]
3402 fn test_evaluate_octal() {
3403 let content = r"
34040 octal 0755 Permissions: %s
3405>4 octal x \b, other: %s
3406";
3407 let rules = parse_magic_content(content);
3408 assert_eq!(rules.len(), 1);
3409
3410 let buf = b"07550644";
3411 let mut slice: &[u8] = &buf[..];
3412 let res = evaluate_rule(&rules[0], &mut slice).unwrap();
3413 // 0755 octal = 493 decimal
3414 assert!(res.description.contains("Permissions: 493"));
3415 // 0644 octal = 420 decimal
3416 assert!(res.description.contains("other: 420"));
3417 }
3418
3419 #[ctb_test]
3420 fn test_evaluate_guid_le_and_be() {
3421 let content = r"
34220 guid 7B5C52E4-D88C-4DA7-AEB1-5378D02996D3 OneNote document
3423>0 leguid x \b, GUID: %s
3424>16 beguid 00112233-4455-6677-8899-AABBCCDDEEFF \b, UUID %s
3425";
3426 let rules = parse_magic_content(content);
3427 assert_eq!(rules.len(), 1);
3428
3429 let mut buf = Vec::new();
3430 // Microsoft mixed-endian GUID for 7B5C52E4-D88C-4DA7-AEB1-5378D02996D3:
3431 // d1: 0x7B5C52E4 (LE: E4 52 5C 7B)
3432 // d2: 0xD88C (LE: 8C D8)
3433 // d3: 0x4DA7 (LE: A7 4D)
3434 // d4: AE B1 53 78 D0 29 96 D3
3435 buf.extend_from_slice(&[
3436 0xE4, 0x52, 0x5C, 0x7B, 0x8C, 0xD8, 0xA7, 0x4D, 0xAE, 0xB1, 0x53,
3437 0x78, 0xD0, 0x29, 0x96, 0xD3,
3438 ]);
3439 // RFC 4122 Big-endian UUID 00112233-4455-6677-8899-AABBCCDDEEFF:
3440 buf.extend_from_slice(&[
3441 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA,
3442 0xBB, 0xCC, 0xDD, 0xEE, 0xFF,
3443 ]);
3444
3445 let mut slice: &[u8] = &buf;
3446 let res = evaluate_rule(&rules[0], &mut slice).unwrap();
3447 assert!(res.description.contains("OneNote document"));
3448 assert!(
3449 res.description
3450 .contains("GUID: 7B5C52E4-D88C-4DA7-AEB1-5378D02996D3")
3451 );
3452 assert!(
3453 res.description
3454 .contains("UUID 00112233-4455-6677-8899-AABBCCDDEEFF")
3455 );
3456 }
3457
3458 #[ctb_test]
3459 fn test_indirect_offset_arithmetic_and_bitwise() {
3460 let content = r"
34610 string TEST Header
3462>(4.s*2) leshort 0x1234 \b, mul target
3463>(8.s&0xFF) leshort 0x5678 \b, and target
3464>(12,s) leshort 0x9abc \b, signed target
3465";
3466 let rules = parse_magic_content(content);
3467 let mut data = vec![0u8; 64];
3468 data[0..4].copy_from_slice(b"TEST");
3469 // offset 4: short pointer = 8 -> multiplied by 2 = 16.
3470 data[4..6].copy_from_slice(&8u16.to_le_bytes());
3471 data[16..18].copy_from_slice(&0x1234u16.to_le_bytes());
3472
3473 // offset 8: short pointer = 0x0114 -> & 0xFF = 0x14 (20).
3474 data[8..10].copy_from_slice(&0x0114u16.to_le_bytes());
3475 data[20..22].copy_from_slice(&0x5678u16.to_le_bytes());
3476
3477 // offset 12: signed short pointer = 24.
3478 data[12..14].copy_from_slice(&24i16.to_le_bytes());
3479 data[24..26].copy_from_slice(&0x9abcu16.to_le_bytes());
3480
3481 let mut slice: &[u8] = &data;
3482 let res = evaluate_rule(&rules[0], &mut slice).unwrap();
3483 assert!(res.description.contains("mul target"));
3484 assert!(res.description.contains("and target"));
3485 assert!(res.description.contains("signed target"));
3486 }
3487
3488 #[ctb_test]
3489 fn test_conditional_branching_evaluation() {
3490 let content = r"
34910 string TEST Header
3492>4 if byte 1 \b, branch 1
3493>4 elif byte 2 \b, branch 2
3494>4 else byte x \b, fallback
3495>0 clear x
3496>5 byte 9 \b, post-clear
3497";
3498 let rules = parse_magic_content(content);
3499
3500 // Case 1: byte at 4 is 1 -> branch 1 matches, elif and else skipped.
3501 let mut data1 = vec![0u8; 16];
3502 data1[0..4].copy_from_slice(b"TEST");
3503 data1[4] = 1;
3504 data1[5] = 9;
3505 let mut slice1: &[u8] = &data1;
3506 let res1 = evaluate_rule(&rules[0], &mut slice1).unwrap();
3507 assert!(res1.description.contains("branch 1"));
3508 assert!(!res1.description.contains("branch 2"));
3509 assert!(!res1.description.contains("fallback"));
3510 assert!(res1.description.contains("post-clear"));
3511
3512 // Case 2: byte at 4 is 2 -> elif matches.
3513 let mut data2 = vec![0u8; 16];
3514 data2[0..4].copy_from_slice(b"TEST");
3515 data2[4] = 2;
3516 data2[5] = 9;
3517 let mut slice2: &[u8] = &data2;
3518 let res2 = evaluate_rule(&rules[0], &mut slice2).unwrap();
3519 assert!(!res2.description.contains("branch 1"));
3520 assert!(res2.description.contains("branch 2"));
3521 assert!(!res2.description.contains("fallback"));
3522 assert!(res2.description.contains("post-clear"));
3523
3524 // Case 3: byte at 4 is 3 -> else matches.
3525 let mut data3 = vec![0u8; 16];
3526 data3[0..4].copy_from_slice(b"TEST");
3527 data3[4] = 3;
3528 data3[5] = 9;
3529 let mut slice3: &[u8] = &data3;
3530 let res3 = evaluate_rule(&rules[0], &mut slice3).unwrap();
3531 assert!(!res3.description.contains("branch 1"));
3532 assert!(!res3.description.contains("branch 2"));
3533 assert!(res3.description.contains("fallback"));
3534 assert!(res3.description.contains("post-clear"));
3535 }
3536
3537 #[ctb_test]
3538 fn test_string_modifiers_evaluation() {
3539 let content = r"
35400 string/w hello\ world Spaced Header
3541>20 string/f test \b, word bounded
3542>30 string/t textfile \b, text only
3543>40 string/b binfile \b, binary only
3544";
3545 let rules = parse_magic_content(content);
3546
3547 // Text data matching /w ("hello world") and /f ("test" surrounded by spaces)
3548 let mut text_data = vec![b' '; 64];
3549 text_data[0..13].copy_from_slice(b"hello world");
3550 text_data[20..24].copy_from_slice(b"test");
3551 text_data[30..38].copy_from_slice(b"textfile");
3552 text_data[40..47].copy_from_slice(b"binfile");
3553
3554 let mut slice: &[u8] = &text_data;
3555 let res = evaluate_rule(&rules[0], &mut slice).unwrap();
3556 assert!(res.description.contains("Spaced Header"));
3557 assert!(res.description.contains("word bounded"));
3558 assert!(res.description.contains("text only"));
3559 // string/b should NOT match text source
3560 assert!(!res.description.contains("binary only"));
3561
3562 // Negative test for /f: if "test" is followed by alphanumeric e.g. "testing"
3563 let mut non_boundary = text_data.clone();
3564 non_boundary[24] = b's'; // "tests"
3565 let mut slice_nb: &[u8] = &non_boundary;
3566 let res_nb = evaluate_rule(&rules[0], &mut slice_nb).unwrap();
3567 assert!(!res_nb.description.contains("word bounded"));
3568 }
3569
3570 #[ctb_test]
3571 fn test_regex_line_limit_evaluation() {
3572 let content = r"
35730 string HEAD Regex Header
3574>4 regex/1l TARGET \b, line 1 found
3575>4 regex/2l SECOND \b, line 2 found
3576";
3577 let rules = parse_magic_content(content);
3578
3579 let data = b"HEAD LINE1\nSECOND\nTARGET\n";
3580 let mut slice: &[u8] = data;
3581 let res = evaluate_rule(&rules[0], &mut slice).unwrap();
3582 // TARGET is on line 3 from offset 4, so regex/1l should not find TARGET
3583 assert!(!res.description.contains("line 1 found"));
3584 // SECOND is on line 2 from offset 4, so regex/2l matches SECOND
3585 assert!(res.description.contains("line 2 found"));
3586 }
3587}
3588/*
3589/*
3590 * Adapted from: apptype.c, Written by Eberhard Mattes and put into the
3591 * file_public domain
3592 *
3593 * Notes: 1. Qualify the filename so that DosQueryAppType does not do extraneous
3594 * searches.
3595 *
3596 * 2. DosQueryAppType will return FAPPTYP_DOS on a file ending with ".com"
3597 * (other than an OS/2 exe or Win exe with this name). Eberhard Mattes
3598 * remarks Tue, 6 Apr 93: Moreover, it reports the type of the (new and very
3599 * bug ridden) Win Emacs as "OS/2 executable".
3600 *
3601 * 3. apptype() uses the filename if given, otherwise a tmp file is created with
3602 * the contents of buf. If buf is not the complete file, apptype can
3603 * incorrectly identify the exe type. The "-z" option of "file" is the reason
3604 * for this ugly code.
3605 */
3606
3607The preceding notice is from src/apptype.c in `file`.
3608
3609
3610
3611/*-
3612 * Copyright (c) 2008 Christos Zoulas
3613 * All rights reserved.
3614 *
3615 * Redistribution and use in source and binary forms, with or without
3616 * modification, are permitted provided that the following conditions
3617 * are met:
3618 * 1. Redistributions of source code must retain the above copyright
3619 * notice, this list of conditions and the following disclaimer.
3620 * 2. Redistributions in binary form must reproduce the above copyright
3621 * notice, this list of conditions and the following disclaimer in the
3622 * documentation and/or other materials provided with the distribution.
3623 *
3624 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
3625 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
3626 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
3627 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
3628 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
3629 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
3630 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
3631 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
3632 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
3633 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
3634 * POSSIBILITY OF SUCH DAMAGE.
3635 */
3636
3637The preceding notice is from src/cdf.c, src/cdf.h, and src/cdf_time.c in `file`.
3638
3639
3640
3641/*-
3642 * Copyright (c) 2016 Christos Zoulas
3643 * All rights reserved.
3644 *
3645 * Redistribution and use in source and binary forms, with or without
3646 * modification, are permitted provided that the following conditions
3647 * are met:
3648 * 1. Redistributions of source code must retain the above copyright
3649 * notice, this list of conditions and the following disclaimer.
3650 * 2. Redistributions in binary form must reproduce the above copyright
3651 * notice, this list of conditions and the following disclaimer in the
3652 * documentation and/or other materials provided with the distribution.
3653 *
3654 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
3655 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
3656 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
3657 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
3658 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
3659 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
3660 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
3661 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
3662 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
3663 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
3664 * POSSIBILITY OF SUCH DAMAGE.
3665 */
3666
3667The preceding notice is from src/der.c and src/der.h in `file`.
3668
3669
3670
3671/*-
3672 * Copyright (c) 2019 Christos Zoulas
3673 * All rights reserved.
3674 *
3675 * Redistribution and use in source and binary forms, with or without
3676 * modification, are permitted provided that the following conditions
3677 * are met:
3678 * 1. Redistributions of source code must retain the above copyright
3679 * notice, this list of conditions and the following disclaimer.
3680 * 2. Redistributions in binary form must reproduce the above copyright
3681 * notice, this list of conditions and the following disclaimer in the
3682 * documentation and/or other materials provided with the distribution.
3683 *
3684 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
3685 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
3686 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
3687 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
3688 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
3689 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
3690 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
3691 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
3692 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
3693 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
3694 * POSSIBILITY OF SUCH DAMAGE.
3695 */
3696
3697The preceding notice is from src/is_csv.c in `file`.
3698
3699
3700
3701/*-
3702 * Copyright (c) 2018 Christos Zoulas
3703 * All rights reserved.
3704 *
3705 * Redistribution and use in source and binary forms, with or without
3706 * modification, are permitted provided that the following conditions
3707 * are met:
3708 * 1. Redistributions of source code must retain the above copyright
3709 * notice, this list of conditions and the following disclaimer.
3710 * 2. Redistributions in binary form must reproduce the above copyright
3711 * notice, this list of conditions and the following disclaimer in the
3712 * documentation and/or other materials provided with the distribution.
3713 *
3714 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
3715 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
3716 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
3717 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
3718 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
3719 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
3720 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
3721 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
3722 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
3723 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
3724 * POSSIBILITY OF SUCH DAMAGE.
3725 */
3726
3727The preceding notice is from src/is_json.c in `file`.
3728
3729
3730
3731/*-
3732 * Copyright (c) 2023 Christos Zoulas
3733 * All rights reserved.
3734 *
3735 * Redistribution and use in source and binary forms, with or without
3736 * modification, are permitted provided that the following conditions
3737 * are met:
3738 * 1. Redistributions of source code must retain the above copyright
3739 * notice, this list of conditions and the following disclaimer.
3740 * 2. Redistributions in binary form must reproduce the above copyright
3741 * notice, this list of conditions and the following disclaimer in the
3742 * documentation and/or other materials provided with the distribution.
3743 *
3744 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
3745 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
3746 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
3747 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
3748 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
3749 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
3750 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
3751 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
3752 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
3753 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
3754 * POSSIBILITY OF SUCH DAMAGE.
3755 */
3756
3757The preceding notice is from src/is_simh.c in `file`.
3758
3759
3760
3761/*-
3762 * SPDX-License-Identifier: BSD-3-Clause
3763 *
3764 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
3765 * Copyright (c) 1992, 1993, 1994
3766 * The Regents of the University of California. All rights reserved.
3767 *
3768 * This code is derived from software contributed to Berkeley by
3769 * Henry Spencer.
3770 *
3771 * Redistribution and use in source and binary forms, with or without
3772 * modification, are permitted provided that the following conditions
3773 * are met:
3774 * 1. Redistributions of source code must retain the above copyright
3775 * notice, this list of conditions and the following disclaimer.
3776 * 2. Redistributions in binary form must reproduce the above copyright
3777 * notice, this list of conditions and the following disclaimer in the
3778 * documentation and/or other materials provided with the distribution.
3779 * 3. Neither the name of the University nor the names of its contributors
3780 * may be used to endorse or promote products derived from this software
3781 * without specific prior written permission.
3782 *
3783 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3784 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3785 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3786 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3787 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3788 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3789 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3790 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3791 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3792 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3793 * SUCH DAMAGE.
3794 *
3795 * @(#)cname.h 8.3 (Berkeley) 3/20/94
3796 * $FreeBSD: head/lib/libc/regex/cname.h 326025 2017-11-20 19:49:47Z pfg $
3797 */
3798
3799The preceding notice is from src/missing/cname.h in `file`.
3800
3801
3802
3803/*-
3804 * SPDX-License-Identifier: BSD-3-Clause
3805 *
3806 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
3807 * Copyright (c) 1992, 1993, 1994
3808 * The Regents of the University of California. All rights reserved.
3809 *
3810 * This code is derived from software contributed to Berkeley by
3811 * Henry Spencer.
3812 *
3813 * Redistribution and use in source and binary forms, with or without
3814 * modification, are permitted provided that the following conditions
3815 * are met:
3816 * 1. Redistributions of source code must retain the above copyright
3817 * notice, this list of conditions and the following disclaimer.
3818 * 2. Redistributions in binary form must reproduce the above copyright
3819 * notice, this list of conditions and the following disclaimer in the
3820 * documentation and/or other materials provided with the distribution.
3821 * 3. Neither the name of the University nor the names of its contributors
3822 * may be used to endorse or promote products derived from this software
3823 * without specific prior written permission.
3824 *
3825 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3826 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3827 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3828 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3829 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3830 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3831 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3832 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3833 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3834 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3835 * SUCH DAMAGE.
3836 *
3837 * @(#)engine.c 8.5 (Berkeley) 3/20/94
3838 */
3839
3840The preceding notice is from src/missing/engine.c in `file`.
3841
3842
3843
3844/*-
3845 * Copyright (c) 2000 The NetBSD Foundation, Inc.
3846 * All rights reserved.
3847 *
3848 * This code was contributed to The NetBSD Foundation by Allen Briggs.
3849 *
3850 * Redistribution and use in source and binary forms, with or without
3851 * modification, are permitted provided that the following conditions
3852 * are met:
3853 * 1. Redistributions of source code must retain the above copyright
3854 * notice, this list of conditions and the following disclaimer.
3855 * 2. Redistributions in binary form must reproduce the above copyright
3856 * notice, this list of conditions and the following disclaimer in the
3857 * documentation and/or other materials provided with the distribution.
3858 *
3859 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
3860 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
3861 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
3862 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
3863 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
3864 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
3865 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
3866 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
3867 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
3868 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
3869 * POSSIBILITY OF SUCH DAMAGE.
3870 */
3871
3872The preceding notice is from src/missing/fmtcheck.c in `file`.
3873
3874
3875
3876/*-
3877 * Copyright (c) 2011 The NetBSD Foundation, Inc.
3878 * All rights reserved.
3879 *
3880 * This code is derived from software contributed to The NetBSD Foundation
3881 * by Christos Zoulas.
3882 *
3883 * Redistribution and use in source and binary forms, with or without
3884 * modification, are permitted provided that the following conditions
3885 * are met:
3886 * 1. Redistributions of source code must retain the above copyright
3887 * notice, this list of conditions and the following disclaimer.
3888 * 2. Redistributions in binary form must reproduce the above copyright
3889 * notice, this list of conditions and the following disclaimer in the
3890 * documentation and/or other materials provided with the distribution.
3891 *
3892 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
3893 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
3894 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
3895 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
3896 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
3897 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
3898 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
3899 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
3900 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
3901 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
3902 * POSSIBILITY OF SUCH DAMAGE.
3903 */
3904
3905The preceding notice is from src/missing/getline.c in `file`.
3906
3907
3908
3909/*-
3910 * Copyright (c) 2000 The NetBSD Foundation, Inc.
3911 * All rights reserved.
3912 *
3913 * This code is derived from software contributed to The NetBSD Foundation
3914 * by Dieter Baron and Thomas Klausner.
3915 *
3916 * Redistribution and use in source and binary forms, with or without
3917 * modification, are permitted provided that the following conditions
3918 * are met:
3919 * 1. Redistributions of source code must retain the above copyright
3920 * notice, this list of conditions and the following disclaimer.
3921 * 2. Redistributions in binary form must reproduce the above copyright
3922 * notice, this list of conditions and the following disclaimer in the
3923 * documentation and/or other materials provided with the distribution.
3924 *
3925 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
3926 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
3927 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
3928 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
3929 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
3930 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
3931 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
3932 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
3933 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
3934 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
3935 * POSSIBILITY OF SUCH DAMAGE.
3936 */
3937
3938The preceding notice is from src/missing/getopt_long.c and src/mygetopt.h in `file`.
3939
3940
3941
3942/*
3943 * Public domain fallback for reallocarray(3), for platforms (e.g.
3944 * AmigaOS/libnix) whose C library declares it but does not implement it.
3945 */
3946
3947The preceding notice is from src/missing/reallocarray.c in `file`.
3948
3949
3950
3951/*-
3952 * SPDX-License-Identifier: BSD-3-Clause
3953 *
3954 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
3955 * Copyright (c) 1992, 1993, 1994
3956 * The Regents of the University of California. All rights reserved.
3957 *
3958 * Copyright (c) 2011 The FreeBSD Foundation
3959 * All rights reserved.
3960 * Portions of this software were developed by David Chisnall
3961 * under sponsorship from the FreeBSD Foundation.
3962 *
3963 * This code is derived from software contributed to Berkeley by
3964 * Henry Spencer.
3965 *
3966 * Redistribution and use in source and binary forms, with or without
3967 * modification, are permitted provided that the following conditions
3968 * are met:
3969 * 1. Redistributions of source code must retain the above copyright
3970 * notice, this list of conditions and the following disclaimer.
3971 * 2. Redistributions in binary form must reproduce the above copyright
3972 * notice, this list of conditions and the following disclaimer in the
3973 * documentation and/or other materials provided with the distribution.
3974 * 3. Neither the name of the University nor the names of its contributors
3975 * may be used to endorse or promote products derived from this software
3976 * without specific prior written permission.
3977 *
3978 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3979 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3980 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3981 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3982 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3983 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3984 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3985 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3986 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3987 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3988 * SUCH DAMAGE.
3989 *
3990 * @(#)regcomp.c 8.5 (Berkeley) 3/20/94
3991 */
3992
3993The preceding notice is from src/missing/regcomp.c in `file`.
3994
3995
3996
3997/*-
3998 * SPDX-License-Identifier: BSD-3-Clause
3999 *
4000 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
4001 * Copyright (c) 1992, 1993, 1994
4002 * The Regents of the University of California. All rights reserved.
4003 *
4004 * This code is derived from software contributed to Berkeley by
4005 * Henry Spencer.
4006 *
4007 * Redistribution and use in source and binary forms, with or without
4008 * modification, are permitted provided that the following conditions
4009 * are met:
4010 * 1. Redistributions of source code must retain the above copyright
4011 * notice, this list of conditions and the following disclaimer.
4012 * 2. Redistributions in binary form must reproduce the above copyright
4013 * notice, this list of conditions and the following disclaimer in the
4014 * documentation and/or other materials provided with the distribution.
4015 * 3. Neither the name of the University nor the names of its contributors
4016 * may be used to endorse or promote products derived from this software
4017 * without specific prior written permission.
4018 *
4019 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
4020 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
4021 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
4022 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
4023 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
4024 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
4025 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
4026 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
4027 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
4028 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
4029 * SUCH DAMAGE.
4030 *
4031 * @(#)regerror.c 8.4 (Berkeley) 3/20/94
4032 */
4033
4034The preceding notice is from src/missing/regerror.c in `file`.
4035
4036
4037
4038$NetBSD: COPYRIGHT,v 1.5 2003/08/07 16:43:19 agc Exp $
4039
4040Copyright 1992, 1993, 1994 Henry Spencer. All rights reserved.
4041This software is not subject to any license of the American Telephone
4042and Telegraph Company or of the Regents of the University of California.
4043
4044Permission is granted to anyone to use this software for any purpose on
4045any computer system, and to alter it and redistribute it, subject
4046to the following restrictions:
4047
40481. The author is not responsible for the consequences of use of this
4049 software, no matter how awful, even if they arise from flaws in it.
4050
40512. The origin of this software must not be misrepresented, either by
4052 explicit claim or by omission. Since few users ever read sources,
4053 credits must appear in the documentation.
4054
40553. Altered versions must be plainly marked as such, and must not be
4056 misrepresented as being the original software. Since few users
4057 ever read sources, credits must appear in the documentation.
4058
40594. This notice may not be removed or altered.
4060
4061=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
4062/*-
4063 * Copyright (c) 1994
4064 * The Regents of the University of California. All rights reserved.
4065 *
4066 * Redistribution and use in source and binary forms, with or without
4067 * modification, are permitted provided that the following conditions
4068 * are met:
4069 * 1. Redistributions of source code must retain the above copyright
4070 * notice, this list of conditions and the following disclaimer.
4071 * 2. Redistributions in binary form must reproduce the above copyright
4072 * notice, this list of conditions and the following disclaimer in the
4073 * documentation and/or other materials provided with the distribution.
4074 * 3. Neither the name of the University nor the names of its contributors
4075 * may be used to endorse or promote products derived from this software
4076 * without specific prior written permission.
4077 *
4078 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
4079 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
4080 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
4081 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
4082 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
4083 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
4084 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
4085 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
4086 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
4087 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
4088 * SUCH DAMAGE.
4089 *
4090 * @(#)COPYRIGHT 8.1 (Berkeley) 3/16/94
4091 */
4092
4093The preceding notice is from src/missing/REGEX-COPYRIGHT in `file`.
4094
4095
4096
4097/*-
4098 * SPDX-License-Identifier: BSD-3-Clause
4099 *
4100 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
4101 * Copyright (c) 1992, 1993, 1994
4102 * The Regents of the University of California. All rights reserved.
4103 *
4104 * This code is derived from software contributed to Berkeley by
4105 * Henry Spencer.
4106 *
4107 * Redistribution and use in source and binary forms, with or without
4108 * modification, are permitted provided that the following conditions
4109 * are met:
4110 * 1. Redistributions of source code must retain the above copyright
4111 * notice, this list of conditions and the following disclaimer.
4112 * 2. Redistributions in binary form must reproduce the above copyright
4113 * notice, this list of conditions and the following disclaimer in the
4114 * documentation and/or other materials provided with the distribution.
4115 * 3. Neither the name of the University nor the names of its contributors
4116 * may be used to endorse or promote products derived from this software
4117 * without specific prior written permission.
4118 *
4119 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
4120 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
4121 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
4122 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
4123 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
4124 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
4125 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
4126 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
4127 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
4128 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
4129 * SUCH DAMAGE.
4130 *
4131 * @(#)regex2.h 8.4 (Berkeley) 3/20/94
4132 * $FreeBSD: head/lib/libc/regex/regex2.h 368359 2020-12-05 03:18:48Z kevans $
4133 */
4134
4135The preceding notice is from src/missing/regex2.h in `file`.
4136
4137
4138
4139/*-
4140 * SPDX-License-Identifier: BSD-3-Clause
4141 *
4142 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
4143 * Copyright (c) 1992, 1993, 1994
4144 * The Regents of the University of California. All rights reserved.
4145 *
4146 * This code is derived from software contributed to Berkeley by
4147 * Henry Spencer.
4148 *
4149 * Redistribution and use in source and binary forms, with or without
4150 * modification, are permitted provided that the following conditions
4151 * are met:
4152 * 1. Redistributions of source code must retain the above copyright
4153 * notice, this list of conditions and the following disclaimer.
4154 * 2. Redistributions in binary form must reproduce the above copyright
4155 * notice, this list of conditions and the following disclaimer in the
4156 * documentation and/or other materials provided with the distribution.
4157 * 3. Neither the name of the University nor the names of its contributors
4158 * may be used to endorse or promote products derived from this software
4159 * without specific prior written permission.
4160 *
4161 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
4162 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
4163 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
4164 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
4165 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
4166 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
4167 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
4168 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
4169 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
4170 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
4171 * SUCH DAMAGE.
4172 *
4173 * @(#)regexec.c 8.3 (Berkeley) 3/20/94
4174 */
4175
4176The preceding notice is from src/missing/regexec.c in `file`.
4177
4178
4179
4180/*-
4181 * SPDX-License-Identifier: BSD-3-Clause
4182 *
4183 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
4184 * Copyright (c) 1992, 1993, 1994
4185 * The Regents of the University of California. All rights reserved.
4186 *
4187 * This code is derived from software contributed to Berkeley by
4188 * Henry Spencer.
4189 *
4190 * Redistribution and use in source and binary forms, with or without
4191 * modification, are permitted provided that the following conditions
4192 * are met:
4193 * 1. Redistributions of source code must retain the above copyright
4194 * notice, this list of conditions and the following disclaimer.
4195 * 2. Redistributions in binary form must reproduce the above copyright
4196 * notice, this list of conditions and the following disclaimer in the
4197 * documentation and/or other materials provided with the distribution.
4198 * 3. Neither the name of the University nor the names of its contributors
4199 * may be used to endorse or promote products derived from this software
4200 * without specific prior written permission.
4201 *
4202 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
4203 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
4204 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
4205 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
4206 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
4207 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
4208 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
4209 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
4210 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
4211 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
4212 * SUCH DAMAGE.
4213 *
4214 * @(#)regfree.c 8.3 (Berkeley) 3/20/94
4215 */
4216
4217The preceding notice is from src/missing/regfree.c in `file`.
4218
4219
4220
4221/*-
4222 * Copyright (c) 1990, 1993
4223 * The Regents of the University of California. All rights reserved.
4224 *
4225 * This code is derived from software contributed to Berkeley by
4226 * Chris Torek.
4227 *
4228 * Redistribution and use in source and binary forms, with or without
4229 * modification, are permitted provided that the following conditions
4230 * are met:
4231 * 1. Redistributions of source code must retain the above copyright
4232 * notice, this list of conditions and the following disclaimer.
4233 * 2. Redistributions in binary form must reproduce the above copyright
4234 * notice, this list of conditions and the following disclaimer in the
4235 * documentation and/or other materials provided with the distribution.
4236 * 3. Neither the name of the University nor the names of its contributors
4237 * may be used to endorse or promote products derived from this software
4238 * without specific prior written permission.
4239 *
4240 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
4241 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
4242 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
4243 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
4244 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
4245 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
4246 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
4247 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
4248 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
4249 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
4250 * SUCH DAMAGE.
4251 */
4252
4253The preceding notice is from src/missing/strcasestr.c in `file`.
4254
4255
4256
4257/*
4258 * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
4259 *
4260 * Permission to use, copy, modify, and distribute this software for any
4261 * purpose with or without fee is hereby granted, provided that the above
4262 * copyright notice and this permission notice appear in all copies.
4263 *
4264 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
4265 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
4266 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
4267 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
4268 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
4269 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
4270 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
4271 */
4272
4273The preceding notice is from src/missing/strlcat.c and src/missing/strlcpy.c in `file`.
4274
4275
4276
4277/*-
4278 * SPDX-License-Identifier: BSD-3-Clause
4279 *
4280 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
4281 * Copyright (c) 1992, 1993, 1994
4282 * The Regents of the University of California. All rights reserved.
4283 *
4284 * This code is derived from software contributed to Berkeley by
4285 * Henry Spencer.
4286 *
4287 * Redistribution and use in source and binary forms, with or without
4288 * modification, are permitted provided that the following conditions
4289 * are met:
4290 * 1. Redistributions of source code must retain the above copyright
4291 * notice, this list of conditions and the following disclaimer.
4292 * 2. Redistributions in binary form must reproduce the above copyright
4293 * notice, this list of conditions and the following disclaimer in the
4294 * documentation and/or other materials provided with the distribution.
4295 * 3. Neither the name of the University nor the names of its contributors
4296 * may be used to endorse or promote products derived from this software
4297 * without specific prior written permission.
4298 *
4299 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
4300 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
4301 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
4302 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
4303 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
4304 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
4305 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
4306 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
4307 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
4308 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
4309 * SUCH DAMAGE.
4310 *
4311 * @(#)utils.h 8.3 (Berkeley) 3/20/94
4312 * $FreeBSD: head/lib/libc/regex/utils.h 341838 2018-12-12 04:23:00Z yuripv $
4313 */
4314
4315The preceding notice is from src/missing/utils.h in `file`.
4316
4317
4318
4319/*-
4320 * Copyright (c) 2008, 2016 Christos Zoulas
4321 * All rights reserved.
4322 *
4323 * Redistribution and use in source and binary forms, with or without
4324 * modification, are permitted provided that the following conditions
4325 * are met:
4326 * 1. Redistributions of source code must retain the above copyright
4327 * notice, this list of conditions and the following disclaimer.
4328 * 2. Redistributions in binary form must reproduce the above copyright
4329 * notice, this list of conditions and the following disclaimer in the
4330 * documentation and/or other materials provided with the distribution.
4331 *
4332 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
4333 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
4334 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
4335 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
4336 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
4337 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
4338 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
4339 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
4340 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
4341 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
4342 * POSSIBILITY OF SUCH DAMAGE.
4343 */
4344
4345The preceding notice is from src/readcdf.c in `file`.
4346
4347
4348
4349/*-
4350 * Copyright (c) 1992 Henry Spencer.
4351 * Copyright (c) 1992, 1993
4352 * The Regents of the University of California. All rights reserved.
4353 *
4354 * This code is derived from software contributed to Berkeley by
4355 * Henry Spencer of the University of Toronto.
4356 *
4357 * Redistribution and use in source and binary forms, with or without
4358 * modification, are permitted provided that the following conditions
4359 * are met:
4360 * 1. Redistributions of source code must retain the above copyright
4361 * notice, this list of conditions and the following disclaimer.
4362 * 2. Redistributions in binary form must reproduce the above copyright
4363 * notice, this list of conditions and the following disclaimer in the
4364 * documentation and/or other materials provided with the distribution.
4365 * 3. Neither the name of the University nor the names of its contributors
4366 * may be used to endorse or promote products derived from this software
4367 * without specific prior written permission.
4368 *
4369 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
4370 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
4371 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
4372 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
4373 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
4374 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
4375 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
4376 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
4377 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
4378 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
4379 * SUCH DAMAGE.
4380 *
4381 * @(#)regex.h 8.2 (Berkeley) 1/3/94
4382 * $FreeBSD: src/include/regex.h,v 1.12 2010/02/16 19:39:50 imp Exp $
4383 */
4384
4385The preceding notice is from src/regex-bsd.h in `file`.
4386*/
4387/*
4388
4389Text of LICENSE from DROID:
4390
4391Copyright (c) 2016, The National Archives <pronom@nationalarchives.gov.uk>
4392All rights reserved.
4393
4394Redistribution and use in source and binary forms, with or without
4395modification, are permitted provided that the following
4396conditions are met:
4397
4398 * Redistributions of source code must retain the above copyright
4399 notice, this list of conditions and the following disclaimer.
4400
4401 * Redistributions in binary form must reproduce the above copyright
4402 notice, this list of conditions and the following disclaimer in the
4403 documentation and/or other materials provided with the distribution.
4404
4405 * Neither the name of the The National Archives nor the
4406 names of its contributors may be used to endorse or promote products
4407 derived from this software without specific prior written permission.
4408
4409THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
4410AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
4411IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
4412PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
4413CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
4414EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
4415PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
4416PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
4417LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
4418NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
4419SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
4420*/
4421
4422/*
4423
4424Text of LICENSE from fileid:
4425
4426The MIT License (MIT)
4427
4428Copyright (c) 2015 David B Heise
4429
4430Permission is hereby granted, free of charge, to any person obtaining a copy of
4431this software and associated documentation files (the "Software"), to deal in
4432the Software without restriction, including without limitation the rights to
4433use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
4434the Software, and to permit persons to whom the Software is furnished to do so,
4435subject to the following conditions:
4436
4437The above copyright notice and this permission notice shall be included in all
4438copies or substantial portions of the Software.
4439
4440THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
4441IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
4442FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
4443COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
4444IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
4445CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
4446
4447
4448*/
4449
4450/*
4451Text of LICENSE from binwalk:
4452
4453
4454MIT License
4455
4456Copyright (c) 2024 devttys0
4457
4458Permission is hereby granted, free of charge, to any person obtaining a copy
4459of this software and associated documentation files (the "Software"), to deal
4460in the Software without restriction, including without limitation the rights
4461to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
4462copies of the Software, and to permit persons to whom the Software is
4463furnished to do so, subject to the following conditions:
4464
4465The above copyright notice and this permission notice shall be included in all
4466copies or substantial portions of the Software.
4467
4468THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
4469IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
4470FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
4471AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
4472LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
4473OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
4474SOFTWARE.
4475
4476*/
4477
4478/*
4479Text of LICENSE from polyfile:
4480
4481
4482 Apache License
4483 Version 2.0, January 2004
4484 http://www.apache.org/licenses/
4485
4486 TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
4487
4488 1. Definitions.
4489
4490 "License" shall mean the terms and conditions for use, reproduction,
4491 and distribution as defined by Sections 1 through 9 of this document.
4492
4493 "Licensor" shall mean the copyright owner or entity authorized by
4494 the copyright owner that is granting the License.
4495
4496 "Legal Entity" shall mean the union of the acting entity and all
4497 other entities that control, are controlled by, or are under common
4498 control with that entity. For the purposes of this definition,
4499 "control" means (i) the power, direct or indirect, to cause the
4500 direction or management of such entity, whether by contract or
4501 otherwise, or (ii) ownership of fifty percent (50%) or more of the
4502 outstanding shares, or (iii) beneficial ownership of such entity.
4503
4504 "You" (or "Your") shall mean an individual or Legal Entity
4505 exercising permissions granted by this License.
4506
4507 "Source" form shall mean the preferred form for making modifications,
4508 including but not limited to software source code, documentation
4509 source, and configuration files.
4510
4511 "Object" form shall mean any form resulting from mechanical
4512 transformation or translation of a Source form, including but
4513 not limited to compiled object code, generated documentation,
4514 and conversions to other media types.
4515
4516 "Work" shall mean the work of authorship, whether in Source or
4517 Object form, made available under the License, as indicated by a
4518 copyright notice that is included in or attached to the work
4519 (an example is provided in the Appendix below).
4520
4521 "Derivative Works" shall mean any work, whether in Source or Object
4522 form, that is based on (or derived from) the Work and for which the
4523 editorial revisions, annotations, elaborations, or other modifications
4524 represent, as a whole, an original work of authorship. For the purposes
4525 of this License, Derivative Works shall not include works that remain
4526 separable from, or merely link (or bind by name) to the interfaces of,
4527 the Work and Derivative Works thereof.
4528
4529 "Contribution" shall mean any work of authorship, including
4530 the original version of the Work and any modifications or additions
4531 to that Work or Derivative Works thereof, that is intentionally
4532 submitted to Licensor for inclusion in the Work by the copyright owner
4533 or by an individual or Legal Entity authorized to submit on behalf of
4534 the copyright owner. For the purposes of this definition, "submitted"
4535 means any form of electronic, verbal, or written communication sent
4536 to the Licensor or its representatives, including but not limited to
4537 communication on electronic mailing lists, source code control systems,
4538 and issue tracking systems that are managed by, or on behalf of, the
4539 Licensor for the purpose of discussing and improving the Work, but
4540 excluding communication that is conspicuously marked or otherwise
4541 designated in writing by the copyright owner as "Not a Contribution."
4542
4543 "Contributor" shall mean Licensor and any individual or Legal Entity
4544 on behalf of whom a Contribution has been received by Licensor and
4545 subsequently incorporated within the Work.
4546
4547 2. Grant of Copyright License. Subject to the terms and conditions of
4548 this License, each Contributor hereby grants to You a perpetual,
4549 worldwide, non-exclusive, no-charge, royalty-free, irrevocable
4550 copyright license to reproduce, prepare Derivative Works of,
4551 publicly display, publicly perform, sublicense, and distribute the
4552 Work and such Derivative Works in Source or Object form.
4553
4554 3. Grant of Patent License. Subject to the terms and conditions of
4555 this License, each Contributor hereby grants to You a perpetual,
4556 worldwide, non-exclusive, no-charge, royalty-free, irrevocable
4557 (except as stated in this section) patent license to make, have made,
4558 use, offer to sell, sell, import, and otherwise transfer the Work,
4559 where such license applies only to those patent claims licensable
4560 by such Contributor that are necessarily infringed by their
4561 Contribution(s) alone or by combination of their Contribution(s)
4562 with the Work to which such Contribution(s) was submitted. If You
4563 institute patent litigation against any entity (including a
4564 cross-claim or counterclaim in a lawsuit) alleging that the Work
4565 or a Contribution incorporated within the Work constitutes direct
4566 or contributory patent infringement, then any patent licenses
4567 granted to You under this License for that Work shall terminate
4568 as of the date such litigation is filed.
4569
4570 4. Redistribution. You may reproduce and distribute copies of the
4571 Work or Derivative Works thereof in any medium, with or without
4572 modifications, and in Source or Object form, provided that You
4573 meet the following conditions:
4574
4575 (a) You must give any other recipients of the Work or
4576 Derivative Works a copy of this License; and
4577
4578 (b) You must cause any modified files to carry prominent notices
4579 stating that You changed the files; and
4580
4581 (c) You must retain, in the Source form of any Derivative Works
4582 that You distribute, all copyright, patent, trademark, and
4583 attribution notices from the Source form of the Work,
4584 excluding those notices that do not pertain to any part of
4585 the Derivative Works; and
4586
4587 (d) If the Work includes a "NOTICE" text file as part of its
4588 distribution, then any Derivative Works that You distribute must
4589 include a readable copy of the attribution notices contained
4590 within such NOTICE file, excluding those notices that do not
4591 pertain to any part of the Derivative Works, in at least one
4592 of the following places: within a NOTICE text file distributed
4593 as part of the Derivative Works; within the Source form or
4594 documentation, if provided along with the Derivative Works; or,
4595 within a display generated by the Derivative Works, if and
4596 wherever such third-party notices normally appear. The contents
4597 of the NOTICE file are for informational purposes only and
4598 do not modify the License. You may add Your own attribution
4599 notices within Derivative Works that You distribute, alongside
4600 or as an addendum to the NOTICE text from the Work, provided
4601 that such additional attribution notices cannot be construed
4602 as modifying the License.
4603
4604 You may add Your own copyright statement to Your modifications and
4605 may provide additional or different license terms and conditions
4606 for use, reproduction, or distribution of Your modifications, or
4607 for any such Derivative Works as a whole, provided Your use,
4608 reproduction, and distribution of the Work otherwise complies with
4609 the conditions stated in this License.
4610
4611 5. Submission of Contributions. Unless You explicitly state otherwise,
4612 any Contribution intentionally submitted for inclusion in the Work
4613 by You to the Licensor shall be under the terms and conditions of
4614 this License, without any additional terms or conditions.
4615 Notwithstanding the above, nothing herein shall supersede or modify
4616 the terms of any separate license agreement you may have executed
4617 with Licensor regarding such Contributions.
4618
4619 6. Trademarks. This License does not grant permission to use the trade
4620 names, trademarks, service marks, or product names of the Licensor,
4621 except as required for reasonable and customary use in describing the
4622 origin of the Work and reproducing the content of the NOTICE file.
4623
4624 7. Disclaimer of Warranty. Unless required by applicable law or
4625 agreed to in writing, Licensor provides the Work (and each
4626 Contributor provides its Contributions) on an "AS IS" BASIS,
4627 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
4628 implied, including, without limitation, any warranties or conditions
4629 of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
4630 PARTICULAR PURPOSE. You are solely responsible for determining the
4631 appropriateness of using or redistributing the Work and assume any
4632 risks associated with Your exercise of permissions under this License.
4633
4634 8. Limitation of Liability. In no event and under no legal theory,
4635 whether in tort (including negligence), contract, or otherwise,
4636 unless required by applicable law (such as deliberate and grossly
4637 negligent acts) or agreed to in writing, shall any Contributor be
4638 liable to You for damages, including any direct, indirect, special,
4639 incidental, or consequential damages of any character arising as a
4640 result of this License or out of the use or inability to use the
4641 Work (including but not limited to damages for loss of goodwill,
4642 work stoppage, computer failure or malfunction, or any and all
4643 other commercial damages or losses), even if such Contributor
4644 has been advised of the possibility of such damages.
4645
4646 9. Accepting Warranty or Additional Liability. While redistributing
4647 the Work or Derivative Works thereof, You may choose to offer,
4648 and charge a fee for, acceptance of support, warranty, indemnity,
4649 or other liability obligations and/or rights consistent with this
4650 License. However, in accepting such obligations, You may act only
4651 on Your own behalf and on Your sole responsibility, not on behalf
4652 of any other Contributor, and only if You agree to indemnify,
4653 defend, and hold each Contributor harmless for any liability
4654 incurred by, or claims asserted against, such Contributor by reason
4655 of your accepting any such warranty or additional liability.
4656
4657 END OF TERMS AND CONDITIONS
4658
4659 APPENDIX: How to apply the Apache License to your work.
4660
4661 To apply the Apache License to your work, attach the following
4662 boilerplate notice, with the fields enclosed by brackets "[]"
4663 replaced with your own identifying information. (Don't include
4664 the brackets!) The text should be enclosed in the appropriate
4665 comment syntax for the file format. We also recommend that a
4666 file or class name and description of purpose be included on the
4667 same "printed page" as the copyright notice for easier
4668 identification within third-party archives.
4669
4670 Copyright [yyyy] [name of copyright owner]
4671
4672 Licensed under the Apache License, Version 2.0 (the "License");
4673 you may not use this file except in compliance with the License.
4674 You may obtain a copy of the License at
4675
4676 http://www.apache.org/licenses/LICENSE-2.0
4677
4678 Unless required by applicable law or agreed to in writing, software
4679 distributed under the License is distributed on an "AS IS" BASIS,
4680 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4681 See the License for the specific language governing permissions and
4682 limitations under the License.
4683
4684*/