ctb_formats_detection/
magic_parser.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//! Parser for libmagic-style hierarchical magic signature rule files (`Magdir`).
446
447#[allow(
448    unused_imports,
449    clippy::wildcard_imports,
450    reason = "Standard workspace module prelude"
451)]
452use crate::utilities::*;
453
454/// Location in file payload to inspect.
455#[derive(Debug, Clone, PartialEq, Eq)]
456pub enum Offset {
457    /// Beginning-of-file absolute offset.
458    Bof(u64),
459    /// End-of-file negative offset (bytes backwards from end).
460    Eof(u64),
461    /// Relative offset relative to the end of the previous match level (`&<offset>`).
462    Relative(i64),
463    /// Indirect offset pointer dereference: `(<offset>[.,]<type>[~][op][in_offset]+<adjustment>)`.
464    Indirect {
465        base: Box<Offset>,
466        ind_type: IndirectType,
467        is_signed: bool,
468        is_inverse: bool,
469        op: Option<IndirectOp>,
470        adjustment: i64,
471    },
472    /// Relative indirect offset pointer dereference: `&(<offset>[.,]<type>[~][op][in_offset]+<adjustment>)`.
473    RelativeIndirect {
474        base: Box<Offset>,
475        ind_type: IndirectType,
476        is_signed: bool,
477        is_inverse: bool,
478        op: Option<IndirectOp>,
479        adjustment: i64,
480    },
481    /// Search within window starting at given offset.
482    Search { start: u64, max_bytes: usize },
483}
484
485/// Binary operation applied to indirect offset dereferenced pointer before applying adjustment.
486#[derive(Debug, Clone, Copy, PartialEq, Eq)]
487pub enum IndirectOp {
488    Mul(i64),
489    Div(i64),
490    Mod(i64),
491    And(i64),
492    Or(i64),
493    Xor(i64),
494    Add(i64),
495    Sub(i64),
496}
497
498/// Data type dereferenced by an indirect offset.
499#[derive(Debug, Clone, Copy, PartialEq, Eq)]
500pub enum IndirectType {
501    Byte,
502    ShortLe,
503    ShortBe,
504    LongLe,
505    LongBe,
506    QuadLe,
507    QuadBe,
508    Id3Le,
509    Id3Be,
510}
511
512/// String matching modifiers for `string` and `search` tests.
513#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
514pub struct StringFlags {
515    pub case_insensitive: bool,
516    pub trim: bool,
517    pub compact_whitespace: bool,
518    pub optional_whitespace: bool,
519    pub full_word: bool,
520    pub text_only: bool,
521    pub binary_only: bool,
522}
523
524/// Pascal string length prefix specification.
525#[derive(Debug, Clone, Copy, PartialEq, Eq)]
526pub enum PascalLengthSize {
527    Byte,
528    ShortLe,
529    ShortBe,
530    LongLe,
531    LongBe,
532}
533
534/// Relational comparison operator for tests.
535#[derive(Debug, Clone, Copy, PartialEq, Eq)]
536pub enum RelOp {
537    Eq,
538    Ne,
539    Gt,
540    Lt,
541    BitAnd,
542    BitClear,
543    Any,
544}
545
546/// Arithmetic operations applied to read numeric values before comparison/format.
547#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
548pub enum NumOp {
549    #[default]
550    None,
551    Div(u64),
552    Mod(u64),
553    Mul(u64),
554    Add(u64),
555    Sub(u64),
556}
557
558/// Type and comparison test of a magic rule.
559#[derive(Debug, Clone, PartialEq, Eq)]
560pub enum MagicTest {
561    ExactBytes(Vec<u8>),
562    MaskedBytes {
563        bytes: Vec<u8>,
564        mask: Vec<u8>,
565    },
566    String {
567        pattern: Vec<u8>,
568        flags: StringFlags,
569    },
570    PascalString {
571        pattern: Vec<u8>,
572        length_size: PascalLengthSize,
573        length_includes_itself: bool,
574    },
575    Regex {
576        pattern: String,
577        case_insensitive: bool,
578        max_bytes: usize,
579        line_limit: Option<usize>,
580        offset_start: bool,
581    },
582    U8 {
583        value: u8,
584        op: RelOp,
585        mask: Option<u8>,
586        num_op: NumOp,
587    },
588    U16Le {
589        value: u16,
590        op: RelOp,
591        mask: Option<u16>,
592        num_op: NumOp,
593    },
594    U16Be {
595        value: u16,
596        op: RelOp,
597        mask: Option<u16>,
598        num_op: NumOp,
599    },
600    U32Le {
601        value: u32,
602        op: RelOp,
603        mask: Option<u32>,
604        num_op: NumOp,
605    },
606    U32Be {
607        value: u32,
608        op: RelOp,
609        mask: Option<u32>,
610        num_op: NumOp,
611    },
612    U64Le {
613        value: u64,
614        op: RelOp,
615        mask: Option<u64>,
616        num_op: NumOp,
617    },
618    U64Be {
619        value: u64,
620        op: RelOp,
621        mask: Option<u64>,
622        num_op: NumOp,
623    },
624    Date32Le {
625        value: u32,
626        op: RelOp,
627        adjustment: i64,
628    },
629    Date32Be {
630        value: u32,
631        op: RelOp,
632        adjustment: i64,
633    },
634    Date64Le {
635        value: u64,
636        op: RelOp,
637        adjustment: i64,
638    },
639    Date64Be {
640        value: u64,
641        op: RelOp,
642        adjustment: i64,
643    },
644    Search {
645        pattern: Vec<u8>,
646        max_bytes: usize,
647        flags: StringFlags,
648        negated: bool,
649    },
650    Indirect,
651    StringAny(StringFlags),
652    StringRelOp {
653        pattern: Vec<u8>,
654        op: RelOp,
655        flags: StringFlags,
656    },
657    PascalStringAny {
658        length_size: PascalLengthSize,
659        length_includes_itself: bool,
660    },
661    MsDosDate,
662    MsDosTime,
663    Guid([u8; 16]),
664    GuidLe([u8; 16]),
665    GuidBe([u8; 16]),
666    GuidLeAny,
667    GuidBeAny,
668    FloatLe {
669        value_bits: u32,
670        op: RelOp,
671    },
672    FloatBe {
673        value_bits: u32,
674        op: RelOp,
675    },
676    DoubleLe {
677        value_bits: u64,
678        op: RelOp,
679    },
680    DoubleBe {
681        value_bits: u64,
682        op: RelOp,
683    },
684    String16Le {
685        pattern: Vec<u8>,
686        flags: StringFlags,
687        op: RelOp,
688    },
689    String16Be {
690        pattern: Vec<u8>,
691        flags: StringFlags,
692        op: RelOp,
693    },
694    String16LeAny(StringFlags),
695    String16BeAny(StringFlags),
696    VarintLe {
697        value: u64,
698        op: RelOp,
699        mask: Option<u64>,
700    },
701    VarintBe {
702        value: u64,
703        op: RelOp,
704        mask: Option<u64>,
705    },
706    DateWindows64Le {
707        value: u64,
708        op: RelOp,
709        adjustment: i64,
710    },
711    DateWindows64Be {
712        value: u64,
713        op: RelOp,
714        adjustment: i64,
715    },
716    Octal {
717        pattern: Vec<u8>,
718        is_any: bool,
719    },
720    OffsetVal,
721    Default,
722    Clear,
723    Use(String),
724    Name(String),
725    Der(crate::der::DerPattern),
726}
727
728/// Rule branching condition type.
729#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
730pub enum MagicCond {
731    #[default]
732    None,
733    If,
734    Elif,
735    Else,
736}
737
738/// A parsed hierarchical libmagic rule with optional child rules.
739#[derive(Debug, Clone, PartialEq, Eq)]
740pub struct HierarchicalMagicRule {
741    pub cont_level: usize,
742    pub offset: Offset,
743    pub cond: MagicCond,
744    pub test: MagicTest,
745    pub description: Option<String>,
746    pub mime: Option<String>,
747    pub ext: Option<String>,
748    pub apple: Option<String>,
749    pub strength: u32,
750    pub children: Vec<HierarchicalMagicRule>,
751}
752
753impl HierarchicalMagicRule {
754    /// Constructs a root rule with given offset, test, and description.
755    pub fn new_root(
756        offset: Offset,
757        test: MagicTest,
758        description: Option<String>,
759    ) -> Self {
760        Self {
761            cont_level: 0,
762            offset,
763            cond: MagicCond::None,
764            test,
765            description,
766            mime: None,
767            ext: None,
768            apple: None,
769            strength: 50,
770            children: Vec::new(),
771        }
772    }
773}
774
775/// Decodes escape sequences (e.g. \037\235, \x1f, \n, \r, \t, \ ) from libmagic strings.
776pub fn decode_magic_escapes(raw: &str) -> Vec<u8> {
777    let mut out = Vec::new();
778    let bytes = raw.as_bytes();
779    let mut i = 0;
780
781    while i < bytes.len() {
782        if let Some(&b'\\') = bytes.get(i) {
783            i = i.saturating_add(1);
784            if i >= bytes.len() {
785                out.push(b'\\');
786                break;
787            }
788
789            match bytes.get(i) {
790                Some(b'n') => {
791                    out.push(b'\n');
792                    i = i.saturating_add(1);
793                }
794                Some(b'r') => {
795                    out.push(b'\r');
796                    i = i.saturating_add(1);
797                }
798                Some(b't') => {
799                    out.push(b'\t');
800                    i = i.saturating_add(1);
801                }
802                Some(b'b') => {
803                    out.push(8); // backspace
804                    i = i.saturating_add(1);
805                }
806                Some(b'\\') => {
807                    out.push(b'\\');
808                    i = i.saturating_add(1);
809                }
810                Some(b' ') => {
811                    out.push(b' ');
812                    i = i.saturating_add(1);
813                }
814                Some(b'x' | b'X') => {
815                    i = i.saturating_add(1);
816                    let mut hex_str = String::new();
817                    for _ in 0..2 {
818                        if let Some(&c) = bytes.get(i) {
819                            if c.is_ascii_hexdigit() {
820                                hex_str.push(char::from(c));
821                                i = i.saturating_add(1);
822                            } else {
823                                break;
824                            }
825                        }
826                    }
827                    if let Ok(byte) = u8::from_str_radix(&hex_str, 16) {
828                        out.push(byte);
829                    }
830                }
831                Some(&c) if (b'0'..=b'7').contains(&c) => {
832                    let mut oct_str = String::new();
833                    for _ in 0..3 {
834                        if let Some(&oc) = bytes.get(i) {
835                            if (b'0'..=b'7').contains(&oc) {
836                                oct_str.push(char::from(oc));
837                                i = i.saturating_add(1);
838                            } else {
839                                break;
840                            }
841                        }
842                    }
843                    if let Ok(byte) = u8::from_str_radix(&oct_str, 8) {
844                        out.push(byte);
845                    }
846                }
847                Some(&other) => {
848                    out.push(other);
849                    i = i.saturating_add(1);
850                }
851                None => break,
852            }
853        } else if let Some(&b) = bytes.get(i) {
854            out.push(b);
855            i = i.saturating_add(1);
856        }
857    }
858
859    out
860}
861
862/// Splits a libmagic rule line into whitespace-separated tokens, respecting escaped spaces (`\ `).
863fn split_magic_tokens(line: &str) -> Vec<String> {
864    let mut tokens = Vec::new();
865    let mut current = String::new();
866    let mut in_escape = false;
867
868    for ch in line.chars() {
869        if in_escape {
870            current.push(ch);
871            in_escape = false;
872        } else if ch == '\\' {
873            current.push(ch);
874            in_escape = true;
875        } else if ch.is_whitespace() {
876            if !current.is_empty() {
877                tokens.push(current);
878                current = String::new();
879            }
880        } else {
881            current.push(ch);
882        }
883    }
884
885    if !current.is_empty() {
886        tokens.push(current);
887    }
888
889    tokens
890}
891
892/// Parses an integer string with decimal, hex (`0x`), or octal (`0`) notation.
893fn parse_magic_int(val: &str) -> Option<u64> {
894    let trimmed = val.trim();
895    if let Some(hex) = trimmed
896        .strip_prefix("0x")
897        .or_else(|| trimmed.strip_prefix("0X"))
898    {
899        u64::from_str_radix(hex.trim_end_matches(['L', 'h']), 16).ok()
900    } else if trimmed.starts_with('0')
901        && trimmed.len() > 1
902        && trimmed.chars().all(|c| ('0'..='7').contains(&c))
903    {
904        u64::from_str_radix(trimmed, 8).ok()
905    } else {
906        trimmed.parse::<u64>().ok()
907    }
908}
909
910/// Parses a signed integer string with optional `+` or `-` prefix.
911fn parse_signed_magic_int(val: &str) -> Option<i64> {
912    let trimmed = val.trim();
913    if let Some(stripped) = trimmed.strip_prefix('-') {
914        let u = parse_magic_int(stripped)?;
915        let i = i64::try_from(u).ok()?;
916        (0i64).checked_sub(i)
917    } else if let Some(stripped) = trimmed.strip_prefix('+') {
918        let u = parse_magic_int(stripped)?;
919        i64::try_from(u).ok()
920    } else {
921        let u = parse_magic_int(trimmed)?;
922        i64::try_from(u).ok()
923    }
924}
925
926fn split_trailing_adj(s: &str) -> (&str, i64) {
927    if let Some(idx) = s.rfind('+') {
928        if idx > 0 {
929            if let Some(adj) = s.get(idx..).and_then(parse_signed_magic_int) {
930                if let Some(before) = s.get(..idx) {
931                    return (before, adj);
932                }
933            }
934        }
935    } else if let Some(idx) = s.rfind('-') {
936        if idx > 0 && !s.ends_with('-') {
937            if let Some(adj) = s.get(idx..).and_then(parse_signed_magic_int) {
938                if let Some(before) = s.get(..idx) {
939                    return (before, adj);
940                }
941            }
942        }
943    }
944    (s, 0)
945}
946
947fn parse_indirect_op_and_adj(s: &str) -> (Option<IndirectOp>, i64) {
948    let trimmed = s.trim();
949    if trimmed.is_empty() {
950        return (None, 0);
951    }
952    let first_char = match trimmed.chars().next() {
953        Some(c) => c,
954        None => return (None, 0),
955    };
956    match first_char {
957        '*' | '/' | '%' | '&' | '|' | '^' => {
958            // Reason for fallback: slice boundary defaults to empty string if trimmed is empty
959            let after_op =
960                trimmed.get(first_char.len_utf8()..).unwrap_or("").trim();
961            let (operand_str, adj) = split_trailing_adj(after_op);
962            // Reason for fallback: invalid or missing operand defaults to identity multiplier/divisor 1
963            let operand = parse_signed_magic_int(operand_str).unwrap_or(1);
964            let op = match first_char {
965                '*' => Some(IndirectOp::Mul(operand)),
966                '/' => Some(IndirectOp::Div(operand)),
967                '%' => Some(IndirectOp::Mod(operand)),
968                '&' => Some(IndirectOp::And(operand)),
969                '|' => Some(IndirectOp::Or(operand)),
970                '^' => Some(IndirectOp::Xor(operand)),
971                _ => None,
972            };
973            (op, adj)
974        }
975        '+' | '-' => {
976            // Reason for fallback: missing or invalid signed adjustment defaults to 0
977            let adj = parse_signed_magic_int(trimmed).unwrap_or(0);
978            (None, adj)
979        }
980        _ => (None, 0),
981    }
982}
983
984/// Parses an indirect offset specification: `(<offset>[.,]<type>[~][op][in_offset]+<adjustment>)`.
985fn parse_indirect_offset(raw: &str) -> Option<Offset> {
986    let mut inner = raw.strip_prefix('(')?.strip_suffix(')')?.trim();
987    let starts_with_tilde = if let Some(stripped) = inner.strip_prefix('~') {
988        inner = stripped.trim();
989        true
990    } else {
991        false
992    };
993    let (base_part, ind_type, is_signed, is_inverse, op, adjustment) =
994        if let Some(sep_idx) = inner.find(['.', ',']) {
995            let base_str = inner.get(..sep_idx)?;
996            let sep = inner.as_bytes().get(sep_idx)?;
997            let is_signed = *sep == b',';
998            let after_sep = inner.get(sep_idx.saturating_add(1)..)?.trim();
999
1000            let (after_tilde, mut is_inverse) =
1001                if let Some(stripped) = after_sep.strip_prefix('~') {
1002                    (stripped, true)
1003                } else {
1004                    (after_sep, false)
1005                };
1006            if starts_with_tilde {
1007                is_inverse = true;
1008            }
1009
1010            let type_char = after_tilde.chars().next()?;
1011            let type_char_len = type_char.len_utf8();
1012            let rest_after_type = after_tilde.get(type_char_len..)?.trim();
1013
1014            let rest_clean =
1015                if let Some(stripped) = rest_after_type.strip_prefix('~') {
1016                    is_inverse = true;
1017                    stripped.trim()
1018                } else {
1019                    rest_after_type
1020                };
1021
1022            let t = match type_char {
1023                'b' | 'B' | 'c' | 'C' => IndirectType::Byte,
1024                's' | 'h' => IndirectType::ShortLe,
1025                'S' | 'H' => IndirectType::ShortBe,
1026                'l' => IndirectType::LongLe,
1027                'L' => IndirectType::LongBe,
1028                'i' => IndirectType::Id3Le,
1029                'I' => IndirectType::Id3Be,
1030                'q' | 'm' | 'e' | 'f' | 'g' => IndirectType::QuadLe,
1031                'Q' | 'E' | 'F' | 'G' => IndirectType::QuadBe,
1032                _ => IndirectType::LongLe,
1033            };
1034
1035            let (op, adjustment) = parse_indirect_op_and_adj(rest_clean);
1036            (base_str.trim(), t, is_signed, is_inverse, op, adjustment)
1037        } else {
1038            let (before_adj, adjustment) = split_trailing_adj(inner);
1039            (
1040                before_adj.trim(),
1041                IndirectType::LongLe,
1042                false,
1043                starts_with_tilde,
1044                None,
1045                adjustment,
1046            )
1047        };
1048
1049    let base = if let Some(stripped) = base_part.strip_prefix('&') {
1050        let rel_val = parse_signed_magic_int(stripped)?;
1051        Offset::Relative(rel_val)
1052    } else if let Some(stripped) = base_part.strip_prefix('-') {
1053        let off = parse_magic_int(stripped)?;
1054        Offset::Eof(off)
1055    } else {
1056        let abs_val = parse_magic_int(base_part)?;
1057        Offset::Bof(abs_val)
1058    };
1059
1060    Some(Offset::Indirect {
1061        base: Box::new(base),
1062        ind_type,
1063        is_signed,
1064        is_inverse,
1065        op,
1066        adjustment,
1067    })
1068}
1069
1070/// Parses offset string into an `Offset` enum variant.
1071pub fn parse_offset(offset_str: &str) -> Option<Offset> {
1072    let trimmed = offset_str.trim();
1073    if trimmed.starts_with("&(") && trimmed.ends_with(')') {
1074        let inner = trimmed.strip_prefix('&')?;
1075        let ind = parse_indirect_offset(inner)?;
1076        if let Offset::Indirect {
1077            base,
1078            ind_type,
1079            is_signed,
1080            is_inverse,
1081            op,
1082            adjustment,
1083        } = ind
1084        {
1085            Some(Offset::RelativeIndirect {
1086                base,
1087                ind_type,
1088                is_signed,
1089                is_inverse,
1090                op,
1091                adjustment,
1092            })
1093        } else {
1094            None
1095        }
1096    } else if trimmed.starts_with('(') && trimmed.ends_with(')') {
1097        parse_indirect_offset(trimmed)
1098    } else if let Some(stripped) = trimmed.strip_prefix('&') {
1099        let rel_val = parse_signed_magic_int(stripped)?;
1100        Some(Offset::Relative(rel_val))
1101    } else if let Some(stripped) = trimmed.strip_prefix('+') {
1102        let rel_val = parse_signed_magic_int(stripped)?;
1103        Some(Offset::Relative(rel_val))
1104    } else if let Some(stripped) = trimmed.strip_prefix('-') {
1105        let off = parse_magic_int(stripped)?;
1106        Some(Offset::Eof(off))
1107    } else {
1108        let off = parse_magic_int(trimmed)?;
1109        Some(Offset::Bof(off))
1110    }
1111}
1112
1113/// Parses a 16-byte mixed-endian GUID string e.g. `C1C41626-504C-4092-ACA9-41F936934328`.
1114fn parse_guid(s: &str) -> Option<[u8; 16]> {
1115    let clean = s.trim().replace('-', "");
1116    if clean.len() != 32 {
1117        return None;
1118    }
1119    let d1 = u32::from_str_radix(clean.get(0..8)?, 16)
1120        .ok()?
1121        .to_le_bytes();
1122    let d2 = u16::from_str_radix(clean.get(8..12)?, 16)
1123        .ok()?
1124        .to_le_bytes();
1125    let d3 = u16::from_str_radix(clean.get(12..16)?, 16)
1126        .ok()?
1127        .to_le_bytes();
1128    let mut out = [0u8; 16];
1129    out[0..4].copy_from_slice(&d1);
1130    out[4..6].copy_from_slice(&d2);
1131    out[6..8].copy_from_slice(&d3);
1132    for (i, chunk) in clean.get(16..32)?.as_bytes().chunks_exact(2).enumerate()
1133    {
1134        let chunk_str = std::str::from_utf8(chunk).ok()?;
1135        let b = u8::from_str_radix(chunk_str, 16).ok()?;
1136        let idx = 8usize.saturating_add(i);
1137        if let Some(slot) = out.get_mut(idx) {
1138            *slot = b;
1139        }
1140    }
1141    Some(out)
1142}
1143
1144/// Parses a 16-byte big-endian RFC 4122 UUID string.
1145fn parse_guid_be(s: &str) -> Option<[u8; 16]> {
1146    let clean = s.trim().replace('-', "");
1147    if clean.len() != 32 {
1148        return None;
1149    }
1150    let mut out = [0u8; 16];
1151    for (i, chunk) in clean.as_bytes().chunks_exact(2).enumerate() {
1152        let chunk_str = std::str::from_utf8(chunk).ok()?;
1153        let b = u8::from_str_radix(chunk_str, 16).ok()?;
1154        if let Some(slot) = out.get_mut(i) {
1155            *slot = b;
1156        }
1157    }
1158    Some(out)
1159}
1160
1161fn parse_string_flags(flags_str: Option<&str>) -> StringFlags {
1162    let mut flags = StringFlags::default();
1163    if let Some(s) = flags_str {
1164        flags.case_insensitive = s.contains('c') || s.contains('C');
1165        flags.trim = s.contains('T');
1166        flags.compact_whitespace = s.contains('W');
1167        flags.optional_whitespace = s.contains('w');
1168        flags.full_word = s.contains('f') || s.contains('F');
1169        flags.text_only = s.contains('t');
1170        flags.binary_only = s.contains('b') || s.contains('B');
1171    }
1172    flags
1173}
1174
1175fn parse_pstring_flags(flags_str: Option<&str>) -> (PascalLengthSize, bool) {
1176    let mut size = PascalLengthSize::Byte;
1177    let mut inc = false;
1178    if let Some(s) = flags_str {
1179        if s.contains('H') {
1180            size = PascalLengthSize::ShortBe;
1181        } else if s.contains('h') {
1182            size = PascalLengthSize::ShortLe;
1183        } else if s.contains('L') {
1184            size = PascalLengthSize::LongBe;
1185        } else if s.contains('l') {
1186            size = PascalLengthSize::LongLe;
1187        } else if s.contains('B') {
1188            size = PascalLengthSize::Byte;
1189        }
1190        inc = s.contains('J') || s.contains('j');
1191    }
1192    (size, inc)
1193}
1194
1195fn parse_regex_flags(
1196    flags_str: Option<&str>,
1197) -> (bool, usize, Option<usize>, bool) {
1198    let mut case_insensitive = false;
1199    let mut line_limit = None;
1200    let mut offset_start = false;
1201    let mut max_bytes = 4096;
1202    if let Some(s) = flags_str {
1203        case_insensitive = s.contains('c') || s.contains('C');
1204        let has_line = s.contains('l') || s.contains('L');
1205        offset_start = s.contains('s') || s.contains('S');
1206        let digits: String = s.chars().filter(char::is_ascii_digit).collect();
1207        let parsed_num = digits.parse::<usize>().ok();
1208        if has_line {
1209            // Reason for fallback: regex /l flag without explicit count defaults to 1 line
1210            let count = parsed_num.unwrap_or(1).max(1);
1211            line_limit = Some(count);
1212            max_bytes = count.saturating_mul(8192);
1213        } else if let Some(num) = parsed_num {
1214            if num > 0 {
1215                max_bytes = num;
1216            }
1217        }
1218    }
1219    (case_insensitive, max_bytes, line_limit, offset_start)
1220}
1221
1222fn parse_search_flags(flags_str: Option<&str>) -> (StringFlags, usize) {
1223    let flags = parse_string_flags(flags_str);
1224    let mut max_bytes = 65536;
1225    if let Some(s) = flags_str {
1226        let digits: String = s.chars().filter(char::is_ascii_digit).collect();
1227        if let Ok(num) = digits.parse::<usize>() {
1228            if num > 0 {
1229                max_bytes = num;
1230            }
1231        }
1232    }
1233    (flags, max_bytes)
1234}
1235
1236fn convert_regex_octal_escapes(pattern: &str) -> String {
1237    let mut res = String::with_capacity(pattern.len());
1238    let mut chars = pattern.chars().peekable();
1239    while let Some(c) = chars.next() {
1240        if c == '\\' {
1241            if let Some(&first_digit) = chars.peek() {
1242                if ('0'..='7').contains(&first_digit) {
1243                    chars.next();
1244                    #[expect(
1245                        clippy::expect_used,
1246                        reason = "character checked in '0'..='7' so to_digit(8) is infallible"
1247                    )]
1248                    let mut oct_val = first_digit
1249                        .to_digit(8)
1250                        .expect("first_digit in '0'..='7' is valid octal");
1251                    for _ in 0..2 {
1252                        if let Some(&d) = chars.peek() {
1253                            if ('0'..='7').contains(&d) {
1254                                chars.next();
1255                                #[expect(
1256                                    clippy::expect_used,
1257                                    reason = "character checked in '0'..='7' so to_digit(8) is infallible"
1258                                )]
1259                                let d_val = d.to_digit(8).expect(
1260                                    "digit in '0'..='7' is valid octal",
1261                                );
1262                                oct_val = oct_val
1263                                    .saturating_mul(8)
1264                                    .saturating_add(d_val);
1265                            } else {
1266                                break;
1267                            }
1268                        }
1269                    }
1270                    if let Ok(byte_val) = u8::try_from(oct_val) {
1271                        res.push_str(&format!("\\x{byte_val:02x}"));
1272                    } else {
1273                        res.push('\\');
1274                        res.push(first_digit);
1275                    }
1276                    continue;
1277                }
1278            }
1279            res.push('\\');
1280        } else {
1281            res.push(c);
1282        }
1283    }
1284    res
1285}
1286
1287/// Parses a single libmagic rule line into components.
1288pub fn parse_magic_line(
1289    line: &str,
1290) -> Option<(usize, Offset, MagicCond, MagicTest, Option<String>)> {
1291    let trimmed = line.trim();
1292    if trimmed.is_empty()
1293        || trimmed.starts_with('#')
1294        || trimmed.starts_with("!:")
1295    {
1296        return None;
1297    }
1298
1299    // Determine continuation level
1300    let mut cont_level: usize = 0;
1301    let mut rest = trimmed;
1302    while let Some(stripped) = rest.strip_prefix('>') {
1303        cont_level = cont_level.saturating_add(1);
1304        rest = stripped;
1305    }
1306
1307    let mut tokens = split_magic_tokens(rest);
1308    if tokens.is_empty() {
1309        return None;
1310    }
1311
1312    let mut cond = MagicCond::None;
1313    if tokens.first().map(std::string::String::as_str) == Some("if") {
1314        cond = MagicCond::If;
1315        tokens.remove(0);
1316        tokens.insert(0, "0".to_string());
1317    } else if tokens.first().map(std::string::String::as_str) == Some("elif") {
1318        cond = MagicCond::Elif;
1319        tokens.remove(0);
1320        tokens.insert(0, "0".to_string());
1321    } else if tokens.first().map(std::string::String::as_str) == Some("else") {
1322        cond = MagicCond::Else;
1323        tokens.remove(0);
1324        tokens.insert(0, "0".to_string());
1325    } else if tokens.len() > 1 {
1326        if tokens.get(1).map(std::string::String::as_str) == Some("if") {
1327            cond = MagicCond::If;
1328            tokens.remove(1);
1329        } else if tokens.get(1).map(std::string::String::as_str) == Some("elif")
1330        {
1331            cond = MagicCond::Elif;
1332            tokens.remove(1);
1333        } else if tokens.get(1).map(std::string::String::as_str) == Some("else")
1334        {
1335            cond = MagicCond::Else;
1336            tokens.remove(1);
1337        }
1338    }
1339
1340    // Handle `else` shorthand when type/test are omitted (in libmagic, `else` has no condition)
1341    if cond == MagicCond::Else {
1342        if tokens.get(1).map(std::string::String::as_str) != Some("default") {
1343            let desc = if tokens.len() > 1 {
1344                let rest_tokens = tokens.split_off(1);
1345                Some(rest_tokens.join(" "))
1346            } else {
1347                None
1348            };
1349            tokens.push("default".to_string());
1350            tokens.push("x".to_string());
1351            if let Some(d) = desc {
1352                tokens.push(d);
1353            }
1354        }
1355    }
1356
1357    if tokens.len() < 3 {
1358        return None;
1359    }
1360
1361    let offset_str = match tokens.first() {
1362        Some(s) => s.as_str(),
1363        None => return None,
1364    };
1365    let type_str = match tokens.get(1) {
1366        Some(s) => s.as_str(),
1367        None => return None,
1368    };
1369    let val_str = match tokens.get(2) {
1370        Some(s) => s.as_str(),
1371        None => return None,
1372    };
1373
1374    // Description is the remainder of the line after token 2 with backspace decoding
1375    let description = if tokens.len() > 3 {
1376        let raw = tokens.get(3..)?.join(" ");
1377        let decoded = raw
1378            .replace(r"\b", "\u{8}")
1379            .replace(r"\n", "\n")
1380            .replace(r"\t", "\t");
1381        Some(decoded)
1382    } else {
1383        None
1384    };
1385
1386    let offset = parse_offset(offset_str)?;
1387
1388    // Handle named templates and use invocations
1389    if type_str == "name" {
1390        return Some((
1391            cont_level,
1392            offset,
1393            cond,
1394            MagicTest::Name(val_str.to_string()),
1395            description,
1396        ));
1397    }
1398    if type_str == "use" {
1399        return Some((
1400            cont_level,
1401            offset,
1402            cond,
1403            MagicTest::Use(val_str.to_string()),
1404            description,
1405        ));
1406    }
1407    if type_str == "indirect" {
1408        return Some((
1409            cont_level,
1410            offset,
1411            cond,
1412            MagicTest::Indirect,
1413            description,
1414        ));
1415    }
1416
1417    // Parse type and optional mask (&...)
1418    let (type_no_mask, mask_str) = if let Some(idx) = type_str.find('&') {
1419        let (t, m) = type_str.split_at(idx);
1420        (t, m.strip_prefix('&'))
1421    } else {
1422        (type_str, None)
1423    };
1424
1425    // Parse type and optional numeric operator (%N, /N) or string flags (/...)
1426    let (base_type, flags_str, num_op) =
1427        if let Some(idx) = type_no_mask.find('%') {
1428            let (t, op_str) = type_no_mask.split_at(idx);
1429            // Reason for fallback: default to modulo 1 if operator operand is missing or invalid
1430            let operand = op_str
1431                .strip_prefix('%')
1432                .and_then(parse_magic_int)
1433                .unwrap_or(1);
1434            (t, None, NumOp::Mod(operand))
1435        } else if let Some(idx) = type_no_mask.find('/') {
1436            let (t, rest) = type_no_mask.split_at(idx);
1437            // Reason for fallback: strip leading slash from type flags or division string, defaulting to empty string
1438            let f = rest.strip_prefix('/').unwrap_or("");
1439            if f.chars().all(|c| c.is_ascii_digit())
1440                && !f.is_empty()
1441                && (t.contains("long")
1442                    || t.contains("short")
1443                    || t.contains("byte")
1444                    || t.contains("quad"))
1445            {
1446                // Reason for fallback: default to division by 1 if division operand is invalid
1447                let operand = parse_magic_int(f).unwrap_or(1);
1448                (t, None, NumOp::Div(operand))
1449            } else {
1450                (t, Some(f), NumOp::None)
1451            }
1452        } else {
1453            (type_no_mask, None, NumOp::None)
1454        };
1455
1456    // Parse type adjustment e.g. leldate+631065600
1457    let (base_type_no_adj, type_adj) = if let Some(idx) = base_type.find('+') {
1458        let (t, a) = base_type.split_at(idx);
1459        // Reason for fallback: default to zero offset adjustment if positive adjustment is invalid or missing
1460        let adj = a
1461            .strip_prefix('+')
1462            .and_then(parse_signed_magic_int)
1463            .unwrap_or(0);
1464        (t, adj)
1465    } else if let Some(idx) = base_type.find('-') {
1466        let (t, a) = base_type.split_at(idx);
1467        // Reason for fallback: default to zero offset adjustment if negative adjustment is invalid or missing
1468        let adj = a
1469            .strip_prefix('-')
1470            .and_then(parse_signed_magic_int)
1471            .map_or(0, i64::saturating_neg);
1472        (t, adj)
1473    } else {
1474        (base_type, 0)
1475    };
1476
1477    // Parse test
1478    let test = match base_type_no_adj {
1479        "string" | "ustring" => {
1480            let flags = parse_string_flags(flags_str);
1481            if val_str == "x" {
1482                MagicTest::StringAny(flags)
1483            } else if let Some(stripped) = val_str.strip_prefix('>') {
1484                let bytes = decode_magic_escapes(stripped);
1485                MagicTest::StringRelOp {
1486                    pattern: bytes,
1487                    op: RelOp::Gt,
1488                    flags,
1489                }
1490            } else if let Some(stripped) = val_str.strip_prefix('<') {
1491                let bytes = decode_magic_escapes(stripped);
1492                MagicTest::StringRelOp {
1493                    pattern: bytes,
1494                    op: RelOp::Lt,
1495                    flags,
1496                }
1497            } else if let Some(stripped) = val_str.strip_prefix('!') {
1498                let bytes = decode_magic_escapes(stripped);
1499                MagicTest::StringRelOp {
1500                    pattern: bytes,
1501                    op: RelOp::Ne,
1502                    flags,
1503                }
1504            } else if let Some(stripped) = val_str.strip_prefix('=') {
1505                let bytes = decode_magic_escapes(stripped);
1506                MagicTest::String {
1507                    pattern: bytes,
1508                    flags,
1509                }
1510            } else {
1511                let bytes = decode_magic_escapes(val_str);
1512                if flags == StringFlags::default() {
1513                    MagicTest::ExactBytes(bytes)
1514                } else {
1515                    MagicTest::String {
1516                        pattern: bytes,
1517                        flags,
1518                    }
1519                }
1520            }
1521        }
1522        "pstring" => {
1523            let (length_size, length_includes_itself) =
1524                parse_pstring_flags(flags_str);
1525            if val_str == "x" {
1526                MagicTest::PascalStringAny {
1527                    length_size,
1528                    length_includes_itself,
1529                }
1530            } else {
1531                let bytes = decode_magic_escapes(val_str);
1532                MagicTest::PascalString {
1533                    pattern: bytes,
1534                    length_size,
1535                    length_includes_itself,
1536                }
1537            }
1538        }
1539        "regex" => {
1540            let (case_insensitive, max_bytes, line_limit, offset_start) =
1541                parse_regex_flags(flags_str);
1542            let (_, pattern_raw) = parse_op_and_val(val_str);
1543            let unescaped_pattern =
1544                if let Some(stripped) = pattern_raw.strip_prefix(r"\^") {
1545                    format!("^{stripped}")
1546                } else if let Some(stripped) = pattern_raw.strip_prefix(r"\<") {
1547                    format!("<{stripped}")
1548                } else if let Some(stripped) = pattern_raw.strip_prefix(r"\>") {
1549                    format!(">{stripped}")
1550                } else {
1551                    pattern_raw.to_string()
1552                };
1553            let converted_pattern =
1554                convert_regex_octal_escapes(&unescaped_pattern);
1555            MagicTest::Regex {
1556                pattern: converted_pattern,
1557                case_insensitive,
1558                max_bytes,
1559                line_limit,
1560                offset_start,
1561            }
1562        }
1563        "byte" | "ubyte" => {
1564            let mask = mask_str.and_then(|m| {
1565                parse_magic_int(m).and_then(|v| u8::try_from(v).ok())
1566            });
1567            let (op, num_str) = parse_op_and_val(val_str);
1568            if op == RelOp::Any {
1569                MagicTest::U8 {
1570                    value: 0,
1571                    op: RelOp::Any,
1572                    mask,
1573                    num_op,
1574                }
1575            } else {
1576                let val_u64 = parse_magic_int(num_str)?;
1577                let val = u8::try_from(val_u64).ok()?;
1578                MagicTest::U8 {
1579                    value: val,
1580                    op,
1581                    mask,
1582                    num_op,
1583                }
1584            }
1585        }
1586        "leshort" | "short" | "ushort" | "uleshort" => {
1587            let mask = mask_str.and_then(|m| {
1588                parse_magic_int(m).and_then(|v| u16::try_from(v).ok())
1589            });
1590            let (op, num_str) = parse_op_and_val(val_str);
1591            if op == RelOp::Any {
1592                MagicTest::U16Le {
1593                    value: 0,
1594                    op: RelOp::Any,
1595                    mask,
1596                    num_op,
1597                }
1598            } else {
1599                let val_u64 = parse_magic_int(num_str)?;
1600                let val = u16::try_from(val_u64).ok()?;
1601                MagicTest::U16Le {
1602                    value: val,
1603                    op,
1604                    mask,
1605                    num_op,
1606                }
1607            }
1608        }
1609        "beshort" | "ubeshort" => {
1610            let mask = mask_str.and_then(|m| {
1611                parse_magic_int(m).and_then(|v| u16::try_from(v).ok())
1612            });
1613            let (op, num_str) = parse_op_and_val(val_str);
1614            if op == RelOp::Any {
1615                MagicTest::U16Be {
1616                    value: 0,
1617                    op: RelOp::Any,
1618                    mask,
1619                    num_op,
1620                }
1621            } else {
1622                let val_u64 = parse_magic_int(num_str)?;
1623                let val = u16::try_from(val_u64).ok()?;
1624                MagicTest::U16Be {
1625                    value: val,
1626                    op,
1627                    mask,
1628                    num_op,
1629                }
1630            }
1631        }
1632        "lelong" | "long" | "ulong" | "ulelong" => {
1633            let mask = mask_str.and_then(|m| {
1634                parse_magic_int(m).and_then(|v| u32::try_from(v).ok())
1635            });
1636            let (op, num_str) = parse_op_and_val(val_str);
1637            if op == RelOp::Any {
1638                MagicTest::U32Le {
1639                    value: 0,
1640                    op: RelOp::Any,
1641                    mask,
1642                    num_op,
1643                }
1644            } else {
1645                let val_u64 = parse_magic_int(num_str)?;
1646                let val = u32::try_from(val_u64).ok()?;
1647                MagicTest::U32Le {
1648                    value: val,
1649                    op,
1650                    mask,
1651                    num_op,
1652                }
1653            }
1654        }
1655        "belong" | "ubelong" => {
1656            let mask = mask_str.and_then(|m| {
1657                parse_magic_int(m).and_then(|v| u32::try_from(v).ok())
1658            });
1659            let (op, num_str) = parse_op_and_val(val_str);
1660            if op == RelOp::Any {
1661                MagicTest::U32Be {
1662                    value: 0,
1663                    op: RelOp::Any,
1664                    mask,
1665                    num_op,
1666                }
1667            } else {
1668                let val_u64 = parse_magic_int(num_str)?;
1669                let val = u32::try_from(val_u64).ok()?;
1670                MagicTest::U32Be {
1671                    value: val,
1672                    op,
1673                    mask,
1674                    num_op,
1675                }
1676            }
1677        }
1678        "lequad" | "ulequad" => {
1679            let mask = mask_str.and_then(parse_magic_int);
1680            let (op, num_str) = parse_op_and_val(val_str);
1681            if op == RelOp::Any {
1682                MagicTest::U64Le {
1683                    value: 0,
1684                    op: RelOp::Any,
1685                    mask,
1686                    num_op,
1687                }
1688            } else {
1689                let val = parse_magic_int(num_str)?;
1690                MagicTest::U64Le {
1691                    value: val,
1692                    op,
1693                    mask,
1694                    num_op,
1695                }
1696            }
1697        }
1698        "bequad" | "ubequad" | "quad" => {
1699            let mask = mask_str.and_then(parse_magic_int);
1700            let (op, num_str) = parse_op_and_val(val_str);
1701            if op == RelOp::Any {
1702                MagicTest::U64Be {
1703                    value: 0,
1704                    op: RelOp::Any,
1705                    mask,
1706                    num_op,
1707                }
1708            } else {
1709                let val = parse_magic_int(num_str)?;
1710                MagicTest::U64Be {
1711                    value: val,
1712                    op,
1713                    mask,
1714                    num_op,
1715                }
1716            }
1717        }
1718        "date" | "bedate" | "ldate" | "beldate" => {
1719            let (op, num_str) = parse_op_and_val(val_str);
1720            if op == RelOp::Any {
1721                MagicTest::Date32Be {
1722                    value: 0,
1723                    op: RelOp::Any,
1724                    adjustment: type_adj,
1725                }
1726            } else {
1727                let val_u64 = parse_magic_int(num_str)?;
1728                let val = u32::try_from(val_u64).ok()?;
1729                MagicTest::Date32Be {
1730                    value: val,
1731                    op,
1732                    adjustment: type_adj,
1733                }
1734            }
1735        }
1736        "ledate" | "leldate" | "medate" => {
1737            let (op, num_str) = parse_op_and_val(val_str);
1738            if op == RelOp::Any {
1739                MagicTest::Date32Le {
1740                    value: 0,
1741                    op: RelOp::Any,
1742                    adjustment: type_adj,
1743                }
1744            } else {
1745                let val_u64 = parse_magic_int(num_str)?;
1746                let val = u32::try_from(val_u64).ok()?;
1747                MagicTest::Date32Le {
1748                    value: val,
1749                    op,
1750                    adjustment: type_adj,
1751                }
1752            }
1753        }
1754        "qdate" | "beqdate" => {
1755            let (op, num_str) = parse_op_and_val(val_str);
1756            if op == RelOp::Any {
1757                MagicTest::Date64Be {
1758                    value: 0,
1759                    op: RelOp::Any,
1760                    adjustment: type_adj,
1761                }
1762            } else {
1763                let val = parse_magic_int(num_str)?;
1764                MagicTest::Date64Be {
1765                    value: val,
1766                    op,
1767                    adjustment: type_adj,
1768                }
1769            }
1770        }
1771        "leqdate" => {
1772            let (op, num_str) = parse_op_and_val(val_str);
1773            if op == RelOp::Any {
1774                MagicTest::Date64Le {
1775                    value: 0,
1776                    op: RelOp::Any,
1777                    adjustment: type_adj,
1778                }
1779            } else {
1780                let val = parse_magic_int(num_str)?;
1781                MagicTest::Date64Le {
1782                    value: val,
1783                    op,
1784                    adjustment: type_adj,
1785                }
1786            }
1787        }
1788        "lemsdosdate" | "msdosdate" => MagicTest::MsDosDate,
1789        "lemsdostime" | "msdostime" => MagicTest::MsDosTime,
1790        "guid" | "leguid" => {
1791            if val_str == "x" {
1792                MagicTest::GuidLeAny
1793            } else {
1794                let g = parse_guid(val_str)?;
1795                MagicTest::GuidLe(g)
1796            }
1797        }
1798        "beguid" => {
1799            if val_str == "x" {
1800                MagicTest::GuidBeAny
1801            } else {
1802                let g = parse_guid_be(val_str)?;
1803                MagicTest::GuidBe(g)
1804            }
1805        }
1806        "float" | "lefloat" => {
1807            let (op, num_str) = parse_op_and_val(val_str);
1808            if op == RelOp::Any {
1809                MagicTest::FloatLe {
1810                    value_bits: 0,
1811                    op: RelOp::Any,
1812                }
1813            } else {
1814                let val: f32 = num_str.parse().ok()?;
1815                MagicTest::FloatLe {
1816                    value_bits: val.to_bits(),
1817                    op,
1818                }
1819            }
1820        }
1821        "befloat" => {
1822            let (op, num_str) = parse_op_and_val(val_str);
1823            if op == RelOp::Any {
1824                MagicTest::FloatBe {
1825                    value_bits: 0,
1826                    op: RelOp::Any,
1827                }
1828            } else {
1829                let val: f32 = num_str.parse().ok()?;
1830                MagicTest::FloatBe {
1831                    value_bits: val.to_bits(),
1832                    op,
1833                }
1834            }
1835        }
1836        "double" | "ledouble" => {
1837            let (op, num_str) = parse_op_and_val(val_str);
1838            if op == RelOp::Any {
1839                MagicTest::DoubleLe {
1840                    value_bits: 0,
1841                    op: RelOp::Any,
1842                }
1843            } else {
1844                let val: f64 = num_str.parse().ok()?;
1845                MagicTest::DoubleLe {
1846                    value_bits: val.to_bits(),
1847                    op,
1848                }
1849            }
1850        }
1851        "bedouble" => {
1852            let (op, num_str) = parse_op_and_val(val_str);
1853            if op == RelOp::Any {
1854                MagicTest::DoubleBe {
1855                    value_bits: 0,
1856                    op: RelOp::Any,
1857                }
1858            } else {
1859                let val: f64 = num_str.parse().ok()?;
1860                MagicTest::DoubleBe {
1861                    value_bits: val.to_bits(),
1862                    op,
1863                }
1864            }
1865        }
1866        "lestring16" => {
1867            let flags = parse_string_flags(flags_str);
1868            if val_str == "x" {
1869                MagicTest::String16LeAny(flags)
1870            } else if let Some(stripped) = val_str.strip_prefix('>') {
1871                let bytes = decode_magic_escapes(stripped);
1872                MagicTest::String16Le {
1873                    pattern: bytes,
1874                    flags,
1875                    op: RelOp::Gt,
1876                }
1877            } else if let Some(stripped) = val_str.strip_prefix('<') {
1878                let bytes = decode_magic_escapes(stripped);
1879                MagicTest::String16Le {
1880                    pattern: bytes,
1881                    flags,
1882                    op: RelOp::Lt,
1883                }
1884            } else if let Some(stripped) = val_str.strip_prefix('!') {
1885                let bytes = decode_magic_escapes(stripped);
1886                MagicTest::String16Le {
1887                    pattern: bytes,
1888                    flags,
1889                    op: RelOp::Ne,
1890                }
1891            } else if let Some(stripped) = val_str.strip_prefix('=') {
1892                let bytes = decode_magic_escapes(stripped);
1893                MagicTest::String16Le {
1894                    pattern: bytes,
1895                    flags,
1896                    op: RelOp::Eq,
1897                }
1898            } else {
1899                let bytes = decode_magic_escapes(val_str);
1900                MagicTest::String16Le {
1901                    pattern: bytes,
1902                    flags,
1903                    op: RelOp::Eq,
1904                }
1905            }
1906        }
1907        "bestring16" => {
1908            let flags = parse_string_flags(flags_str);
1909            if val_str == "x" {
1910                MagicTest::String16BeAny(flags)
1911            } else if let Some(stripped) = val_str.strip_prefix('>') {
1912                let bytes = decode_magic_escapes(stripped);
1913                MagicTest::String16Be {
1914                    pattern: bytes,
1915                    flags,
1916                    op: RelOp::Gt,
1917                }
1918            } else if let Some(stripped) = val_str.strip_prefix('<') {
1919                let bytes = decode_magic_escapes(stripped);
1920                MagicTest::String16Be {
1921                    pattern: bytes,
1922                    flags,
1923                    op: RelOp::Lt,
1924                }
1925            } else if let Some(stripped) = val_str.strip_prefix('!') {
1926                let bytes = decode_magic_escapes(stripped);
1927                MagicTest::String16Be {
1928                    pattern: bytes,
1929                    flags,
1930                    op: RelOp::Ne,
1931                }
1932            } else if let Some(stripped) = val_str.strip_prefix('=') {
1933                let bytes = decode_magic_escapes(stripped);
1934                MagicTest::String16Be {
1935                    pattern: bytes,
1936                    flags,
1937                    op: RelOp::Eq,
1938                }
1939            } else {
1940                let bytes = decode_magic_escapes(val_str);
1941                MagicTest::String16Be {
1942                    pattern: bytes,
1943                    flags,
1944                    op: RelOp::Eq,
1945                }
1946            }
1947        }
1948        "levarint" => {
1949            let mask = mask_str.and_then(parse_magic_int);
1950            let (op, num_str) = parse_op_and_val(val_str);
1951            if op == RelOp::Any {
1952                MagicTest::VarintLe {
1953                    value: 0,
1954                    op: RelOp::Any,
1955                    mask,
1956                }
1957            } else {
1958                let val = parse_magic_int(num_str)?;
1959                MagicTest::VarintLe {
1960                    value: val,
1961                    op,
1962                    mask,
1963                }
1964            }
1965        }
1966        "bevarint" => {
1967            let mask = mask_str.and_then(parse_magic_int);
1968            let (op, num_str) = parse_op_and_val(val_str);
1969            if op == RelOp::Any {
1970                MagicTest::VarintBe {
1971                    value: 0,
1972                    op: RelOp::Any,
1973                    mask,
1974                }
1975            } else {
1976                let val = parse_magic_int(num_str)?;
1977                MagicTest::VarintBe {
1978                    value: val,
1979                    op,
1980                    mask,
1981                }
1982            }
1983        }
1984        "qwdate" | "beqwdate" => {
1985            let (op, num_str) = parse_op_and_val(val_str);
1986            if op == RelOp::Any {
1987                MagicTest::DateWindows64Be {
1988                    value: 0,
1989                    op: RelOp::Any,
1990                    adjustment: type_adj,
1991                }
1992            } else {
1993                let val = parse_magic_int(num_str)?;
1994                MagicTest::DateWindows64Be {
1995                    value: val,
1996                    op,
1997                    adjustment: type_adj,
1998                }
1999            }
2000        }
2001        "leqwdate" => {
2002            let (op, num_str) = parse_op_and_val(val_str);
2003            if op == RelOp::Any {
2004                MagicTest::DateWindows64Le {
2005                    value: 0,
2006                    op: RelOp::Any,
2007                    adjustment: type_adj,
2008                }
2009            } else {
2010                let val = parse_magic_int(num_str)?;
2011                MagicTest::DateWindows64Le {
2012                    value: val,
2013                    op,
2014                    adjustment: type_adj,
2015                }
2016            }
2017        }
2018        "octal" => {
2019            if val_str == "x" {
2020                MagicTest::Octal {
2021                    pattern: Vec::new(),
2022                    is_any: true,
2023                }
2024            } else {
2025                let bytes = decode_magic_escapes(val_str);
2026                MagicTest::Octal {
2027                    pattern: bytes,
2028                    is_any: false,
2029                }
2030            }
2031        }
2032        "offset" => MagicTest::OffsetVal,
2033        "default" => MagicTest::Default,
2034        "clear" => MagicTest::Clear,
2035        "der" => {
2036            let pat = crate::der::parse_der_pattern(val_str)?;
2037            MagicTest::Der(pat)
2038        }
2039        _ if base_type_no_adj.starts_with("search") => {
2040            let (flags, max_bytes) = parse_search_flags(flags_str);
2041            let (negated, target_val) =
2042                if let Some(stripped) = val_str.strip_prefix('!') {
2043                    (true, stripped)
2044                } else if let Some(stripped) = val_str.strip_prefix('=') {
2045                    (false, stripped)
2046                } else {
2047                    (false, val_str)
2048                };
2049            let bytes = decode_magic_escapes(target_val);
2050            MagicTest::Search {
2051                pattern: bytes,
2052                max_bytes,
2053                flags,
2054                negated,
2055            }
2056        }
2057        _ => return None,
2058    };
2059
2060    Some((cont_level, offset, cond, test, description))
2061}
2062
2063fn parse_op_and_val(raw: &str) -> (RelOp, &str) {
2064    let trimmed = raw.trim();
2065    if trimmed == "x" {
2066        (RelOp::Any, "")
2067    } else if let Some(s) = trimmed.strip_prefix('=') {
2068        (RelOp::Eq, s.trim())
2069    } else if let Some(s) = trimmed.strip_prefix('!') {
2070        (RelOp::Ne, s.trim())
2071    } else if let Some(s) = trimmed.strip_prefix('>') {
2072        (RelOp::Gt, s.trim())
2073    } else if let Some(s) = trimmed.strip_prefix('<') {
2074        (RelOp::Lt, s.trim())
2075    } else if let Some(s) = trimmed.strip_prefix('&') {
2076        (RelOp::BitAnd, s.trim())
2077    } else if let Some(s) = trimmed.strip_prefix('^') {
2078        (RelOp::BitClear, s.trim())
2079    } else {
2080        (RelOp::Eq, trimmed)
2081    }
2082}
2083
2084// Reason for fallback: pattern length exceeding u32::MAX saturates to u32::MAX
2085fn pattern_len_strength(len: usize) -> u32 {
2086    u32::try_from(len).unwrap_or(u32::MAX)
2087}
2088
2089/// Calculates rule strength faithful to upstream `apprentice_magic_strength_1`.
2090pub fn calculate_rule_strength(test: &MagicTest) -> u32 {
2091    let mult = 10u32;
2092    let base = 20u32;
2093    match test {
2094        MagicTest::Default => 0,
2095        MagicTest::Clear
2096        | MagicTest::Name(_)
2097        | MagicTest::Use(_)
2098        | MagicTest::Indirect => 0,
2099        MagicTest::ExactBytes(b) => base
2100            .saturating_add(pattern_len_strength(b.len()).saturating_mul(mult)),
2101        MagicTest::MaskedBytes { bytes, .. } => base.saturating_add(
2102            pattern_len_strength(bytes.len()).saturating_mul(mult),
2103        ),
2104        MagicTest::String { pattern, .. } => base.saturating_add(
2105            pattern_len_strength(pattern.len()).saturating_mul(mult),
2106        ),
2107        MagicTest::StringAny(_) => 0,
2108        MagicTest::StringRelOp { pattern, .. } => base.saturating_add(
2109            pattern_len_strength(pattern.len()).saturating_mul(mult),
2110        ),
2111        MagicTest::PascalString { pattern, .. } => base.saturating_add(
2112            pattern_len_strength(pattern.len()).saturating_mul(mult),
2113        ),
2114        MagicTest::PascalStringAny { .. } => 20,
2115        MagicTest::Search { pattern, .. } => base.saturating_add(
2116            pattern_len_strength(pattern.len()).saturating_mul(mult),
2117        ),
2118        MagicTest::Regex { pattern, .. } => base.saturating_add(
2119            pattern_len_strength(pattern.len().min(10)).saturating_mul(mult),
2120        ),
2121        MagicTest::U8 { op, .. } => {
2122            if *op == RelOp::Any {
2123                0
2124            } else {
2125                base.saturating_add(10)
2126            }
2127        }
2128        MagicTest::U16Le { op, .. } | MagicTest::U16Be { op, .. } => {
2129            if *op == RelOp::Any {
2130                0
2131            } else {
2132                base.saturating_add(20)
2133            }
2134        }
2135        MagicTest::U32Le { op, .. } | MagicTest::U32Be { op, .. } => {
2136            if *op == RelOp::Any {
2137                0
2138            } else {
2139                base.saturating_add(40)
2140            }
2141        }
2142        MagicTest::U64Le { op, .. } | MagicTest::U64Be { op, .. } => {
2143            if *op == RelOp::Any {
2144                0
2145            } else {
2146                base.saturating_add(80)
2147            }
2148        }
2149        MagicTest::Date32Le { op, .. } | MagicTest::Date32Be { op, .. } => {
2150            if *op == RelOp::Any {
2151                0
2152            } else {
2153                base.saturating_add(40)
2154            }
2155        }
2156        MagicTest::Date64Le { op, .. } | MagicTest::Date64Be { op, .. } => {
2157            if *op == RelOp::Any {
2158                0
2159            } else {
2160                base.saturating_add(80)
2161            }
2162        }
2163        MagicTest::Guid(_) | MagicTest::GuidLe(_) | MagicTest::GuidBe(_) => {
2164            base.saturating_add(160)
2165        }
2166        MagicTest::GuidLeAny | MagicTest::GuidBeAny => 0,
2167        MagicTest::FloatLe { op, .. } | MagicTest::FloatBe { op, .. } => {
2168            if *op == RelOp::Any {
2169                0
2170            } else {
2171                base.saturating_add(40)
2172            }
2173        }
2174        MagicTest::DoubleLe { op, .. } | MagicTest::DoubleBe { op, .. } => {
2175            if *op == RelOp::Any {
2176                0
2177            } else {
2178                base.saturating_add(80)
2179            }
2180        }
2181        MagicTest::String16Le { pattern, .. }
2182        | MagicTest::String16Be { pattern, .. } => {
2183            // Reason for fallback: Divisor 2 is non-zero so dividing 16-bit byte length to character count cannot fail.
2184            let char_count = pattern.len().checked_div(2).unwrap_or(0);
2185            base.saturating_add(
2186                pattern_len_strength(char_count).saturating_mul(mult),
2187            )
2188        }
2189        MagicTest::String16LeAny(_) | MagicTest::String16BeAny(_) => 0,
2190        MagicTest::VarintLe { op, .. } | MagicTest::VarintBe { op, .. } => {
2191            if *op == RelOp::Any {
2192                0
2193            } else {
2194                base.saturating_add(80)
2195            }
2196        }
2197        MagicTest::DateWindows64Le { op, .. }
2198        | MagicTest::DateWindows64Be { op, .. } => {
2199            if *op == RelOp::Any {
2200                0
2201            } else {
2202                base.saturating_add(80)
2203            }
2204        }
2205        MagicTest::Octal { pattern, is_any } => {
2206            if *is_any {
2207                0
2208            } else {
2209                base.saturating_add(
2210                    pattern_len_strength(pattern.len()).saturating_mul(mult),
2211                )
2212            }
2213        }
2214        MagicTest::MsDosDate | MagicTest::MsDosTime | MagicTest::OffsetVal => {
2215            base.saturating_add(20)
2216        }
2217        MagicTest::Der(pat) => {
2218            if pat.expected_val.as_deref() == Some("x")
2219                || (pat.expected_len.is_none() && pat.expected_val.is_none())
2220            {
2221                base
2222            } else {
2223                base.saturating_add(mult)
2224            }
2225        }
2226    }
2227}
2228
2229/// Parses an entire libmagic file content into hierarchical root rules and named templates.
2230pub fn parse_magic_content_with_templates(
2231    content: &str,
2232) -> (
2233    Vec<HierarchicalMagicRule>,
2234    std::collections::HashMap<String, HierarchicalMagicRule>,
2235) {
2236    let mut root_rules = Vec::new();
2237    let mut named_templates: std::collections::HashMap<
2238        String,
2239        HierarchicalMagicRule,
2240    > = std::collections::HashMap::new();
2241    let mut stack: Vec<HierarchicalMagicRule> = Vec::new();
2242    let mut current_template_name: Option<String> = None;
2243
2244    for line in content.lines() {
2245        let trimmed = line.trim();
2246        if trimmed.is_empty() || trimmed.starts_with('#') {
2247            continue;
2248        }
2249
2250        // Check directives: !:mime, !:ext, !:apple, !:strength
2251        if let Some(directive) = trimmed.strip_prefix("!:") {
2252            let parts: Vec<&str> =
2253                directive.splitn(2, char::is_whitespace).collect();
2254            // Reason for fallback: empty directive parts default to empty string
2255            let name = parts.first().copied().unwrap_or("");
2256            // Reason for fallback: directive without value defaults to empty string
2257            let val = parts.get(1).copied().unwrap_or("").trim();
2258
2259            if let Some(target) = stack.last_mut() {
2260                match name {
2261                    "mime" => target.mime = Some(val.to_string()),
2262                    "ext" => target.ext = Some(val.to_string()),
2263                    "apple" => target.apple = Some(val.to_string()),
2264                    "strength" => {
2265                        let clean = val.replace(' ', "");
2266                        if let Some(root_target) = stack.first_mut() {
2267                            if let Some(rest) = clean.strip_prefix('+') {
2268                                if let Ok(delta) = rest.parse::<u32>() {
2269                                    root_target.strength = root_target
2270                                        .strength
2271                                        .saturating_add(delta);
2272                                }
2273                            } else if let Some(rest) = clean.strip_prefix('-') {
2274                                if let Ok(delta) = rest.parse::<u32>() {
2275                                    root_target.strength = root_target
2276                                        .strength
2277                                        .saturating_sub(delta);
2278                                }
2279                            } else if let Some(rest) = clean.strip_prefix('*') {
2280                                if let Ok(factor) = rest.parse::<u32>() {
2281                                    root_target.strength = root_target
2282                                        .strength
2283                                        .saturating_mul(factor);
2284                                }
2285                            } else if let Some(rest) = clean.strip_prefix('/') {
2286                                if let Ok(div) = rest.parse::<u32>() {
2287                                    if let Some(res) =
2288                                        root_target.strength.checked_div(div)
2289                                    {
2290                                        root_target.strength = res;
2291                                    }
2292                                }
2293                            } else if let Ok(s) = clean.parse::<u32>() {
2294                                root_target.strength = s;
2295                            }
2296                        }
2297                    }
2298                    _ => {}
2299                }
2300            }
2301            continue;
2302        }
2303
2304        let Some((level, offset, cond, test, description)) =
2305            parse_magic_line(trimmed)
2306        else {
2307            continue;
2308        };
2309
2310        let initial_strength = calculate_rule_strength(&test);
2311        let new_rule = HierarchicalMagicRule {
2312            cont_level: level,
2313            offset,
2314            cond,
2315            test,
2316            description,
2317            mime: None,
2318            ext: None,
2319            apple: None,
2320            strength: initial_strength,
2321            children: Vec::new(),
2322        };
2323
2324        if level == 0 {
2325            // Pop entire stack and store in root_rules or named_templates
2326            if let Some(root) = collapse_stack(&mut stack) {
2327                if let Some(tpl_name) = current_template_name.take() {
2328                    named_templates.insert(tpl_name, root);
2329                } else {
2330                    root_rules.push(root);
2331                }
2332            }
2333
2334            if let MagicTest::Name(ref tpl_name) = new_rule.test {
2335                current_template_name = Some(tpl_name.clone());
2336            } else {
2337                current_template_name = None;
2338            }
2339
2340            stack.push(new_rule);
2341        } else {
2342            if stack.is_empty() {
2343                continue;
2344            }
2345            while stack.len() > level {
2346                let popped = match stack.pop() {
2347                    Some(p) => p,
2348                    None => break,
2349                };
2350                if let Some(parent) = stack.last_mut() {
2351                    parent.children.push(popped);
2352                }
2353            }
2354            stack.push(new_rule);
2355        }
2356    }
2357
2358    if let Some(root) = collapse_stack(&mut stack) {
2359        if let Some(tpl_name) = current_template_name.take() {
2360            named_templates.insert(tpl_name, root);
2361        } else {
2362            root_rules.push(root);
2363        }
2364    }
2365
2366    (root_rules, named_templates)
2367}
2368
2369/// Parses an entire libmagic file content into a list of hierarchical root rules.
2370pub fn parse_magic_content(content: &str) -> Vec<HierarchicalMagicRule> {
2371    parse_magic_content_with_templates(content).0
2372}
2373
2374fn collapse_stack(
2375    stack: &mut Vec<HierarchicalMagicRule>,
2376) -> Option<HierarchicalMagicRule> {
2377    while stack.len() > 1 {
2378        let child = stack.pop()?;
2379        if let Some(parent) = stack.last_mut() {
2380            parent.children.push(child);
2381        }
2382    }
2383    stack.pop()
2384}
2385
2386#[cfg(test)]
2387#[allow(
2388    clippy::panic,
2389    clippy::expect_used,
2390    clippy::unwrap_used,
2391    clippy::unwrap_in_result,
2392    clippy::panic_in_result_fn,
2393    clippy::indexing_slicing,
2394    clippy::arithmetic_side_effects,
2395    reason = "Standard repository test boilerplate"
2396)]
2397mod tests {
2398    use super::*;
2399
2400    #[crate::ctb_test]
2401    fn test_parse_simple_libmagic_rule() {
2402        let content = r"
2403# Gzip rule
24040	string		\037\213	gzip compressed data
2405!:mime	application/gzip
2406!:ext	gz
2407>2	byte		8		deflated
2408";
2409        let rules = parse_magic_content(content);
2410        assert_eq!(rules.len(), 1);
2411        let root = &rules[0];
2412        assert_eq!(root.cont_level, 0);
2413        assert_eq!(root.offset, Offset::Bof(0));
2414        assert_eq!(root.test, MagicTest::ExactBytes(vec![0x1F, 0x8B]));
2415        assert_eq!(root.mime, Some("application/gzip".to_string()));
2416        assert_eq!(root.ext, Some("gz".to_string()));
2417        assert_eq!(root.children.len(), 1);
2418        assert_eq!(root.children[0].cont_level, 1);
2419    }
2420
2421    #[crate::ctb_test]
2422    fn test_parse_relative_and_indirect_offsets() {
2423        let content = r"
24240	string		MZ		DOS executable
2425>(0x3c.l)	string	PE\0\0		PE executable
2426>>&0	leshort		0x014c		for Intel 80386
2427>>(&4.s+2)	byte	x		subsystem
2428";
2429        let rules = parse_magic_content(content);
2430        assert_eq!(rules.len(), 1);
2431        let pe_child = &rules[0].children[0];
2432        assert_eq!(
2433            pe_child.offset,
2434            Offset::Indirect {
2435                base: Box::new(Offset::Bof(0x3c)),
2436                ind_type: IndirectType::LongLe,
2437                is_signed: false,
2438                is_inverse: false,
2439                op: None,
2440                adjustment: 0,
2441            }
2442        );
2443        let rel_child = &pe_child.children[0];
2444        assert_eq!(rel_child.offset, Offset::Relative(0));
2445        let ind_rel = &pe_child.children[1];
2446        assert_eq!(
2447            ind_rel.offset,
2448            Offset::Indirect {
2449                base: Box::new(Offset::Relative(4)),
2450                ind_type: IndirectType::ShortLe,
2451                is_signed: false,
2452                is_inverse: false,
2453                op: None,
2454                adjustment: 2,
2455            }
2456        );
2457    }
2458
2459    #[crate::ctb_test]
2460    fn test_parse_negative_indirect_base_and_multiplier() {
2461        let content = r"
24620	string		TEST		Test Header
2463>(-6.l)	string		FOOT		negative base indirect
2464>(4.l*4+16)	string		DATA		multiplied indirect
2465>(6.I+10)	string		TAG1		id3 big-endian synchsafe
2466>(6.i+10)	string		TAG2		id3 little-endian synchsafe
2467>0	search/64	!NOTFOUND	negated search
2468>0	indirect	x		recursive indirect magic
2469";
2470        let rules = parse_magic_content(content);
2471        assert_eq!(rules.len(), 1);
2472        let root = &rules[0];
2473        assert_eq!(root.children.len(), 6);
2474        assert_eq!(
2475            root.children[0].offset,
2476            Offset::Indirect {
2477                base: Box::new(Offset::Eof(6)),
2478                ind_type: IndirectType::LongLe,
2479                is_signed: false,
2480                is_inverse: false,
2481                op: None,
2482                adjustment: 0,
2483            }
2484        );
2485        assert_eq!(
2486            root.children[1].offset,
2487            Offset::Indirect {
2488                base: Box::new(Offset::Bof(4)),
2489                ind_type: IndirectType::LongLe,
2490                is_signed: false,
2491                is_inverse: false,
2492                op: Some(IndirectOp::Mul(4)),
2493                adjustment: 16,
2494            }
2495        );
2496        assert_eq!(
2497            root.children[2].offset,
2498            Offset::Indirect {
2499                base: Box::new(Offset::Bof(6)),
2500                ind_type: IndirectType::Id3Be,
2501                is_signed: false,
2502                is_inverse: false,
2503                op: None,
2504                adjustment: 10,
2505            }
2506        );
2507        assert_eq!(
2508            root.children[3].offset,
2509            Offset::Indirect {
2510                base: Box::new(Offset::Bof(6)),
2511                ind_type: IndirectType::Id3Le,
2512                is_signed: false,
2513                is_inverse: false,
2514                op: None,
2515                adjustment: 10,
2516            }
2517        );
2518        assert!(matches!(
2519            root.children[4].test,
2520            MagicTest::Search { negated: true, ref pattern, .. } if pattern == b"NOTFOUND"
2521        ));
2522        assert_eq!(root.children[5].test, MagicTest::Indirect);
2523    }
2524
2525    #[crate::ctb_test]
2526    fn test_parse_quad_dates_and_flags() {
2527        let content = r"
25280	lequad		0x123456789abcdef0	quad match
2529>8	date		x			modified %s
2530>12	pstring/H	foo			pascal string
2531>20	string/c	bar			case-insensitive bar
2532>30	regex/c/1024	^BEGIN			regex match
2533";
2534        let rules = parse_magic_content(content);
2535        assert_eq!(rules.len(), 1);
2536        let root = &rules[0];
2537        assert_eq!(
2538            root.test,
2539            MagicTest::U64Le {
2540                value: 0x123456789abcdef0,
2541                op: RelOp::Eq,
2542                mask: None,
2543                num_op: NumOp::None,
2544            }
2545        );
2546        assert_eq!(root.children.len(), 4);
2547        assert_eq!(
2548            root.children[0].test,
2549            MagicTest::Date32Be {
2550                value: 0,
2551                op: RelOp::Any,
2552                adjustment: 0,
2553            }
2554        );
2555        assert_eq!(
2556            root.children[1].test,
2557            MagicTest::PascalString {
2558                pattern: b"foo".to_vec(),
2559                length_size: PascalLengthSize::ShortBe,
2560                length_includes_itself: false,
2561            }
2562        );
2563    }
2564
2565    #[crate::ctb_test]
2566    fn test_parse_named_templates_and_use() {
2567        let content = r"
25680	name		elf-details
2569>4	byte		1		32-bit
2570>4	byte		2		64-bit
2571
25720	string		\177ELF		ELF file
2573>0	use		elf-details
2574";
2575        let (rules, templates) = parse_magic_content_with_templates(content);
2576        assert_eq!(templates.len(), 1);
2577        assert!(templates.contains_key("elf-details"));
2578        let tpl = &templates["elf-details"];
2579        assert_eq!(tpl.children.len(), 2);
2580
2581        assert_eq!(rules.len(), 1);
2582        assert_eq!(rules[0].children.len(), 1);
2583        assert_eq!(
2584            rules[0].children[0].test,
2585            MagicTest::Use("elf-details".to_string())
2586        );
2587    }
2588
2589    #[crate::ctb_test]
2590    fn test_parse_new_magic_types() {
2591        let content = r"
25920	string		TEST		Header
2593>0	lefloat		>0.0001		lefloat rule
2594>4	befloat		!0.0		befloat rule
2595>8	ledouble	8.642135e+130	ledouble rule
2596>16	bedouble	x		bedouble wildcard
2597>24	lestring16	Workbook	lestring16 match
2598>32	bestring16/c	Title		bestring16 case-insensitive
2599>40	lestring16	x		lestring16 any
2600>48	bestring16	x		bestring16 any
2601>56	levarint	300		levarint rule
2602>64	bevarint&0xFF	120		bevarint with mask
2603>72	qwdate+3600	x		qwdate with adjustment
2604>80	leqwdate	>1000		leqwdate rule
2605>88	octal		0755		octal pattern
2606>96	octal		x		octal any
2607>104	guid		7B5C52E4-D88C-4DA7-AEB1-5378D02996D3	guid match
2608>120	leguid		x		leguid any
2609>136	beguid		00112233-4455-6677-8899-AABBCCDDEEFF	beguid match
2610>152	beguid		x		beguid any
2611";
2612        let rules = parse_magic_content(content);
2613        assert_eq!(rules.len(), 1);
2614        let root = &rules[0];
2615        assert_eq!(root.children.len(), 18);
2616
2617        // lefloat >0.0001
2618        assert!(matches!(
2619            root.children[0].test,
2620            MagicTest::FloatLe { op: RelOp::Gt, .. }
2621        ));
2622        // befloat !0.0
2623        assert!(matches!(
2624            root.children[1].test,
2625            MagicTest::FloatBe { op: RelOp::Ne, .. }
2626        ));
2627        // ledouble
2628        assert!(matches!(
2629            root.children[2].test,
2630            MagicTest::DoubleLe { op: RelOp::Eq, .. }
2631        ));
2632        // bedouble x
2633        assert!(matches!(
2634            root.children[3].test,
2635            MagicTest::DoubleBe { op: RelOp::Any, .. }
2636        ));
2637        // lestring16 Workbook
2638        assert!(
2639            matches!(root.children[4].test, MagicTest::String16Le { ref pattern, op: RelOp::Eq, .. } if pattern == b"Workbook")
2640        );
2641        // bestring16/c Title
2642        assert!(
2643            matches!(root.children[5].test, MagicTest::String16Be { ref pattern, flags, .. } if pattern == b"Title" && flags.case_insensitive)
2644        );
2645        // lestring16 x / bestring16 x
2646        assert!(matches!(root.children[6].test, MagicTest::String16LeAny(_)));
2647        assert!(matches!(root.children[7].test, MagicTest::String16BeAny(_)));
2648        // levarint / bevarint
2649        assert!(matches!(
2650            root.children[8].test,
2651            MagicTest::VarintLe {
2652                value: 300,
2653                op: RelOp::Eq,
2654                mask: None
2655            }
2656        ));
2657        assert!(matches!(
2658            root.children[9].test,
2659            MagicTest::VarintBe {
2660                value: 120,
2661                op: RelOp::Eq,
2662                mask: Some(0xFF)
2663            }
2664        ));
2665        // qwdate / leqwdate
2666        assert!(matches!(
2667            root.children[10].test,
2668            MagicTest::DateWindows64Be {
2669                op: RelOp::Any,
2670                adjustment: 3600,
2671                ..
2672            }
2673        ));
2674        assert!(matches!(
2675            root.children[11].test,
2676            MagicTest::DateWindows64Le {
2677                value: 1000,
2678                op: RelOp::Gt,
2679                ..
2680            }
2681        ));
2682        // octal
2683        assert!(
2684            matches!(root.children[12].test, MagicTest::Octal { ref pattern, is_any: false } if pattern == b"0755")
2685        );
2686        assert!(matches!(
2687            root.children[13].test,
2688            MagicTest::Octal { is_any: true, .. }
2689        ));
2690        // guid / leguid / beguid
2691        assert!(matches!(root.children[14].test, MagicTest::GuidLe(_)));
2692        assert!(matches!(root.children[15].test, MagicTest::GuidLeAny));
2693        assert!(matches!(root.children[16].test, MagicTest::GuidBe(_)));
2694        assert!(matches!(root.children[17].test, MagicTest::GuidBeAny));
2695    }
2696
2697    #[crate::ctb_test]
2698    fn test_parse_indirect_operators_and_modifiers() {
2699        let content = r"
27000	string		TEST		Header
2701>(4.s*2)	leshort		1		mul test
2702>(4.l&0xFF)	lelong		2		and test
2703>(4.l|0x01)	lelong		3		or test
2704>(4.l^0x0F)	lelong		4		xor test
2705>(4.l/4)	lelong		5		div test
2706>(4.l%8)	lelong		6		mod test
2707>(~4.l)		lelong		7		inverse test
2708>(4,l+10)	lelong		8		signed test
2709";
2710        let rules = parse_magic_content(content);
2711        assert_eq!(rules.len(), 1);
2712        let root = &rules[0];
2713        assert_eq!(root.children.len(), 8);
2714
2715        assert_eq!(
2716            root.children[0].offset,
2717            Offset::Indirect {
2718                base: Box::new(Offset::Bof(4)),
2719                ind_type: IndirectType::ShortLe,
2720                is_signed: false,
2721                is_inverse: false,
2722                op: Some(IndirectOp::Mul(2)),
2723                adjustment: 0,
2724            }
2725        );
2726        assert_eq!(
2727            root.children[1].offset,
2728            Offset::Indirect {
2729                base: Box::new(Offset::Bof(4)),
2730                ind_type: IndirectType::LongLe,
2731                is_signed: false,
2732                is_inverse: false,
2733                op: Some(IndirectOp::And(0xFF)),
2734                adjustment: 0,
2735            }
2736        );
2737        assert_eq!(
2738            root.children[2].offset,
2739            Offset::Indirect {
2740                base: Box::new(Offset::Bof(4)),
2741                ind_type: IndirectType::LongLe,
2742                is_signed: false,
2743                is_inverse: false,
2744                op: Some(IndirectOp::Or(0x01)),
2745                adjustment: 0,
2746            }
2747        );
2748        assert_eq!(
2749            root.children[3].offset,
2750            Offset::Indirect {
2751                base: Box::new(Offset::Bof(4)),
2752                ind_type: IndirectType::LongLe,
2753                is_signed: false,
2754                is_inverse: false,
2755                op: Some(IndirectOp::Xor(0x0F)),
2756                adjustment: 0,
2757            }
2758        );
2759        assert_eq!(
2760            root.children[4].offset,
2761            Offset::Indirect {
2762                base: Box::new(Offset::Bof(4)),
2763                ind_type: IndirectType::LongLe,
2764                is_signed: false,
2765                is_inverse: false,
2766                op: Some(IndirectOp::Div(4)),
2767                adjustment: 0,
2768            }
2769        );
2770        assert_eq!(
2771            root.children[5].offset,
2772            Offset::Indirect {
2773                base: Box::new(Offset::Bof(4)),
2774                ind_type: IndirectType::LongLe,
2775                is_signed: false,
2776                is_inverse: false,
2777                op: Some(IndirectOp::Mod(8)),
2778                adjustment: 0,
2779            }
2780        );
2781        assert_eq!(
2782            root.children[6].offset,
2783            Offset::Indirect {
2784                base: Box::new(Offset::Bof(4)),
2785                ind_type: IndirectType::LongLe,
2786                is_signed: false,
2787                is_inverse: true,
2788                op: None,
2789                adjustment: 0,
2790            }
2791        );
2792        assert_eq!(
2793            root.children[7].offset,
2794            Offset::Indirect {
2795                base: Box::new(Offset::Bof(4)),
2796                ind_type: IndirectType::LongLe,
2797                is_signed: true,
2798                is_inverse: false,
2799                op: None,
2800                adjustment: 10,
2801            }
2802        );
2803    }
2804
2805    #[crate::ctb_test]
2806    fn test_parse_conditionals_and_string_flags() {
2807        let content = r"
28080	string/w	TEST		Header
2809>0	if		byte	1	if branch
2810>>4	string/f	hello		word boundary
2811>0	elif		byte	2	elif branch
2812>>4	string/t	world		text only
2813>0	else		else branch
2814>>4	string/b	raw		binary only
2815>0	clear		x
2816";
2817        let rules = parse_magic_content(content);
2818        assert_eq!(rules.len(), 1);
2819        let root = &rules[0];
2820        assert_eq!(root.cond, MagicCond::None);
2821        assert!(
2822            matches!(root.test, MagicTest::String { flags, .. } if flags.optional_whitespace)
2823        );
2824        assert_eq!(root.children.len(), 4);
2825        assert_eq!(root.children[0].cond, MagicCond::If);
2826        assert!(
2827            matches!(root.children[0].children[0].test, MagicTest::String { flags, .. } if flags.full_word)
2828        );
2829        assert_eq!(root.children[1].cond, MagicCond::Elif);
2830        assert!(
2831            matches!(root.children[1].children[0].test, MagicTest::String { flags, .. } if flags.text_only)
2832        );
2833        assert_eq!(root.children[2].cond, MagicCond::Else);
2834        assert!(
2835            matches!(root.children[2].children[0].test, MagicTest::String { flags, .. } if flags.binary_only)
2836        );
2837        assert_eq!(root.children[3].test, MagicTest::Clear);
2838    }
2839}
2840/*
2841/*
2842 * Adapted from: apptype.c, Written by Eberhard Mattes and put into the
2843 * file_public domain
2844 *
2845 * Notes: 1. Qualify the filename so that DosQueryAppType does not do extraneous
2846 * searches.
2847 *
2848 * 2. DosQueryAppType will return FAPPTYP_DOS on a file ending with ".com"
2849 * (other than an OS/2 exe or Win exe with this name). Eberhard Mattes
2850 * remarks Tue, 6 Apr 93: Moreover, it reports the type of the (new and very
2851 * bug ridden) Win Emacs as "OS/2 executable".
2852 *
2853 * 3. apptype() uses the filename if given, otherwise a tmp file is created with
2854 * the contents of buf. If buf is not the complete file, apptype can
2855 * incorrectly identify the exe type. The "-z" option of "file" is the reason
2856 * for this ugly code.
2857 */
2858
2859The preceding notice is from src/apptype.c in `file`.
2860
2861
2862
2863/*-
2864 * Copyright (c) 2008 Christos Zoulas
2865 * All rights reserved.
2866 *
2867 * Redistribution and use in source and binary forms, with or without
2868 * modification, are permitted provided that the following conditions
2869 * are met:
2870 * 1. Redistributions of source code must retain the above copyright
2871 *    notice, this list of conditions and the following disclaimer.
2872 * 2. Redistributions in binary form must reproduce the above copyright
2873 *    notice, this list of conditions and the following disclaimer in the
2874 *    documentation and/or other materials provided with the distribution.
2875 *
2876 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
2877 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
2878 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
2879 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
2880 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
2881 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
2882 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
2883 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
2884 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
2885 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
2886 * POSSIBILITY OF SUCH DAMAGE.
2887 */
2888
2889The preceding notice is from src/cdf.c, src/cdf.h, and src/cdf_time.c in `file`.
2890
2891
2892
2893/*-
2894 * Copyright (c) 2016 Christos Zoulas
2895 * All rights reserved.
2896 *
2897 * Redistribution and use in source and binary forms, with or without
2898 * modification, are permitted provided that the following conditions
2899 * are met:
2900 * 1. Redistributions of source code must retain the above copyright
2901 *    notice, this list of conditions and the following disclaimer.
2902 * 2. Redistributions in binary form must reproduce the above copyright
2903 *    notice, this list of conditions and the following disclaimer in the
2904 *    documentation and/or other materials provided with the distribution.
2905 *
2906 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
2907 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
2908 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
2909 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
2910 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
2911 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
2912 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
2913 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
2914 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
2915 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
2916 * POSSIBILITY OF SUCH DAMAGE.
2917 */
2918
2919The preceding notice is from src/der.c and src/der.h in `file`.
2920
2921
2922
2923/*-
2924 * Copyright (c) 2019 Christos Zoulas
2925 * All rights reserved.
2926 *
2927 * Redistribution and use in source and binary forms, with or without
2928 * modification, are permitted provided that the following conditions
2929 * are met:
2930 * 1. Redistributions of source code must retain the above copyright
2931 *    notice, this list of conditions and the following disclaimer.
2932 * 2. Redistributions in binary form must reproduce the above copyright
2933 *    notice, this list of conditions and the following disclaimer in the
2934 *    documentation and/or other materials provided with the distribution.
2935 *
2936 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
2937 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
2938 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
2939 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
2940 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
2941 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
2942 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
2943 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
2944 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
2945 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
2946 * POSSIBILITY OF SUCH DAMAGE.
2947 */
2948
2949The preceding notice is from src/is_csv.c in `file`.
2950
2951
2952
2953/*-
2954 * Copyright (c) 2018 Christos Zoulas
2955 * All rights reserved.
2956 *
2957 * Redistribution and use in source and binary forms, with or without
2958 * modification, are permitted provided that the following conditions
2959 * are met:
2960 * 1. Redistributions of source code must retain the above copyright
2961 *    notice, this list of conditions and the following disclaimer.
2962 * 2. Redistributions in binary form must reproduce the above copyright
2963 *    notice, this list of conditions and the following disclaimer in the
2964 *    documentation and/or other materials provided with the distribution.
2965 *
2966 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
2967 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
2968 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
2969 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
2970 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
2971 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
2972 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
2973 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
2974 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
2975 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
2976 * POSSIBILITY OF SUCH DAMAGE.
2977 */
2978
2979The preceding notice is from src/is_json.c in `file`.
2980
2981
2982
2983/*-
2984 * Copyright (c) 2023 Christos Zoulas
2985 * All rights reserved.
2986 *
2987 * Redistribution and use in source and binary forms, with or without
2988 * modification, are permitted provided that the following conditions
2989 * are met:
2990 * 1. Redistributions of source code must retain the above copyright
2991 *    notice, this list of conditions and the following disclaimer.
2992 * 2. Redistributions in binary form must reproduce the above copyright
2993 *    notice, this list of conditions and the following disclaimer in the
2994 *    documentation and/or other materials provided with the distribution.
2995 *
2996 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
2997 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
2998 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
2999 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
3000 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
3001 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
3002 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
3003 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
3004 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
3005 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
3006 * POSSIBILITY OF SUCH DAMAGE.
3007 */
3008
3009The preceding notice is from src/is_simh.c in `file`.
3010
3011
3012
3013/*-
3014 * SPDX-License-Identifier: BSD-3-Clause
3015 *
3016 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
3017 * Copyright (c) 1992, 1993, 1994
3018 *      The Regents of the University of California.  All rights reserved.
3019 *
3020 * This code is derived from software contributed to Berkeley by
3021 * Henry Spencer.
3022 *
3023 * Redistribution and use in source and binary forms, with or without
3024 * modification, are permitted provided that the following conditions
3025 * are met:
3026 * 1. Redistributions of source code must retain the above copyright
3027 *    notice, this list of conditions and the following disclaimer.
3028 * 2. Redistributions in binary form must reproduce the above copyright
3029 *    notice, this list of conditions and the following disclaimer in the
3030 *    documentation and/or other materials provided with the distribution.
3031 * 3. Neither the name of the University nor the names of its contributors
3032 *    may be used to endorse or promote products derived from this software
3033 *    without specific prior written permission.
3034 *
3035 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3036 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3037 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3038 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3039 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3040 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3041 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3042 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3043 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3044 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3045 * SUCH DAMAGE.
3046 *
3047 *      @(#)cname.h     8.3 (Berkeley) 3/20/94
3048 * $FreeBSD: head/lib/libc/regex/cname.h 326025 2017-11-20 19:49:47Z pfg $
3049 */
3050
3051The preceding notice is from src/missing/cname.h in `file`.
3052
3053
3054
3055/*-
3056 * SPDX-License-Identifier: BSD-3-Clause
3057 *
3058 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
3059 * Copyright (c) 1992, 1993, 1994
3060 *      The Regents of the University of California.  All rights reserved.
3061 *
3062 * This code is derived from software contributed to Berkeley by
3063 * Henry Spencer.
3064 *
3065 * Redistribution and use in source and binary forms, with or without
3066 * modification, are permitted provided that the following conditions
3067 * are met:
3068 * 1. Redistributions of source code must retain the above copyright
3069 *    notice, this list of conditions and the following disclaimer.
3070 * 2. Redistributions in binary form must reproduce the above copyright
3071 *    notice, this list of conditions and the following disclaimer in the
3072 *    documentation and/or other materials provided with the distribution.
3073 * 3. Neither the name of the University nor the names of its contributors
3074 *    may be used to endorse or promote products derived from this software
3075 *    without specific prior written permission.
3076 *
3077 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3078 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3079 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3080 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3081 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3082 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3083 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3084 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3085 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3086 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3087 * SUCH DAMAGE.
3088 *
3089 *      @(#)engine.c    8.5 (Berkeley) 3/20/94
3090 */
3091
3092The preceding notice is from src/missing/engine.c in `file`.
3093
3094
3095
3096/*-
3097 * Copyright (c) 2000 The NetBSD Foundation, Inc.
3098 * All rights reserved.
3099 *
3100 * This code was contributed to The NetBSD Foundation by Allen Briggs.
3101 *
3102 * Redistribution and use in source and binary forms, with or without
3103 * modification, are permitted provided that the following conditions
3104 * are met:
3105 * 1. Redistributions of source code must retain the above copyright
3106 *    notice, this list of conditions and the following disclaimer.
3107 * 2. Redistributions in binary form must reproduce the above copyright
3108 *    notice, this list of conditions and the following disclaimer in the
3109 *    documentation and/or other materials provided with the distribution.
3110 *
3111 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
3112 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
3113 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
3114 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
3115 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
3116 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
3117 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
3118 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
3119 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
3120 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
3121 * POSSIBILITY OF SUCH DAMAGE.
3122 */
3123
3124The preceding notice is from src/missing/fmtcheck.c in `file`.
3125
3126
3127
3128/*-
3129 * Copyright (c) 2011 The NetBSD Foundation, Inc.
3130 * All rights reserved.
3131 *
3132 * This code is derived from software contributed to The NetBSD Foundation
3133 * by Christos Zoulas.
3134 *
3135 * Redistribution and use in source and binary forms, with or without
3136 * modification, are permitted provided that the following conditions
3137 * are met:
3138 * 1. Redistributions of source code must retain the above copyright
3139 *    notice, this list of conditions and the following disclaimer.
3140 * 2. Redistributions in binary form must reproduce the above copyright
3141 *    notice, this list of conditions and the following disclaimer in the
3142 *    documentation and/or other materials provided with the distribution.
3143 *
3144 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
3145 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
3146 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
3147 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
3148 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
3149 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
3150 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
3151 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
3152 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
3153 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
3154 * POSSIBILITY OF SUCH DAMAGE.
3155 */
3156
3157The preceding notice is from src/missing/getline.c in `file`.
3158
3159
3160
3161/*-
3162 * Copyright (c) 2000 The NetBSD Foundation, Inc.
3163 * All rights reserved.
3164 *
3165 * This code is derived from software contributed to The NetBSD Foundation
3166 * by Dieter Baron and Thomas Klausner.
3167 *
3168 * Redistribution and use in source and binary forms, with or without
3169 * modification, are permitted provided that the following conditions
3170 * are met:
3171 * 1. Redistributions of source code must retain the above copyright
3172 *    notice, this list of conditions and the following disclaimer.
3173 * 2. Redistributions in binary form must reproduce the above copyright
3174 *    notice, this list of conditions and the following disclaimer in the
3175 *    documentation and/or other materials provided with the distribution.
3176 *
3177 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
3178 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
3179 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
3180 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
3181 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
3182 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
3183 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
3184 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
3185 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
3186 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
3187 * POSSIBILITY OF SUCH DAMAGE.
3188 */
3189
3190The preceding notice is from src/missing/getopt_long.c and src/mygetopt.h in `file`.
3191
3192
3193
3194/*
3195 * Public domain fallback for reallocarray(3), for platforms (e.g.
3196 * AmigaOS/libnix) whose C library declares it but does not implement it.
3197 */
3198
3199The preceding notice is from src/missing/reallocarray.c in `file`.
3200
3201
3202
3203/*-
3204 * SPDX-License-Identifier: BSD-3-Clause
3205 *
3206 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
3207 * Copyright (c) 1992, 1993, 1994
3208 *      The Regents of the University of California.  All rights reserved.
3209 *
3210 * Copyright (c) 2011 The FreeBSD Foundation
3211 * All rights reserved.
3212 * Portions of this software were developed by David Chisnall
3213 * under sponsorship from the FreeBSD Foundation.
3214 *
3215 * This code is derived from software contributed to Berkeley by
3216 * Henry Spencer.
3217 *
3218 * Redistribution and use in source and binary forms, with or without
3219 * modification, are permitted provided that the following conditions
3220 * are met:
3221 * 1. Redistributions of source code must retain the above copyright
3222 *    notice, this list of conditions and the following disclaimer.
3223 * 2. Redistributions in binary form must reproduce the above copyright
3224 *    notice, this list of conditions and the following disclaimer in the
3225 *    documentation and/or other materials provided with the distribution.
3226 * 3. Neither the name of the University nor the names of its contributors
3227 *    may be used to endorse or promote products derived from this software
3228 *    without specific prior written permission.
3229 *
3230 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3231 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3232 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3233 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3234 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3235 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3236 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3237 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3238 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3239 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3240 * SUCH DAMAGE.
3241 *
3242 *      @(#)regcomp.c   8.5 (Berkeley) 3/20/94
3243 */
3244
3245The preceding notice is from src/missing/regcomp.c in `file`.
3246
3247
3248
3249/*-
3250 * SPDX-License-Identifier: BSD-3-Clause
3251 *
3252 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
3253 * Copyright (c) 1992, 1993, 1994
3254 *      The Regents of the University of California.  All rights reserved.
3255 *
3256 * This code is derived from software contributed to Berkeley by
3257 * Henry Spencer.
3258 *
3259 * Redistribution and use in source and binary forms, with or without
3260 * modification, are permitted provided that the following conditions
3261 * are met:
3262 * 1. Redistributions of source code must retain the above copyright
3263 *    notice, this list of conditions and the following disclaimer.
3264 * 2. Redistributions in binary form must reproduce the above copyright
3265 *    notice, this list of conditions and the following disclaimer in the
3266 *    documentation and/or other materials provided with the distribution.
3267 * 3. Neither the name of the University nor the names of its contributors
3268 *    may be used to endorse or promote products derived from this software
3269 *    without specific prior written permission.
3270 *
3271 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3272 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3273 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3274 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3275 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3276 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3277 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3278 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3279 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3280 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3281 * SUCH DAMAGE.
3282 *
3283 *      @(#)regerror.c  8.4 (Berkeley) 3/20/94
3284 */
3285
3286The preceding notice is from src/missing/regerror.c in `file`.
3287
3288
3289
3290$NetBSD: COPYRIGHT,v 1.5 2003/08/07 16:43:19 agc Exp $
3291
3292Copyright 1992, 1993, 1994 Henry Spencer.  All rights reserved.
3293This software is not subject to any license of the American Telephone
3294and Telegraph Company or of the Regents of the University of California.
3295
3296Permission is granted to anyone to use this software for any purpose on
3297any computer system, and to alter it and redistribute it, subject
3298to the following restrictions:
3299
33001. The author is not responsible for the consequences of use of this
3301   software, no matter how awful, even if they arise from flaws in it.
3302
33032. The origin of this software must not be misrepresented, either by
3304   explicit claim or by omission.  Since few users ever read sources,
3305   credits must appear in the documentation.
3306
33073. Altered versions must be plainly marked as such, and must not be
3308   misrepresented as being the original software.  Since few users
3309   ever read sources, credits must appear in the documentation.
3310
33114. This notice may not be removed or altered.
3312
3313=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
3314/*-
3315 * Copyright (c) 1994
3316 *      The Regents of the University of California.  All rights reserved.
3317 *
3318 * Redistribution and use in source and binary forms, with or without
3319 * modification, are permitted provided that the following conditions
3320 * are met:
3321 * 1. Redistributions of source code must retain the above copyright
3322 *    notice, this list of conditions and the following disclaimer.
3323 * 2. Redistributions in binary form must reproduce the above copyright
3324 *    notice, this list of conditions and the following disclaimer in the
3325 *    documentation and/or other materials provided with the distribution.
3326 * 3. Neither the name of the University nor the names of its contributors
3327 *    may be used to endorse or promote products derived from this software
3328 *    without specific prior written permission.
3329 *
3330 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3331 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3332 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3333 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3334 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3335 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3336 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3337 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3338 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3339 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3340 * SUCH DAMAGE.
3341 *
3342 *      @(#)COPYRIGHT   8.1 (Berkeley) 3/16/94
3343 */
3344
3345The preceding notice is from src/missing/REGEX-COPYRIGHT in `file`.
3346
3347
3348
3349/*-
3350 * SPDX-License-Identifier: BSD-3-Clause
3351 *
3352 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
3353 * Copyright (c) 1992, 1993, 1994
3354 *      The Regents of the University of California.  All rights reserved.
3355 *
3356 * This code is derived from software contributed to Berkeley by
3357 * Henry Spencer.
3358 *
3359 * Redistribution and use in source and binary forms, with or without
3360 * modification, are permitted provided that the following conditions
3361 * are met:
3362 * 1. Redistributions of source code must retain the above copyright
3363 *    notice, this list of conditions and the following disclaimer.
3364 * 2. Redistributions in binary form must reproduce the above copyright
3365 *    notice, this list of conditions and the following disclaimer in the
3366 *    documentation and/or other materials provided with the distribution.
3367 * 3. Neither the name of the University nor the names of its contributors
3368 *    may be used to endorse or promote products derived from this software
3369 *    without specific prior written permission.
3370 *
3371 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3372 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3373 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3374 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3375 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3376 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3377 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3378 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3379 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3380 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3381 * SUCH DAMAGE.
3382 *
3383 *      @(#)regex2.h    8.4 (Berkeley) 3/20/94
3384 * $FreeBSD: head/lib/libc/regex/regex2.h 368359 2020-12-05 03:18:48Z kevans $
3385 */
3386
3387The preceding notice is from src/missing/regex2.h in `file`.
3388
3389
3390
3391/*-
3392 * SPDX-License-Identifier: BSD-3-Clause
3393 *
3394 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
3395 * Copyright (c) 1992, 1993, 1994
3396 *      The Regents of the University of California.  All rights reserved.
3397 *
3398 * This code is derived from software contributed to Berkeley by
3399 * Henry Spencer.
3400 *
3401 * Redistribution and use in source and binary forms, with or without
3402 * modification, are permitted provided that the following conditions
3403 * are met:
3404 * 1. Redistributions of source code must retain the above copyright
3405 *    notice, this list of conditions and the following disclaimer.
3406 * 2. Redistributions in binary form must reproduce the above copyright
3407 *    notice, this list of conditions and the following disclaimer in the
3408 *    documentation and/or other materials provided with the distribution.
3409 * 3. Neither the name of the University nor the names of its contributors
3410 *    may be used to endorse or promote products derived from this software
3411 *    without specific prior written permission.
3412 *
3413 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3414 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3415 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3416 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3417 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3418 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3419 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3420 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3421 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3422 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3423 * SUCH DAMAGE.
3424 *
3425 *      @(#)regexec.c   8.3 (Berkeley) 3/20/94
3426 */
3427
3428The preceding notice is from src/missing/regexec.c in `file`.
3429
3430
3431
3432/*-
3433 * SPDX-License-Identifier: BSD-3-Clause
3434 *
3435 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
3436 * Copyright (c) 1992, 1993, 1994
3437 *      The Regents of the University of California.  All rights reserved.
3438 *
3439 * This code is derived from software contributed to Berkeley by
3440 * Henry Spencer.
3441 *
3442 * Redistribution and use in source and binary forms, with or without
3443 * modification, are permitted provided that the following conditions
3444 * are met:
3445 * 1. Redistributions of source code must retain the above copyright
3446 *    notice, this list of conditions and the following disclaimer.
3447 * 2. Redistributions in binary form must reproduce the above copyright
3448 *    notice, this list of conditions and the following disclaimer in the
3449 *    documentation and/or other materials provided with the distribution.
3450 * 3. Neither the name of the University nor the names of its contributors
3451 *    may be used to endorse or promote products derived from this software
3452 *    without specific prior written permission.
3453 *
3454 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3455 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3456 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3457 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3458 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3459 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3460 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3461 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3462 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3463 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3464 * SUCH DAMAGE.
3465 *
3466 *      @(#)regfree.c   8.3 (Berkeley) 3/20/94
3467 */
3468
3469The preceding notice is from src/missing/regfree.c in `file`.
3470
3471
3472
3473/*-
3474 * Copyright (c) 1990, 1993
3475 *      The Regents of the University of California.  All rights reserved.
3476 *
3477 * This code is derived from software contributed to Berkeley by
3478 * Chris Torek.
3479 *
3480 * Redistribution and use in source and binary forms, with or without
3481 * modification, are permitted provided that the following conditions
3482 * are met:
3483 * 1. Redistributions of source code must retain the above copyright
3484 *    notice, this list of conditions and the following disclaimer.
3485 * 2. Redistributions in binary form must reproduce the above copyright
3486 *    notice, this list of conditions and the following disclaimer in the
3487 *    documentation and/or other materials provided with the distribution.
3488 * 3. Neither the name of the University nor the names of its contributors
3489 *    may be used to endorse or promote products derived from this software
3490 *    without specific prior written permission.
3491 *
3492 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3493 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3494 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3495 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3496 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3497 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3498 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3499 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3500 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3501 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3502 * SUCH DAMAGE.
3503 */
3504
3505The preceding notice is from src/missing/strcasestr.c in `file`.
3506
3507
3508
3509/*
3510 * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
3511 *
3512 * Permission to use, copy, modify, and distribute this software for any
3513 * purpose with or without fee is hereby granted, provided that the above
3514 * copyright notice and this permission notice appear in all copies.
3515 *
3516 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
3517 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
3518 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
3519 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
3520 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
3521 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
3522 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
3523 */
3524
3525The preceding notice is from src/missing/strlcat.c and src/missing/strlcpy.c in `file`.
3526
3527
3528
3529/*-
3530 * SPDX-License-Identifier: BSD-3-Clause
3531 *
3532 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
3533 * Copyright (c) 1992, 1993, 1994
3534 *      The Regents of the University of California.  All rights reserved.
3535 *
3536 * This code is derived from software contributed to Berkeley by
3537 * Henry Spencer.
3538 *
3539 * Redistribution and use in source and binary forms, with or without
3540 * modification, are permitted provided that the following conditions
3541 * are met:
3542 * 1. Redistributions of source code must retain the above copyright
3543 *    notice, this list of conditions and the following disclaimer.
3544 * 2. Redistributions in binary form must reproduce the above copyright
3545 *    notice, this list of conditions and the following disclaimer in the
3546 *    documentation and/or other materials provided with the distribution.
3547 * 3. Neither the name of the University nor the names of its contributors
3548 *    may be used to endorse or promote products derived from this software
3549 *    without specific prior written permission.
3550 *
3551 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3552 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3553 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3554 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3555 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3556 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3557 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3558 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3559 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3560 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3561 * SUCH DAMAGE.
3562 *
3563 *      @(#)utils.h     8.3 (Berkeley) 3/20/94
3564 * $FreeBSD: head/lib/libc/regex/utils.h 341838 2018-12-12 04:23:00Z yuripv $
3565 */
3566
3567The preceding notice is from src/missing/utils.h in `file`.
3568
3569
3570
3571/*-
3572 * Copyright (c) 2008, 2016 Christos Zoulas
3573 * All rights reserved.
3574 *
3575 * Redistribution and use in source and binary forms, with or without
3576 * modification, are permitted provided that the following conditions
3577 * are met:
3578 * 1. Redistributions of source code must retain the above copyright
3579 *    notice, this list of conditions and the following disclaimer.
3580 * 2. Redistributions in binary form must reproduce the above copyright
3581 *    notice, this list of conditions and the following disclaimer in the
3582 *    documentation and/or other materials provided with the distribution.
3583 *
3584 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
3585 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
3586 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
3587 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
3588 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
3589 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
3590 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
3591 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
3592 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
3593 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
3594 * POSSIBILITY OF SUCH DAMAGE.
3595 */
3596
3597The preceding notice is from src/readcdf.c in `file`.
3598
3599
3600
3601/*-
3602 * Copyright (c) 1992 Henry Spencer.
3603 * Copyright (c) 1992, 1993
3604 *      The Regents of the University of California.  All rights reserved.
3605 *
3606 * This code is derived from software contributed to Berkeley by
3607 * Henry Spencer of the University of Toronto.
3608 *
3609 * Redistribution and use in source and binary forms, with or without
3610 * modification, are permitted provided that the following conditions
3611 * are met:
3612 * 1. Redistributions of source code must retain the above copyright
3613 *    notice, this list of conditions and the following disclaimer.
3614 * 2. Redistributions in binary form must reproduce the above copyright
3615 *    notice, this list of conditions and the following disclaimer in the
3616 *    documentation and/or other materials provided with the distribution.
3617 * 3. Neither the name of the University nor the names of its contributors
3618 *    may be used to endorse or promote products derived from this software
3619 *    without specific prior written permission.
3620 *
3621 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3622 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3623 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3624 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3625 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3626 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3627 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3628 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3629 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3630 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3631 * SUCH DAMAGE.
3632 *
3633 *      @(#)regex.h     8.2 (Berkeley) 1/3/94
3634 * $FreeBSD: src/include/regex.h,v 1.12 2010/02/16 19:39:50 imp Exp $
3635 */
3636
3637The preceding notice is from src/regex-bsd.h in `file`.
3638*/
3639/*
3640
3641Text of LICENSE from DROID:
3642
3643Copyright (c) 2016, The National Archives <pronom@nationalarchives.gov.uk>
3644All rights reserved.
3645
3646Redistribution and use in source and binary forms, with or without
3647modification, are permitted provided that the following
3648conditions are met:
3649
3650 * Redistributions of source code must retain the above copyright
3651   notice, this list of conditions and the following disclaimer.
3652
3653 * Redistributions in binary form must reproduce the above copyright
3654   notice, this list of conditions and the following disclaimer in the
3655   documentation and/or other materials provided with the distribution.
3656
3657 * Neither the name of the The National Archives nor the
3658   names of its contributors may be used to endorse or promote products
3659   derived from this software without specific prior written permission.
3660
3661THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
3662AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3663IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
3664PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
3665CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
3666EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
3667PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
3668PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
3669LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
3670NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
3671SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3672*/
3673
3674/*
3675
3676Text of LICENSE from fileid:
3677
3678The MIT License (MIT)
3679
3680Copyright (c) 2015 David B Heise
3681
3682Permission is hereby granted, free of charge, to any person obtaining a copy of
3683this software and associated documentation files (the "Software"), to deal in
3684the Software without restriction, including without limitation the rights to
3685use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
3686the Software, and to permit persons to whom the Software is furnished to do so,
3687subject to the following conditions:
3688
3689The above copyright notice and this permission notice shall be included in all
3690copies or substantial portions of the Software.
3691
3692THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
3693IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
3694FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
3695COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
3696IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
3697CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
3698
3699
3700*/
3701
3702/*
3703Text of LICENSE from binwalk:
3704
3705
3706MIT License
3707
3708Copyright (c) 2024 devttys0
3709
3710Permission is hereby granted, free of charge, to any person obtaining a copy
3711of this software and associated documentation files (the "Software"), to deal
3712in the Software without restriction, including without limitation the rights
3713to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
3714copies of the Software, and to permit persons to whom the Software is
3715furnished to do so, subject to the following conditions:
3716
3717The above copyright notice and this permission notice shall be included in all
3718copies or substantial portions of the Software.
3719
3720THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
3721IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
3722FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
3723AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
3724LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
3725OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
3726SOFTWARE.
3727
3728*/
3729
3730/*
3731Text of LICENSE from polyfile:
3732
3733
3734                                 Apache License
3735                           Version 2.0, January 2004
3736                        http://www.apache.org/licenses/
3737
3738   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
3739
3740   1. Definitions.
3741
3742      "License" shall mean the terms and conditions for use, reproduction,
3743      and distribution as defined by Sections 1 through 9 of this document.
3744
3745      "Licensor" shall mean the copyright owner or entity authorized by
3746      the copyright owner that is granting the License.
3747
3748      "Legal Entity" shall mean the union of the acting entity and all
3749      other entities that control, are controlled by, or are under common
3750      control with that entity. For the purposes of this definition,
3751      "control" means (i) the power, direct or indirect, to cause the
3752      direction or management of such entity, whether by contract or
3753      otherwise, or (ii) ownership of fifty percent (50%) or more of the
3754      outstanding shares, or (iii) beneficial ownership of such entity.
3755
3756      "You" (or "Your") shall mean an individual or Legal Entity
3757      exercising permissions granted by this License.
3758
3759      "Source" form shall mean the preferred form for making modifications,
3760      including but not limited to software source code, documentation
3761      source, and configuration files.
3762
3763      "Object" form shall mean any form resulting from mechanical
3764      transformation or translation of a Source form, including but
3765      not limited to compiled object code, generated documentation,
3766      and conversions to other media types.
3767
3768      "Work" shall mean the work of authorship, whether in Source or
3769      Object form, made available under the License, as indicated by a
3770      copyright notice that is included in or attached to the work
3771      (an example is provided in the Appendix below).
3772
3773      "Derivative Works" shall mean any work, whether in Source or Object
3774      form, that is based on (or derived from) the Work and for which the
3775      editorial revisions, annotations, elaborations, or other modifications
3776      represent, as a whole, an original work of authorship. For the purposes
3777      of this License, Derivative Works shall not include works that remain
3778      separable from, or merely link (or bind by name) to the interfaces of,
3779      the Work and Derivative Works thereof.
3780
3781      "Contribution" shall mean any work of authorship, including
3782      the original version of the Work and any modifications or additions
3783      to that Work or Derivative Works thereof, that is intentionally
3784      submitted to Licensor for inclusion in the Work by the copyright owner
3785      or by an individual or Legal Entity authorized to submit on behalf of
3786      the copyright owner. For the purposes of this definition, "submitted"
3787      means any form of electronic, verbal, or written communication sent
3788      to the Licensor or its representatives, including but not limited to
3789      communication on electronic mailing lists, source code control systems,
3790      and issue tracking systems that are managed by, or on behalf of, the
3791      Licensor for the purpose of discussing and improving the Work, but
3792      excluding communication that is conspicuously marked or otherwise
3793      designated in writing by the copyright owner as "Not a Contribution."
3794
3795      "Contributor" shall mean Licensor and any individual or Legal Entity
3796      on behalf of whom a Contribution has been received by Licensor and
3797      subsequently incorporated within the Work.
3798
3799   2. Grant of Copyright License. Subject to the terms and conditions of
3800      this License, each Contributor hereby grants to You a perpetual,
3801      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
3802      copyright license to reproduce, prepare Derivative Works of,
3803      publicly display, publicly perform, sublicense, and distribute the
3804      Work and such Derivative Works in Source or Object form.
3805
3806   3. Grant of Patent License. Subject to the terms and conditions of
3807      this License, each Contributor hereby grants to You a perpetual,
3808      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
3809      (except as stated in this section) patent license to make, have made,
3810      use, offer to sell, sell, import, and otherwise transfer the Work,
3811      where such license applies only to those patent claims licensable
3812      by such Contributor that are necessarily infringed by their
3813      Contribution(s) alone or by combination of their Contribution(s)
3814      with the Work to which such Contribution(s) was submitted. If You
3815      institute patent litigation against any entity (including a
3816      cross-claim or counterclaim in a lawsuit) alleging that the Work
3817      or a Contribution incorporated within the Work constitutes direct
3818      or contributory patent infringement, then any patent licenses
3819      granted to You under this License for that Work shall terminate
3820      as of the date such litigation is filed.
3821
3822   4. Redistribution. You may reproduce and distribute copies of the
3823      Work or Derivative Works thereof in any medium, with or without
3824      modifications, and in Source or Object form, provided that You
3825      meet the following conditions:
3826
3827      (a) You must give any other recipients of the Work or
3828          Derivative Works a copy of this License; and
3829
3830      (b) You must cause any modified files to carry prominent notices
3831          stating that You changed the files; and
3832
3833      (c) You must retain, in the Source form of any Derivative Works
3834          that You distribute, all copyright, patent, trademark, and
3835          attribution notices from the Source form of the Work,
3836          excluding those notices that do not pertain to any part of
3837          the Derivative Works; and
3838
3839      (d) If the Work includes a "NOTICE" text file as part of its
3840          distribution, then any Derivative Works that You distribute must
3841          include a readable copy of the attribution notices contained
3842          within such NOTICE file, excluding those notices that do not
3843          pertain to any part of the Derivative Works, in at least one
3844          of the following places: within a NOTICE text file distributed
3845          as part of the Derivative Works; within the Source form or
3846          documentation, if provided along with the Derivative Works; or,
3847          within a display generated by the Derivative Works, if and
3848          wherever such third-party notices normally appear. The contents
3849          of the NOTICE file are for informational purposes only and
3850          do not modify the License. You may add Your own attribution
3851          notices within Derivative Works that You distribute, alongside
3852          or as an addendum to the NOTICE text from the Work, provided
3853          that such additional attribution notices cannot be construed
3854          as modifying the License.
3855
3856      You may add Your own copyright statement to Your modifications and
3857      may provide additional or different license terms and conditions
3858      for use, reproduction, or distribution of Your modifications, or
3859      for any such Derivative Works as a whole, provided Your use,
3860      reproduction, and distribution of the Work otherwise complies with
3861      the conditions stated in this License.
3862
3863   5. Submission of Contributions. Unless You explicitly state otherwise,
3864      any Contribution intentionally submitted for inclusion in the Work
3865      by You to the Licensor shall be under the terms and conditions of
3866      this License, without any additional terms or conditions.
3867      Notwithstanding the above, nothing herein shall supersede or modify
3868      the terms of any separate license agreement you may have executed
3869      with Licensor regarding such Contributions.
3870
3871   6. Trademarks. This License does not grant permission to use the trade
3872      names, trademarks, service marks, or product names of the Licensor,
3873      except as required for reasonable and customary use in describing the
3874      origin of the Work and reproducing the content of the NOTICE file.
3875
3876   7. Disclaimer of Warranty. Unless required by applicable law or
3877      agreed to in writing, Licensor provides the Work (and each
3878      Contributor provides its Contributions) on an "AS IS" BASIS,
3879      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
3880      implied, including, without limitation, any warranties or conditions
3881      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
3882      PARTICULAR PURPOSE. You are solely responsible for determining the
3883      appropriateness of using or redistributing the Work and assume any
3884      risks associated with Your exercise of permissions under this License.
3885
3886   8. Limitation of Liability. In no event and under no legal theory,
3887      whether in tort (including negligence), contract, or otherwise,
3888      unless required by applicable law (such as deliberate and grossly
3889      negligent acts) or agreed to in writing, shall any Contributor be
3890      liable to You for damages, including any direct, indirect, special,
3891      incidental, or consequential damages of any character arising as a
3892      result of this License or out of the use or inability to use the
3893      Work (including but not limited to damages for loss of goodwill,
3894      work stoppage, computer failure or malfunction, or any and all
3895      other commercial damages or losses), even if such Contributor
3896      has been advised of the possibility of such damages.
3897
3898   9. Accepting Warranty or Additional Liability. While redistributing
3899      the Work or Derivative Works thereof, You may choose to offer,
3900      and charge a fee for, acceptance of support, warranty, indemnity,
3901      or other liability obligations and/or rights consistent with this
3902      License. However, in accepting such obligations, You may act only
3903      on Your own behalf and on Your sole responsibility, not on behalf
3904      of any other Contributor, and only if You agree to indemnify,
3905      defend, and hold each Contributor harmless for any liability
3906      incurred by, or claims asserted against, such Contributor by reason
3907      of your accepting any such warranty or additional liability.
3908
3909   END OF TERMS AND CONDITIONS
3910
3911   APPENDIX: How to apply the Apache License to your work.
3912
3913      To apply the Apache License to your work, attach the following
3914      boilerplate notice, with the fields enclosed by brackets "[]"
3915      replaced with your own identifying information. (Don't include
3916      the brackets!)  The text should be enclosed in the appropriate
3917      comment syntax for the file format. We also recommend that a
3918      file or class name and description of purpose be included on the
3919      same "printed page" as the copyright notice for easier
3920      identification within third-party archives.
3921
3922   Copyright [yyyy] [name of copyright owner]
3923
3924   Licensed under the Apache License, Version 2.0 (the "License");
3925   you may not use this file except in compliance with the License.
3926   You may obtain a copy of the License at
3927
3928       http://www.apache.org/licenses/LICENSE-2.0
3929
3930   Unless required by applicable law or agreed to in writing, software
3931   distributed under the License is distributed on an "AS IS" BASIS,
3932   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3933   See the License for the specific language governing permissions and
3934   limitations under the License.
3935
3936*/