ctb_formats_apple_single_double/apple_single_double.rs
1// SPDX-License-Identifier: AGPL-3.0-or-later AND GPL-1.0-or-later AND LGPL-2.1-or-later
2// SPDX-License-Identifier for parts derived from Mac-AppleSingleDouble-1.0: GPL-1.0-or-later
3// SPDX-License-Identifier for parts derived from TheUnarchiver: LGPL-2.1-or-later
4/*
5This file is part of Collective Toolbox, a database and document workspace and utilities.
6Copyright (C) 2026 Collective Toolbox Developers
7Contact: info@collectivetoolbox.com
8
9This program is free software: you can redistribute it and/or modify it under
10the terms of the GNU Affero General Public License as published by the Free
11Software Foundation, either version 3 of the License, or (at your option) any
12later version.
13
14This program is distributed in the hope that it will be useful, but WITHOUT ANY
15WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
17
18You should have received a copy of the GNU Affero General Public License along
19with this program. If not, see <https://www.gnu.org/licenses/>.
20*/
21
22// Parts derived from Mac-AppleSingleDouble-1.0:
23// # Mac::AppleSingleDouble.pm, (C) 2001 Jamie Flournoy (jamie@white-mountain.org).
24
25// Parts derived from TheUnarchiver:
26// Dag Ă…gren, <paracelsus@gmail.com>
27
28// See full licensing details at the end of this file.
29
30//! AppleSingle and AppleDouble archive format reader and JSON exporter.
31//!
32//! Syntactically, AppleSingle and AppleDouble share the same container
33//! format with distinct magic numbers:
34//! - AppleSingle (`0x00051600`): holds data fork, resource fork, and metadata.
35//! - AppleDouble (`0x00051607`): holds resource fork and metadata in an
36//! auxiliary companion file (such as `._<filename>`), keeping the data fork
37//! in a separate plain file.
38
39#[allow(
40 unused_imports,
41 clippy::wildcard_imports,
42 reason = "Standard workspace crate prelude"
43)]
44pub(crate) use ctb_utilities::*;
45
46use ctb_formats_dcstring::{
47 DcMixedDecode, DcMixedEncode, DcProjectionContext, NodeId,
48};
49use serde::{Deserialize, Serialize};
50use std::path::{Path, PathBuf};
51
52/// Retrieves AppleSingle / AppleDouble test fixture data by path key.
53#[must_use]
54pub fn get_apple_single_double_data(key: &str) -> Option<Vec<u8>> {
55 ctb_utilities::load_manifest_fixture(env!("CARGO_MANIFEST_DIR"), key)
56}
57
58/// AppleSingle magic number in big-endian byte order.
59pub const APPLESINGLE_MAGIC_BE: u32 = 0x0005_1600;
60
61/// AppleSingle magic number in little-endian byte order.
62pub const APPLESINGLE_MAGIC_LE: u32 = 0x0016_0500;
63
64/// AppleDouble magic number in big-endian byte order.
65pub const APPLEDOUBLE_MAGIC_BE: u32 = 0x0005_1607;
66
67/// AppleDouble magic number in little-endian byte order.
68pub const APPLEDOUBLE_MAGIC_LE: u32 = 0x0716_0500;
69
70/// Standard AppleSingle/AppleDouble format version 2.0.
71pub const VERSION_2_0_BE: u32 = 0x0002_0000;
72
73/// Standard AppleSingle/AppleDouble format version 2.0 in little-endian.
74pub const VERSION_2_0_LE: u32 = 0x0000_0200;
75
76/// Legacy format version 1.0.
77pub const VERSION_1_0_BE: u32 = 0x0001_0000;
78
79/// Legacy format version 1.0 in little-endian.
80pub const VERSION_1_0_LE: u32 = 0x0000_0100;
81
82/// Extended attributes magic "ATTR" in big-endian (`0x41545452`).
83pub const ATTR_MAGIC_BE: u32 = 0x4154_5452;
84
85/// Sentinel value indicating an unset timestamp in AppleSingle v2 date records.
86pub const TIMESTAMP_UNSET_SENTINEL: u32 = 0x8000_0000;
87
88/// Number of seconds between Unix epoch (1970-01-01) and Mac OS 2000 epoch (2000-01-01).
89pub const SECONDS_1970_TO_2000: i64 = 946_684_800;
90
91/// Archive format variant identified by the header magic.
92#[derive(
93 Debug,
94 Clone,
95 Copy,
96 PartialEq,
97 Eq,
98 Serialize,
99 Deserialize,
100 ctb_formats_dcstring::DcMixed,
101)]
102pub enum AppleFormat {
103 /// Single-file archive containing data fork and metadata.
104 #[dc(f315)]
105 AppleSingle,
106 /// Header/metadata archive companion file.
107 #[dc(f316)]
108 AppleDouble,
109}
110
111/// The storage style used for auxiliary AppleDouble companion files.
112#[derive(
113 Debug,
114 Clone,
115 Copy,
116 PartialEq,
117 Eq,
118 Hash,
119 clap::ValueEnum,
120 Serialize,
121 Deserialize,
122)]
123pub enum AppleDoubleStyle {
124 /// Normal alongside companion file prefixed by `._` in the same directory.
125 Alongside,
126 /// Companion file in top-level `__MACOSX` directory mirroring relative path.
127 Zip,
128 /// Netatalk `.AppleDouble/<filename>` and `.AppleDouble/.Parent` companion
129 /// files.
130 Netatalk,
131}
132
133impl AppleDoubleStyle {
134 /// Canonical string identifier for this style.
135 #[must_use]
136 pub const fn as_str(&self) -> &'static str {
137 match self {
138 Self::Alongside => "alongside",
139 Self::Zip => "zip",
140 Self::Netatalk => "netatalk",
141 }
142 }
143}
144
145/// Extension convention for AppleSingle files.
146#[derive(
147 Debug,
148 Clone,
149 Copy,
150 PartialEq,
151 Eq,
152 Default,
153 Serialize,
154 Deserialize,
155 clap::ValueEnum,
156)]
157pub enum AppleSingleExtension {
158 /// No extension added (bare filename, e.g. `foo`). Default for writing.
159 #[default]
160 WithoutExtension,
161 /// `StuffIt` style `.as` extension (e.g. `foo.as`).
162 As,
163 /// `.asf` extension (e.g. `foo.asf`).
164 Asf,
165}
166
167impl AppleSingleExtension {
168 /// Canonical string identifier for CLI and serialization.
169 #[must_use]
170 pub const fn as_str(self) -> &'static str {
171 match self {
172 Self::WithoutExtension => "without-extension",
173 Self::As => "as",
174 Self::Asf => "asf",
175 }
176 }
177
178 /// Appends the extension to a filename if one is configured.
179 #[must_use]
180 pub fn apply_to_name(
181 self,
182 name: impl AsRef<std::ffi::OsStr>,
183 ) -> std::ffi::OsString {
184 let mut result = name.as_ref().to_os_string();
185 match self {
186 Self::WithoutExtension => {}
187 Self::As => result.push(".as"),
188 Self::Asf => result.push(".asf"),
189 }
190 result
191 }
192
193 /// Removes the configured extension without transcoding the filename.
194 #[must_use]
195 pub fn strip_from_name(
196 self,
197 name: &std::ffi::OsStr,
198 ) -> Option<&std::ffi::OsStr> {
199 let extension = match self {
200 Self::WithoutExtension => return Some(name),
201 Self::As => b"as".as_slice(),
202 Self::Asf => b"asf".as_slice(),
203 };
204 let path = Path::new(name);
205 if path
206 .extension()?
207 .as_encoded_bytes()
208 .eq_ignore_ascii_case(extension)
209 {
210 path.file_stem()
211 } else {
212 None
213 }
214 }
215}
216
217impl std::str::FromStr for AppleSingleExtension {
218 type Err = anyhow::Error;
219
220 fn from_str(s: &str) -> Result<Self, Self::Err> {
221 match s.trim().to_ascii_lowercase().as_str() {
222 "without-extension" | "none" | "no" | "bare" => {
223 Ok(Self::WithoutExtension)
224 }
225 "as" => Ok(Self::As),
226 "asf" => Ok(Self::Asf),
227 other => anyhow::bail!(
228 "Invalid AppleSingle extension '{other}'. Expected 'as', \
229 'asf', or 'without-extension'"
230 ),
231 }
232 }
233}
234
235/// Options controlling which AppleSingle, AppleDouble, and Windows alternate
236/// data stream companion styles to detect and unpack on read.
237#[derive(
238 Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize,
239)]
240pub struct AppleReadOptions {
241 /// Read alongside ._<filename> companion files. Defaults to false.
242 pub read_apple_double_alongside: bool,
243 /// Read __MACOSX/ companion files. Defaults to false.
244 pub read_apple_double_zip: bool,
245 /// Read Netatalk .AppleDouble/<filename> and .AppleDouble/.Parent companion
246 /// files. Defaults to false.
247 pub read_apple_double_netatalk: bool,
248 /// Read bare AppleSingle files without extension. Defaults to false.
249 pub read_apple_single_without_extension: bool,
250 /// Read bare AppleSingle files without extension (compatibility alias).
251 /// Defaults to false.
252 pub read_apple_single: bool,
253 /// Read AppleSingle files with .as extension and strip .as upon decode.
254 /// Defaults to false.
255 pub read_apple_single_as: bool,
256 /// Read AppleSingle files with .asf extension and strip .asf upon decode.
257 /// Defaults to false.
258 pub read_apple_single_asf: bool,
259 /// Read alongside `<filename>:<stream_name>` Windows alternate data stream
260 /// companion files (such as `<filename>:Zone.Identifier`). Defaults to false.
261 #[serde(default)]
262 pub read_windows_ads_alongside: bool,
263}
264
265impl AppleReadOptions {
266 /// Returns true if any AppleSingle read style is enabled.
267 #[must_use]
268 pub fn any_apple_single(&self) -> bool {
269 self.read_apple_single_without_extension
270 || self.read_apple_single
271 || self.read_apple_single_as
272 || self.read_apple_single_asf
273 }
274}
275
276/// Computes the path to an AppleDouble companion file according to `style`.
277#[must_use]
278pub fn get_companion_path(
279 parent_dir: &Path,
280 file_name: &Path,
281 is_dir: bool,
282 style: AppleDoubleStyle,
283 root_dest: Option<&Path>,
284 relative_path: Option<&Path>,
285) -> PathBuf {
286 match style {
287 AppleDoubleStyle::Alongside => {
288 let mut name = std::ffi::OsString::from("._");
289 name.push(file_name);
290 parent_dir.join(name)
291 }
292 AppleDoubleStyle::Zip => {
293 // Reason for fallback: root destination defaults to parent
294 // directory when unprovided
295 let base = root_dest.unwrap_or(parent_dir);
296 // Reason for fallback: relative path defaults to file name when
297 // unprovided
298 let rel = relative_path.unwrap_or(file_name);
299 // Reason for fallback: top-level files have no parent directory
300 // component, defaulting to empty path
301 let rel_parent = rel.parent().unwrap_or_else(|| Path::new(""));
302 let mut name = std::ffi::OsString::from("._");
303 // Reason for fallback: path without a file name component defaults
304 // to original file name
305 name.push(rel.file_name().unwrap_or(file_name.as_os_str()));
306 base.join("__MACOSX").join(rel_parent).join(name)
307 }
308 AppleDoubleStyle::Netatalk => {
309 if is_dir {
310 parent_dir
311 .join(file_name)
312 .join(".AppleDouble")
313 .join(".Parent")
314 } else {
315 parent_dir.join(".AppleDouble").join(file_name)
316 }
317 }
318 }
319}
320
321/// Returns whether the file at `path` is a regular file starting with
322/// AppleDouble magic bytes.
323pub fn is_apple_double_file(path: &Path) -> bool {
324 let Ok(meta) = path.symlink_metadata() else {
325 return false;
326 };
327 if !meta.is_file() {
328 return false;
329 }
330 let Ok(mut file) = std::fs::File::open(path) else {
331 return false;
332 };
333 use std::io::Read;
334 let mut header = [0u8; 4];
335 if file.read_exact(&mut header).is_err() {
336 return false;
337 }
338 let Ok(magic_arr) = <[u8; 4]>::try_from(&header[..4]) else {
339 return false;
340 };
341 let magic = u32::from_be_bytes(magic_arr);
342 magic == APPLEDOUBLE_MAGIC_BE || magic == APPLEDOUBLE_MAGIC_LE
343}
344
345/// Returns whether the file at `path` is a regular file starting with
346/// AppleSingle magic bytes.
347pub fn is_apple_single_file(path: &Path) -> bool {
348 let Ok(meta) = path.symlink_metadata() else {
349 return false;
350 };
351 if !meta.is_file() {
352 return false;
353 }
354 let Ok(mut file) = std::fs::File::open(path) else {
355 return false;
356 };
357 use std::io::Read;
358 let mut header = [0u8; 4];
359 if file.read_exact(&mut header).is_err() {
360 return false;
361 }
362 let Ok(magic_arr) = <[u8; 4]>::try_from(&header[..4]) else {
363 return false;
364 };
365 let magic = u32::from_be_bytes(magic_arr);
366 magic == APPLESINGLE_MAGIC_BE || magic == APPLESINGLE_MAGIC_LE
367}
368
369/// Standard AppleSingle / AppleDouble entry identifier.
370#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
371pub enum EntryType {
372 /// Data fork payload (ID 1).
373 DataFork,
374 /// Classic Mac OS resource fork payload (ID 2).
375 ResourceFork,
376 /// Real filename on filesystems supporting native attributes (ID 3).
377 RealName,
378 /// Standard file comment (ID 4).
379 Comment,
380 /// Black and white icon (ID 5).
381 IconBw,
382 /// Color icon (ID 6).
383 IconColor,
384 /// File info record (attributes, dates) in AppleDouble 1.0 (ID 7).
385 FileInfo,
386 /// File timestamps info (ID 8).
387 FileDatesInfo,
388 /// Macintosh Finder metadata (FInfo + FXInfo) (ID 9).
389 FinderInfo,
390 /// Macintosh file information (ID 10).
391 MacintoshFileInfo,
392 /// ProDOS file information (ID 11).
393 ProdosFileInfo,
394 /// MS-DOS file information (ID 12).
395 MsdosFileInfo,
396 /// AFP short filename (ID 13).
397 AfpShortName,
398 /// AFP file information (ID 14).
399 AfpFileInfo,
400 /// Directory ID (ID 15). FIXME confirm if this is something AFP-specific.
401 DirectoryId,
402 /// ProDOS / GS/OS Data file pathname in AppleDouble 1.0 (ID 100).
403 DataPathname,
404 /// Unknown or vendor-specific entry ID.
405 Unknown(u32),
406}
407
408impl EntryType {
409 /// Maps a raw 32-bit entry ID to known entry type.
410 #[must_use]
411 pub const fn from_u32(raw: u32) -> Self {
412 match raw {
413 1 => Self::DataFork,
414 2 => Self::ResourceFork,
415 3 => Self::RealName,
416 4 => Self::Comment,
417 5 => Self::IconBw,
418 6 => Self::IconColor,
419 7 => Self::FileInfo,
420 8 => Self::FileDatesInfo,
421 9 => Self::FinderInfo,
422 10 => Self::MacintoshFileInfo,
423 11 => Self::ProdosFileInfo,
424 12 => Self::MsdosFileInfo,
425 13 => Self::AfpShortName,
426 14 => Self::AfpFileInfo,
427 15 => Self::DirectoryId,
428 100 => Self::DataPathname,
429 other => Self::Unknown(other),
430 }
431 }
432
433 /// Returns human-readable description of entry type.
434 #[must_use]
435 pub const fn as_str(&self) -> &'static str {
436 match self {
437 Self::DataFork => "Data Fork",
438 Self::ResourceFork => "Resource Fork",
439 Self::RealName => "Real Name",
440 Self::Comment => "Comment",
441 Self::IconBw => "Icon, B&W",
442 Self::IconColor => "Icon, Color",
443 Self::FileInfo => "File Info",
444 Self::FileDatesInfo => "File Dates Info",
445 Self::FinderInfo => "Finder Info",
446 Self::MacintoshFileInfo => "Macintosh File Info",
447 Self::ProdosFileInfo => "ProDOS File Info",
448 Self::MsdosFileInfo => "MS-DOS File Info",
449 Self::AfpShortName => "AFP Short Name",
450 Self::AfpFileInfo => "AFP File Info",
451 Self::DirectoryId => "Directory ID",
452 Self::DataPathname => "Data Pathname",
453 Self::Unknown(_) => "Unknown Entry",
454 }
455 }
456
457 /// Maps this entry type to its standard 32-bit entry ID.
458 #[must_use]
459 pub const fn to_u32(&self) -> u32 {
460 match self {
461 Self::DataFork => 1,
462 Self::ResourceFork => 2,
463 Self::RealName => 3,
464 Self::Comment => 4,
465 Self::IconBw => 5,
466 Self::IconColor => 6,
467 Self::FileInfo => 7,
468 Self::FileDatesInfo => 8,
469 Self::FinderInfo => 9,
470 Self::MacintoshFileInfo => 10,
471 Self::ProdosFileInfo => 11,
472 Self::MsdosFileInfo => 12,
473 Self::AfpShortName => 13,
474 Self::AfpFileInfo => 14,
475 Self::DirectoryId => 15,
476 Self::DataPathname => 100,
477 Self::Unknown(other) => *other,
478 }
479 }
480}
481
482/// Raw entry descriptor within the archive header table.
483#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
484pub struct AppleArchiveEntry {
485 /// Entry classification.
486 pub entry_type: EntryType,
487 /// Raw numeric entry ID.
488 pub raw_id: u32,
489 /// Human-readable entry name.
490 pub name: String,
491 /// Offset of entry body in bytes from start of archive.
492 pub offset: u32,
493 /// Length of entry body in bytes.
494 pub length: u32,
495}
496
497/// Preserved raw unrecognized entry from AppleSingle or AppleDouble archive.
498#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
499pub struct AppleRawEntry {
500 /// 32-bit entry type identifier (e.g. 5 for `IconBw`, 6 for `IconColor`, 10 for `MacintoshFileInfo`).
501 pub entry_id: u32,
502 /// Raw payload bytes of the entry.
503 pub data: Vec<u8>,
504}
505
506/// Type alias reflecting that raw entries preserve unrecognized container records.
507pub type AppleUnrecognizedEntry = AppleRawEntry;
508
509/// Decoded Finder flags boolean flags.
510#[expect(
511 clippy::struct_excessive_bools,
512 reason = "Mirrors 10 boolean flags from Finder metadata bitmask"
513)]
514#[derive(
515 Debug,
516 Clone,
517 Copy,
518 PartialEq,
519 Eq,
520 Default,
521 Serialize,
522 Deserialize,
523 ctb_formats_dcstring::DcMixed,
524)]
525#[dc(begin = 388, end = 389, flags)]
526pub struct FinderFlags {
527 /// File icon resides on desktop.
528 #[dc(499)]
529 pub is_on_desk: bool,
530 /// File is shared.
531 #[dc(500)]
532 pub is_shared: bool,
533 /// Extension or control panel contains no INIT resource.
534 #[dc(501)]
535 pub has_no_inits: bool,
536 /// Finder has initialized this file.
537 #[dc(502)]
538 pub has_been_inited: bool,
539 /// File has custom icon resource.
540 #[dc(503)]
541 pub has_custom_icon: bool,
542 /// File is stationery / template.
543 #[dc(504)]
544 pub is_stationery: bool,
545 /// File cannot be renamed.
546 #[dc(505)]
547 pub name_locked: bool,
548 /// File has bundle resource.
549 #[dc(506)]
550 pub has_bundle: bool,
551 /// File is hidden / invisible in GUI.
552 #[dc(507, alias = 413)]
553 pub is_invisible: bool,
554 /// File is an alias / shortcut.
555 #[dc(508)]
556 pub is_alias: bool,
557}
558
559impl FinderFlags {
560 /// Constructs `FinderFlags` by decoding the 16-bit Finder flags bitmask.
561 #[must_use]
562 pub const fn from_raw_u16(raw: u16) -> Self {
563 Self {
564 is_on_desk: (raw & 0x0001) != 0,
565 is_shared: (raw & 0x0040) != 0,
566 has_no_inits: (raw & 0x0080) != 0,
567 has_been_inited: (raw & 0x0100) != 0,
568 has_custom_icon: (raw & 0x0400) != 0,
569 is_stationery: (raw & 0x0800) != 0,
570 name_locked: (raw & 0x1000) != 0,
571 has_bundle: (raw & 0x2000) != 0,
572 is_invisible: (raw & 0x4000) != 0,
573 is_alias: (raw & 0x8000) != 0,
574 }
575 }
576
577 /// Encodes boolean flags into a 16-bit Finder flags bitmask.
578 #[must_use]
579 pub const fn to_raw_u16(&self) -> u16 {
580 let mut raw = 0u16;
581 if self.is_on_desk {
582 raw |= 0x0001;
583 }
584 if self.is_shared {
585 raw |= 0x0040;
586 }
587 if self.has_no_inits {
588 raw |= 0x0080;
589 }
590 if self.has_been_inited {
591 raw |= 0x0100;
592 }
593 if self.has_custom_icon {
594 raw |= 0x0400;
595 }
596 if self.is_stationery {
597 raw |= 0x0800;
598 }
599 if self.name_locked {
600 raw |= 0x1000;
601 }
602 if self.has_bundle {
603 raw |= 0x2000;
604 }
605 if self.is_invisible {
606 raw |= 0x4000;
607 }
608 if self.is_alias {
609 raw |= 0x8000;
610 }
611 raw
612 }
613}
614
615impl From<u16> for FinderFlags {
616 fn from(val: u16) -> Self {
617 Self::from_raw_u16(val)
618 }
619}
620
621impl From<FinderFlags> for u16 {
622 fn from(flags: FinderFlags) -> Self {
623 flags.to_raw_u16()
624 }
625}
626
627impl ctb_formats_dcstring::DcMixedNumber for FinderFlags {
628 fn encode_dc_number(
629 &self,
630 mst: &mut ctb_formats_dcstring::DcWriter<'_>,
631 ) -> Result<()> {
632 self.to_raw_u16().encode_dc_mixed_to(mst)
633 }
634
635 fn decode_dc_number(
636 ctx: &mut DcProjectionContext<'_, '_>,
637 node_id: NodeId,
638 ) -> Result<Self> {
639 let raw = u16::decode_dc_node(ctx, node_id)?;
640 Ok(Self::from_raw_u16(raw))
641 }
642}
643
644/// Extended Finder boolean flags decoded from classic Mac OS 8-bit `xflags`.
645#[derive(
646 Debug,
647 Clone,
648 Copy,
649 PartialEq,
650 Eq,
651 Default,
652 Serialize,
653 Deserialize,
654 ctb_formats_dcstring::DcMixed,
655)]
656#[dc(begin = 388, end = 389, flags)]
657pub struct ExtendedFlags {
658 /// Mac OS object has a custom badge.
659 #[dc(497)]
660 pub custom_badge: bool,
661 /// Mac OS object has routing info.
662 #[dc(498)]
663 pub routing_info: bool,
664 /// Mac OS extended Finder flags are invalid.
665 #[dc(509)]
666 pub extended_flags_invalid: bool,
667}
668
669impl ExtendedFlags {
670 /// Constructs `ExtendedFlags` from raw `u8`.
671 #[must_use]
672 pub const fn from_raw_u8(raw: u8) -> Self {
673 Self {
674 custom_badge: (raw & 0x01) != 0,
675 routing_info: (raw & 0x04) != 0,
676 extended_flags_invalid: (raw & 0x80) != 0,
677 }
678 }
679
680 /// Encodes `ExtendedFlags` into raw `u8`.
681 #[must_use]
682 pub const fn to_raw_u8(&self) -> u8 {
683 let mut raw = 0u8;
684 if self.custom_badge {
685 raw |= 0x01;
686 }
687 if self.routing_info {
688 raw |= 0x04;
689 }
690 if self.extended_flags_invalid {
691 raw |= 0x80;
692 }
693 raw
694 }
695}
696
697impl From<u8> for ExtendedFlags {
698 fn from(val: u8) -> Self {
699 Self::from_raw_u8(val)
700 }
701}
702
703impl From<ExtendedFlags> for u8 {
704 fn from(flags: ExtendedFlags) -> Self {
705 flags.to_raw_u8()
706 }
707}
708
709impl ctb_formats_dcstring::DcMixedNumber for ExtendedFlags {
710 fn encode_dc_number(
711 &self,
712 mst: &mut ctb_formats_dcstring::DcWriter<'_>,
713 ) -> Result<()> {
714 self.to_raw_u8().encode_dc_mixed_to(mst)
715 }
716
717 fn decode_dc_number(
718 ctx: &mut DcProjectionContext<'_, '_>,
719 node_id: NodeId,
720 ) -> Result<Self> {
721 let raw = u8::decode_dc_node(ctx, node_id)?;
722 Ok(Self::from_raw_u8(raw))
723 }
724}
725
726/// Decoded Finder label color and names.
727#[derive(
728 Debug,
729 Clone,
730 Copy,
731 PartialEq,
732 Eq,
733 Default,
734 Serialize,
735 Deserialize,
736 ctb_formats_dcstring::DcMixed,
737)]
738#[repr(u8)]
739pub enum FinderLabel {
740 #[default]
741 #[dc(482)]
742 None = 0,
743 #[dc(483)]
744 Project2 = 1,
745 #[dc(484)]
746 Project1 = 2,
747 #[dc(485)]
748 Personal = 3,
749 #[dc(486)]
750 Cool = 4,
751 #[dc(487)]
752 InProgress = 5,
753 #[dc(488)]
754 Hot = 6,
755 #[dc(489)]
756 Essential = 7,
757}
758
759impl FinderLabel {
760 /// Returns the 0..=7 index of the label.
761 #[must_use]
762 pub const fn index(self) -> u8 {
763 match self {
764 Self::None => 0,
765 Self::Project2 => 1,
766 Self::Project1 => 2,
767 Self::Personal => 3,
768 Self::Cool => 4,
769 Self::InProgress => 5,
770 Self::Hot => 6,
771 Self::Essential => 7,
772 }
773 }
774
775 /// Maps label index (0..7) to `FinderLabel`.
776 #[must_use]
777 pub const fn from_index(index: u8) -> Self {
778 match index {
779 1 => Self::Project2,
780 2 => Self::Project1,
781 3 => Self::Personal,
782 4 => Self::Cool,
783 5 => Self::InProgress,
784 6 => Self::Hot,
785 7 => Self::Essential,
786 _ => Self::None,
787 }
788 }
789
790 /// Classic Mac OS label name.
791 #[must_use]
792 pub const fn classic_name(self) -> &'static str {
793 match self {
794 Self::None => "None",
795 Self::Project2 => "Project 2",
796 Self::Project1 => "Project 1",
797 Self::Personal => "Personal",
798 Self::Cool => "Cool",
799 Self::InProgress => "In Progress",
800 Self::Hot => "Hot",
801 Self::Essential => "Essential",
802 }
803 }
804
805 /// Classic Mac OS label color name.
806 #[must_use]
807 pub const fn classic_color(self) -> &'static str {
808 match self {
809 Self::None => "Black",
810 Self::Project2 => "Brown",
811 Self::Project1 => "Green",
812 Self::Personal => "Blue",
813 Self::Cool => "Cyan",
814 Self::InProgress => "Pink",
815 Self::Hot => "Red",
816 Self::Essential => "Orange",
817 }
818 }
819
820 /// Mac OS X / modern macOS label name / color.
821 #[must_use]
822 pub const fn osx_color(self) -> &'static str {
823 match self {
824 Self::None => "None",
825 Self::Project2 => "Gray",
826 Self::Project1 => "Green",
827 Self::Personal => "Purple",
828 Self::Cool => "Blue",
829 Self::InProgress => "Yellow",
830 Self::Hot => "Red",
831 Self::Essential => "Orange",
832 }
833 }
834}
835
836impl From<FinderLabel> for u8 {
837 fn from(label: FinderLabel) -> Self {
838 label.index()
839 }
840}
841
842impl TryFrom<u8> for FinderLabel {
843 type Error = anyhow::Error;
844
845 fn try_from(val: u8) -> Result<Self> {
846 match val {
847 0 => Ok(Self::None),
848 1 => Ok(Self::Project2),
849 2 => Ok(Self::Project1),
850 3 => Ok(Self::Personal),
851 4 => Ok(Self::Cool),
852 5 => Ok(Self::InProgress),
853 6 => Ok(Self::Hot),
854 7 => Ok(Self::Essential),
855 other => anyhow::bail!("Invalid FinderLabel index: {other}"),
856 }
857 }
858}
859
860impl ctb_formats_dcstring::DcMixedNumber for FinderLabel {
861 fn encode_dc_number(
862 &self,
863 mst: &mut ctb_formats_dcstring::DcWriter<'_>,
864 ) -> Result<()> {
865 self.index().encode_dc_mixed_to(mst)
866 }
867
868 fn decode_dc_number(
869 ctx: &mut DcProjectionContext<'_, '_>,
870 node_id: NodeId,
871 ) -> Result<Self> {
872 let idx = u8::decode_dc_node(ctx, node_id)?;
873 Self::try_from(idx)
874 }
875}
876
877/// Extended Finder information (`FXInfo`, 16 bytes).
878#[derive(
879 Debug,
880 Clone,
881 Copy,
882 PartialEq,
883 Eq,
884 Default,
885 Serialize,
886 Deserialize,
887 ctb_formats_dcstring::DcMixed,
888)]
889#[dc(begin = 490, end = 491)]
890pub struct ExtendedFinderInfo {
891 /// Custom icon ID (for files).
892 #[dc(492, default, omit_default)]
893 pub icon_id: i16,
894 /// Script system code.
895 #[dc(493, default, omit_default)]
896 pub script: i8,
897 /// Extended flags byte.
898 #[dc(562, nested = 388, default, omit_default)]
899 pub xflags: ExtendedFlags,
900 /// Comment ID.
901 #[dc(494, default, omit_default)]
902 pub comment: i16,
903 /// Directory ID for put away.
904 #[dc(495, default, omit_default)]
905 pub put_away: u32,
906 /// Icon view scroll position for folders (`DXInfo` `frScroll`).
907 #[dc(407, representation = f523, default, omit_default)]
908 pub scroll_position: Option<(i16, i16)>,
909}
910
911/// Complete Finder metadata (`FInfo` + optional `FXInfo`).
912#[derive(
913 Debug,
914 Clone,
915 PartialEq,
916 Eq,
917 Default,
918 Serialize,
919 Deserialize,
920 ctb_formats_dcstring::DcMixed,
921)]
922#[dc(begin = 401, end = 402)]
923pub struct FinderInfo {
924 /// 4-character Mac OS file type code (e.g. "TEXT", "BINA").
925 #[dc(403, default, omit_default)]
926 pub file_type: String,
927 /// 4-character Mac OS file creator code (e.g. "ttxt", "SITx").
928 #[dc(404, default, omit_default)]
929 pub file_creator: String,
930 /// Decoded label.
931 #[dc(405, equivalents = (405, number), default, omit_default)]
932 pub label: FinderLabel,
933 /// Decoded boolean flag details.
934 #[dc(406, nested = 388, default, omit_default)]
935 pub flags: FinderFlags,
936 /// Icon coordinates in QuickDraw grid `(v, h)`.
937 #[dc(407, representation = f523, default, omit_default)]
938 pub location: (i16, i16),
939 /// Window / folder ID (or folder view mode `frView`).
940 #[dc(408, default, omit_default)]
941 pub folder_id: i16,
942 /// Extended Finder info if present.
943 #[dc(nested = (490))]
944 pub extended: Option<ExtendedFinderInfo>,
945 /// Folder window rectangle `[top, left, bottom, right]` for directory records (`DInfo`).
946 #[dc(510, representation = f524, default, omit_default)]
947 pub window_bounds: Option<[i16; 4]>,
948}
949
950impl FinderInfo {
951 /// Calculates the raw 16-bit Finder flags bitmask including the embedded label index.
952 #[must_use]
953 pub const fn raw_flags(&self) -> u16 {
954 let label_idx = match self.label {
955 FinderLabel::None => 0,
956 FinderLabel::Project2 => 1,
957 FinderLabel::Project1 => 2,
958 FinderLabel::Personal => 3,
959 FinderLabel::Cool => 4,
960 FinderLabel::InProgress => 5,
961 FinderLabel::Hot => 6,
962 FinderLabel::Essential => 7,
963 };
964 self.flags.to_raw_u16() | (label_idx << 1)
965 }
966}
967
968/// Extended attribute extracted from AppleDouble `ATTR` block.
969#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
970pub struct AppleExtendedAttribute {
971 /// Attribute name (e.g. "com.apple.metadata:kMDItemWhereFroms").
972 pub name: String,
973 /// Attribute raw binary payload.
974 #[serde(skip_serializing)]
975 pub data: Vec<u8>,
976 /// Size of payload in bytes.
977 pub size: usize,
978}
979
980/// Complete timestamps record for AppleSingle / AppleDouble file dates entry (ID 7).
981#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
982pub struct AppleDatesInfo {
983 /// Creation time / birth time in seconds since Unix epoch (1970-01-01), if recorded.
984 pub birthtime_sec: Option<i64>,
985 /// Modification time in seconds since Unix epoch.
986 pub mtime_sec: i64,
987 /// Status / metadata change time in seconds since Unix epoch.
988 pub ctime_sec: i64,
989 /// Access time in seconds since Unix epoch.
990 pub atime_sec: i64,
991 /// Backup timestamp in seconds since Unix epoch, if recorded.
992 pub backup_sec: Option<i64>,
993}
994
995/// Decoded AppleSingle or AppleDouble archive.
996#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
997pub struct AppleArchive {
998 /// Container format (`AppleSingle` or `AppleDouble`).
999 pub format: AppleFormat,
1000 /// Container format version (typically `0x00020000`).
1001 pub version: u32,
1002 /// Original file name stored in archive, if present.
1003 pub real_name: Option<String>,
1004 /// File comment, if present.
1005 pub comment: Option<String>,
1006 /// Complete timestamps record.
1007 pub timestamps: Option<AppleDatesInfo>,
1008 /// Backup timestamp in seconds since Unix epoch, if recorded.
1009 pub backup_timestamp_sec: Option<i64>,
1010 /// Decoded Macintosh Finder information.
1011 pub finder_info: Option<FinderInfo>,
1012 /// Extended attributes decoded from modern OS X `ATTR` header.
1013 pub extended_attributes: Vec<AppleExtendedAttribute>,
1014 /// Preserved unrecognized archive entries (e.g. icons, legacy OS info).
1015 pub unrecognized_entries: Vec<AppleRawEntry>,
1016 /// Raw data fork payload (AppleSingle only).
1017 #[serde(skip_serializing)]
1018 pub data_fork: Option<Vec<u8>>,
1019 /// Raw resource fork payload.
1020 #[serde(skip_serializing)]
1021 pub resource_fork: Option<Vec<u8>>,
1022 /// Size of data fork in bytes, if present.
1023 pub data_fork_size: Option<usize>,
1024 /// Size of resource fork in bytes, if present.
1025 pub resource_fork_size: Option<usize>,
1026 /// Table of all entry descriptors found in container.
1027 pub entries: Vec<AppleArchiveEntry>,
1028}
1029
1030impl AppleArchive {
1031 /// Serializes archive metadata to compact JSON string.
1032 pub fn to_json(&self) -> Result<String> {
1033 serde_json::to_string(self)
1034 .context("Failed to serialize AppleArchive to JSON")
1035 }
1036
1037 /// Serializes archive metadata to pretty-printed JSON string.
1038 pub fn to_json_pretty(&self) -> Result<String> {
1039 serde_json::to_string_pretty(self)
1040 .context("Failed to serialize AppleArchive to pretty JSON")
1041 }
1042
1043 /// Converts archive metadata to `serde_json::Value`.
1044 pub fn to_json_value(&self) -> Result<serde_json::Value> {
1045 serde_json::to_value(self)
1046 .context("Failed to convert AppleArchive to serde_json::Value")
1047 }
1048}
1049
1050/// Reads an AppleSingle or AppleDouble file from a raw byte slice.
1051pub fn read_apple_single_double(bytes: &[u8]) -> Result<AppleArchive> {
1052 ensure!(
1053 bytes.len() >= 26,
1054 "File too small to be AppleSingle/AppleDouble (minimum 26 bytes header)"
1055 );
1056
1057 let magic_raw = read_u32_be(bytes, 0)?;
1058 let (format, is_big_endian) = if magic_raw == APPLESINGLE_MAGIC_BE {
1059 (AppleFormat::AppleSingle, true)
1060 } else if magic_raw == APPLEDOUBLE_MAGIC_BE {
1061 (AppleFormat::AppleDouble, true)
1062 } else if magic_raw == APPLESINGLE_MAGIC_LE {
1063 (AppleFormat::AppleSingle, false)
1064 } else if magic_raw == APPLEDOUBLE_MAGIC_LE {
1065 (AppleFormat::AppleDouble, false)
1066 } else {
1067 bail!("Invalid AppleSingle/AppleDouble magic: {magic_raw:#010x}");
1068 };
1069
1070 let version = if is_big_endian {
1071 read_u32_be(bytes, 4)?
1072 } else {
1073 read_u32_le(bytes, 4)?
1074 };
1075
1076 let num_entries = if is_big_endian {
1077 read_u16_be(bytes, 24)?
1078 } else {
1079 read_u16_le(bytes, 24)?
1080 };
1081
1082 let entries = parse_descriptors(bytes, num_entries, is_big_endian)?;
1083
1084 let mut real_name = None;
1085 let mut comment = None;
1086 let mut timestamps = None;
1087 let mut backup_timestamp_sec = None;
1088 let mut finder_info = None;
1089 let mut extended_attributes = Vec::new();
1090 let mut unrecognized_entries = Vec::new();
1091 let mut data_fork = None;
1092 let mut resource_fork = None;
1093
1094 for entry in &entries {
1095 let start = usize::try_from(entry.offset)
1096 .context("Entry offset exceeds usize")?;
1097 let len = usize::try_from(entry.length)
1098 .context("Entry length exceeds usize")?;
1099 let end = start
1100 .checked_add(len)
1101 .context("Entry boundary calculation overflow")?;
1102 let slice = bytes.get(start..end).ok_or_else(|| {
1103 anyhow::anyhow!("Entry out of file bounds: {start}..{end}")
1104 })?;
1105
1106 match entry.entry_type {
1107 EntryType::DataFork => {
1108 data_fork = Some(slice.to_vec());
1109 }
1110 EntryType::ResourceFork => {
1111 resource_fork = Some(slice.to_vec());
1112 }
1113 EntryType::RealName => {
1114 let name = String::from_utf8_lossy(slice)
1115 .trim_matches('\0')
1116 .to_string();
1117 if !name.is_empty() {
1118 real_name = Some(name);
1119 }
1120 }
1121 EntryType::Comment => {
1122 let text = String::from_utf8_lossy(slice)
1123 .trim_matches('\0')
1124 .to_string();
1125 if !text.is_empty() {
1126 comment = Some(text);
1127 }
1128 }
1129 EntryType::FileDatesInfo => {
1130 let (ts, backup) = parse_dates_info(slice)?;
1131 timestamps = Some(ts);
1132 backup_timestamp_sec = backup;
1133 }
1134 EntryType::FinderInfo => {
1135 let (finfo, xattrs) =
1136 parse_finder_info(slice, bytes, is_big_endian)?;
1137 finder_info = Some(finfo);
1138 extended_attributes = xattrs;
1139 }
1140 _ => {
1141 unrecognized_entries.push(AppleRawEntry {
1142 entry_id: entry.raw_id,
1143 data: slice.to_vec(),
1144 });
1145 }
1146 }
1147 }
1148
1149 let data_fork_size = data_fork.as_ref().map(Vec::len);
1150 let resource_fork_size = resource_fork.as_ref().map(Vec::len);
1151
1152 Ok(AppleArchive {
1153 format,
1154 version,
1155 real_name,
1156 comment,
1157 timestamps,
1158 backup_timestamp_sec,
1159 finder_info,
1160 extended_attributes,
1161 unrecognized_entries,
1162 data_fork,
1163 resource_fork,
1164 data_fork_size,
1165 resource_fork_size,
1166 entries,
1167 })
1168}
1169
1170fn parse_dates_info(slice: &[u8]) -> Result<(AppleDatesInfo, Option<i64>)> {
1171 ensure!(
1172 slice.len() >= 4,
1173 "FileDatesInfo too short (minimum 4 bytes required)"
1174 );
1175
1176 let creation_raw = read_u32_be(slice, 0)?;
1177 let mod_raw = if slice.len() >= 8 {
1178 read_u32_be(slice, 4)?
1179 } else {
1180 TIMESTAMP_UNSET_SENTINEL
1181 };
1182 let backup_raw = if slice.len() >= 12 {
1183 read_u32_be(slice, 8)?
1184 } else {
1185 TIMESTAMP_UNSET_SENTINEL
1186 };
1187 let access_raw = if slice.len() >= 16 {
1188 read_u32_be(slice, 12)?
1189 } else {
1190 TIMESTAMP_UNSET_SENTINEL
1191 };
1192
1193 let convert_timestamp = |raw: u32| -> Option<i64> {
1194 if raw == TIMESTAMP_UNSET_SENTINEL {
1195 None
1196 } else {
1197 let signed_seconds =
1198 i64::from(i32::from_be_bytes(raw.to_be_bytes()));
1199 SECONDS_1970_TO_2000.checked_add(signed_seconds)
1200 }
1201 };
1202
1203 let birthtime_sec = convert_timestamp(creation_raw);
1204 // Reason for fallback: If modification timestamp is missing or unset in the record, fall back to birthtime or Unix epoch 0.
1205 let mtime_sec = convert_timestamp(mod_raw).or(birthtime_sec).unwrap_or(0);
1206 // Reason for fallback: If access timestamp is missing or unset in the record, default to the file modification time.
1207 let atime_sec = convert_timestamp(access_raw).unwrap_or(mtime_sec);
1208 let backup_sec = convert_timestamp(backup_raw);
1209
1210 let timestamps = AppleDatesInfo {
1211 birthtime_sec,
1212 mtime_sec,
1213 ctime_sec: mtime_sec,
1214 atime_sec,
1215 backup_sec,
1216 };
1217
1218 Ok((timestamps, backup_sec))
1219}
1220
1221fn parse_finder_info(
1222 slice: &[u8],
1223 file_bytes: &[u8],
1224 is_big_endian: bool,
1225) -> Result<(FinderInfo, Vec<AppleExtendedAttribute>)> {
1226 ensure!(
1227 slice.len() >= 16,
1228 "FinderInfo must be at least 16 bytes for FInfo"
1229 );
1230
1231 let type_bytes = slice
1232 .get(0..4)
1233 .ok_or_else(|| anyhow::anyhow!("Missing file type bytes"))?;
1234 let creator_bytes = slice
1235 .get(4..8)
1236 .ok_or_else(|| anyhow::anyhow!("Missing creator bytes"))?;
1237
1238 let top = if is_big_endian {
1239 read_i16_be(slice, 0)?
1240 } else {
1241 read_i16_le(slice, 0)?
1242 };
1243 let left = if is_big_endian {
1244 read_i16_be(slice, 2)?
1245 } else {
1246 read_i16_le(slice, 2)?
1247 };
1248 let bottom = if is_big_endian {
1249 read_i16_be(slice, 4)?
1250 } else {
1251 read_i16_le(slice, 4)?
1252 };
1253 let right = if is_big_endian {
1254 read_i16_be(slice, 6)?
1255 } else {
1256 read_i16_le(slice, 6)?
1257 };
1258
1259 let is_type_printable =
1260 type_bytes.iter().all(|&b| (0x20..=0x7e).contains(&b));
1261 let is_creator_printable =
1262 creator_bytes.iter().all(|&b| (0x20..=0x7e).contains(&b));
1263
1264 let (file_type, file_creator, window_bounds) = if (!is_type_printable
1265 || !is_creator_printable)
1266 && (bottom > top && right > left && bottom < 4000 && right < 4000)
1267 {
1268 (
1269 String::new(),
1270 String::new(),
1271 Some([top, left, bottom, right]),
1272 )
1273 } else {
1274 let f_type = if type_bytes == [0, 0, 0, 0] {
1275 String::new()
1276 } else {
1277 String::from_utf8_lossy(type_bytes).to_string()
1278 };
1279 let f_creator = if creator_bytes == [0, 0, 0, 0] {
1280 String::new()
1281 } else {
1282 String::from_utf8_lossy(creator_bytes).to_string()
1283 };
1284 (f_type, f_creator, None)
1285 };
1286
1287 let raw_flags = if is_big_endian {
1288 read_u16_be(slice, 8)?
1289 } else {
1290 read_u16_le(slice, 8)?
1291 };
1292
1293 let loc_v = if is_big_endian {
1294 read_i16_be(slice, 10)?
1295 } else {
1296 read_i16_le(slice, 10)?
1297 };
1298 let loc_h = if is_big_endian {
1299 read_i16_be(slice, 12)?
1300 } else {
1301 read_i16_le(slice, 12)?
1302 };
1303 let folder_id = if is_big_endian {
1304 read_i16_be(slice, 14)?
1305 } else {
1306 read_i16_le(slice, 14)?
1307 };
1308
1309 // Reason for fallback: Bit shift and mask guarantees the value is within 0..7; defaults to 0 (None) if conversion fails.
1310 let label_idx = u8::try_from((raw_flags >> 1) & 0x07).unwrap_or(0);
1311 let label = FinderLabel::from_index(label_idx);
1312
1313 let flags = FinderFlags::from_raw_u16(raw_flags);
1314
1315 let is_directory = window_bounds.is_some();
1316
1317 let extended = if slice.len() >= 32 {
1318 parse_extended_finder_info(slice, is_big_endian, is_directory)?
1319 } else {
1320 None
1321 };
1322
1323 let mut extended_attributes = Vec::new();
1324 if slice.len() > 70 {
1325 if let Ok(attrs) = parse_apple_double_xattrs(slice, file_bytes) {
1326 extended_attributes = attrs;
1327 }
1328 }
1329
1330 let finfo = FinderInfo {
1331 file_type,
1332 file_creator,
1333 label,
1334 flags,
1335 location: (loc_v, loc_h),
1336 folder_id,
1337 extended,
1338 window_bounds,
1339 };
1340
1341 Ok((finfo, extended_attributes))
1342}
1343
1344fn parse_apple_double_xattrs(
1345 finder_slice: &[u8],
1346 file_bytes: &[u8],
1347) -> Result<Vec<AppleExtendedAttribute>> {
1348 let attr_offset: usize = if finder_slice.len() >= 38
1349 && read_u32_be(finder_slice, 34).ok() == Some(ATTR_MAGIC_BE)
1350 {
1351 34_usize
1352 } else if finder_slice.len() >= 36
1353 && read_u32_be(finder_slice, 32).ok() == Some(ATTR_MAGIC_BE)
1354 {
1355 32_usize
1356 } else {
1357 bail!("ATTR magic not found in extended FinderInfo");
1358 };
1359
1360 let flags_pos = attr_offset
1361 .checked_add(32_usize)
1362 .context("ATTR flags overflow")?;
1363 let num_pos = flags_pos
1364 .checked_add(2_usize)
1365 .context("ATTR numattrs overflow")?;
1366
1367 let num_attrs = read_u16_be(finder_slice, num_pos)?;
1368 let mut current_desc_offset = num_pos
1369 .checked_add(2_usize)
1370 .context("First attribute descriptor overflow")?;
1371
1372 let mut xattrs = Vec::new();
1373
1374 for _ in 0..num_attrs {
1375 let entry_offset = read_u32_be(finder_slice, current_desc_offset)?;
1376 let entry_len = read_u32_be(
1377 finder_slice,
1378 current_desc_offset
1379 .checked_add(4)
1380 .context("Length pos overflow")?,
1381 )?;
1382 let namelen = *finder_slice
1383 .get(
1384 current_desc_offset
1385 .checked_add(10)
1386 .context("Namelen pos overflow")?,
1387 )
1388 .ok_or_else(|| anyhow::anyhow!("Namelen byte out of bounds"))?;
1389
1390 let name_start = current_desc_offset
1391 .checked_add(11)
1392 .context("Name start overflow")?;
1393 let name_len_usize = usize::from(namelen);
1394 let name_end = name_start
1395 .checked_add(name_len_usize)
1396 .context("Name end overflow")?;
1397
1398 let name_bytes = finder_slice
1399 .get(name_start..name_end)
1400 .ok_or_else(|| anyhow::anyhow!("Name bytes out of bounds"))?;
1401 let name_str = String::from_utf8_lossy(name_bytes)
1402 .trim_matches('\0')
1403 .to_string();
1404
1405 let total_desc = usize::from(namelen).saturating_add(11);
1406 let rem = total_desc & 3;
1407 let pad = if rem == 0 {
1408 0
1409 } else {
1410 4_usize.saturating_sub(rem)
1411 };
1412 current_desc_offset = name_end
1413 .checked_add(pad)
1414 .context("Descriptor stride overflow")?;
1415
1416 let data_off = usize::try_from(entry_offset)
1417 .context("Entry offset exceeds usize")?;
1418 let data_len_usize =
1419 usize::try_from(entry_len).context("Entry length exceeds usize")?;
1420 let data_end = data_off
1421 .checked_add(data_len_usize)
1422 .context("Data end overflow")?;
1423
1424 let payload = if let Some(sl) = file_bytes.get(data_off..data_end) {
1425 sl.to_vec()
1426 } else if let Some(sl) = finder_slice.get(data_off..data_end) {
1427 sl.to_vec()
1428 } else {
1429 Vec::new()
1430 };
1431
1432 let size = payload.len();
1433 xattrs.push(AppleExtendedAttribute {
1434 name: name_str,
1435 data: payload,
1436 size,
1437 });
1438 }
1439
1440 Ok(xattrs)
1441}
1442
1443fn read_u16_be(bytes: &[u8], offset: usize) -> Result<u16> {
1444 let end = offset
1445 .checked_add(2)
1446 .context("u16 read offset calculation overflow")?;
1447 let slice = bytes.get(offset..end).ok_or_else(|| {
1448 anyhow::anyhow!("Offset {offset} out of bounds for u16")
1449 })?;
1450 let arr: [u8; 2] = slice
1451 .try_into()
1452 .context("Failed to convert slice to u16 array")?;
1453 Ok(u16::from_be_bytes(arr))
1454}
1455
1456fn read_u16_le(bytes: &[u8], offset: usize) -> Result<u16> {
1457 let end = offset
1458 .checked_add(2)
1459 .context("u16 read offset calculation overflow")?;
1460 let slice = bytes.get(offset..end).ok_or_else(|| {
1461 anyhow::anyhow!("Offset {offset} out of bounds for u16")
1462 })?;
1463 let arr: [u8; 2] = slice
1464 .try_into()
1465 .context("Failed to convert slice to u16 array")?;
1466 Ok(u16::from_le_bytes(arr))
1467}
1468
1469fn read_i16_be(bytes: &[u8], offset: usize) -> Result<i16> {
1470 let end = offset
1471 .checked_add(2)
1472 .context("i16 read offset calculation overflow")?;
1473 let slice = bytes.get(offset..end).ok_or_else(|| {
1474 anyhow::anyhow!("Offset {offset} out of bounds for i16")
1475 })?;
1476 let arr: [u8; 2] = slice
1477 .try_into()
1478 .context("Failed to convert slice to i16 array")?;
1479 Ok(i16::from_be_bytes(arr))
1480}
1481
1482fn read_i16_le(bytes: &[u8], offset: usize) -> Result<i16> {
1483 let end = offset
1484 .checked_add(2)
1485 .context("i16 read offset calculation overflow")?;
1486 let slice = bytes.get(offset..end).ok_or_else(|| {
1487 anyhow::anyhow!("Offset {offset} out of bounds for i16")
1488 })?;
1489 let arr: [u8; 2] = slice
1490 .try_into()
1491 .context("Failed to convert slice to i16 array")?;
1492 Ok(i16::from_le_bytes(arr))
1493}
1494
1495fn read_u32_be(bytes: &[u8], offset: usize) -> Result<u32> {
1496 let end = offset
1497 .checked_add(4)
1498 .context("u32 read offset calculation overflow")?;
1499 let slice = bytes.get(offset..end).ok_or_else(|| {
1500 anyhow::anyhow!("Offset {offset} out of bounds for u32")
1501 })?;
1502 let arr: [u8; 4] = slice
1503 .try_into()
1504 .context("Failed to convert slice to u32 array")?;
1505 Ok(u32::from_be_bytes(arr))
1506}
1507
1508fn read_u32_le(bytes: &[u8], offset: usize) -> Result<u32> {
1509 let end = offset
1510 .checked_add(4)
1511 .context("u32 read offset calculation overflow")?;
1512 let slice = bytes.get(offset..end).ok_or_else(|| {
1513 anyhow::anyhow!("Offset {offset} out of bounds for u32")
1514 })?;
1515 let arr: [u8; 4] = slice
1516 .try_into()
1517 .context("Failed to convert slice to u32 array")?;
1518 Ok(u32::from_le_bytes(arr))
1519}
1520
1521fn parse_descriptors(
1522 bytes: &[u8],
1523 num_entries: u16,
1524 is_big_endian: bool,
1525) -> Result<Vec<AppleArchiveEntry>> {
1526 let mut entries = Vec::with_capacity(usize::from(num_entries));
1527 let mut current_offset: usize = 26;
1528
1529 for _ in 0..num_entries {
1530 let entry_id = if is_big_endian {
1531 read_u32_be(bytes, current_offset)?
1532 } else {
1533 read_u32_le(bytes, current_offset)?
1534 };
1535 let offset_pos = current_offset
1536 .checked_add(4)
1537 .context("Descriptor offset overflow")?;
1538 let entry_offset = if is_big_endian {
1539 read_u32_be(bytes, offset_pos)?
1540 } else {
1541 read_u32_le(bytes, offset_pos)?
1542 };
1543 let len_pos = current_offset
1544 .checked_add(8)
1545 .context("Descriptor length pos overflow")?;
1546 let entry_length = if is_big_endian {
1547 read_u32_be(bytes, len_pos)?
1548 } else {
1549 read_u32_le(bytes, len_pos)?
1550 };
1551
1552 current_offset = current_offset
1553 .checked_add(12)
1554 .context("Descriptor advance overflow")?;
1555
1556 let entry_type = EntryType::from_u32(entry_id);
1557 entries.push(AppleArchiveEntry {
1558 entry_type,
1559 raw_id: entry_id,
1560 name: entry_type.as_str().to_string(),
1561 offset: entry_offset,
1562 length: entry_length,
1563 });
1564 }
1565
1566 Ok(entries)
1567}
1568
1569fn parse_extended_finder_info(
1570 slice: &[u8],
1571 is_big_endian: bool,
1572 is_directory: bool,
1573) -> Result<Option<ExtendedFinderInfo>> {
1574 let script_byte = *slice
1575 .get(24)
1576 .ok_or_else(|| anyhow::anyhow!("Missing script byte"))?;
1577 let script = i8::from_be_bytes([script_byte]);
1578 let xflags = *slice
1579 .get(25)
1580 .ok_or_else(|| anyhow::anyhow!("Missing xflags byte"))?;
1581 let comment = if is_big_endian {
1582 read_i16_be(slice, 26)?
1583 } else {
1584 read_i16_le(slice, 26)?
1585 };
1586 let put_away = if is_big_endian {
1587 read_u32_be(slice, 28)?
1588 } else {
1589 read_u32_le(slice, 28)?
1590 };
1591 let (icon_id, scroll_position) = if is_directory {
1592 let scroll_v = if is_big_endian {
1593 read_i16_be(slice, 16)?
1594 } else {
1595 read_i16_le(slice, 16)?
1596 };
1597 let scroll_h = if is_big_endian {
1598 read_i16_be(slice, 18)?
1599 } else {
1600 read_i16_le(slice, 18)?
1601 };
1602 (0, Some((scroll_v, scroll_h)))
1603 } else {
1604 let icon_id = if is_big_endian {
1605 read_i16_be(slice, 16)?
1606 } else {
1607 read_i16_le(slice, 16)?
1608 };
1609 (icon_id, None)
1610 };
1611 Ok(Some(ExtendedFinderInfo {
1612 icon_id,
1613 script,
1614 xflags: ExtendedFlags::from_raw_u8(xflags),
1615 comment,
1616 put_away,
1617 scroll_position,
1618 }))
1619}
1620
1621/// Serializes an [`AppleArchive`] to a raw byte buffer (AppleSingle or AppleDouble).
1622pub fn write_apple_single_double(archive: &AppleArchive) -> Result<Vec<u8>> {
1623 let magic = match archive.format {
1624 AppleFormat::AppleSingle => APPLESINGLE_MAGIC_BE,
1625 AppleFormat::AppleDouble => APPLEDOUBLE_MAGIC_BE,
1626 };
1627 let version = if archive.version != 0 {
1628 archive.version
1629 } else {
1630 VERSION_2_0_BE
1631 };
1632
1633 struct RawEntry {
1634 raw_id: u32,
1635 data: Vec<u8>,
1636 }
1637
1638 let mut raw_entries: Vec<RawEntry> = Vec::new();
1639
1640 // 1. Data Fork (Entry ID 1, AppleSingle only)
1641 if archive.format == AppleFormat::AppleSingle {
1642 if let Some(ref data) = archive.data_fork {
1643 raw_entries.push(RawEntry {
1644 raw_id: EntryType::DataFork.to_u32(),
1645 data: data.clone(),
1646 });
1647 }
1648 }
1649
1650 // 2. Resource Fork (Entry ID 2)
1651 if let Some(ref rsrc) = archive.resource_fork {
1652 raw_entries.push(RawEntry {
1653 raw_id: EntryType::ResourceFork.to_u32(),
1654 data: rsrc.clone(),
1655 });
1656 }
1657
1658 // 3. Real Name (Entry ID 3)
1659 if let Some(ref name) = archive.real_name {
1660 raw_entries.push(RawEntry {
1661 raw_id: EntryType::RealName.to_u32(),
1662 data: name.as_bytes().to_vec(),
1663 });
1664 }
1665
1666 // 4. Comment (Entry ID 4)
1667 if let Some(ref comment) = archive.comment {
1668 raw_entries.push(RawEntry {
1669 raw_id: EntryType::Comment.to_u32(),
1670 data: comment.as_bytes().to_vec(),
1671 });
1672 }
1673
1674 // 5. File Dates Info (Entry ID 8)
1675 if let Some(ref ts) = archive.timestamps {
1676 let mut dates_bytes = Vec::with_capacity(16);
1677 let encode_ts = |sec_opt: Option<i64>| -> [u8; 4] {
1678 let Some(sec) = sec_opt else {
1679 return TIMESTAMP_UNSET_SENTINEL.to_be_bytes();
1680 };
1681 let diff = sec.saturating_sub(SECONDS_1970_TO_2000);
1682 // Reason for fallback: timestamps exceeding i32 range clamp to i32::MAX to prevent overflow
1683 let val = i32::try_from(diff).unwrap_or(i32::MAX);
1684 val.to_be_bytes()
1685 };
1686
1687 dates_bytes.extend_from_slice(&encode_ts(ts.birthtime_sec));
1688 dates_bytes.extend_from_slice(&encode_ts(Some(ts.mtime_sec)));
1689 dates_bytes.extend_from_slice(&encode_ts(
1690 ts.backup_sec.or(archive.backup_timestamp_sec),
1691 ));
1692 dates_bytes.extend_from_slice(&encode_ts(Some(ts.atime_sec)));
1693
1694 raw_entries.push(RawEntry {
1695 raw_id: EntryType::FileDatesInfo.to_u32(),
1696 data: dates_bytes,
1697 });
1698 }
1699
1700 // 6. Finder Info (Entry ID 9)
1701 if archive.finder_info.is_some() || !archive.extended_attributes.is_empty()
1702 {
1703 let mut finfo_bytes = vec![0u8; 32];
1704 if let Some(ref finfo) = archive.finder_info {
1705 if let Some(bounds) = finfo.window_bounds {
1706 if let Some(slot) = finfo_bytes.get_mut(0..2) {
1707 slot.copy_from_slice(&bounds[0].to_be_bytes());
1708 }
1709 if let Some(slot) = finfo_bytes.get_mut(2..4) {
1710 slot.copy_from_slice(&bounds[1].to_be_bytes());
1711 }
1712 if let Some(slot) = finfo_bytes.get_mut(4..6) {
1713 slot.copy_from_slice(&bounds[2].to_be_bytes());
1714 }
1715 if let Some(slot) = finfo_bytes.get_mut(6..8) {
1716 slot.copy_from_slice(&bounds[3].to_be_bytes());
1717 }
1718 } else {
1719 let type_bytes = finfo.file_type.as_bytes();
1720 for (i, &b) in type_bytes.iter().take(4).enumerate() {
1721 if let Some(slot) = finfo_bytes.get_mut(i) {
1722 *slot = b;
1723 }
1724 }
1725 let creator_bytes = finfo.file_creator.as_bytes();
1726 for (i, &b) in creator_bytes.iter().take(4).enumerate() {
1727 if let Some(slot) =
1728 finfo_bytes.get_mut(4_usize.saturating_add(i))
1729 {
1730 *slot = b;
1731 }
1732 }
1733 }
1734
1735 let raw_flags = finfo.raw_flags();
1736
1737 if let Some(slot) = finfo_bytes.get_mut(8..10) {
1738 slot.copy_from_slice(&raw_flags.to_be_bytes());
1739 }
1740 if let Some(slot) = finfo_bytes.get_mut(10..12) {
1741 slot.copy_from_slice(&finfo.location.0.to_be_bytes());
1742 }
1743 if let Some(slot) = finfo_bytes.get_mut(12..14) {
1744 slot.copy_from_slice(&finfo.location.1.to_be_bytes());
1745 }
1746 if let Some(slot) = finfo_bytes.get_mut(14..16) {
1747 slot.copy_from_slice(&finfo.folder_id.to_be_bytes());
1748 }
1749
1750 if let Some(ref ext) = finfo.extended {
1751 if finfo.window_bounds.is_some()
1752 || ext.scroll_position.is_some()
1753 {
1754 // Reason for fallback: In Finder DXInfo / folder window records, if window bounds are present but scroll position was not explicitly specified, default to unscrolled origin (0, 0).
1755 let (v, h) = ext.scroll_position.unwrap_or((0, 0));
1756 if let Some(slot) = finfo_bytes.get_mut(16..18) {
1757 slot.copy_from_slice(&v.to_be_bytes());
1758 }
1759 if let Some(slot) = finfo_bytes.get_mut(18..20) {
1760 slot.copy_from_slice(&h.to_be_bytes());
1761 }
1762 } else {
1763 if let Some(slot) = finfo_bytes.get_mut(16..18) {
1764 slot.copy_from_slice(&ext.icon_id.to_be_bytes());
1765 }
1766 if let Some(slot) = finfo_bytes.get_mut(18..20) {
1767 slot.copy_from_slice(&[0u8, 0u8]);
1768 }
1769 }
1770 if let Some(slot) = finfo_bytes.get_mut(24) {
1771 *slot = u8::from_be_bytes(ext.script.to_be_bytes());
1772 }
1773 if let Some(slot) = finfo_bytes.get_mut(25) {
1774 *slot = ext.xflags.to_raw_u8();
1775 }
1776 if let Some(slot) = finfo_bytes.get_mut(26..28) {
1777 slot.copy_from_slice(&ext.comment.to_be_bytes());
1778 }
1779 if let Some(slot) = finfo_bytes.get_mut(28..32) {
1780 slot.copy_from_slice(&ext.put_away.to_be_bytes());
1781 }
1782 }
1783 }
1784
1785 raw_entries.push(RawEntry {
1786 raw_id: EntryType::FinderInfo.to_u32(),
1787 data: finfo_bytes,
1788 });
1789 }
1790
1791 // 7. Unrecognized entries
1792 for unrec in &archive.unrecognized_entries {
1793 raw_entries.push(RawEntry {
1794 raw_id: unrec.entry_id,
1795 data: unrec.data.clone(),
1796 });
1797 }
1798
1799 let num_entries = u16::try_from(raw_entries.len())
1800 .context("Too many archive entries to fit in u16")?;
1801 let header_and_descriptors_len = 26_usize
1802 .checked_add(
1803 usize::from(num_entries)
1804 .checked_mul(12)
1805 .context("Descriptors length overflow")?,
1806 )
1807 .context("Header length overflow")?;
1808
1809 if !archive.extended_attributes.is_empty() {
1810 if let Some(finfo_idx) = raw_entries
1811 .iter()
1812 .position(|e| e.raw_id == EntryType::FinderInfo.to_u32())
1813 {
1814 let mut entry_finder_start = header_and_descriptors_len;
1815 for i in 0..finfo_idx {
1816 if let Some(e) = raw_entries.get(i) {
1817 entry_finder_start =
1818 entry_finder_start.saturating_add(e.data.len());
1819 }
1820 }
1821
1822 let mut attr_block = Vec::new();
1823 attr_block.extend_from_slice(&[0u8, 0u8]); // 2 bytes padding to offset 34
1824 attr_block.extend_from_slice(&ATTR_MAGIC_BE.to_be_bytes()); // 4 bytes magic (offset 34..38)
1825 attr_block.extend_from_slice(&[0u8; 28]); // 28 bytes header (offset 38..66)
1826 attr_block.extend_from_slice(&[0u8, 0u8]); // 2 bytes debug/flags (offset 66..68)
1827 let num_attrs = u16::try_from(archive.extended_attributes.len())
1828 .context("Too many extended attributes")?;
1829 attr_block.extend_from_slice(&num_attrs.to_be_bytes()); // 2 bytes num_attrs (offset 68..70)
1830
1831 let mut descriptors_total_len = 0_usize;
1832 for attr in &archive.extended_attributes {
1833 let namelen = u8::try_from(attr.name.len())
1834 .context("Extended attribute name exceeds 255 bytes")?;
1835 let total_desc = usize::from(namelen).saturating_add(11);
1836 let rem = total_desc & 3;
1837 let pad = if rem == 0 {
1838 0
1839 } else {
1840 4_usize.saturating_sub(rem)
1841 };
1842 descriptors_total_len = descriptors_total_len
1843 .saturating_add(total_desc)
1844 .saturating_add(pad);
1845 }
1846
1847 let first_payload_rel =
1848 70_usize.saturating_add(descriptors_total_len);
1849 let mut running_payload_offset =
1850 entry_finder_start.saturating_add(first_payload_rel);
1851
1852 let mut payloads = Vec::new();
1853 for attr in &archive.extended_attributes {
1854 let namelen = u8::try_from(attr.name.len())
1855 .context("Extended attribute name exceeds 255 bytes")?;
1856 let entry_offset_u32 = u32::try_from(running_payload_offset)
1857 .context("Attribute offset exceeds u32")?;
1858 let entry_len_u32 = u32::try_from(attr.data.len())
1859 .context("Attribute length exceeds u32")?;
1860
1861 attr_block.extend_from_slice(&entry_offset_u32.to_be_bytes());
1862 attr_block.extend_from_slice(&entry_len_u32.to_be_bytes());
1863 attr_block.extend_from_slice(&0u16.to_be_bytes()); // flags
1864 attr_block.push(namelen);
1865 attr_block.extend_from_slice(attr.name.as_bytes());
1866
1867 let total_desc = usize::from(namelen).saturating_add(11);
1868 let rem = total_desc & 3;
1869 let pad = if rem == 0 {
1870 0
1871 } else {
1872 4_usize.saturating_sub(rem)
1873 };
1874 for _ in 0..pad {
1875 attr_block.push(0);
1876 }
1877
1878 running_payload_offset =
1879 running_payload_offset.saturating_add(attr.data.len());
1880 payloads.extend_from_slice(&attr.data);
1881 }
1882
1883 attr_block.extend_from_slice(&payloads);
1884
1885 if let Some(entry) = raw_entries.get_mut(finfo_idx) {
1886 entry.data.extend_from_slice(&attr_block);
1887 }
1888 }
1889 }
1890
1891 let mut out = Vec::with_capacity(header_and_descriptors_len);
1892 out.extend_from_slice(&magic.to_be_bytes());
1893 out.extend_from_slice(&version.to_be_bytes());
1894 out.extend_from_slice(b"Mac OS X ");
1895 out.extend_from_slice(&num_entries.to_be_bytes());
1896
1897 let mut current_offset = header_and_descriptors_len;
1898 for entry in &raw_entries {
1899 let entry_len = u32::try_from(entry.data.len())
1900 .context("Entry payload exceeds u32")?;
1901 let entry_off = u32::try_from(current_offset)
1902 .context("Entry offset exceeds u32")?;
1903 out.extend_from_slice(&entry.raw_id.to_be_bytes());
1904 out.extend_from_slice(&entry_off.to_be_bytes());
1905 out.extend_from_slice(&entry_len.to_be_bytes());
1906 current_offset = current_offset.saturating_add(entry.data.len());
1907 }
1908
1909 for entry in &raw_entries {
1910 out.extend_from_slice(&entry.data);
1911 }
1912
1913 Ok(out)
1914}
1915
1916#[cfg(test)]
1917#[allow(
1918 clippy::panic,
1919 clippy::expect_used,
1920 clippy::unwrap_used,
1921 clippy::unwrap_in_result,
1922 clippy::panic_in_result_fn,
1923 clippy::indexing_slicing,
1924 clippy::arithmetic_side_effects,
1925 reason = "Standard repository test boilerplate"
1926)]
1927mod tests {
1928 use super::*;
1929
1930 #[crate::ctb_test]
1931 fn test_apple_single_fixtures() -> anyhow::Result<()> {
1932 let data1 =
1933 get_apple_single_double_data("fixtures/AppleSingle/test file.as")
1934 .context("test file.as fixture missing")?;
1935 let archive1 = read_apple_single_double(&data1)?;
1936
1937 ensure!(archive1.format == AppleFormat::AppleSingle);
1938 ensure!(archive1.version == VERSION_2_0_BE);
1939 ensure!(archive1.real_name.as_deref() == Some("test file"));
1940 ensure!(archive1.data_fork.as_deref() == Some(b"test file".as_slice()));
1941 ensure!(archive1.data_fork_size == Some(9));
1942 ensure!(archive1.resource_fork_size == Some(332));
1943
1944 let finfo1 = archive1
1945 .finder_info
1946 .as_ref()
1947 .context("missing finder_info")?;
1948 ensure!(finfo1.file_type == "TEXT");
1949 ensure!(finfo1.file_creator == "ttxt");
1950 ensure!(finfo1.label.index() == 0);
1951 ensure!(finfo1.label.classic_color() == "Black");
1952 ensure!(finfo1.label.osx_color() == "None");
1953 ensure!(finfo1.flags.has_been_inited);
1954
1955 let ts1 = archive1.timestamps.as_ref().context("missing timestamps")?;
1956 ensure!(ts1.birthtime_sec == Some(1_789_356_839));
1957 ensure!(ts1.mtime_sec == 1_789_356_839);
1958
1959 // Test JSON export
1960 let json1 = archive1.to_json()?;
1961 ensure!(json1.contains("\"format\":\"AppleSingle\""));
1962 ensure!(json1.contains("\"real_name\":\"test file\""));
1963 let json_val1: serde_json::Value = serde_json::from_str(&json1)?;
1964 ensure!(json_val1["format"] == "AppleSingle");
1965
1966 // Test roundtrip serialization
1967 let written1 = write_apple_single_double(&archive1)?;
1968 let parsed1 = read_apple_single_double(&written1)?;
1969 ensure!(parsed1.format == AppleFormat::AppleSingle);
1970 ensure!(parsed1.real_name == archive1.real_name);
1971 ensure!(parsed1.data_fork == archive1.data_fork);
1972 ensure!(parsed1.resource_fork == archive1.resource_fork);
1973 ensure!(parsed1.finder_info == archive1.finder_info);
1974 ensure!(parsed1.timestamps == archive1.timestamps);
1975
1976 // Test second AppleSingle fixture with green label
1977 let data2 = get_apple_single_double_data(
1978 "fixtures/AppleSingle/test file green2.as",
1979 )
1980 .context("test file green2.as fixture missing")?;
1981 let archive2 = read_apple_single_double(&data2)?;
1982
1983 ensure!(archive2.format == AppleFormat::AppleSingle);
1984 ensure!(archive2.real_name.as_deref() == Some("test file green2"));
1985 ensure!(
1986 archive2.data_fork.as_deref() == Some(b"test file\x01".as_slice())
1987 );
1988 ensure!(archive2.data_fork_size == Some(10));
1989 ensure!(archive2.resource_fork_size == Some(372));
1990
1991 let finfo2 = archive2
1992 .finder_info
1993 .as_ref()
1994 .context("missing finder_info")?;
1995 ensure!(finfo2.file_type == "TEXT");
1996 ensure!(finfo2.file_creator == "ttxt");
1997 ensure!(finfo2.label.index() == 2);
1998 ensure!(finfo2.label.classic_color() == "Green");
1999 ensure!(finfo2.label.osx_color() == "Green");
2000
2001 let ts2 = archive2.timestamps.as_ref().context("missing timestamps")?;
2002 ensure!(ts2.birthtime_sec == Some(1_789_356_860));
2003 ensure!(ts2.mtime_sec == 1_789_356_875);
2004
2005 // Test roundtrip serialization of archive2
2006 let written2 = write_apple_single_double(&archive2)?;
2007 let parsed2 = read_apple_single_double(&written2)?;
2008 ensure!(parsed2.format == AppleFormat::AppleSingle);
2009 ensure!(parsed2.real_name == archive2.real_name);
2010 ensure!(parsed2.data_fork == archive2.data_fork);
2011 ensure!(parsed2.resource_fork == archive2.resource_fork);
2012
2013 Ok(())
2014 }
2015
2016 #[crate::ctb_test]
2017 fn test_apple_double_alongside_fixtures() -> anyhow::Result<()> {
2018 let data1 = get_apple_single_double_data(
2019 "fixtures/AppleDouble/Alongside/test file/._test file",
2020 )
2021 .context("Alongside ._test file missing")?;
2022 let archive1 = read_apple_single_double(&data1)?;
2023
2024 ensure!(archive1.format == AppleFormat::AppleDouble);
2025 ensure!(archive1.data_fork.is_none());
2026 ensure!(archive1.resource_fork_size == Some(332));
2027
2028 let finfo1 = archive1
2029 .finder_info
2030 .as_ref()
2031 .context("missing finder_info")?;
2032 ensure!(finfo1.file_type == "TEXT");
2033 ensure!(finfo1.file_creator == "ttxt");
2034 ensure!(finfo1.label.index() == 0);
2035
2036 let data2 = get_apple_single_double_data("fixtures/AppleDouble/Alongside/test file green2/._test file green2")
2037 .context("Alongside ._test file green2 missing")?;
2038 let archive2 = read_apple_single_double(&data2)?;
2039
2040 ensure!(archive2.format == AppleFormat::AppleDouble);
2041 ensure!(archive2.data_fork.is_none());
2042 ensure!(archive2.resource_fork_size == Some(372));
2043
2044 let finfo2 = archive2
2045 .finder_info
2046 .as_ref()
2047 .context("missing finder_info")?;
2048 ensure!(finfo2.file_type == "TEXT");
2049 ensure!(finfo2.file_creator == "ttxt");
2050 ensure!(finfo2.label.index() == 2);
2051 ensure!(finfo2.label.classic_color() == "Green");
2052 ensure!(finfo2.location == (88, 220));
2053
2054 // Test roundtrip serialization of AppleDouble
2055 let written2 = write_apple_single_double(&archive2)?;
2056 let parsed2 = read_apple_single_double(&written2)?;
2057 ensure!(parsed2.format == AppleFormat::AppleDouble);
2058 ensure!(parsed2.resource_fork == archive2.resource_fork);
2059 let parsed_finfo2 = parsed2
2060 .finder_info
2061 .as_ref()
2062 .context("missing parsed finfo")?;
2063 ensure!(parsed_finfo2.file_type == finfo2.file_type);
2064 ensure!(parsed_finfo2.file_creator == finfo2.file_creator);
2065 ensure!(parsed_finfo2.label.index() == finfo2.label.index());
2066 ensure!(parsed_finfo2.location == finfo2.location);
2067
2068 Ok(())
2069 }
2070
2071 #[crate::ctb_test]
2072 fn test_apple_double_brown_bin_fixture() -> anyhow::Result<()> {
2073 let data = get_apple_single_double_data(
2074 "fixtures/AppleDouble/__MACOSX-style/test file green2 brown.bin/__MACOSX/._test file green2 brown.bin",
2075 )
2076 .context("brown.bin fixture missing")?;
2077 let archive = read_apple_single_double(&data)?;
2078
2079 ensure!(archive.format == AppleFormat::AppleDouble);
2080 ensure!(archive.entries.len() == 1);
2081 ensure!(archive.entries[0].entry_type == EntryType::FinderInfo);
2082 ensure!(archive.resource_fork.is_none());
2083
2084 let finfo = archive
2085 .finder_info
2086 .as_ref()
2087 .context("missing finder_info")?;
2088 ensure!(finfo.file_type == "BINA");
2089 ensure!(finfo.file_creator == "SITx");
2090 ensure!(finfo.label.index() == 1);
2091 ensure!(finfo.label.classic_name() == "Project 2");
2092 ensure!(finfo.label.classic_color() == "Brown");
2093 ensure!(finfo.label.osx_color() == "Gray");
2094 ensure!(finfo.location == (448, 129));
2095
2096 Ok(())
2097 }
2098
2099 #[crate::ctb_test]
2100 fn test_apple_double_with_xattrs_roundtrip() -> anyhow::Result<()> {
2101 let archive = AppleArchive {
2102 format: AppleFormat::AppleDouble,
2103 version: VERSION_2_0_BE,
2104 real_name: Some("example.txt".to_string()),
2105 comment: Some("Test comment".to_string()),
2106 timestamps: Some(AppleDatesInfo {
2107 birthtime_sec: Some(1_700_000_000),
2108 mtime_sec: 1_700_001_000,
2109 ctime_sec: 1_700_001_000,
2110 atime_sec: 1_700_002_000,
2111 backup_sec: Some(1_700_000_500),
2112 }),
2113 backup_timestamp_sec: Some(1_700_000_500),
2114 finder_info: Some(FinderInfo {
2115 file_type: "TEXT".to_string(),
2116 file_creator: "ttxt".to_string(),
2117 label: FinderLabel::from_index(3),
2118 flags: FinderFlags {
2119 is_on_desk: false,
2120 is_shared: false,
2121 has_no_inits: false,
2122 has_been_inited: true,
2123 has_custom_icon: false,
2124 is_stationery: false,
2125 name_locked: false,
2126 has_bundle: false,
2127 is_invisible: false,
2128 is_alias: false,
2129 },
2130 location: (100, 200),
2131 folder_id: 0,
2132 extended: None,
2133 window_bounds: None,
2134 }),
2135 extended_attributes: vec![
2136 AppleExtendedAttribute {
2137 name: "com.apple.metadata:kMDItemWhereFroms".to_string(),
2138 data: b"https://example.com/download".to_vec(),
2139 size: 28,
2140 },
2141 AppleExtendedAttribute {
2142 name: "user.custom.note".to_string(),
2143 data: b"important payload".to_vec(),
2144 size: 17,
2145 },
2146 ],
2147 data_fork: None,
2148 resource_fork: Some(b"mock resource fork binary data".to_vec()),
2149 data_fork_size: None,
2150 resource_fork_size: Some(30),
2151 unrecognized_entries: Vec::new(),
2152 entries: Vec::new(),
2153 };
2154
2155 let bytes = write_apple_single_double(&archive)?;
2156 let parsed = read_apple_single_double(&bytes)?;
2157
2158 ensure!(parsed.format == AppleFormat::AppleDouble);
2159 ensure!(parsed.real_name == archive.real_name);
2160 ensure!(parsed.comment == archive.comment);
2161 ensure!(parsed.resource_fork == archive.resource_fork);
2162
2163 let parsed_ts =
2164 parsed.timestamps.as_ref().context("missing timestamps")?;
2165 ensure!(
2166 parsed_ts.birthtime_sec
2167 == archive.timestamps.as_ref().unwrap().birthtime_sec
2168 );
2169 ensure!(
2170 parsed_ts.mtime_sec
2171 == archive.timestamps.as_ref().unwrap().mtime_sec
2172 );
2173
2174 let parsed_finfo =
2175 parsed.finder_info.as_ref().context("missing finfo")?;
2176 ensure!(parsed_finfo.file_type == "TEXT");
2177 ensure!(parsed_finfo.file_creator == "ttxt");
2178 ensure!(parsed_finfo.location == (100, 200));
2179
2180 ensure!(parsed.extended_attributes.len() == 2);
2181 ensure!(
2182 parsed.extended_attributes[0].name
2183 == "com.apple.metadata:kMDItemWhereFroms"
2184 );
2185 ensure!(
2186 parsed.extended_attributes[0].data
2187 == b"https://example.com/download"
2188 );
2189 ensure!(parsed.extended_attributes[1].name == "user.custom.note");
2190 ensure!(parsed.extended_attributes[1].data == b"important payload");
2191
2192 Ok(())
2193 }
2194
2195 #[crate::ctb_test]
2196 fn test_apple_double_style_companion_paths() -> anyhow::Result<()> {
2197 let parent = Path::new("/tmp/testdir");
2198 let file = Path::new("hello.txt");
2199
2200 // Alongside style
2201 let alongside = get_companion_path(
2202 parent,
2203 file,
2204 false,
2205 AppleDoubleStyle::Alongside,
2206 None,
2207 None,
2208 );
2209 ensure!(alongside == PathBuf::from("/tmp/testdir/._hello.txt"));
2210
2211 // Zip style
2212 let root = Path::new("/tmp/root");
2213 let rel = Path::new("sub/hello.txt");
2214 let zip_path = get_companion_path(
2215 parent,
2216 file,
2217 false,
2218 AppleDoubleStyle::Zip,
2219 Some(root),
2220 Some(rel),
2221 );
2222 ensure!(
2223 zip_path == PathBuf::from("/tmp/root/__MACOSX/sub/._hello.txt")
2224 );
2225
2226 // Netatalk style for file
2227 let netatalk_file = get_companion_path(
2228 parent,
2229 file,
2230 false,
2231 AppleDoubleStyle::Netatalk,
2232 None,
2233 None,
2234 );
2235 ensure!(
2236 netatalk_file
2237 == PathBuf::from("/tmp/testdir/.AppleDouble/hello.txt")
2238 );
2239
2240 // Netatalk style for directory
2241 let dir = Path::new("subdir");
2242 let netatalk_dir = get_companion_path(
2243 parent,
2244 dir,
2245 true,
2246 AppleDoubleStyle::Netatalk,
2247 None,
2248 None,
2249 );
2250 ensure!(
2251 netatalk_dir
2252 == PathBuf::from("/tmp/testdir/subdir/.AppleDouble/.Parent")
2253 );
2254
2255 Ok(())
2256 }
2257
2258 #[crate::ctb_test]
2259 fn test_native_name_extensions_and_companions() -> Result<()> {
2260 let mut names = vec![
2261 std::ffi::OsString::from("caf\u{e9}"),
2262 std::ffi::OsString::from("cafe\u{301}"),
2263 ];
2264 #[cfg(unix)]
2265 {
2266 use std::os::unix::ffi::OsStringExt;
2267 names.push(std::ffi::OsString::from_vec(b"name\xff".to_vec()));
2268 }
2269 #[cfg(windows)]
2270 {
2271 use std::os::windows::ffi::OsStringExt;
2272 names.push(std::ffi::OsString::from_wide(&[
2273 110, 97, 109, 101, 0xD800,
2274 ]));
2275 }
2276 for name in names {
2277 for extension in [
2278 AppleSingleExtension::WithoutExtension,
2279 AppleSingleExtension::As,
2280 AppleSingleExtension::Asf,
2281 ] {
2282 let encoded = extension.apply_to_name(&name);
2283 ensure!(
2284 extension.strip_from_name(&encoded)
2285 == Some(name.as_os_str())
2286 );
2287 }
2288 let mut mixed_case = name.clone();
2289 mixed_case.push(".aSf");
2290 ensure!(
2291 AppleSingleExtension::Asf.strip_from_name(&mixed_case)
2292 == Some(name.as_os_str())
2293 );
2294 let mut companion = std::ffi::OsString::from("._");
2295 companion.push(&name);
2296 let relative = PathBuf::from("nested").join(&name);
2297 for style in [
2298 AppleDoubleStyle::Alongside,
2299 AppleDoubleStyle::Zip,
2300 AppleDoubleStyle::Netatalk,
2301 ] {
2302 let actual = get_companion_path(
2303 Path::new("destination"),
2304 Path::new(&name),
2305 false,
2306 style,
2307 Some(Path::new("destination")),
2308 Some(&relative),
2309 );
2310 let expected = match style {
2311 AppleDoubleStyle::Alongside => {
2312 PathBuf::from("destination").join(&companion)
2313 }
2314 AppleDoubleStyle::Zip => {
2315 PathBuf::from("destination/__MACOSX/nested")
2316 .join(&companion)
2317 }
2318 AppleDoubleStyle::Netatalk => {
2319 PathBuf::from("destination/.AppleDouble").join(&name)
2320 }
2321 };
2322 ensure!(actual == expected);
2323 }
2324 }
2325 ensure!(
2326 AppleSingleExtension::As
2327 .strip_from_name(std::ffi::OsStr::new(".as"))
2328 .is_none()
2329 );
2330 ensure!(
2331 AppleSingleExtension::As
2332 .strip_from_name(std::ffi::OsStr::new("file.asf"))
2333 .is_none()
2334 );
2335 Ok(())
2336 }
2337
2338 #[crate::ctb_test]
2339 fn test_apple_single_extension_handling() -> anyhow::Result<()> {
2340 ensure!(
2341 AppleSingleExtension::WithoutExtension.apply_to_name("file")
2342 == "file"
2343 );
2344 ensure!(AppleSingleExtension::As.apply_to_name("file") == "file.as");
2345 ensure!(AppleSingleExtension::Asf.apply_to_name("file") == "file.asf");
2346
2347 use std::str::FromStr;
2348 ensure!(
2349 AppleSingleExtension::from_str("as")? == AppleSingleExtension::As
2350 );
2351 ensure!(
2352 AppleSingleExtension::from_str("asf")? == AppleSingleExtension::Asf
2353 );
2354 ensure!(
2355 AppleSingleExtension::from_str("without-extension")?
2356 == AppleSingleExtension::WithoutExtension
2357 );
2358
2359 let read_opts = AppleReadOptions::default();
2360 ensure!(!read_opts.any_apple_single());
2361 let mut read_opts_single = read_opts;
2362 read_opts_single.read_apple_single_as = true;
2363 ensure!(read_opts_single.any_apple_single());
2364
2365 Ok(())
2366 }
2367
2368 #[crate::ctb_test]
2369 fn test_finder_label_dc_document_roundtrip() -> Result<()> {
2370 use ctb_formats_dcstring::{
2371 DcChar, DcMixedDecode, DcMixedEncode, DcMstring,
2372 };
2373
2374 for index in 0..=7 {
2375 let label = FinderLabel::try_from(index)?;
2376 let finfo = FinderInfo {
2377 file_type: "TEXT".to_string(),
2378 label,
2379 ..FinderInfo::default()
2380 };
2381 ctb_formats_dcstring::assert_dc_document_roundtrip(&finfo)?;
2382
2383 for numeric in [false, true] {
2384 let mut mst = DcMstring::new();
2385 mst.push_char(DcChar::from_short(401));
2386 mst.push_char(DcChar::from_short(403));
2387 "TEXT".encode_dc_mixed(&mut mst)?;
2388 mst.push_char(DcChar::from_short(405));
2389 if numeric {
2390 index.encode_dc_mixed(&mut mst)?;
2391 } else {
2392 label.encode_dc_mixed(&mut mst)?;
2393 }
2394 mst.push_char(DcChar::from_short(402));
2395 ctb_formats_dcstring::validate_dc_mixed_strict(&mst)
2396 .with_context(|| {
2397 format!("Finder label {index}, numeric={numeric}")
2398 })?;
2399 let decoded: FinderInfo = mst.decode(
2400 &ctb_formats_dcstring::DcProjectionPolicy::strict(),
2401 )?;
2402 ensure!(decoded == finfo);
2403 }
2404 }
2405 Ok(())
2406 }
2407
2408 #[crate::ctb_test]
2409 fn test_finder_label_equivalent_list_type_header() -> Result<()> {
2410 use ctb_formats_dcstring::{
2411 DcChar, DcMixedDecode, DcMixedEncode, DcProjectionPolicy,
2412 };
2413
2414 let finfo = FinderInfo {
2415 label: FinderLabel::InProgress,
2416 ..FinderInfo::default()
2417 };
2418 let encoded = finfo.to_dc_mixed()?;
2419 let mut tokens = encoded.to_dc_tokens()?;
2420 let prefix = [401, 405, 397, 310, 275, 487]
2421 .map(|id| DcChar::from_short(id).to_u128());
2422 ensure!(tokens.get(..prefix.len()) == Some(prefix.as_slice()));
2423 tokens.remove(4);
2424 ensure!(
2425 ctb_formats_dcstring::validate_dc_tokens_strict(&tokens).is_err(),
2426 "Untyped equivalent list passed strict validation"
2427 );
2428
2429 let mut old_encoded = ctb_formats_dcstring::DcMstring::new();
2430 for token in tokens {
2431 old_encoded.push_char(DcChar::from_u128(token));
2432 }
2433 ensure!(
2434 old_encoded
2435 .decode::<FinderInfo>(&DcProjectionPolicy::strict())
2436 .is_err(),
2437 "Untyped equivalent list was decoded"
2438 );
2439 for malformed in [
2440 vec![401, 405, 397, 487, 402],
2441 vec![401, 405, 397, 310, 275, 311, 402],
2442 vec![401, 405, 397, 310, 275, 487, 487, 311, 402],
2443 vec![401, 405, 397, 310, 275, 487, 312, 311, 402],
2444 vec![401, 405, 397, 310, 275, 487, 402],
2445 vec![401, 405, 397, 310, 275, 487],
2446 ] {
2447 let mut mst = ctb_formats_dcstring::DcMstring::new();
2448 for &token in &malformed {
2449 mst.push_char(DcChar::from_short(token));
2450 }
2451 ensure!(
2452 mst.decode::<FinderInfo>(&DcProjectionPolicy::strict())
2453 .is_err(),
2454 "Malformed equivalent list was decoded"
2455 );
2456 }
2457 Ok(())
2458 }
2459
2460 #[crate::ctb_test]
2461 fn test_finder_full_record_strict_roundtrip() -> Result<()> {
2462 for index in 0..=7 {
2463 for location in [(i16::MIN, i16::MAX), (-1, 1), (0, 0)] {
2464 for scroll_position in [None, Some((0, 0)), Some(location)] {
2465 let extended = ExtendedFinderInfo {
2466 icon_id: i16::MIN,
2467 script: i8::MIN,
2468 xflags: ExtendedFlags::from_raw_u8(0x85),
2469 comment: i16::MAX,
2470 put_away: u32::MAX,
2471 scroll_position,
2472 };
2473 ctb_formats_dcstring::assert_dc_document_roundtrip(
2474 &extended,
2475 )?;
2476 let finfo = FinderInfo {
2477 file_type: "TEXT".to_string(),
2478 file_creator: "ttxt".to_string(),
2479 label: FinderLabel::try_from(index)?,
2480 flags: FinderFlags::from_raw_u16(0xffc1),
2481 location,
2482 folder_id: i16::MIN,
2483 extended: Some(extended),
2484 window_bounds: Some([i16::MIN, -1, 1, i16::MAX]),
2485 };
2486 ctb_formats_dcstring::assert_dc_document_roundtrip(&finfo)?;
2487 }
2488 }
2489 }
2490 ctb_formats_dcstring::assert_dc_document_roundtrip(
2491 &FinderFlags::default(),
2492 )?;
2493 ctb_formats_dcstring::assert_dc_document_roundtrip(
2494 &ExtendedFlags::default(),
2495 )?;
2496 ctb_formats_dcstring::assert_dc_document_roundtrip(
2497 &ExtendedFinderInfo::default(),
2498 )?;
2499 ctb_formats_dcstring::assert_dc_document_roundtrip(&FinderInfo {
2500 extended: Some(ExtendedFinderInfo::default()),
2501 ..FinderInfo::default()
2502 })?;
2503 Ok(())
2504 }
2505
2506 #[crate::ctb_test]
2507 fn test_apple_dc_mixed_roundtrip() -> anyhow::Result<()> {
2508 use ctb_formats_dcstring::{
2509 DcMixedDecode, DcMixedEncode, DcMstring, DcProjectionPolicy,
2510 };
2511
2512 // 1. AppleFormat enum roundtrip with format Dcs (f315, f316)
2513 let fmt = AppleFormat::AppleDouble;
2514 let mut mst = DcMstring::new();
2515 fmt.encode_dc_mixed(&mut mst)?;
2516 let decoded_fmt: AppleFormat =
2517 mst.decode(&DcProjectionPolicy::strict())?;
2518 ensure!(decoded_fmt == fmt);
2519
2520 // 2. ExtendedFinderInfo roundtrip (begin = 490, end = 491; xflags preserved)
2521 let ext = ExtendedFinderInfo {
2522 icon_id: -16455,
2523 script: 1,
2524 xflags: ExtendedFlags::from_raw_u8(0x85),
2525 comment: 42,
2526 put_away: 105,
2527 scroll_position: Some((10, 20)),
2528 };
2529 let mut mst = DcMstring::new();
2530 ext.encode_dc_mixed(&mut mst)?;
2531 let decoded_ext: ExtendedFinderInfo =
2532 mst.decode(&DcProjectionPolicy::strict())?;
2533 ensure!(decoded_ext == ext);
2534 ctb_formats_dcstring::assert_dc_document_roundtrip(&ext)?;
2535
2536 // 3. FinderFlags bitmask conversion
2537 let label = FinderLabel::from_index(5);
2538 let raw_flags =
2539 0x4181u16 | (u16::from(label.index()).checked_shl(1).unwrap_or(0));
2540 let flags = FinderFlags::from_raw_u16(raw_flags);
2541 ensure!(flags.is_on_desk);
2542 ensure!(flags.has_no_inits);
2543 ensure!(flags.has_been_inited);
2544 ensure!(flags.is_invisible);
2545 ensure!(!flags.is_alias);
2546 ensure!(flags.to_raw_u16() == 0x4181u16);
2547
2548 // 4. FinderInfo roundtrip (begin = 401, end = 402)
2549 let finfo = FinderInfo {
2550 file_type: "TEXT".to_string(),
2551 file_creator: "ttxt".to_string(),
2552 label,
2553 flags,
2554 location: (120, 340),
2555 folder_id: -1,
2556 extended: Some(ext),
2557 window_bounds: Some([50, 60, 400, 500]),
2558 };
2559 let mut mst = DcMstring::new();
2560 finfo.encode_dc_mixed(&mut mst)?;
2561 let decoded_finfo: FinderInfo =
2562 mst.decode(&DcProjectionPolicy::strict())?;
2563 ensure!(decoded_finfo == finfo);
2564 ctb_formats_dcstring::assert_dc_document_roundtrip(&finfo)?;
2565
2566 // 5. Test decoding from Dc with semantic flags only
2567 let mut custom_mst = DcMstring::new();
2568 custom_mst.push_char(ctb_formats_dcstring::DcChar::from_short(401));
2569 custom_mst.push_char(ctb_formats_dcstring::DcChar::from_short(406));
2570 custom_mst.push_char(ctb_formats_dcstring::DcChar::from_short(388));
2571 custom_mst.push_char(ctb_formats_dcstring::dc::DC_BEGIN_LIST);
2572 custom_mst.push_char(ctb_formats_dcstring::DcChar::from_short(275));
2573 custom_mst.push_char(ctb_formats_dcstring::DcChar::from_short(499)); // ondesk
2574 custom_mst
2575 .push_char(ctb_formats_dcstring::dc::DC_LIST_ELEMENT_SEPARATOR);
2576 custom_mst.push_char(ctb_formats_dcstring::DcChar::from_short(501)); // noinits
2577 custom_mst
2578 .push_char(ctb_formats_dcstring::dc::DC_LIST_ELEMENT_SEPARATOR);
2579 custom_mst.push_char(ctb_formats_dcstring::DcChar::from_short(507)); // invisible
2580 custom_mst.push_char(ctb_formats_dcstring::dc::DC_END_LIST);
2581 custom_mst.push_char(ctb_formats_dcstring::DcChar::from_short(389));
2582 custom_mst.push_char(ctb_formats_dcstring::DcChar::from_short(402));
2583
2584 let decoded_custom: FinderInfo =
2585 custom_mst.decode(&DcProjectionPolicy::strict())?;
2586 ensure!(decoded_custom.flags.is_on_desk);
2587 ensure!(decoded_custom.flags.has_no_inits);
2588 ensure!(decoded_custom.flags.is_invisible);
2589 ensure!(!decoded_custom.flags.has_bundle);
2590
2591 Ok(())
2592 }
2593}
2594
2595/* Licensing details for TheUnarchiver, from License.txt:
2596
2597This program, "The Unarchiver", its accompanying libraries, "XADMaster"
2598and "UniversalDetector", and the various smaller utility programs, such
2599as "unar" and "lsar", are distributed under the GNU Lesser General
2600Public License as published by the Free Software Foundation; either
2601version 2.1 of the License, or (at your option) any later version.
2602
2603"UniversalDetector" is also available under other licenses, such as the
2604Mozilla Public License. Please refer to the files in its subdirectory
2605for further information.
2606
2607The GNU Lesser General Public License might be too restrictive for some
2608users of this code. Parts of the code are derived from earlier
2609LGPL-licensed code and will as such always be bound by the LGPL, but
2610some parts of the code are developed from scratch by the author of The
2611Unarchiver, Dag Ă…gren, and can thus be made available under a more
2612permissive license. For simplicity, everything is currently licensed
2613under the LGPL, but if you are interested in using any code from this
2614project under another license, please contact the author for further
2615information.
2616
2617 - Dag Ă…gren, <paracelsus@gmail.com>
2618
2619
2620
2621-----------------------------------------------------------------------
2622 GNU LESSER GENERAL PUBLIC LICENSE
2623 Version 2.1, February 1999
2624
2625 Copyright (C) 1991, 1999 Free Software Foundation, Inc.
2626 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2627 Everyone is permitted to copy and distribute verbatim copies
2628 of this license document, but changing it is not allowed.
2629
2630[This is the first released version of the Lesser GPL. It also counts
2631 as the successor of the GNU Library Public License, version 2, hence
2632 the version number 2.1.]
2633
2634 Preamble
2635
2636 The licenses for most software are designed to take away your
2637freedom to share and change it. By contrast, the GNU General Public
2638Licenses are intended to guarantee your freedom to share and change
2639free software--to make sure the software is free for all its users.
2640
2641 This license, the Lesser General Public License, applies to some
2642specially designated software packages--typically libraries--of the
2643Free Software Foundation and other authors who decide to use it. You
2644can use it too, but we suggest you first think carefully about whether
2645this license or the ordinary General Public License is the better
2646strategy to use in any particular case, based on the explanations below.
2647
2648 When we speak of free software, we are referring to freedom of use,
2649not price. Our General Public Licenses are designed to make sure that
2650you have the freedom to distribute copies of free software (and charge
2651for this service if you wish); that you receive source code or can get
2652it if you want it; that you can change the software and use pieces of
2653it in new free programs; and that you are informed that you can do
2654these things.
2655
2656 To protect your rights, we need to make restrictions that forbid
2657distributors to deny you these rights or to ask you to surrender these
2658rights. These restrictions translate to certain responsibilities for
2659you if you distribute copies of the library or if you modify it.
2660
2661 For example, if you distribute copies of the library, whether gratis
2662or for a fee, you must give the recipients all the rights that we gave
2663you. You must make sure that they, too, receive or can get the source
2664code. If you link other code with the library, you must provide
2665complete object files to the recipients, so that they can relink them
2666with the library after making changes to the library and recompiling
2667it. And you must show them these terms so they know their rights.
2668
2669 We protect your rights with a two-step method: (1) we copyright the
2670library, and (2) we offer you this license, which gives you legal
2671permission to copy, distribute and/or modify the library.
2672
2673 To protect each distributor, we want to make it very clear that
2674there is no warranty for the free library. Also, if the library is
2675modified by someone else and passed on, the recipients should know
2676that what they have is not the original version, so that the original
2677author's reputation will not be affected by problems that might be
2678introduced by others.
2679
2680 Finally, software patents pose a constant threat to the existence of
2681any free program. We wish to make sure that a company cannot
2682effectively restrict the users of a free program by obtaining a
2683restrictive license from a patent holder. Therefore, we insist that
2684any patent license obtained for a version of the library must be
2685consistent with the full freedom of use specified in this license.
2686
2687 Most GNU software, including some libraries, is covered by the
2688ordinary GNU General Public License. This license, the GNU Lesser
2689General Public License, applies to certain designated libraries, and
2690is quite different from the ordinary General Public License. We use
2691this license for certain libraries in order to permit linking those
2692libraries into non-free programs.
2693
2694 When a program is linked with a library, whether statically or using
2695a shared library, the combination of the two is legally speaking a
2696combined work, a derivative of the original library. The ordinary
2697General Public License therefore permits such linking only if the
2698entire combination fits its criteria of freedom. The Lesser General
2699Public License permits more lax criteria for linking other code with
2700the library.
2701
2702 We call this license the "Lesser" General Public License because it
2703does Less to protect the user's freedom than the ordinary General
2704Public License. It also provides other free software developers Less
2705of an advantage over competing non-free programs. These disadvantages
2706are the reason we use the ordinary General Public License for many
2707libraries. However, the Lesser license provides advantages in certain
2708special circumstances.
2709
2710 For example, on rare occasions, there may be a special need to
2711encourage the widest possible use of a certain library, so that it becomes
2712a de-facto standard. To achieve this, non-free programs must be
2713allowed to use the library. A more frequent case is that a free
2714library does the same job as widely used non-free libraries. In this
2715case, there is little to gain by limiting the free library to free
2716software only, so we use the Lesser General Public License.
2717
2718 In other cases, permission to use a particular library in non-free
2719programs enables a greater number of people to use a large body of
2720free software. For example, permission to use the GNU C Library in
2721non-free programs enables many more people to use the whole GNU
2722operating system, as well as its variant, the GNU/Linux operating
2723system.
2724
2725 Although the Lesser General Public License is Less protective of the
2726users' freedom, it does ensure that the user of a program that is
2727linked with the Library has the freedom and the wherewithal to run
2728that program using a modified version of the Library.
2729
2730 The precise terms and conditions for copying, distribution and
2731modification follow. Pay close attention to the difference between a
2732"work based on the library" and a "work that uses the library". The
2733former contains code derived from the library, whereas the latter must
2734be combined with the library in order to run.
2735
2736 GNU LESSER GENERAL PUBLIC LICENSE
2737 TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
2738
2739 0. This License Agreement applies to any software library or other
2740program which contains a notice placed by the copyright holder or
2741other authorized party saying it may be distributed under the terms of
2742this Lesser General Public License (also called "this License").
2743Each licensee is addressed as "you".
2744
2745 A "library" means a collection of software functions and/or data
2746prepared so as to be conveniently linked with application programs
2747(which use some of those functions and data) to form executables.
2748
2749 The "Library", below, refers to any such software library or work
2750which has been distributed under these terms. A "work based on the
2751Library" means either the Library or any derivative work under
2752copyright law: that is to say, a work containing the Library or a
2753portion of it, either verbatim or with modifications and/or translated
2754straightforwardly into another language. (Hereinafter, translation is
2755included without limitation in the term "modification".)
2756
2757 "Source code" for a work means the preferred form of the work for
2758making modifications to it. For a library, complete source code means
2759all the source code for all modules it contains, plus any associated
2760interface definition files, plus the scripts used to control compilation
2761and installation of the library.
2762
2763 Activities other than copying, distribution and modification are not
2764covered by this License; they are outside its scope. The act of
2765running a program using the Library is not restricted, and output from
2766such a program is covered only if its contents constitute a work based
2767on the Library (independent of the use of the Library in a tool for
2768writing it). Whether that is true depends on what the Library does
2769and what the program that uses the Library does.
2770
2771 1. You may copy and distribute verbatim copies of the Library's
2772complete source code as you receive it, in any medium, provided that
2773you conspicuously and appropriately publish on each copy an
2774appropriate copyright notice and disclaimer of warranty; keep intact
2775all the notices that refer to this License and to the absence of any
2776warranty; and distribute a copy of this License along with the
2777Library.
2778
2779 You may charge a fee for the physical act of transferring a copy,
2780and you may at your option offer warranty protection in exchange for a
2781fee.
2782
2783 2. You may modify your copy or copies of the Library or any portion
2784of it, thus forming a work based on the Library, and copy and
2785distribute such modifications or work under the terms of Section 1
2786above, provided that you also meet all of these conditions:
2787
2788 a) The modified work must itself be a software library.
2789
2790 b) You must cause the files modified to carry prominent notices
2791 stating that you changed the files and the date of any change.
2792
2793 c) You must cause the whole of the work to be licensed at no
2794 charge to all third parties under the terms of this License.
2795
2796 d) If a facility in the modified Library refers to a function or a
2797 table of data to be supplied by an application program that uses
2798 the facility, other than as an argument passed when the facility
2799 is invoked, then you must make a good faith effort to ensure that,
2800 in the event an application does not supply such function or
2801 table, the facility still operates, and performs whatever part of
2802 its purpose remains meaningful.
2803
2804 (For example, a function in a library to compute square roots has
2805 a purpose that is entirely well-defined independent of the
2806 application. Therefore, Subsection 2d requires that any
2807 application-supplied function or table used by this function must
2808 be optional: if the application does not supply it, the square
2809 root function must still compute square roots.)
2810
2811These requirements apply to the modified work as a whole. If
2812identifiable sections of that work are not derived from the Library,
2813and can be reasonably considered independent and separate works in
2814themselves, then this License, and its terms, do not apply to those
2815sections when you distribute them as separate works. But when you
2816distribute the same sections as part of a whole which is a work based
2817on the Library, the distribution of the whole must be on the terms of
2818this License, whose permissions for other licensees extend to the
2819entire whole, and thus to each and every part regardless of who wrote
2820it.
2821
2822Thus, it is not the intent of this section to claim rights or contest
2823your rights to work written entirely by you; rather, the intent is to
2824exercise the right to control the distribution of derivative or
2825collective works based on the Library.
2826
2827In addition, mere aggregation of another work not based on the Library
2828with the Library (or with a work based on the Library) on a volume of
2829a storage or distribution medium does not bring the other work under
2830the scope of this License.
2831
2832 3. You may opt to apply the terms of the ordinary GNU General Public
2833License instead of this License to a given copy of the Library. To do
2834this, you must alter all the notices that refer to this License, so
2835that they refer to the ordinary GNU General Public License, version 2,
2836instead of to this License. (If a newer version than version 2 of the
2837ordinary GNU General Public License has appeared, then you can specify
2838that version instead if you wish.) Do not make any other change in
2839these notices.
2840
2841 Once this change is made in a given copy, it is irreversible for
2842that copy, so the ordinary GNU General Public License applies to all
2843subsequent copies and derivative works made from that copy.
2844
2845 This option is useful when you wish to copy part of the code of
2846the Library into a program that is not a library.
2847
2848 4. You may copy and distribute the Library (or a portion or
2849derivative of it, under Section 2) in object code or executable form
2850under the terms of Sections 1 and 2 above provided that you accompany
2851it with the complete corresponding machine-readable source code, which
2852must be distributed under the terms of Sections 1 and 2 above on a
2853medium customarily used for software interchange.
2854
2855 If distribution of object code is made by offering access to copy
2856from a designated place, then offering equivalent access to copy the
2857source code from the same place satisfies the requirement to
2858distribute the source code, even though third parties are not
2859compelled to copy the source along with the object code.
2860
2861 5. A program that contains no derivative of any portion of the
2862Library, but is designed to work with the Library by being compiled or
2863linked with it, is called a "work that uses the Library". Such a
2864work, in isolation, is not a derivative work of the Library, and
2865therefore falls outside the scope of this License.
2866
2867 However, linking a "work that uses the Library" with the Library
2868creates an executable that is a derivative of the Library (because it
2869contains portions of the Library), rather than a "work that uses the
2870library". The executable is therefore covered by this License.
2871Section 6 states terms for distribution of such executables.
2872
2873 When a "work that uses the Library" uses material from a header file
2874that is part of the Library, the object code for the work may be a
2875derivative work of the Library even though the source code is not.
2876Whether this is true is especially significant if the work can be
2877linked without the Library, or if the work is itself a library. The
2878threshold for this to be true is not precisely defined by law.
2879
2880 If such an object file uses only numerical parameters, data
2881structure layouts and accessors, and small macros and small inline
2882functions (ten lines or less in length), then the use of the object
2883file is unrestricted, regardless of whether it is legally a derivative
2884work. (Executables containing this object code plus portions of the
2885Library will still fall under Section 6.)
2886
2887 Otherwise, if the work is a derivative of the Library, you may
2888distribute the object code for the work under the terms of Section 6.
2889Any executables containing that work also fall under Section 6,
2890whether or not they are linked directly with the Library itself.
2891
2892 6. As an exception to the Sections above, you may also combine or
2893link a "work that uses the Library" with the Library to produce a
2894work containing portions of the Library, and distribute that work
2895under terms of your choice, provided that the terms permit
2896modification of the work for the customer's own use and reverse
2897engineering for debugging such modifications.
2898
2899 You must give prominent notice with each copy of the work that the
2900Library is used in it and that the Library and its use are covered by
2901this License. You must supply a copy of this License. If the work
2902during execution displays copyright notices, you must include the
2903copyright notice for the Library among them, as well as a reference
2904directing the user to the copy of this License. Also, you must do one
2905of these things:
2906
2907 a) Accompany the work with the complete corresponding
2908 machine-readable source code for the Library including whatever
2909 changes were used in the work (which must be distributed under
2910 Sections 1 and 2 above); and, if the work is an executable linked
2911 with the Library, with the complete machine-readable "work that
2912 uses the Library", as object code and/or source code, so that the
2913 user can modify the Library and then relink to produce a modified
2914 executable containing the modified Library. (It is understood
2915 that the user who changes the contents of definitions files in the
2916 Library will not necessarily be able to recompile the application
2917 to use the modified definitions.)
2918
2919 b) Use a suitable shared library mechanism for linking with the
2920 Library. A suitable mechanism is one that (1) uses at run time a
2921 copy of the library already present on the user's computer system,
2922 rather than copying library functions into the executable, and (2)
2923 will operate properly with a modified version of the library, if
2924 the user installs one, as long as the modified version is
2925 interface-compatible with the version that the work was made with.
2926
2927 c) Accompany the work with a written offer, valid for at
2928 least three years, to give the same user the materials
2929 specified in Subsection 6a, above, for a charge no more
2930 than the cost of performing this distribution.
2931
2932 d) If distribution of the work is made by offering access to copy
2933 from a designated place, offer equivalent access to copy the above
2934 specified materials from the same place.
2935
2936 e) Verify that the user has already received a copy of these
2937 materials or that you have already sent this user a copy.
2938
2939 For an executable, the required form of the "work that uses the
2940Library" must include any data and utility programs needed for
2941reproducing the executable from it. However, as a special exception,
2942the materials to be distributed need not include anything that is
2943normally distributed (in either source or binary form) with the major
2944components (compiler, kernel, and so on) of the operating system on
2945which the executable runs, unless that component itself accompanies
2946the executable.
2947
2948 It may happen that this requirement contradicts the license
2949restrictions of other proprietary libraries that do not normally
2950accompany the operating system. Such a contradiction means you cannot
2951use both them and the Library together in an executable that you
2952distribute.
2953
2954 7. You may place library facilities that are a work based on the
2955Library side-by-side in a single library together with other library
2956facilities not covered by this License, and distribute such a combined
2957library, provided that the separate distribution of the work based on
2958the Library and of the other library facilities is otherwise
2959permitted, and provided that you do these two things:
2960
2961 a) Accompany the combined library with a copy of the same work
2962 based on the Library, uncombined with any other library
2963 facilities. This must be distributed under the terms of the
2964 Sections above.
2965
2966 b) Give prominent notice with the combined library of the fact
2967 that part of it is a work based on the Library, and explaining
2968 where to find the accompanying uncombined form of the same work.
2969
2970 8. You may not copy, modify, sublicense, link with, or distribute
2971the Library except as expressly provided under this License. Any
2972attempt otherwise to copy, modify, sublicense, link with, or
2973distribute the Library is void, and will automatically terminate your
2974rights under this License. However, parties who have received copies,
2975or rights, from you under this License will not have their licenses
2976terminated so long as such parties remain in full compliance.
2977
2978 9. You are not required to accept this License, since you have not
2979signed it. However, nothing else grants you permission to modify or
2980distribute the Library or its derivative works. These actions are
2981prohibited by law if you do not accept this License. Therefore, by
2982modifying or distributing the Library (or any work based on the
2983Library), you indicate your acceptance of this License to do so, and
2984all its terms and conditions for copying, distributing or modifying
2985the Library or works based on it.
2986
2987 10. Each time you redistribute the Library (or any work based on the
2988Library), the recipient automatically receives a license from the
2989original licensor to copy, distribute, link with or modify the Library
2990subject to these terms and conditions. You may not impose any further
2991restrictions on the recipients' exercise of the rights granted herein.
2992You are not responsible for enforcing compliance by third parties with
2993this License.
2994
2995 11. If, as a consequence of a court judgment or allegation of patent
2996infringement or for any other reason (not limited to patent issues),
2997conditions are imposed on you (whether by court order, agreement or
2998otherwise) that contradict the conditions of this License, they do not
2999excuse you from the conditions of this License. If you cannot
3000distribute so as to satisfy simultaneously your obligations under this
3001License and any other pertinent obligations, then as a consequence you
3002may not distribute the Library at all. For example, if a patent
3003license would not permit royalty-free redistribution of the Library by
3004all those who receive copies directly or indirectly through you, then
3005the only way you could satisfy both it and this License would be to
3006refrain entirely from distribution of the Library.
3007
3008If any portion of this section is held invalid or unenforceable under any
3009particular circumstance, the balance of the section is intended to apply,
3010and the section as a whole is intended to apply in other circumstances.
3011
3012It is not the purpose of this section to induce you to infringe any
3013patents or other property right claims or to contest validity of any
3014such claims; this section has the sole purpose of protecting the
3015integrity of the free software distribution system which is
3016implemented by public license practices. Many people have made
3017generous contributions to the wide range of software distributed
3018through that system in reliance on consistent application of that
3019system; it is up to the author/donor to decide if he or she is willing
3020to distribute software through any other system and a licensee cannot
3021impose that choice.
3022
3023This section is intended to make thoroughly clear what is believed to
3024be a consequence of the rest of this License.
3025
3026 12. If the distribution and/or use of the Library is restricted in
3027certain countries either by patents or by copyrighted interfaces, the
3028original copyright holder who places the Library under this License may add
3029an explicit geographical distribution limitation excluding those countries,
3030so that distribution is permitted only in or among countries not thus
3031excluded. In such case, this License incorporates the limitation as if
3032written in the body of this License.
3033
3034 13. The Free Software Foundation may publish revised and/or new
3035versions of the Lesser General Public License from time to time.
3036Such new versions will be similar in spirit to the present version,
3037but may differ in detail to address new problems or concerns.
3038
3039Each version is given a distinguishing version number. If the Library
3040specifies a version number of this License which applies to it and
3041"any later version", you have the option of following the terms and
3042conditions either of that version or of any later version published by
3043the Free Software Foundation. If the Library does not specify a
3044license version number, you may choose any version ever published by
3045the Free Software Foundation.
3046
3047 14. If you wish to incorporate parts of the Library into other free
3048programs whose distribution conditions are incompatible with these,
3049write to the author to ask for permission. For software which is
3050copyrighted by the Free Software Foundation, write to the Free
3051Software Foundation; we sometimes make exceptions for this. Our
3052decision will be guided by the two goals of preserving the free status
3053of all derivatives of our free software and of promoting the sharing
3054and reuse of software generally.
3055
3056 NO WARRANTY
3057
3058 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
3059WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
3060EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
3061OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
3062KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
3063IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
3064PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
3065LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
3066THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
3067
3068 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
3069WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
3070AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
3071FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
3072CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
3073LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
3074RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
3075FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
3076SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
3077DAMAGES.
3078
3079 END OF TERMS AND CONDITIONS
3080
3081 How to Apply These Terms to Your New Libraries
3082
3083 If you develop a new library, and you want it to be of the greatest
3084possible use to the public, we recommend making it free software that
3085everyone can redistribute and change. You can do so by permitting
3086redistribution under these terms (or, alternatively, under the terms of the
3087ordinary General Public License).
3088
3089 To apply these terms, attach the following notices to the library. It is
3090safest to attach them to the start of each source file to most effectively
3091convey the exclusion of warranty; and each file should have at least the
3092"copyright" line and a pointer to where the full notice is found.
3093
3094 <one line to give the library's name and a brief idea of what it does.>
3095 Copyright (C) <year> <name of author>
3096
3097 This library is free software; you can redistribute it and/or
3098 modify it under the terms of the GNU Lesser General Public
3099 License as published by the Free Software Foundation; either
3100 version 2.1 of the License, or (at your option) any later version.
3101
3102 This library is distributed in the hope that it will be useful,
3103 but WITHOUT ANY WARRANTY; without even the implied warranty of
3104 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
3105 Lesser General Public License for more details.
3106
3107 You should have received a copy of the GNU Lesser General Public
3108 License along with this library; if not, write to the Free Software
3109 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
3110
3111Also add information on how to contact you by electronic and paper mail.
3112
3113You should also get your employer (if you work as a programmer) or your
3114school, if any, to sign a "copyright disclaimer" for the library, if
3115necessary. Here is a sample; alter the names:
3116
3117 Yoyodyne, Inc., hereby disclaims all copyright interest in the
3118 library `Frob' (a library for tweaking knobs) written by James Random Hacker.
3119
3120 <signature of Ty Coon>, 1 April 1990
3121 Ty Coon, President of Vice
3122
3123That's all there is to it!
3124
3125*/
3126
3127/* Licensing details for Mac-AppleSingleDouble-1.0, from LICENSE (note that Collective Toolbox reuses it under the GPL-1.0-or-later terms, not under the Artistic License, though both are reproduced below):
3128```
3129Terms of Perl itself
3130
3131a) the GNU General Public License as published by the Free
3132 Software Foundation; either version 1, or (at your option) any
3133 later version, or
3134b) the "Artistic License"
3135
3136----------------------------------------------------------------------------
3137
3138The General Public License (GPL)
3139Version 2, June 1991
3140
3141Copyright (C) 1989, 1991 Free Software Foundation, Inc. 675 Mass Ave,
3142Cambridge, MA 02139, USA. Everyone is permitted to copy and distribute
3143verbatim copies of this license document, but changing it is not allowed.
3144
3145Preamble
3146
3147The licenses for most software are designed to take away your freedom to share
3148and change it. By contrast, the GNU General Public License is intended to
3149guarantee your freedom to share and change free software--to make sure the
3150software is free for all its users. This General Public License applies to most of
3151the Free Software Foundation's software and to any other program whose
3152authors commit to using it. (Some other Free Software Foundation software is
3153covered by the GNU Library General Public License instead.) You can apply it to
3154your programs, too.
3155
3156When we speak of free software, we are referring to freedom, not price. Our
3157General Public Licenses are designed to make sure that you have the freedom
3158to distribute copies of free software (and charge for this service if you wish), that
3159you receive source code or can get it if you want it, that you can change the
3160software or use pieces of it in new free programs; and that you know you can do
3161these things.
3162
3163To protect your rights, we need to make restrictions that forbid anyone to deny
3164you these rights or to ask you to surrender the rights. These restrictions
3165translate to certain responsibilities for you if you distribute copies of the
3166software, or if you modify it.
3167
3168For example, if you distribute copies of such a program, whether gratis or for a
3169fee, you must give the recipients all the rights that you have. You must make
3170sure that they, too, receive or can get the source code. And you must show
3171them these terms so they know their rights.
3172
3173We protect your rights with two steps: (1) copyright the software, and (2) offer
3174you this license which gives you legal permission to copy, distribute and/or
3175modify the software.
3176
3177Also, for each author's protection and ours, we want to make certain that
3178everyone understands that there is no warranty for this free software. If the
3179software is modified by someone else and passed on, we want its recipients to
3180know that what they have is not the original, so that any problems introduced by
3181others will not reflect on the original authors' reputations.
3182
3183Finally, any free program is threatened constantly by software patents. We wish
3184to avoid the danger that redistributors of a free program will individually obtain
3185patent licenses, in effect making the program proprietary. To prevent this, we
3186have made it clear that any patent must be licensed for everyone's free use or
3187not licensed at all.
3188
3189The precise terms and conditions for copying, distribution and modification
3190follow.
3191
3192GNU GENERAL PUBLIC LICENSE
3193TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND
3194MODIFICATION
3195
31960. This License applies to any program or other work which contains a notice
3197placed by the copyright holder saying it may be distributed under the terms of
3198this General Public License. The "Program", below, refers to any such program
3199or work, and a "work based on the Program" means either the Program or any
3200derivative work under copyright law: that is to say, a work containing the
3201Program or a portion of it, either verbatim or with modifications and/or translated
3202into another language. (Hereinafter, translation is included without limitation in
3203the term "modification".) Each licensee is addressed as "you".
3204
3205Activities other than copying, distribution and modification are not covered by
3206this License; they are outside its scope. The act of running the Program is not
3207restricted, and the output from the Program is covered only if its contents
3208constitute a work based on the Program (independent of having been made by
3209running the Program). Whether that is true depends on what the Program does.
3210
32111. You may copy and distribute verbatim copies of the Program's source code as
3212you receive it, in any medium, provided that you conspicuously and appropriately
3213publish on each copy an appropriate copyright notice and disclaimer of warranty;
3214keep intact all the notices that refer to this License and to the absence of any
3215warranty; and give any other recipients of the Program a copy of this License
3216along with the Program.
3217
3218You may charge a fee for the physical act of transferring a copy, and you may at
3219your option offer warranty protection in exchange for a fee.
3220
32212. You may modify your copy or copies of the Program or any portion of it, thus
3222forming a work based on the Program, and copy and distribute such
3223modifications or work under the terms of Section 1 above, provided that you also
3224meet all of these conditions:
3225
3226a) You must cause the modified files to carry prominent notices stating that you
3227changed the files and the date of any change.
3228
3229b) You must cause any work that you distribute or publish, that in whole or in
3230part contains or is derived from the Program or any part thereof, to be licensed
3231as a whole at no charge to all third parties under the terms of this License.
3232
3233c) If the modified program normally reads commands interactively when run, you
3234must cause it, when started running for such interactive use in the most ordinary
3235way, to print or display an announcement including an appropriate copyright
3236notice and a notice that there is no warranty (or else, saying that you provide a
3237warranty) and that users may redistribute the program under these conditions,
3238and telling the user how to view a copy of this License. (Exception: if the
3239Program itself is interactive but does not normally print such an announcement,
3240your work based on the Program is not required to print an announcement.)
3241
3242These requirements apply to the modified work as a whole. If identifiable
3243sections of that work are not derived from the Program, and can be reasonably
3244considered independent and separate works in themselves, then this License,
3245and its terms, do not apply to those sections when you distribute them as
3246separate works. But when you distribute the same sections as part of a whole
3247which is a work based on the Program, the distribution of the whole must be on
3248the terms of this License, whose permissions for other licensees extend to the
3249entire whole, and thus to each and every part regardless of who wrote it.
3250
3251Thus, it is not the intent of this section to claim rights or contest your rights to
3252work written entirely by you; rather, the intent is to exercise the right to control
3253the distribution of derivative or collective works based on the Program.
3254
3255In addition, mere aggregation of another work not based on the Program with the
3256Program (or with a work based on the Program) on a volume of a storage or
3257distribution medium does not bring the other work under the scope of this
3258License.
3259
32603. You may copy and distribute the Program (or a work based on it, under
3261Section 2) in object code or executable form under the terms of Sections 1 and 2
3262above provided that you also do one of the following:
3263
3264a) Accompany it with the complete corresponding machine-readable source
3265code, which must be distributed under the terms of Sections 1 and 2 above on a
3266medium customarily used for software interchange; or,
3267
3268b) Accompany it with a written offer, valid for at least three years, to give any
3269third party, for a charge no more than your cost of physically performing source
3270distribution, a complete machine-readable copy of the corresponding source
3271code, to be distributed under the terms of Sections 1 and 2 above on a medium
3272customarily used for software interchange; or,
3273
3274c) Accompany it with the information you received as to the offer to distribute
3275corresponding source code. (This alternative is allowed only for noncommercial
3276distribution and only if you received the program in object code or executable
3277form with such an offer, in accord with Subsection b above.)
3278
3279The source code for a work means the preferred form of the work for making
3280modifications to it. For an executable work, complete source code means all the
3281source code for all modules it contains, plus any associated interface definition
3282files, plus the scripts used to control compilation and installation of the
3283executable. However, as a special exception, the source code distributed need
3284not include anything that is normally distributed (in either source or binary form)
3285with the major components (compiler, kernel, and so on) of the operating system
3286on which the executable runs, unless that component itself accompanies the
3287executable.
3288
3289If distribution of executable or object code is made by offering access to copy
3290from a designated place, then offering equivalent access to copy the source
3291code from the same place counts as distribution of the source code, even though
3292third parties are not compelled to copy the source along with the object code.
3293
32944. You may not copy, modify, sublicense, or distribute the Program except as
3295expressly provided under this License. Any attempt otherwise to copy, modify,
3296sublicense or distribute the Program is void, and will automatically terminate
3297your rights under this License. However, parties who have received copies, or
3298rights, from you under this License will not have their licenses terminated so long
3299as such parties remain in full compliance.
3300
33015. You are not required to accept this License, since you have not signed it.
3302However, nothing else grants you permission to modify or distribute the Program
3303or its derivative works. These actions are prohibited by law if you do not accept
3304this License. Therefore, by modifying or distributing the Program (or any work
3305based on the Program), you indicate your acceptance of this License to do so,
3306and all its terms and conditions for copying, distributing or modifying the
3307Program or works based on it.
3308
33096. Each time you redistribute the Program (or any work based on the Program),
3310the recipient automatically receives a license from the original licensor to copy,
3311distribute or modify the Program subject to these terms and conditions. You
3312may not impose any further restrictions on the recipients' exercise of the rights
3313granted herein. You are not responsible for enforcing compliance by third parties
3314to this License.
3315
33167. If, as a consequence of a court judgment or allegation of patent infringement
3317or for any other reason (not limited to patent issues), conditions are imposed on
3318you (whether by court order, agreement or otherwise) that contradict the
3319conditions of this License, they do not excuse you from the conditions of this
3320License. If you cannot distribute so as to satisfy simultaneously your obligations
3321under this License and any other pertinent obligations, then as a consequence
3322you may not distribute the Program at all. For example, if a patent license would
3323not permit royalty-free redistribution of the Program by all those who receive
3324copies directly or indirectly through you, then the only way you could satisfy
3325both it and this License would be to refrain entirely from distribution of the
3326Program.
3327
3328If any portion of this section is held invalid or unenforceable under any particular
3329circumstance, the balance of the section is intended to apply and the section as
3330a whole is intended to apply in other circumstances.
3331
3332It is not the purpose of this section to induce you to infringe any patents or other
3333property right claims or to contest validity of any such claims; this section has
3334the sole purpose of protecting the integrity of the free software distribution
3335system, which is implemented by public license practices. Many people have
3336made generous contributions to the wide range of software distributed through
3337that system in reliance on consistent application of that system; it is up to the
3338author/donor to decide if he or she is willing to distribute software through any
3339other system and a licensee cannot impose that choice.
3340
3341This section is intended to make thoroughly clear what is believed to be a
3342consequence of the rest of this License.
3343
33448. If the distribution and/or use of the Program is restricted in certain countries
3345either by patents or by copyrighted interfaces, the original copyright holder who
3346places the Program under this License may add an explicit geographical
3347distribution limitation excluding those countries, so that distribution is permitted
3348only in or among countries not thus excluded. In such case, this License
3349incorporates the limitation as if written in the body of this License.
3350
33519. The Free Software Foundation may publish revised and/or new versions of the
3352General Public License from time to time. Such new versions will be similar in
3353spirit to the present version, but may differ in detail to address new problems or
3354concerns.
3355
3356Each version is given a distinguishing version number. If the Program specifies a
3357version number of this License which applies to it and "any later version", you
3358have the option of following the terms and conditions either of that version or of
3359any later version published by the Free Software Foundation. If the Program does
3360not specify a version number of this License, you may choose any version ever
3361published by the Free Software Foundation.
3362
336310. If you wish to incorporate parts of the Program into other free programs
3364whose distribution conditions are different, write to the author to ask for
3365permission. For software which is copyrighted by the Free Software Foundation,
3366write to the Free Software Foundation; we sometimes make exceptions for this.
3367Our decision will be guided by the two goals of preserving the free status of all
3368derivatives of our free software and of promoting the sharing and reuse of
3369software generally.
3370
3371NO WARRANTY
3372
337311. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS
3374NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
3375APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE
3376COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM
3377"AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR
3378IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
3379MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
3380ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
3381PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE,
3382YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
3383CORRECTION.
3384
338512. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED
3386TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY
3387WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS
3388PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
3389GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
3390ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM
3391(INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
3392RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
3393PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY
3394OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS
3395BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
3396
3397END OF TERMS AND CONDITIONS
3398
3399
3400----------------------------------------------------------------------------
3401
3402The Artistic License
3403
3404Preamble
3405
3406The intent of this document is to state the conditions under which a Package
3407may be copied, such that the Copyright Holder maintains some semblance of
3408artistic control over the development of the package, while giving the users of the
3409package the right to use and distribute the Package in a more-or-less customary
3410fashion, plus the right to make reasonable modifications.
3411
3412Definitions:
3413
3414- "Package" refers to the collection of files distributed by the Copyright
3415 Holder, and derivatives of that collection of files created through textual
3416 modification.
3417- "Standard Version" refers to such a Package if it has not been modified,
3418 or has been modified in accordance with the wishes of the Copyright
3419 Holder.
3420- "Copyright Holder" is whoever is named in the copyright or copyrights for
3421 the package.
3422- "You" is you, if you're thinking about copying or distributing this Package.
3423- "Reasonable copying fee" is whatever you can justify on the basis of
3424 media cost, duplication charges, time of people involved, and so on. (You
3425 will not be required to justify it to the Copyright Holder, but only to the
3426 computing community at large as a market that must bear the fee.)
3427- "Freely Available" means that no fee is charged for the item itself, though
3428 there may be fees involved in handling the item. It also means that
3429 recipients of the item may redistribute it under the same conditions they
3430 received it.
3431
34321. You may make and give away verbatim copies of the source form of the
3433Standard Version of this Package without restriction, provided that you duplicate
3434all of the original copyright notices and associated disclaimers.
3435
34362. You may apply bug fixes, portability fixes and other modifications derived from
3437the Public Domain or from the Copyright Holder. A Package modified in such a
3438way shall still be considered the Standard Version.
3439
34403. You may otherwise modify your copy of this Package in any way, provided
3441that you insert a prominent notice in each changed file stating how and when
3442you changed that file, and provided that you do at least ONE of the following:
3443
3444 a) place your modifications in the Public Domain or otherwise
3445 make them Freely Available, such as by posting said modifications
3446 to Usenet or an equivalent medium, or placing the modifications on
3447 a major archive site such as ftp.uu.net, or by allowing the
3448 Copyright Holder to include your modifications in the Standard
3449 Version of the Package.
3450
3451 b) use the modified Package only within your corporation or
3452 organization.
3453
3454 c) rename any non-standard executables so the names do not
3455 conflict with standard executables, which must also be provided,
3456 and provide a separate manual page for each non-standard
3457 executable that clearly documents how it differs from the Standard
3458 Version.
3459
3460 d) make other distribution arrangements with the Copyright Holder.
3461
34624. You may distribute the programs of this Package in object code or executable
3463form, provided that you do at least ONE of the following:
3464
3465 a) distribute a Standard Version of the executables and library
3466 files, together with instructions (in the manual page or equivalent)
3467 on where to get the Standard Version.
3468
3469 b) accompany the distribution with the machine-readable source of
3470 the Package with your modifications.
3471
3472 c) accompany any non-standard executables with their
3473 corresponding Standard Version executables, giving the
3474 non-standard executables non-standard names, and clearly
3475 documenting the differences in manual pages (or equivalent),
3476 together with instructions on where to get the Standard Version.
3477
3478 d) make other distribution arrangements with the Copyright Holder.
3479
34805. You may charge a reasonable copying fee for any distribution of this Package.
3481You may charge any fee you choose for support of this Package. You may not
3482charge a fee for this Package itself. However, you may distribute this Package in
3483aggregate with other (possibly commercial) programs as part of a larger
3484(possibly commercial) software distribution provided that you do not advertise
3485this Package as a product of your own.
3486
34876. The scripts and library files supplied as input to or produced as output from
3488the programs of this Package do not automatically fall under the copyright of this
3489Package, but belong to whomever generated them, and may be sold
3490commercially, and may be aggregated with this Package.
3491
34927. C or perl subroutines supplied by you and linked into this Package shall not
3493be considered part of this Package.
3494
34958. The name of the Copyright Holder may not be used to endorse or promote
3496products derived from this software without specific prior written permission.
3497
34989. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
3499IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
3500WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
3501PURPOSE.
3502
3503The End
3504```
3505
3506
3507
3508Text of the GPL 3, the license Collective Toolbox reuses Mac-AppleSingleDouble-1.0 under per the or-later option:
3509
3510```
3511# GNU GENERAL PUBLIC LICENSE
3512
3513Version 3, 29 June 2007
3514
3515Copyright (C) 2007 Free Software Foundation, Inc.
3516<https://fsf.org/>
3517
3518Everyone is permitted to copy and distribute verbatim copies of this
3519license document, but changing it is not allowed.
3520
3521## Preamble
3522
3523The GNU General Public License is a free, copyleft license for
3524software and other kinds of works.
3525
3526The licenses for most software and other practical works are designed
3527to take away your freedom to share and change the works. By contrast,
3528the GNU General Public License is intended to guarantee your freedom
3529to share and change all versions of a program--to make sure it remains
3530free software for all its users. We, the Free Software Foundation, use
3531the GNU General Public License for most of our software; it applies
3532also to any other work released this way by its authors. You can apply
3533it to your programs, too.
3534
3535When we speak of free software, we are referring to freedom, not
3536price. Our General Public Licenses are designed to make sure that you
3537have the freedom to distribute copies of free software (and charge for
3538them if you wish), that you receive source code or can get it if you
3539want it, that you can change the software or use pieces of it in new
3540free programs, and that you know you can do these things.
3541
3542To protect your rights, we need to prevent others from denying you
3543these rights or asking you to surrender the rights. Therefore, you
3544have certain responsibilities if you distribute copies of the
3545software, or if you modify it: responsibilities to respect the freedom
3546of others.
3547
3548For example, if you distribute copies of such a program, whether
3549gratis or for a fee, you must pass on to the recipients the same
3550freedoms that you received. You must make sure that they, too, receive
3551or can get the source code. And you must show them these terms so they
3552know their rights.
3553
3554Developers that use the GNU GPL protect your rights with two steps:
3555(1) assert copyright on the software, and (2) offer you this License
3556giving you legal permission to copy, distribute and/or modify it.
3557
3558For the developers' and authors' protection, the GPL clearly explains
3559that there is no warranty for this free software. For both users' and
3560authors' sake, the GPL requires that modified versions be marked as
3561changed, so that their problems will not be attributed erroneously to
3562authors of previous versions.
3563
3564Some devices are designed to deny users access to install or run
3565modified versions of the software inside them, although the
3566manufacturer can do so. This is fundamentally incompatible with the
3567aim of protecting users' freedom to change the software. The
3568systematic pattern of such abuse occurs in the area of products for
3569individuals to use, which is precisely where it is most unacceptable.
3570Therefore, we have designed this version of the GPL to prohibit the
3571practice for those products. If such problems arise substantially in
3572other domains, we stand ready to extend this provision to those
3573domains in future versions of the GPL, as needed to protect the
3574freedom of users.
3575
3576Finally, every program is threatened constantly by software patents.
3577States should not allow patents to restrict development and use of
3578software on general-purpose computers, but in those that do, we wish
3579to avoid the special danger that patents applied to a free program
3580could make it effectively proprietary. To prevent this, the GPL
3581assures that patents cannot be used to render the program non-free.
3582
3583The precise terms and conditions for copying, distribution and
3584modification follow.
3585
3586## TERMS AND CONDITIONS
3587
3588### 0. Definitions.
3589
3590"This License" refers to version 3 of the GNU General Public License.
3591
3592"Copyright" also means copyright-like laws that apply to other kinds
3593of works, such as semiconductor masks.
3594
3595"The Program" refers to any copyrightable work licensed under this
3596License. Each licensee is addressed as "you". "Licensees" and
3597"recipients" may be individuals or organizations.
3598
3599To "modify" a work means to copy from or adapt all or part of the work
3600in a fashion requiring copyright permission, other than the making of
3601an exact copy. The resulting work is called a "modified version" of
3602the earlier work or a work "based on" the earlier work.
3603
3604A "covered work" means either the unmodified Program or a work based
3605on the Program.
3606
3607To "propagate" a work means to do anything with it that, without
3608permission, would make you directly or secondarily liable for
3609infringement under applicable copyright law, except executing it on a
3610computer or modifying a private copy. Propagation includes copying,
3611distribution (with or without modification), making available to the
3612public, and in some countries other activities as well.
3613
3614To "convey" a work means any kind of propagation that enables other
3615parties to make or receive copies. Mere interaction with a user
3616through a computer network, with no transfer of a copy, is not
3617conveying.
3618
3619An interactive user interface displays "Appropriate Legal Notices" to
3620the extent that it includes a convenient and prominently visible
3621feature that (1) displays an appropriate copyright notice, and (2)
3622tells the user that there is no warranty for the work (except to the
3623extent that warranties are provided), that licensees may convey the
3624work under this License, and how to view a copy of this License. If
3625the interface presents a list of user commands or options, such as a
3626menu, a prominent item in the list meets this criterion.
3627
3628### 1. Source Code.
3629
3630The "source code" for a work means the preferred form of the work for
3631making modifications to it. "Object code" means any non-source form of
3632a work.
3633
3634A "Standard Interface" means an interface that either is an official
3635standard defined by a recognized standards body, or, in the case of
3636interfaces specified for a particular programming language, one that
3637is widely used among developers working in that language.
3638
3639The "System Libraries" of an executable work include anything, other
3640than the work as a whole, that (a) is included in the normal form of
3641packaging a Major Component, but which is not part of that Major
3642Component, and (b) serves only to enable use of the work with that
3643Major Component, or to implement a Standard Interface for which an
3644implementation is available to the public in source code form. A
3645"Major Component", in this context, means a major essential component
3646(kernel, window system, and so on) of the specific operating system
3647(if any) on which the executable work runs, or a compiler used to
3648produce the work, or an object code interpreter used to run it.
3649
3650The "Corresponding Source" for a work in object code form means all
3651the source code needed to generate, install, and (for an executable
3652work) run the object code and to modify the work, including scripts to
3653control those activities. However, it does not include the work's
3654System Libraries, or general-purpose tools or generally available free
3655programs which are used unmodified in performing those activities but
3656which are not part of the work. For example, Corresponding Source
3657includes interface definition files associated with source files for
3658the work, and the source code for shared libraries and dynamically
3659linked subprograms that the work is specifically designed to require,
3660such as by intimate data communication or control flow between those
3661subprograms and other parts of the work.
3662
3663The Corresponding Source need not include anything that users can
3664regenerate automatically from other parts of the Corresponding Source.
3665
3666The Corresponding Source for a work in source code form is that same
3667work.
3668
3669### 2. Basic Permissions.
3670
3671All rights granted under this License are granted for the term of
3672copyright on the Program, and are irrevocable provided the stated
3673conditions are met. This License explicitly affirms your unlimited
3674permission to run the unmodified Program. The output from running a
3675covered work is covered by this License only if the output, given its
3676content, constitutes a covered work. This License acknowledges your
3677rights of fair use or other equivalent, as provided by copyright law.
3678
3679You may make, run and propagate covered works that you do not convey,
3680without conditions so long as your license otherwise remains in force.
3681You may convey covered works to others for the sole purpose of having
3682them make modifications exclusively for you, or provide you with
3683facilities for running those works, provided that you comply with the
3684terms of this License in conveying all material for which you do not
3685control copyright. Those thus making or running the covered works for
3686you must do so exclusively on your behalf, under your direction and
3687control, on terms that prohibit them from making any copies of your
3688copyrighted material outside their relationship with you.
3689
3690Conveying under any other circumstances is permitted solely under the
3691conditions stated below. Sublicensing is not allowed; section 10 makes
3692it unnecessary.
3693
3694### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
3695
3696No covered work shall be deemed part of an effective technological
3697measure under any applicable law fulfilling obligations under article
369811 of the WIPO copyright treaty adopted on 20 December 1996, or
3699similar laws prohibiting or restricting circumvention of such
3700measures.
3701
3702When you convey a covered work, you waive any legal power to forbid
3703circumvention of technological measures to the extent such
3704circumvention is effected by exercising rights under this License with
3705respect to the covered work, and you disclaim any intention to limit
3706operation or modification of the work as a means of enforcing, against
3707the work's users, your or third parties' legal rights to forbid
3708circumvention of technological measures.
3709
3710### 4. Conveying Verbatim Copies.
3711
3712You may convey verbatim copies of the Program's source code as you
3713receive it, in any medium, provided that you conspicuously and
3714appropriately publish on each copy an appropriate copyright notice;
3715keep intact all notices stating that this License and any
3716non-permissive terms added in accord with section 7 apply to the code;
3717keep intact all notices of the absence of any warranty; and give all
3718recipients a copy of this License along with the Program.
3719
3720You may charge any price or no price for each copy that you convey,
3721and you may offer support or warranty protection for a fee.
3722
3723### 5. Conveying Modified Source Versions.
3724
3725You may convey a work based on the Program, or the modifications to
3726produce it from the Program, in the form of source code under the
3727terms of section 4, provided that you also meet all of these
3728conditions:
3729
3730- a) The work must carry prominent notices stating that you modified
3731 it, and giving a relevant date.
3732- b) The work must carry prominent notices stating that it is
3733 released under this License and any conditions added under
3734 section 7. This requirement modifies the requirement in section 4
3735 to "keep intact all notices".
3736- c) You must license the entire work, as a whole, under this
3737 License to anyone who comes into possession of a copy. This
3738 License will therefore apply, along with any applicable section 7
3739 additional terms, to the whole of the work, and all its parts,
3740 regardless of how they are packaged. This License gives no
3741 permission to license the work in any other way, but it does not
3742 invalidate such permission if you have separately received it.
3743- d) If the work has interactive user interfaces, each must display
3744 Appropriate Legal Notices; however, if the Program has interactive
3745 interfaces that do not display Appropriate Legal Notices, your
3746 work need not make them do so.
3747
3748A compilation of a covered work with other separate and independent
3749works, which are not by their nature extensions of the covered work,
3750and which are not combined with it such as to form a larger program,
3751in or on a volume of a storage or distribution medium, is called an
3752"aggregate" if the compilation and its resulting copyright are not
3753used to limit the access or legal rights of the compilation's users
3754beyond what the individual works permit. Inclusion of a covered work
3755in an aggregate does not cause this License to apply to the other
3756parts of the aggregate.
3757
3758### 6. Conveying Non-Source Forms.
3759
3760You may convey a covered work in object code form under the terms of
3761sections 4 and 5, provided that you also convey the machine-readable
3762Corresponding Source under the terms of this License, in one of these
3763ways:
3764
3765- a) Convey the object code in, or embodied in, a physical product
3766 (including a physical distribution medium), accompanied by the
3767 Corresponding Source fixed on a durable physical medium
3768 customarily used for software interchange.
3769- b) Convey the object code in, or embodied in, a physical product
3770 (including a physical distribution medium), accompanied by a
3771 written offer, valid for at least three years and valid for as
3772 long as you offer spare parts or customer support for that product
3773 model, to give anyone who possesses the object code either (1) a
3774 copy of the Corresponding Source for all the software in the
3775 product that is covered by this License, on a durable physical
3776 medium customarily used for software interchange, for a price no
3777 more than your reasonable cost of physically performing this
3778 conveying of source, or (2) access to copy the Corresponding
3779 Source from a network server at no charge.
3780- c) Convey individual copies of the object code with a copy of the
3781 written offer to provide the Corresponding Source. This
3782 alternative is allowed only occasionally and noncommercially, and
3783 only if you received the object code with such an offer, in accord
3784 with subsection 6b.
3785- d) Convey the object code by offering access from a designated
3786 place (gratis or for a charge), and offer equivalent access to the
3787 Corresponding Source in the same way through the same place at no
3788 further charge. You need not require recipients to copy the
3789 Corresponding Source along with the object code. If the place to
3790 copy the object code is a network server, the Corresponding Source
3791 may be on a different server (operated by you or a third party)
3792 that supports equivalent copying facilities, provided you maintain
3793 clear directions next to the object code saying where to find the
3794 Corresponding Source. Regardless of what server hosts the
3795 Corresponding Source, you remain obligated to ensure that it is
3796 available for as long as needed to satisfy these requirements.
3797- e) Convey the object code using peer-to-peer transmission,
3798 provided you inform other peers where the object code and
3799 Corresponding Source of the work are being offered to the general
3800 public at no charge under subsection 6d.
3801
3802A separable portion of the object code, whose source code is excluded
3803from the Corresponding Source as a System Library, need not be
3804included in conveying the object code work.
3805
3806A "User Product" is either (1) a "consumer product", which means any
3807tangible personal property which is normally used for personal,
3808family, or household purposes, or (2) anything designed or sold for
3809incorporation into a dwelling. In determining whether a product is a
3810consumer product, doubtful cases shall be resolved in favor of
3811coverage. For a particular product received by a particular user,
3812"normally used" refers to a typical or common use of that class of
3813product, regardless of the status of the particular user or of the way
3814in which the particular user actually uses, or expects or is expected
3815to use, the product. A product is a consumer product regardless of
3816whether the product has substantial commercial, industrial or
3817non-consumer uses, unless such uses represent the only significant
3818mode of use of the product.
3819
3820"Installation Information" for a User Product means any methods,
3821procedures, authorization keys, or other information required to
3822install and execute modified versions of a covered work in that User
3823Product from a modified version of its Corresponding Source. The
3824information must suffice to ensure that the continued functioning of
3825the modified object code is in no case prevented or interfered with
3826solely because modification has been made.
3827
3828If you convey an object code work under this section in, or with, or
3829specifically for use in, a User Product, and the conveying occurs as
3830part of a transaction in which the right of possession and use of the
3831User Product is transferred to the recipient in perpetuity or for a
3832fixed term (regardless of how the transaction is characterized), the
3833Corresponding Source conveyed under this section must be accompanied
3834by the Installation Information. But this requirement does not apply
3835if neither you nor any third party retains the ability to install
3836modified object code on the User Product (for example, the work has
3837been installed in ROM).
3838
3839The requirement to provide Installation Information does not include a
3840requirement to continue to provide support service, warranty, or
3841updates for a work that has been modified or installed by the
3842recipient, or for the User Product in which it has been modified or
3843installed. Access to a network may be denied when the modification
3844itself materially and adversely affects the operation of the network
3845or violates the rules and protocols for communication across the
3846network.
3847
3848Corresponding Source conveyed, and Installation Information provided,
3849in accord with this section must be in a format that is publicly
3850documented (and with an implementation available to the public in
3851source code form), and must require no special password or key for
3852unpacking, reading or copying.
3853
3854### 7. Additional Terms.
3855
3856"Additional permissions" are terms that supplement the terms of this
3857License by making exceptions from one or more of its conditions.
3858Additional permissions that are applicable to the entire Program shall
3859be treated as though they were included in this License, to the extent
3860that they are valid under applicable law. If additional permissions
3861apply only to part of the Program, that part may be used separately
3862under those permissions, but the entire Program remains governed by
3863this License without regard to the additional permissions.
3864
3865When you convey a copy of a covered work, you may at your option
3866remove any additional permissions from that copy, or from any part of
3867it. (Additional permissions may be written to require their own
3868removal in certain cases when you modify the work.) You may place
3869additional permissions on material, added by you to a covered work,
3870for which you have or can give appropriate copyright permission.
3871
3872Notwithstanding any other provision of this License, for material you
3873add to a covered work, you may (if authorized by the copyright holders
3874of that material) supplement the terms of this License with terms:
3875
3876- a) Disclaiming warranty or limiting liability differently from the
3877 terms of sections 15 and 16 of this License; or
3878- b) Requiring preservation of specified reasonable legal notices or
3879 author attributions in that material or in the Appropriate Legal
3880 Notices displayed by works containing it; or
3881- c) Prohibiting misrepresentation of the origin of that material,
3882 or requiring that modified versions of such material be marked in
3883 reasonable ways as different from the original version; or
3884- d) Limiting the use for publicity purposes of names of licensors
3885 or authors of the material; or
3886- e) Declining to grant rights under trademark law for use of some
3887 trade names, trademarks, or service marks; or
3888- f) Requiring indemnification of licensors and authors of that
3889 material by anyone who conveys the material (or modified versions
3890 of it) with contractual assumptions of liability to the recipient,
3891 for any liability that these contractual assumptions directly
3892 impose on those licensors and authors.
3893
3894All other non-permissive additional terms are considered "further
3895restrictions" within the meaning of section 10. If the Program as you
3896received it, or any part of it, contains a notice stating that it is
3897governed by this License along with a term that is a further
3898restriction, you may remove that term. If a license document contains
3899a further restriction but permits relicensing or conveying under this
3900License, you may add to a covered work material governed by the terms
3901of that license document, provided that the further restriction does
3902not survive such relicensing or conveying.
3903
3904If you add terms to a covered work in accord with this section, you
3905must place, in the relevant source files, a statement of the
3906additional terms that apply to those files, or a notice indicating
3907where to find the applicable terms.
3908
3909Additional terms, permissive or non-permissive, may be stated in the
3910form of a separately written license, or stated as exceptions; the
3911above requirements apply either way.
3912
3913### 8. Termination.
3914
3915You may not propagate or modify a covered work except as expressly
3916provided under this License. Any attempt otherwise to propagate or
3917modify it is void, and will automatically terminate your rights under
3918this License (including any patent licenses granted under the third
3919paragraph of section 11).
3920
3921However, if you cease all violation of this License, then your license
3922from a particular copyright holder is reinstated (a) provisionally,
3923unless and until the copyright holder explicitly and finally
3924terminates your license, and (b) permanently, if the copyright holder
3925fails to notify you of the violation by some reasonable means prior to
392660 days after the cessation.
3927
3928Moreover, your license from a particular copyright holder is
3929reinstated permanently if the copyright holder notifies you of the
3930violation by some reasonable means, this is the first time you have
3931received notice of violation of this License (for any work) from that
3932copyright holder, and you cure the violation prior to 30 days after
3933your receipt of the notice.
3934
3935Termination of your rights under this section does not terminate the
3936licenses of parties who have received copies or rights from you under
3937this License. If your rights have been terminated and not permanently
3938reinstated, you do not qualify to receive new licenses for the same
3939material under section 10.
3940
3941### 9. Acceptance Not Required for Having Copies.
3942
3943You are not required to accept this License in order to receive or run
3944a copy of the Program. Ancillary propagation of a covered work
3945occurring solely as a consequence of using peer-to-peer transmission
3946to receive a copy likewise does not require acceptance. However,
3947nothing other than this License grants you permission to propagate or
3948modify any covered work. These actions infringe copyright if you do
3949not accept this License. Therefore, by modifying or propagating a
3950covered work, you indicate your acceptance of this License to do so.
3951
3952### 10. Automatic Licensing of Downstream Recipients.
3953
3954Each time you convey a covered work, the recipient automatically
3955receives a license from the original licensors, to run, modify and
3956propagate that work, subject to this License. You are not responsible
3957for enforcing compliance by third parties with this License.
3958
3959An "entity transaction" is a transaction transferring control of an
3960organization, or substantially all assets of one, or subdividing an
3961organization, or merging organizations. If propagation of a covered
3962work results from an entity transaction, each party to that
3963transaction who receives a copy of the work also receives whatever
3964licenses to the work the party's predecessor in interest had or could
3965give under the previous paragraph, plus a right to possession of the
3966Corresponding Source of the work from the predecessor in interest, if
3967the predecessor has it or can get it with reasonable efforts.
3968
3969You may not impose any further restrictions on the exercise of the
3970rights granted or affirmed under this License. For example, you may
3971not impose a license fee, royalty, or other charge for exercise of
3972rights granted under this License, and you may not initiate litigation
3973(including a cross-claim or counterclaim in a lawsuit) alleging that
3974any patent claim is infringed by making, using, selling, offering for
3975sale, or importing the Program or any portion of it.
3976
3977### 11. Patents.
3978
3979A "contributor" is a copyright holder who authorizes use under this
3980License of the Program or a work on which the Program is based. The
3981work thus licensed is called the contributor's "contributor version".
3982
3983A contributor's "essential patent claims" are all patent claims owned
3984or controlled by the contributor, whether already acquired or
3985hereafter acquired, that would be infringed by some manner, permitted
3986by this License, of making, using, or selling its contributor version,
3987but do not include claims that would be infringed only as a
3988consequence of further modification of the contributor version. For
3989purposes of this definition, "control" includes the right to grant
3990patent sublicenses in a manner consistent with the requirements of
3991this License.
3992
3993Each contributor grants you a non-exclusive, worldwide, royalty-free
3994patent license under the contributor's essential patent claims, to
3995make, use, sell, offer for sale, import and otherwise run, modify and
3996propagate the contents of its contributor version.
3997
3998In the following three paragraphs, a "patent license" is any express
3999agreement or commitment, however denominated, not to enforce a patent
4000(such as an express permission to practice a patent or covenant not to
4001sue for patent infringement). To "grant" such a patent license to a
4002party means to make such an agreement or commitment not to enforce a
4003patent against the party.
4004
4005If you convey a covered work, knowingly relying on a patent license,
4006and the Corresponding Source of the work is not available for anyone
4007to copy, free of charge and under the terms of this License, through a
4008publicly available network server or other readily accessible means,
4009then you must either (1) cause the Corresponding Source to be so
4010available, or (2) arrange to deprive yourself of the benefit of the
4011patent license for this particular work, or (3) arrange, in a manner
4012consistent with the requirements of this License, to extend the patent
4013license to downstream recipients. "Knowingly relying" means you have
4014actual knowledge that, but for the patent license, your conveying the
4015covered work in a country, or your recipient's use of the covered work
4016in a country, would infringe one or more identifiable patents in that
4017country that you have reason to believe are valid.
4018
4019If, pursuant to or in connection with a single transaction or
4020arrangement, you convey, or propagate by procuring conveyance of, a
4021covered work, and grant a patent license to some of the parties
4022receiving the covered work authorizing them to use, propagate, modify
4023or convey a specific copy of the covered work, then the patent license
4024you grant is automatically extended to all recipients of the covered
4025work and works based on it.
4026
4027A patent license is "discriminatory" if it does not include within the
4028scope of its coverage, prohibits the exercise of, or is conditioned on
4029the non-exercise of one or more of the rights that are specifically
4030granted under this License. You may not convey a covered work if you
4031are a party to an arrangement with a third party that is in the
4032business of distributing software, under which you make payment to the
4033third party based on the extent of your activity of conveying the
4034work, and under which the third party grants, to any of the parties
4035who would receive the covered work from you, a discriminatory patent
4036license (a) in connection with copies of the covered work conveyed by
4037you (or copies made from those copies), or (b) primarily for and in
4038connection with specific products or compilations that contain the
4039covered work, unless you entered into that arrangement, or that patent
4040license was granted, prior to 28 March 2007.
4041
4042Nothing in this License shall be construed as excluding or limiting
4043any implied license or other defenses to infringement that may
4044otherwise be available to you under applicable patent law.
4045
4046### 12. No Surrender of Others' Freedom.
4047
4048If conditions are imposed on you (whether by court order, agreement or
4049otherwise) that contradict the conditions of this License, they do not
4050excuse you from the conditions of this License. If you cannot convey a
4051covered work so as to satisfy simultaneously your obligations under
4052this License and any other pertinent obligations, then as a
4053consequence you may not convey it at all. For example, if you agree to
4054terms that obligate you to collect a royalty for further conveying
4055from those to whom you convey the Program, the only way you could
4056satisfy both those terms and this License would be to refrain entirely
4057from conveying the Program.
4058
4059### 13. Use with the GNU Affero General Public License.
4060
4061Notwithstanding any other provision of this License, you have
4062permission to link or combine any covered work with a work licensed
4063under version 3 of the GNU Affero General Public License into a single
4064combined work, and to convey the resulting work. The terms of this
4065License will continue to apply to the part which is the covered work,
4066but the special requirements of the GNU Affero General Public License,
4067section 13, concerning interaction through a network will apply to the
4068combination as such.
4069
4070### 14. Revised Versions of this License.
4071
4072The Free Software Foundation may publish revised and/or new versions
4073of the GNU General Public License from time to time. Such new versions
4074will be similar in spirit to the present version, but may differ in
4075detail to address new problems or concerns.
4076
4077Each version is given a distinguishing version number. If the Program
4078specifies that a certain numbered version of the GNU General Public
4079License "or any later version" applies to it, you have the option of
4080following the terms and conditions either of that numbered version or
4081of any later version published by the Free Software Foundation. If the
4082Program does not specify a version number of the GNU General Public
4083License, you may choose any version ever published by the Free
4084Software Foundation.
4085
4086If the Program specifies that a proxy can decide which future versions
4087of the GNU General Public License can be used, that proxy's public
4088statement of acceptance of a version permanently authorizes you to
4089choose that version for the Program.
4090
4091Later license versions may give you additional or different
4092permissions. However, no additional obligations are imposed on any
4093author or copyright holder as a result of your choosing to follow a
4094later version.
4095
4096### 15. Disclaimer of Warranty.
4097
4098THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
4099APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
4100HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
4101WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT
4102LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
4103A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND
4104PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
4105DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
4106CORRECTION.
4107
4108### 16. Limitation of Liability.
4109
4110IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
4111WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR
4112CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
4113INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
4114ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT
4115NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR
4116LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM
4117TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER
4118PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
4119
4120### 17. Interpretation of Sections 15 and 16.
4121
4122If the disclaimer of warranty and limitation of liability provided
4123above cannot be given local legal effect according to their terms,
4124reviewing courts shall apply local law that most closely approximates
4125an absolute waiver of all civil liability in connection with the
4126Program, unless a warranty or assumption of liability accompanies a
4127copy of the Program in return for a fee.
4128
4129END OF TERMS AND CONDITIONS
4130
4131## How to Apply These Terms to Your New Programs
4132
4133If you develop a new program, and you want it to be of the greatest
4134possible use to the public, the best way to achieve this is to make it
4135free software which everyone can redistribute and change under these
4136terms.
4137
4138To do so, attach the following notices to the program. It is safest to
4139attach them to the start of each source file to most effectively state
4140the exclusion of warranty; and each file should have at least the
4141"copyright" line and a pointer to where the full notice is found.
4142
4143 <one line to give the program's name and a brief idea of what it does.>
4144 Copyright (C) <year> <name of author>
4145
4146 This program is free software: you can redistribute it and/or modify
4147 it under the terms of the GNU General Public License as published by
4148 the Free Software Foundation, either version 3 of the License, or
4149 (at your option) any later version.
4150
4151 This program is distributed in the hope that it will be useful,
4152 but WITHOUT ANY WARRANTY; without even the implied warranty of
4153 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
4154 GNU General Public License for more details.
4155
4156 You should have received a copy of the GNU General Public License
4157 along with this program. If not, see <https://www.gnu.org/licenses/>.
4158
4159Also add information on how to contact you by electronic and paper
4160mail.
4161
4162If the program does terminal interaction, make it output a short
4163notice like this when it starts in an interactive mode:
4164
4165 <program> Copyright (C) <year> <name of author>
4166 This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
4167 This is free software, and you are welcome to redistribute it
4168 under certain conditions; type `show c' for details.
4169
4170The hypothetical commands \`show w' and \`show c' should show the
4171appropriate parts of the General Public License. Of course, your
4172program's commands might be different; for a GUI interface, you would
4173use an "about box".
4174
4175You should also get your employer (if you work as a programmer) or
4176school, if any, to sign a "copyright disclaimer" for the program, if
4177necessary. For more information on this, and how to apply and follow
4178the GNU GPL, see <https://www.gnu.org/licenses/>.
4179
4180The GNU General Public License does not permit incorporating your
4181program into proprietary programs. If your program is a subroutine
4182library, you may consider it more useful to permit linking proprietary
4183applications with the library. If this is what you want to do, use the
4184GNU Lesser General Public License instead of this License. But first,
4185please read <https://www.gnu.org/licenses/why-not-lgpl.html>.
4186```
4187
4188*/