├── src ├── test_data │ ├── 35123 │ ├── URL │ ├── Array │ ├── Blank │ ├── Code │ ├── Date │ ├── Email │ ├── Mention │ ├── 0123456789 │ ├── AppMessage │ ├── Attachment │ ├── ExtraData │ ├── Formatted │ ├── LongMessage │ ├── MultiPart │ ├── PhoneNumber │ ├── StyledLink │ ├── TextEffects │ ├── TextStyles │ ├── URLMessage │ ├── WeirdText │ ├── AttachmentI16 │ ├── CustomTapback │ ├── HugeWithRefs │ ├── Transcription │ ├── crabstep.png │ ├── AppleMusicLyrics │ ├── MultiAttachment │ ├── TextStylesMixed │ ├── EmojiBoldUnderline │ ├── OverlappingFormat │ ├── EditedWithFormatting │ ├── MultiPartWithDeleted │ ├── TextStylesSingleRange │ ├── AttributedBodyTextOnly │ └── AttributedBodyTextOnly2 ├── models │ ├── mod.rs │ ├── class.rs │ ├── archived.rs │ ├── types.rs │ └── output_data.rs ├── deserializer │ ├── mod.rs │ ├── constants.rs │ ├── consumed.rs │ ├── header.rs │ ├── read.rs │ ├── string.rs │ ├── number.rs │ ├── iter.rs │ └── typedstream.rs └── error.rs ├── .gitignore ├── Cargo.lock ├── .github └── workflows │ ├── test.yml │ └── release.yml ├── Cargo.toml ├── README.md └── LICENSE /src/test_data/URL: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/URL -------------------------------------------------------------------------------- /src/test_data/35123: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/35123 -------------------------------------------------------------------------------- /src/test_data/Array: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/Array -------------------------------------------------------------------------------- /src/test_data/Blank: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/Blank -------------------------------------------------------------------------------- /src/test_data/Code: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/Code -------------------------------------------------------------------------------- /src/test_data/Date: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/Date -------------------------------------------------------------------------------- /src/test_data/Email: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/Email -------------------------------------------------------------------------------- /src/test_data/Mention: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/Mention -------------------------------------------------------------------------------- /src/test_data/0123456789: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/0123456789 -------------------------------------------------------------------------------- /src/test_data/AppMessage: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/AppMessage -------------------------------------------------------------------------------- /src/test_data/Attachment: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/Attachment -------------------------------------------------------------------------------- /src/test_data/ExtraData: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/ExtraData -------------------------------------------------------------------------------- /src/test_data/Formatted: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/Formatted -------------------------------------------------------------------------------- /src/test_data/LongMessage: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/LongMessage -------------------------------------------------------------------------------- /src/test_data/MultiPart: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/MultiPart -------------------------------------------------------------------------------- /src/test_data/PhoneNumber: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/PhoneNumber -------------------------------------------------------------------------------- /src/test_data/StyledLink: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/StyledLink -------------------------------------------------------------------------------- /src/test_data/TextEffects: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/TextEffects -------------------------------------------------------------------------------- /src/test_data/TextStyles: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/TextStyles -------------------------------------------------------------------------------- /src/test_data/URLMessage: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/URLMessage -------------------------------------------------------------------------------- /src/test_data/WeirdText: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/WeirdText -------------------------------------------------------------------------------- /src/test_data/AttachmentI16: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/AttachmentI16 -------------------------------------------------------------------------------- /src/test_data/CustomTapback: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/CustomTapback -------------------------------------------------------------------------------- /src/test_data/HugeWithRefs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/HugeWithRefs -------------------------------------------------------------------------------- /src/test_data/Transcription: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/Transcription -------------------------------------------------------------------------------- /src/test_data/crabstep.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/crabstep.png -------------------------------------------------------------------------------- /src/test_data/AppleMusicLyrics: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/AppleMusicLyrics -------------------------------------------------------------------------------- /src/test_data/MultiAttachment: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/MultiAttachment -------------------------------------------------------------------------------- /src/test_data/TextStylesMixed: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/TextStylesMixed -------------------------------------------------------------------------------- /src/test_data/EmojiBoldUnderline: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/EmojiBoldUnderline -------------------------------------------------------------------------------- /src/test_data/OverlappingFormat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/OverlappingFormat -------------------------------------------------------------------------------- /src/test_data/EditedWithFormatting: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/EditedWithFormatting -------------------------------------------------------------------------------- /src/test_data/MultiPartWithDeleted: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/MultiPartWithDeleted -------------------------------------------------------------------------------- /src/test_data/TextStylesSingleRange: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/TextStylesSingleRange -------------------------------------------------------------------------------- /src/test_data/AttributedBodyTextOnly: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/AttributedBodyTextOnly -------------------------------------------------------------------------------- /src/test_data/AttributedBodyTextOnly2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReagentX/crabstep/HEAD/src/test_data/AttributedBodyTextOnly2 -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Development environment 2 | /.vscode 3 | 4 | # Generated files 5 | /target 6 | /output 7 | 8 | # OS Files 9 | .DS_Store 10 | -------------------------------------------------------------------------------- /src/models/mod.rs: -------------------------------------------------------------------------------- 1 | //! Contains the data models used in the deserialization process 2 | 3 | pub mod archived; 4 | pub mod class; 5 | pub mod output_data; 6 | pub mod types; 7 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 4 4 | 5 | [[package]] 6 | name = "crabstep" 7 | version = "0.0.0" 8 | -------------------------------------------------------------------------------- /src/deserializer/mod.rs: -------------------------------------------------------------------------------- 1 | //! Provides a deserializer for the `typedstream` format 2 | 3 | pub mod constants; 4 | pub mod consumed; 5 | pub mod header; 6 | pub mod iter; 7 | pub mod number; 8 | pub mod read; 9 | pub mod string; 10 | pub mod typedstream; 11 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - release 7 | - develop 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | Test: 14 | name: crabstep Tests 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v4 19 | - run: rustup update stable && rustup default stable 20 | - run: cargo clippy 21 | - run: cargo test --verbose 22 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "crabstep" 3 | version = "0.0.0" 4 | edition = "2024" 5 | authors = ["Christopher Sardegna "] 6 | license = "GPL-3.0-or-later" 7 | description = "Cross-platform, zero-dependency Apple/NeXTSTEP typedstream deserializer" 8 | exclude = [".github"] 9 | readme = "README.md" 10 | repository = "https://github.com/ReagentX/crabstep" 11 | keywords = ["typedstream", "macos", "ios", "apple"] 12 | categories = ["parsing", "parser-implementations", "database"] 13 | 14 | [dependencies] 15 | 16 | [features] 17 | std=[] -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | release: 5 | types: [released] 6 | 7 | env: 8 | CARGO_TERM_COLOR: always 9 | 10 | jobs: 11 | Release: 12 | name: crabstep Release 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - uses: actions/checkout@v4 17 | - run: rustup update stable && rustup default stable 18 | - run: cargo test --verbose 19 | - run: | 20 | export VERSION=${{ github.event.release.tag_name }} 21 | sed -i "s/0.0.0/$VERSION/g" Cargo.toml 22 | cargo publish --allow-dirty 23 | env: 24 | CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} 25 | -------------------------------------------------------------------------------- /src/deserializer/constants.rs: -------------------------------------------------------------------------------- 1 | //! Constants used in the serialization and deserialization process 2 | 3 | /// Indicates an [`i16`] in the byte stream 4 | pub const I_16: u8 = 0x81; 5 | /// Indicates an [`i32`] in the byte stream 6 | pub const I_32: u8 = 0x82; 7 | /// Indicates an [`f32`] or [`f64`] in the byte stream; the [`Type`](crate::models::types::Type) determines the size 8 | pub const DECIMAL: u8 = 0x83; 9 | /// Indicates the start of a new object 10 | pub const START: u8 = 0x84; 11 | /// Indicates that there is no more data to parse, for example the end of a class inheritance chain 12 | pub const EMPTY: u8 = 0x85; 13 | /// Indicates the last byte of an object 14 | pub const END: u8 = 0x86; 15 | /// Bytes equal or greater in value than the reference tag indicate an index in the table of already-seen types 16 | pub const REFERENCE_TAG: u64 = 0x92; 17 | /// Indicates an array in the byte stream 18 | pub const ARRAY: u8 = 0x5b; 19 | -------------------------------------------------------------------------------- /src/models/class.rs: -------------------------------------------------------------------------------- 1 | //! Represents a class stored in a `typedstream` 2 | 3 | /// Represents a class stored in a `typedstream` 4 | #[derive(Debug, Clone, PartialEq, Eq)] 5 | pub struct Class { 6 | /// A reference to the class name stored in the [`type_table`](crate::deserializer::typedstream::TypedStreamDeserializer::type_table) 7 | pub name_index: usize, 8 | /// The encoded version of the class 9 | pub version: u64, 10 | /// The parent class reference into the [`object_table`](crate::deserializer::typedstream::TypedStreamDeserializer::object_table), if any 11 | pub parent_index: Option, 12 | } 13 | 14 | impl Class { 15 | /// Creates a new class with the given name, version, and optional parent 16 | /// 17 | /// This method is used internally by the deserializer and is not part of the public API. 18 | #[must_use] 19 | pub(crate) fn new(name: usize, version: u64, parent: Option) -> Self { 20 | Self { 21 | name_index: name, 22 | version, 23 | parent_index: parent, 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/models/archived.rs: -------------------------------------------------------------------------------- 1 | //! Types that can be archived into a `typedstream` 2 | 3 | use alloc::vec::Vec; 4 | 5 | use crate::models::{class::Class, output_data::OutputData}; 6 | 7 | /// Types of data that can be archived into the `typedstream` 8 | #[derive(Debug, PartialEq)] 9 | pub enum Archived<'a> { 10 | /// An instance of a class that may contain some embedded data. `typedstream` data doesn't include property 11 | /// names, so data is stored in order of appearance. The class is stored in the [`object_table`](crate::deserializer::typedstream::TypedStreamDeserializer::object_table) and 12 | /// the data is stored in the `data` field. 13 | Object { 14 | /// Index into [`object_table`](crate::deserializer::typedstream::TypedStreamDeserializer::object_table) for this object’s class. 15 | class: usize, 16 | /// Nested data groups for this object. Each item represents a group of data that is logically related. 17 | /// For example, a class may have multiple properties, each represented as a group of data. 18 | data: Vec>>, 19 | }, 20 | /// A class referenced in the `typedstream`, usually part of an inheritance hierarchy that does not contain any data itself. 21 | Class(Class), 22 | /// A placeholder, only used when reserving a spot in the objects table for a reference to be filled with read class information. 23 | /// In a `typedstream`, the classes are stored in order of inheritance, so the top-level class described by the `typedstream` 24 | /// comes before the ones it inherits from. To preserve the order, we reserve the first slot to store the actual object's data 25 | /// and then later add it back to the right place. 26 | Placeholder, 27 | /// An embedded type that describes the [`Type`](crate::models::types::Type) of the subsequent bytes, referred to by its index in the [`type_table`](crate::deserializer::typedstream::TypedStreamDeserializer::type_table). 28 | Type(usize), 29 | } 30 | -------------------------------------------------------------------------------- /src/deserializer/consumed.rs: -------------------------------------------------------------------------------- 1 | //! A wrapper containing a parsed value and the number of bytes consumed during deserialization. 2 | 3 | /// A value of type `T` along with how many bytes were consumed to produce it. 4 | pub struct Consumed { 5 | /// The parsed value. 6 | pub value: T, 7 | /// Number of bytes read from the stream. 8 | pub bytes_consumed: usize, 9 | } 10 | 11 | impl Consumed { 12 | /// Create a new `Consumed` with the given `value` and `bytes_consumed`. 13 | /// 14 | /// # Examples 15 | /// 16 | /// ```no_run 17 | /// use crabstep::deserializer::consumed::Consumed; 18 | /// let consumed = Consumed::new(42, 2); 19 | /// 20 | /// assert_eq!(consumed.value, 42); 21 | /// assert_eq!(consumed.bytes_consumed, 2); 22 | /// ``` 23 | pub fn new(value: T, bytes_consumed: usize) -> Self { 24 | Consumed { 25 | value, 26 | bytes_consumed, 27 | } 28 | } 29 | 30 | /// Transform the contained value to another type, preserving `bytes_consumed`. 31 | /// 32 | /// # Examples 33 | /// 34 | /// ```no_run 35 | /// use crabstep::deserializer::consumed::Consumed; 36 | /// let consumed = Consumed::new(2u8, 1); 37 | /// let mapped = consumed.map(|v| v as u16); 38 | /// 39 | /// assert_eq!(mapped.value, 2u16); 40 | /// assert_eq!(mapped.bytes_consumed, 1); 41 | /// ``` 42 | pub fn map(self, f: F) -> Consumed 43 | where 44 | F: FnOnce(T) -> U, 45 | { 46 | Consumed { 47 | value: f(self.value), 48 | bytes_consumed: self.bytes_consumed, 49 | } 50 | } 51 | } 52 | 53 | impl core::ops::Deref for Consumed { 54 | type Target = T; 55 | 56 | fn deref(&self) -> &Self::Target { 57 | &self.value 58 | } 59 | } 60 | 61 | impl core::ops::DerefMut for Consumed { 62 | fn deref_mut(&mut self) -> &mut Self::Target { 63 | &mut self.value 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # crabstep 2 | 3 | `crabstep` is a Rust library that deserializes Apple's `typedstream` data into cross-platform data structures. 4 | 5 | ## Overview 6 | 7 | The `typedstream` format is a binary serialization protocol designed for `C` and `Objective-C` data structures. It is primarily used in Apple's `Foundation` framework, specifically within the `NSArchiver` and `NSUnarchiver` classes. 8 | 9 | ## Installation 10 | 11 | This library is available on [crates.io](https://crates.io/crates/crabstep). 12 | 13 | ## Documentation 14 | 15 | Documentation is available on [docs.rs](https://docs.rs/crabstep). 16 | 17 | ### Quick Start 18 | 19 | ```rust,no_run 20 | use std::{env::current_dir, fs::File, io::Read}; 21 | 22 | use crabstep::TypedStreamDeserializer; 23 | 24 | // Read the typedstream file into memory 25 | let typedstream_path = current_dir() 26 | .unwrap() 27 | .as_path() 28 | .join("path/to/typedstream/file"); 29 | let mut file = File::open(typedstream_path).unwrap(); 30 | let mut bytes = vec![]; 31 | file.read_to_end(&mut bytes).unwrap(); 32 | 33 | // Create a deserializer 34 | let mut typedstream = TypedStreamDeserializer::new(&bytes); 35 | 36 | // Iterate over the typedstream's properties 37 | typedstream.iter_root() 38 | .unwrap() 39 | .for_each(|prop| println!("{:#?}", prop)) 40 | ``` 41 | 42 | ### Detailed examples 43 | 44 | This crate is heavily leveraged by [`imessage-database`](https://crates.io/crates/imessage-database)'s [`body`](https://github.com/ReagentX/imessage-exporter/blob/develop/imessage-database/src/tables/messages/body.rs) module. 45 | 46 | ## Origin 47 | 48 | The `typedstream` format is derived from the data structure used by `NeXTSTEP`'s `NXTypedStream` APIs. 49 | 50 | ## Features 51 | 52 | - Pure Rust implementation for efficient and safe deserialization 53 | - No dependencies on Apple frameworks 54 | - Robust error handling for malformed or incomplete `typedstream` data 55 | - Ergonomic `TypedStreamDeserializer` with `resolve_properties` iterator for exploring object graphs 56 | 57 | ## Reverse Engineering 58 | 59 | A blog post describing the reverse engineering of `typedstream` is available as [an in-depth article](https://chrissardegna.com/blog/reverse-engineering-apples-typedstream-format/). 60 | 61 | ## Ferris 62 | 63 | ![Ferris the crab walking along a hexadecimal path](src/test_data/crabstep.png) 64 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | //! Error types and result alias for `typedstream` deserialization 2 | 3 | use core::{array::TryFromSliceError, fmt::Display}; 4 | 5 | /// A specialized [`Result`] type for `typedstream` operations. 6 | /// 7 | /// # Examples 8 | /// 9 | /// ```no_run 10 | /// use crabstep::error::Result; 11 | /// use crabstep::TypedStreamDeserializer; 12 | /// 13 | /// fn get_root(data: &[u8]) -> Result { 14 | /// let mut deserializer = TypedStreamDeserializer::new(data); 15 | /// deserializer.oxidize() 16 | /// } 17 | /// ``` 18 | pub type Result = core::result::Result; 19 | 20 | /// Errors that can occur while deserializing a `typedstream`. 21 | #[derive(Debug)] 22 | pub enum TypedStreamError { 23 | /// An invalid object was encountered, such as an unmatched end marker. 24 | InvalidObject, 25 | /// Attempted to access an index outside the stream bounds (requested, length). 26 | OutOfBounds(usize, usize), 27 | /// Error converting a slice into an array of fixed size. 28 | SliceError(TryFromSliceError), 29 | /// Error parsing a string as UTF-8. 30 | StringParseError(core::str::Utf8Error), 31 | /// The `typedstream` header was invalid. 32 | InvalidHeader, 33 | /// Encountered an invalid pointer value. 34 | InvalidPointer(u8), 35 | /// The array header is malformed or too large. 36 | InvalidArray(usize), 37 | /// Encountered an empty string where data was expected. 38 | EmptyString, 39 | } 40 | 41 | impl Display for TypedStreamError { 42 | fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 43 | match self { 44 | TypedStreamError::InvalidObject => { 45 | write!(f, "Invalid object encountered in typedstream!") 46 | } 47 | TypedStreamError::OutOfBounds(n, len) => write!( 48 | f, 49 | "Out of bounds access: tried to access byte {n} in a stream of length {len}" 50 | ), 51 | TypedStreamError::SliceError(try_from_slice_error) => { 52 | write!(f, "Slice conversion error: {try_from_slice_error}") 53 | } 54 | TypedStreamError::StringParseError(utf8_error) => { 55 | write!(f, "String parsing error: {utf8_error}") 56 | } 57 | TypedStreamError::InvalidHeader => write!(f, "Invalid header in typedstream!"), 58 | TypedStreamError::InvalidPointer(pointer) => { 59 | write!(f, "Invalid pointer: {pointer:x}") 60 | } 61 | TypedStreamError::InvalidArray(offset) => { 62 | write!(f, "Invalid array at index: {offset:x}") 63 | } 64 | TypedStreamError::EmptyString => write!(f, "Empty string encountered in typedstream"), 65 | } 66 | } 67 | } 68 | 69 | impl From for TypedStreamError { 70 | fn from(error: TryFromSliceError) -> Self { 71 | TypedStreamError::SliceError(error) 72 | } 73 | } 74 | 75 | impl From for TypedStreamError { 76 | fn from(error: core::str::Utf8Error) -> Self { 77 | TypedStreamError::StringParseError(error) 78 | } 79 | } 80 | 81 | impl core::error::Error for TypedStreamError {} 82 | -------------------------------------------------------------------------------- /src/deserializer/header.rs: -------------------------------------------------------------------------------- 1 | //! Header validation for `TypedStream` format 2 | 3 | use crate::{ 4 | deserializer::{ 5 | consumed::Consumed, 6 | number::{read_signed_int, read_unsigned_int}, 7 | string::read_string, 8 | }, 9 | error::{Result, TypedStreamError}, 10 | }; 11 | 12 | /// Validate the `typedstream` header for macOS/iOS format. 13 | /// 14 | /// Reads version, signature, and system version, returning a [`Consumed`] 15 | /// indicating validity and bytes consumed. 16 | /// 17 | /// # Errors 18 | /// 19 | /// Returns [`TypedStreamError::InvalidHeader`] if the header does not match expected values. 20 | /// 21 | /// # Examples 22 | /// ```no_run 23 | /// use crabstep::deserializer::header::validate_header; 24 | /// 25 | /// let data: &[u8] = &[ 26 | /// 0x04, 0x0b, b's', b't', b'r', b'e', b'a', b'm', b't', b'y', b'p', b'e', b'd', 27 | /// 0x81, 0xe8, 0x03, 28 | /// ]; 29 | /// 30 | /// let result = validate_header(data).unwrap(); 31 | /// assert!(result.value); 32 | /// assert_eq!(result.bytes_consumed, 16); 33 | /// ``` 34 | pub fn validate_header(data: &[u8]) -> Result> { 35 | // Encoding type 36 | let typedstream_version = read_unsigned_int(data)?; 37 | // Encoding signature 38 | let signature = read_string(&data[typedstream_version.bytes_consumed..])?; 39 | // System version 40 | let system_version = 41 | read_signed_int(&data[typedstream_version.bytes_consumed + signature.bytes_consumed..])?; 42 | 43 | if typedstream_version.value != 4 44 | || signature.value != "streamtyped" 45 | || system_version.value != 1000 46 | { 47 | return Err(TypedStreamError::InvalidHeader); 48 | } 49 | 50 | Ok(Consumed::new( 51 | true, 52 | typedstream_version.bytes_consumed 53 | + signature.bytes_consumed 54 | + system_version.bytes_consumed, 55 | )) 56 | } 57 | 58 | #[cfg(test)] 59 | mod header_tests { 60 | extern crate std; 61 | use alloc::vec; 62 | use std::{env::current_dir, fs::File, io::Read, println}; 63 | 64 | use crate::deserializer::{constants::I_16, header::validate_header}; 65 | 66 | #[test] 67 | fn can_validate_header() { 68 | let data = [ 69 | 0x04, // TypedStream version (4) 70 | 0x0b, // Length of the signature 71 | b's', b't', b'r', b'e', b'a', b'm', b't', b'y', b'p', b'e', b'd', // Signature 72 | I_16, 0xe8, 0x03, // System version (1000 in little-endian) 73 | ]; 74 | let result = validate_header(&data).unwrap(); 75 | 76 | assert!(result.value); 77 | assert_eq!(result.bytes_consumed, 16); 78 | } 79 | 80 | #[test] 81 | fn can_validate_real_header() { 82 | let typedstream_path = current_dir() 83 | .unwrap() 84 | .as_path() 85 | .join("src/test_data/AttributedBodyTextOnly"); 86 | println!("Parsing file: {typedstream_path:?}"); 87 | let mut file = File::open(typedstream_path).unwrap(); 88 | let mut bytes = vec![]; 89 | file.read_to_end(&mut bytes).unwrap(); 90 | 91 | // Skip the header for now 92 | let validated = validate_header(&bytes).unwrap(); 93 | 94 | assert!(validated.value); 95 | assert_eq!(validated.bytes_consumed, 16); 96 | } 97 | 98 | #[test] 99 | fn fails_on_invalid_header() { 100 | let data = [0x01]; // Invalid TypedStream version 101 | assert!(validate_header(&data).is_err()); 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /src/deserializer/read.rs: -------------------------------------------------------------------------------- 1 | //! This module provides functions to read data from a byte slice 2 | 3 | use crate::{ 4 | deserializer::{constants::REFERENCE_TAG, consumed::Consumed}, 5 | error::{Result, TypedStreamError}, 6 | }; 7 | 8 | /// Read exactly `n` bytes from a slice of the stream. 9 | /// 10 | /// Returns a slice of length `n` or an error if the data is too short. 11 | /// 12 | /// # Errors 13 | /// 14 | /// Returns [`TypedStreamError::OutOfBounds`] when `data.len() < n`. 15 | /// 16 | /// # Examples 17 | /// ```no_run 18 | /// use crabstep::deserializer::read::read_exact_bytes; 19 | /// 20 | /// let data = [0x01, 0x02, 0x03]; 21 | /// let slice = read_exact_bytes(&data, 2).unwrap(); 22 | /// 23 | /// assert_eq!(slice, &[0x01, 0x02]); 24 | /// ``` 25 | #[inline(always)] 26 | pub fn read_exact_bytes(data: &[u8], n: usize) -> Result<&[u8]> { 27 | let range = data 28 | .get(0..n) 29 | .ok_or(TypedStreamError::OutOfBounds(n, data.len()))?; 30 | 31 | Ok(range) 32 | } 33 | 34 | /// Read a single byte from a slice of the stream at index `idx`. 35 | /// 36 | /// # Errors 37 | /// 38 | /// Returns [`TypedStreamError::OutOfBounds`] when `idx >= data.len()`. 39 | /// 40 | /// # Examples 41 | /// ```rust 42 | /// use crabstep::deserializer::read::read_byte_at; 43 | /// 44 | /// let data = [0xFF]; 45 | /// let byte = read_byte_at(&data, 0).unwrap(); 46 | /// 47 | /// assert_eq!(*byte, 0xFF); 48 | /// ``` 49 | #[inline(always)] 50 | pub fn read_byte_at(data: &[u8], idx: usize) -> Result<&u8> { 51 | data.get(idx) 52 | .ok_or(TypedStreamError::OutOfBounds(idx, data.len())) 53 | } 54 | 55 | /// Read a reference pointer encoded as a single byte. 56 | /// 57 | /// Subtracts the [`REFERENCE_TAG`] constant to yield the zero-based index. 58 | /// 59 | /// # Errors 60 | /// 61 | /// Returns [`TypedStreamError::InvalidPointer`] if the byte is less than `REFERENCE_TAG`. 62 | /// 63 | /// # Examples 64 | /// ```rust 65 | /// use crabstep::{deserializer::{read::read_pointer, constants::REFERENCE_TAG}}; 66 | /// 67 | /// let consumed = read_pointer(&0x94).unwrap(); 68 | /// 69 | /// assert_eq!(consumed.value, 2); 70 | /// assert_eq!(consumed.bytes_consumed, 1); 71 | /// ``` 72 | #[inline(always)] 73 | pub fn read_pointer(pointer: &u8) -> Result> { 74 | let result = u64::from(*pointer) 75 | .checked_sub(REFERENCE_TAG) 76 | .ok_or(TypedStreamError::InvalidPointer(*pointer))?; 77 | 78 | Ok(Consumed::new(result, 1)) 79 | } 80 | 81 | #[cfg(test)] 82 | mod read_tests { 83 | use crate::deserializer::read::{read_exact_bytes, read_pointer}; 84 | use crate::error::TypedStreamError; 85 | 86 | #[test] 87 | fn can_read_exact_bytes() { 88 | let data = [0x01, 0x02, 0x03, 0x04]; 89 | let result = read_exact_bytes(&data, 4).unwrap(); 90 | assert_eq!(result, &data); 91 | } 92 | 93 | #[test] 94 | fn can_read_exact_bytes_partial() { 95 | let data = [0x01, 0x02, 0x03]; 96 | let result = read_exact_bytes(&data, 2).unwrap(); 97 | assert_eq!(result, &data[..2]); 98 | } 99 | 100 | #[test] 101 | fn cannot_read_exact_bytes_out_of_bounds() { 102 | let data = [0x01, 0x02]; 103 | let result = read_exact_bytes(&data, 3); 104 | assert!(matches!(result, Err(TypedStreamError::OutOfBounds(3, 2)))); 105 | } 106 | 107 | #[test] 108 | fn can_read_pointer() { 109 | // Pointer value 3 (0x03) + REFERENCE_TAG (0x92) 110 | let result = read_pointer(&0x95).unwrap(); 111 | assert_eq!(result.value, 3); 112 | assert_eq!(result.bytes_consumed, 1); 113 | } 114 | 115 | #[test] 116 | fn can_read_pointer_zero() { 117 | // Pointer value 30(0x00) + REFERENCE_TAG (0x92) 118 | let result = read_pointer(&0x92).unwrap(); 119 | assert_eq!(result.value, 0); 120 | assert_eq!(result.bytes_consumed, 1); 121 | } 122 | 123 | #[test] 124 | fn cant_read_invalid_pointer() { 125 | // Invalid pointer 126 | let result = read_pointer(&0x10); 127 | assert!(matches!(result, Err(TypedStreamError::InvalidPointer(16)))); 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /src/deserializer/string.rs: -------------------------------------------------------------------------------- 1 | //! Utilities for reading UTF-8 strings from a `typedstream`. 2 | 3 | use crate::{ 4 | deserializer::{consumed::Consumed, number::read_unsigned_int}, 5 | error::Result, 6 | }; 7 | 8 | /// Read a UTF-8 string from the stream, prefixed by its length encoded as an unsigned integer. 9 | /// 10 | /// The function reads the length (`1`, `2`, or `4` bytes as needed), then the UTF-8 bytes. 11 | /// Returns a slice to the string and total bytes consumed. 12 | /// 13 | /// # Errors 14 | /// 15 | /// Returns [`TypedStreamError::OutOfBounds`](crate::error::TypedStreamError::OutOfBounds) if not enough bytes for length or data, 16 | /// or [`TypedStreamError::StringParseError`](crate::error::TypedStreamError::StringParseError) if the bytes are not valid UTF-8. 17 | /// 18 | /// # Examples 19 | /// ```no_run 20 | /// use crabstep::deserializer::string::read_string; 21 | /// 22 | /// let data = [0x05, b'H', b'e', b'l', b'l', b'o']; 23 | /// let consumed = read_string(&data).unwrap(); 24 | /// 25 | /// assert_eq!(consumed.value, "Hello"); 26 | /// assert_eq!(consumed.bytes_consumed, 6); 27 | /// ``` 28 | pub fn read_string(data: &[u8]) -> Result> { 29 | let length = read_unsigned_int(data)?; 30 | Ok(Consumed::new( 31 | core::str::from_utf8( 32 | data.get(length.bytes_consumed..(length.bytes_consumed + length.value as usize)) 33 | .ok_or({ 34 | crate::error::TypedStreamError::OutOfBounds(length.value as usize, data.len()) 35 | })?, 36 | )?, 37 | length.bytes_consumed + length.value as usize, 38 | )) 39 | } 40 | 41 | #[cfg(test)] 42 | mod string_tests { 43 | use alloc::vec::Vec; 44 | 45 | use crate::deserializer::{ 46 | constants::{I_16, I_32}, 47 | string::read_string, 48 | }; 49 | 50 | #[test] 51 | fn can_read_string() { 52 | let data = [0x05, b'H', b'e', b'l', b'l', b'o']; 53 | let result = read_string(&data).unwrap(); 54 | 55 | assert_eq!(result.value, "Hello"); 56 | assert_eq!(result.bytes_consumed, 6); 57 | } 58 | 59 | #[test] 60 | fn can_read_string_extra() { 61 | let data = [ 62 | 0x05, b'H', b'e', b'l', b'l', b'o', b' ', b'W', b'o', b'r', b'l', b'd', 63 | ]; 64 | let result = read_string(&data).unwrap(); 65 | 66 | assert_eq!(result.value, "Hello"); 67 | assert_eq!(result.bytes_consumed, 6); 68 | } 69 | 70 | #[test] 71 | fn can_read_string_long() { 72 | // Bytes to indicate 1000 characters 73 | let start_bytes = [I_16, 0xE8, 0x03]; // 1000 in little-endian 74 | let long_string: Vec = (0..1000).map(|_| b'a').collect(); 75 | let combined = start_bytes 76 | .iter() 77 | .chain(long_string.iter()) 78 | .copied() 79 | .collect::>(); 80 | 81 | let result = read_string(&combined).unwrap(); 82 | 83 | assert_eq!(result.value.len(), 1000); 84 | assert!(result.value.starts_with('a')); 85 | assert!(result.value.ends_with('a')); 86 | // 1 byte for the int type, 2 bytes for I_16, 1000 bytes for the string 87 | assert_eq!(result.bytes_consumed, 1003); 88 | } 89 | 90 | #[test] 91 | fn can_read_string_insanely_long() { 92 | // Bytes to indicate 1000 characters 93 | let start_bytes = [I_32, 0x01, 0x01, 0x01, 0x01]; // 1000 in little-endian 94 | let long_string: Vec = (0..16843009).map(|_| b'a').collect(); 95 | let combined = start_bytes 96 | .iter() 97 | .chain(long_string.iter()) 98 | .copied() 99 | .collect::>(); 100 | 101 | let result = read_string(&combined).unwrap(); 102 | 103 | assert_eq!(result.value.len(), 16843009); 104 | assert!(result.value.starts_with('a')); 105 | assert!(result.value.ends_with('a')); 106 | // 1 byte for the int type, 4 bytes for I_32, 16843009 bytes for the string 107 | assert_eq!(result.bytes_consumed, 16843014); 108 | } 109 | 110 | #[test] 111 | fn can_read_empty_string() { 112 | let data = [0x00]; 113 | let result = read_string(&data).unwrap(); 114 | 115 | assert_eq!(result.value, ""); 116 | assert_eq!(result.bytes_consumed, 1); 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/models/types.rs: -------------------------------------------------------------------------------- 1 | //! Type tags that denote the type of data stored in a `typedstream` 2 | use crate::{ 3 | deserializer::{ 4 | constants::ARRAY, consumed::Consumed, number::read_unsigned_int, read::read_exact_bytes, 5 | }, 6 | error::{Result, TypedStreamError}, 7 | }; 8 | use alloc::{vec, vec::Vec}; 9 | 10 | /// Represents primitive types of data that can be stored in a `typedstream` 11 | /// 12 | /// These type encodings are partially documented [here](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html#//apple_ref/doc/uid/TP40008048-CH100-SW1) by Apple. 13 | #[derive(Debug, Clone, PartialEq)] 14 | pub enum Type<'a> { 15 | /// Encoded string data, usually embedded in an object. Denoted by: 16 | /// 17 | /// | Hex | UTF-8 | 18 | /// |--------|-------| 19 | /// | `0x28` | [`+`](https://www.compart.com/en/unicode/U+002B) | 20 | Utf8String, 21 | /// Encoded bytes that can be parsed again as data. Denoted by: 22 | /// 23 | /// | Hex | UTF-8 | 24 | /// |--------|-------| 25 | /// | `0x2A` | [`*`](https://www.compart.com/en/unicode/U+002A) | 26 | EmbeddedData, 27 | /// An instance of a class, usually with data. Denoted by: 28 | /// 29 | /// | Hex | UTF-8 | 30 | /// |--------|-------| 31 | /// | `0x40` | [`@`](https://www.compart.com/en/unicode/U+0040) | 32 | Object, 33 | /// An [`i8`], [`i16`], or [`i32`]. Denoted by: 34 | /// | Hex | UTF-8 | 35 | /// |--------|-------| 36 | /// | `0x63` | [`c`](https://www.compart.com/en/unicode/U+0063) | 37 | /// | `0x69` | [`i`](https://www.compart.com/en/unicode/U+0069) | 38 | /// | `0x6c` | [`l`](https://www.compart.com/en/unicode/U+006c) | 39 | /// | `0x71` | [`q`](https://www.compart.com/en/unicode/U+0071) | 40 | /// | `0x73` | [`s`](https://www.compart.com/en/unicode/U+0073) | 41 | /// 42 | /// The width is determined by the prefix: [`i8`] has none, [`i16`] has `0x81`, and [`i32`] has `0x82`. 43 | SignedInt, 44 | /// A [`u8`], [`u16`], or [`u32`]. Denoted by: 45 | /// | Hex | UTF-8 | 46 | /// |--------|-------| 47 | /// | `0x43` | [`C`](https://www.compart.com/en/unicode/U+0043) | 48 | /// | `0x49` | [`I`](https://www.compart.com/en/unicode/U+0049) | 49 | /// | `0x4c` | [`L`](https://www.compart.com/en/unicode/U+004c) | 50 | /// | `0x51` | [`Q`](https://www.compart.com/en/unicode/U+0051) | 51 | /// | `0x53` | [`S`](https://www.compart.com/en/unicode/U+0053) | 52 | /// 53 | /// The width is determined by the prefix: [`u8`] has none, [`u16`] has `0x81`, and [`u32`] has `0x82`. 54 | UnsignedInt, 55 | /// An [`f32`]. Denoted by: 56 | /// 57 | /// | Hex | UTF-8 | 58 | /// |--------|-------| 59 | /// | `0x66` | [`f`](https://www.compart.com/en/unicode/U+0066) | 60 | Float, 61 | /// An [`f64`]. Denoted by: 62 | /// 63 | /// | Hex | UTF-8 | 64 | /// |--------|-------| 65 | /// | `0x64` | [`d`](https://www.compart.com/en/unicode/U+0064) | 66 | Double, 67 | /// Some text we can reuse later, i.e. a class name. 68 | String(&'a str), 69 | /// An array containing some data of a given length. Denoted in the stream by braced digits: `[123]`. 70 | Array(usize), 71 | /// Data for which we do not know the type, likely for something this parser does not implement. 72 | Unknown(u8), 73 | } 74 | 75 | impl<'a> Type<'a> { 76 | /// Convert a byte to a Type enum variant 77 | #[inline] 78 | pub(crate) fn from_byte(byte: u8) -> Self { 79 | match byte { 80 | 0x40 => Self::Object, 81 | 0x2B => Self::Utf8String, 82 | 0x2A => Self::EmbeddedData, 83 | 0x66 => Self::Float, 84 | 0x64 => Self::Double, 85 | 0x63 | 0x69 | 0x6c | 0x71 | 0x73 => Self::SignedInt, 86 | 0x43 | 0x49 | 0x4c | 0x51 | 0x53 => Self::UnsignedInt, 87 | other => Self::Unknown(other), 88 | } 89 | } 90 | 91 | #[inline] 92 | pub(crate) fn new_string(str: &'a str) -> Self { 93 | Self::String(str) 94 | } 95 | 96 | pub(crate) fn get_array_length(types: &'_ [u8]) -> Option>> { 97 | if types.first() == Some(&0x5b) { 98 | let len = 99 | types[1..] 100 | .iter() 101 | .take_while(|a| a.is_ascii_digit()) 102 | .fold(None, |acc, ch| { 103 | char::from_u32(u32::from(*ch))? 104 | .to_digit(10) 105 | .map(|b| acc.unwrap_or(0) * 10 + b) 106 | })?; 107 | return Some(vec![Type::Array(len as usize)]); 108 | } 109 | None 110 | } 111 | 112 | pub(crate) fn read_new_type(data: &'_ [u8]) -> Result>>> { 113 | // Get the type of the object 114 | let type_length = read_unsigned_int(data)?; 115 | 116 | // Get the bytes for the type 117 | let type_bytes = read_exact_bytes( 118 | &data[type_length.bytes_consumed..], 119 | type_length.value as usize, 120 | )?; 121 | 122 | // Handle array size 123 | if type_bytes.first() == Some(&ARRAY) { 124 | return Ok(Consumed::new( 125 | Type::get_array_length(type_bytes).ok_or(TypedStreamError::InvalidArray(0))?, 126 | type_length.bytes_consumed + type_bytes.len(), 127 | )); 128 | } 129 | 130 | Ok(Consumed::new( 131 | type_bytes.iter().copied().map(Type::from_byte).collect(), 132 | type_length.bytes_consumed + type_bytes.len(), 133 | )) 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /src/models/output_data.rs: -------------------------------------------------------------------------------- 1 | //! Output data types for the `typedstream` deserializer 2 | 3 | /// Rust structures containing data stored in the `typedstream` 4 | #[derive(Debug, PartialEq)] 5 | pub enum OutputData<'a> { 6 | /// Text data, denoted in the stream by [`Type::String`](crate::models::types::Type::String) 7 | String(&'a str), 8 | /// Signed integer types are coerced into this container, denoted in the stream by [`Type::SignedInt`](crate::models::types::Type::SignedInt) 9 | SignedInteger(i64), 10 | /// Unsigned integer types are coerced into this container, denoted in the stream by [`Type::UnsignedInt`](crate::models::types::Type::UnsignedInt) 11 | UnsignedInteger(u64), 12 | /// Floating point numbers, denoted in the stream by [`Type::Float`](crate::models::types::Type::Float) 13 | Float(f32), 14 | /// Double precision floats, denoted in the stream by [`Type::Double`](crate::models::types::Type::Double) 15 | Double(f64), 16 | /// Bytes whose type is not known, denoted in the stream by [`Type::Unknown`](crate::models::types::Type::Unknown) 17 | Byte(u8), 18 | /// Arbitrary collection of bytes in an array, denoted in the stream by [`Type::Array`](crate::models::types::Type::Array) 19 | Array(&'a [u8]), 20 | /// Reference to another object by index in the [`object_table`](crate::deserializer::typedstream::TypedStreamDeserializer::object_table). 21 | Object(usize), 22 | /// Represents a null value. 23 | Null, 24 | } 25 | 26 | impl<'a> OutputData<'a> { 27 | /// Returns the inner string if this is a `String` variant. 28 | /// 29 | /// # Examples 30 | /// 31 | /// ```no_run 32 | /// use crabstep::models::output_data::OutputData; 33 | /// 34 | /// let data = OutputData::String("Hello"); 35 | /// assert_eq!(data.as_str(), Some("Hello")); 36 | /// ``` 37 | #[must_use] 38 | pub fn as_str(&self) -> Option<&'a str> { 39 | if let OutputData::String(s) = self { 40 | Some(s) 41 | } else { 42 | None 43 | } 44 | } 45 | 46 | /// Returns the inner signed integer if this is a `SignedInteger` variant. 47 | /// 48 | /// # Examples 49 | /// 50 | /// ```no_run 51 | /// use crabstep::models::output_data::OutputData; 52 | /// 53 | /// let data = OutputData::SignedInteger(42); 54 | /// assert_eq!(data.as_i64(), Some(42)); 55 | /// ``` 56 | #[must_use] 57 | pub fn as_i64(&self) -> Option { 58 | if let OutputData::SignedInteger(i) = self { 59 | Some(*i) 60 | } else { 61 | None 62 | } 63 | } 64 | 65 | /// Returns the inner unsigned integer if this is an `UnsignedInteger` variant. 66 | /// 67 | /// # Examples 68 | /// 69 | /// ```no_run 70 | /// use crabstep::models::output_data::OutputData; 71 | /// 72 | /// let data = OutputData::UnsignedInteger(100); 73 | /// assert_eq!(data.as_u64(), Some(100)); 74 | /// ``` 75 | #[must_use] 76 | pub fn as_u64(&self) -> Option { 77 | if let OutputData::UnsignedInteger(u) = self { 78 | Some(*u) 79 | } else { 80 | None 81 | } 82 | } 83 | 84 | /// Returns the inner float if this is a `Float` variant. 85 | /// 86 | /// # Examples 87 | /// 88 | /// ```no_run 89 | /// use crabstep::models::output_data::OutputData; 90 | /// 91 | /// let data = OutputData::Float(3.14); 92 | /// assert_eq!(data.as_f32(), Some(3.14)); 93 | /// ``` 94 | #[must_use] 95 | pub fn as_f32(&self) -> Option { 96 | if let OutputData::Float(f) = self { 97 | Some(*f) 98 | } else { 99 | None 100 | } 101 | } 102 | 103 | /// Returns the inner double if this is a `Double` variant. 104 | /// 105 | /// # Examples 106 | /// 107 | /// ```no_run 108 | /// use crabstep::models::output_data::OutputData; 109 | /// 110 | /// let data = OutputData::Double(2.71828); 111 | /// assert_eq!(data.as_f64(), Some(2.71828)); 112 | /// ``` 113 | #[must_use] 114 | pub fn as_f64(&self) -> Option { 115 | if let OutputData::Double(d) = self { 116 | Some(*d) 117 | } else { 118 | None 119 | } 120 | } 121 | 122 | /// Returns the inner byte if this is a `Byte` variant. 123 | /// 124 | /// # Examples 125 | /// 126 | /// ```no_run 127 | /// use crabstep::models::output_data::OutputData; 128 | /// 129 | /// let data = OutputData::Byte(0xFF); 130 | /// assert_eq!(data.as_byte(), Some(0xFF)); 131 | /// ``` 132 | #[must_use] 133 | pub fn as_byte(&self) -> Option { 134 | if let OutputData::Byte(b) = self { 135 | Some(*b) 136 | } else { 137 | None 138 | } 139 | } 140 | 141 | /// Returns the inner byte slice if this is an `Array` variant. 142 | /// 143 | /// # Examples 144 | /// 145 | /// ```no_run 146 | /// use crabstep::models::output_data::OutputData; 147 | /// 148 | /// let data = OutputData::Array(&[1, 2, 3]); 149 | /// assert_eq!(data.as_array(), Some(&[1, 2, 3][..])); 150 | /// ``` 151 | #[must_use] 152 | pub fn as_array(&self) -> Option<&'a [u8]> { 153 | if let OutputData::Array(arr) = self { 154 | Some(arr) 155 | } else { 156 | None 157 | } 158 | } 159 | 160 | /// Returns the inner object index if this is an `Object` variant. 161 | /// 162 | /// # Examples 163 | /// 164 | /// ```no_run 165 | /// use crabstep::models::output_data::OutputData; 166 | /// 167 | /// let data = OutputData::Object(42); 168 | /// assert_eq!(data.as_object(), Some(42)); 169 | /// ``` 170 | #[must_use] 171 | pub fn as_object(&self) -> Option { 172 | if let OutputData::Object(idx) = self { 173 | Some(*idx) 174 | } else { 175 | None 176 | } 177 | } 178 | } 179 | 180 | // Implement Display for human-friendly formatting 181 | impl core::fmt::Display for OutputData<'_> { 182 | fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 183 | match self { 184 | OutputData::String(s) => write!(f, "{s}"), 185 | OutputData::SignedInteger(i) => write!(f, "{i}"), 186 | OutputData::UnsignedInteger(u) => write!(f, "{u}"), 187 | OutputData::Float(fp) => write!(f, "{fp}"), 188 | OutputData::Double(d) => write!(f, "{d}"), 189 | OutputData::Byte(b) => write!(f, "0x{b:02x}"), 190 | OutputData::Array(arr) => write!(f, "[{arr:02x?}]"), 191 | OutputData::Object(idx) => write!(f, "Object({idx})"), 192 | OutputData::Null => write!(f, "Null"), 193 | } 194 | } 195 | } 196 | -------------------------------------------------------------------------------- /src/deserializer/number.rs: -------------------------------------------------------------------------------- 1 | //! Functions for reading numbers from a byte stream 2 | 3 | use crate::{ 4 | deserializer::{ 5 | constants::{DECIMAL, END, I_16, I_32, REFERENCE_TAG}, 6 | consumed::Consumed, 7 | read::{read_byte_at, read_exact_bytes}, 8 | }, 9 | error::Result, 10 | }; 11 | 12 | /// Read a signed integer from the stream (i8, i16, or i32) and return its value and bytes consumed. 13 | /// 14 | /// The format byte indicates size: 15 | /// - `0x81` (`I_16`) for `i16`, 16 | /// - `0x82` (`I_32`) for `i32`, 17 | /// - otherwise reads a single `i8` or skips reference tags. 18 | /// 19 | /// # Errors 20 | /// 21 | /// Returns [`TypedStreamError::OutOfBounds`](crate::error::TypedStreamError::OutOfBounds) if there are not enough bytes. 22 | /// 23 | /// # Examples 24 | /// ```no_run 25 | /// use crabstep::deserializer::number::read_signed_int; 26 | /// 27 | /// let data = [0x01]; 28 | /// let consumed = read_signed_int(&data).unwrap(); 29 | /// 30 | /// assert_eq!(consumed.value, 1); 31 | /// assert_eq!(consumed.bytes_consumed, 1); 32 | /// ``` 33 | pub fn read_signed_int(data: &[u8]) -> Result> { 34 | let current_byte = read_byte_at(data, 0)?; 35 | let (value, consumed) = match *current_byte { 36 | // The number is 2 bytes long 37 | I_16 => { 38 | let size = 2; 39 | let value = 40 | i16::from_le_bytes(<[u8; 2]>::try_from(read_exact_bytes(&data[1..], size)?)?); 41 | (i64::from(value), size + 1) 42 | } 43 | // The number is 4 bytes long 44 | I_32 => { 45 | let size = 4; 46 | let value = 47 | i32::from_le_bytes(<[u8; 4]>::try_from(read_exact_bytes(&data[1..], size)?)?); 48 | (i64::from(value), size + 1) 49 | } 50 | // The number is 1 byte long and is the current byte 51 | _ => { 52 | // If the current byte is greater than the REFERENCE_TAG, it indicates an index in the table of already-seen types. 53 | if current_byte > &(REFERENCE_TAG as u8) && *read_byte_at(data, 1)? != END { 54 | return read_signed_int(&data[1..]); 55 | } 56 | 57 | let value = i8::from_le_bytes([*current_byte]); 58 | (i64::from(value), 1) 59 | } 60 | }; 61 | 62 | Ok(Consumed::new(value, consumed)) 63 | } 64 | 65 | /// Read an unsigned integer from the stream (u8, u16, or u32) and return its value and bytes consumed. 66 | /// 67 | /// The format byte indicates size: 68 | /// - `0x81` (`I_16`) for `u16`, 69 | /// - `0x82` (`I_32`) for `u32`, 70 | /// - otherwise reads a single `u8` or skips reference tags. 71 | /// 72 | /// # Errors 73 | /// 74 | /// Returns [`TypedStreamError::OutOfBounds`](crate::error::TypedStreamError::OutOfBounds) if there are not enough bytes. 75 | /// 76 | /// # Examples 77 | /// ```no_run 78 | /// use crabstep::deserializer::number::read_unsigned_int; 79 | /// 80 | /// let data = [0xFF]; 81 | /// let consumed = read_unsigned_int(&data).unwrap(); 82 | /// 83 | /// assert_eq!(consumed.value, 255); 84 | /// assert_eq!(consumed.bytes_consumed, 1); 85 | /// ``` 86 | pub fn read_unsigned_int(data: &[u8]) -> Result> { 87 | let current_byte = read_byte_at(data, 0)?; 88 | let (value, consumed) = match *current_byte { 89 | // The number is 2 bytes long 90 | I_16 => { 91 | let size = 2; 92 | let value = 93 | u16::from_le_bytes(<[u8; 2]>::try_from(read_exact_bytes(&data[1..], size)?)?); 94 | (u64::from(value), size + 1) 95 | } 96 | // The number is 4 bytes long 97 | I_32 => { 98 | let size = 4; 99 | let value = 100 | u32::from_le_bytes(<[u8; 4]>::try_from(read_exact_bytes(&data[1..], size)?)?); 101 | (u64::from(value), size + 1) 102 | } 103 | // The number is 1 byte long 104 | _ => { 105 | // If the current byte is greater than the REFERENCE_TAG, it indicates an index in the table of already-seen types. 106 | if current_byte > &(REFERENCE_TAG as u8) && *read_byte_at(data, 1)? != END { 107 | return read_unsigned_int(&data[1..]); 108 | } 109 | 110 | let value = u8::from_le_bytes([*current_byte]); 111 | (u64::from(value), 1) 112 | } 113 | }; 114 | 115 | Ok(Consumed::new(value, consumed)) 116 | } 117 | 118 | /// Read a single-precision float (`f32`) from the byte stream. 119 | /// 120 | /// Prefixed by `DECIMAL` for a raw `f32`, or coerced from integer tags. 121 | /// 122 | /// # Errors 123 | /// 124 | /// Returns [`TypedStreamError::OutOfBounds`](crate::error::TypedStreamError::OutOfBounds) if the underlying byte slice is too short. 125 | /// 126 | /// # Examples 127 | /// ```no_run 128 | /// use crabstep::deserializer::number::read_float; 129 | /// 130 | /// let raw = [0x83, 0x00, 0x00, 0x80, 0x3F]; // DECIMAL tag + little-endian 1.0f32 131 | /// let consumed = read_float(&raw).unwrap(); 132 | /// 133 | /// assert_eq!(consumed.value, 1.0f32); 134 | /// ``` 135 | pub fn read_float(data: &[u8]) -> Result> { 136 | let current_byte = read_byte_at(data, 0)?; 137 | match *current_byte { 138 | DECIMAL => { 139 | let size = 4; 140 | let value = f32::from_le_bytes(<[u8; 4]>::try_from(read_exact_bytes(data, size)?)?); 141 | Ok(Consumed::new(value, size + 1)) 142 | } 143 | I_16 | I_32 => Ok(read_signed_int(data)?.map(|v| v as f32)), 144 | _ => Ok(read_signed_int(data)?.map(|v| v as f32)), 145 | } 146 | } 147 | 148 | /// Read a double-precision float (`f64`) from the byte stream. 149 | /// 150 | /// Prefixed by `DECIMAL` for a raw `f64`, or coerced from integer tags. 151 | /// 152 | /// # Errors 153 | /// 154 | /// Returns [`TypedStreamError::OutOfBounds`](crate::error::TypedStreamError::OutOfBounds) if the underlying byte slice is too short. 155 | /// 156 | /// # Examples 157 | /// ```no_run 158 | /// use crabstep::deserializer::number::read_double; 159 | /// 160 | /// let raw = [0x83, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x3F]; // DECIMAL + 1.0f64 161 | /// let consumed = read_double(&raw).unwrap(); 162 | /// 163 | /// assert_eq!(consumed.value, 1.0f64); 164 | /// ``` 165 | pub fn read_double(data: &[u8]) -> Result> { 166 | let current_byte = read_byte_at(data, 0)?; 167 | match *current_byte { 168 | DECIMAL => { 169 | let size = 8; 170 | let value = f64::from_le_bytes(<[u8; 8]>::try_from(read_exact_bytes(data, size)?)?); 171 | Ok(Consumed::new(value, size + 1)) 172 | } 173 | I_16 | I_32 => Ok(read_signed_int(data)?.map(|v| v as f64)), 174 | _ => Ok(read_signed_int(data)?.map(|v| v as f64)), 175 | } 176 | } 177 | 178 | #[cfg(test)] 179 | mod int_tests { 180 | use crate::deserializer::{ 181 | constants::{I_16, I_32}, 182 | number::{read_signed_int, read_unsigned_int}, 183 | }; 184 | 185 | #[test] 186 | fn can_read_signed_int_small() { 187 | let data = [0x01]; 188 | let result = read_signed_int(&data).unwrap(); 189 | 190 | assert_eq!(result.value, 1); 191 | assert_eq!(result.bytes_consumed, 1); 192 | } 193 | 194 | #[test] 195 | fn can_read_signed_int_16() { 196 | let data = [I_16, 0x01, 0x01]; 197 | let result = read_signed_int(&data).unwrap(); 198 | 199 | assert_eq!(result.value, 257); 200 | assert_eq!(result.bytes_consumed, 3); 201 | } 202 | 203 | #[test] 204 | fn can_read_signed_int_1000() { 205 | let data = [I_16, 0x01, 0x01]; 206 | let result = read_signed_int(&data).unwrap(); 207 | 208 | assert_eq!(result.value, 257); 209 | assert_eq!(result.bytes_consumed, 3); 210 | } 211 | 212 | #[test] 213 | fn can_read_signed_int_32() { 214 | let data = [I_32, 0x01, 0x01, 0x01, 0x01]; 215 | let result = read_signed_int(&data).unwrap(); 216 | 217 | assert_eq!(result.value, 16843009); 218 | assert_eq!(result.bytes_consumed, 5); 219 | } 220 | 221 | #[test] 222 | fn can_read_unsigned_int_small() { 223 | let data = [0x01]; 224 | let result = read_unsigned_int(&data).unwrap(); 225 | 226 | assert_eq!(result.value, 1); 227 | assert_eq!(result.bytes_consumed, 1); 228 | } 229 | 230 | #[test] 231 | fn can_read_unsigned_int_16() { 232 | let data = [I_16, 0x01, 0x01]; 233 | let result = read_unsigned_int(&data).unwrap(); 234 | 235 | assert_eq!(result.value, 257); 236 | assert_eq!(result.bytes_consumed, 3); 237 | } 238 | 239 | #[test] 240 | fn can_read_unsigned_int_32() { 241 | let data = [I_32, 0x01, 0x01, 0x01, 0x01]; 242 | let result = read_unsigned_int(&data).unwrap(); 243 | 244 | assert_eq!(result.value, 16843009); 245 | assert_eq!(result.bytes_consumed, 5); 246 | } 247 | 248 | #[test] 249 | fn cant_read_unsigned_int_16_too_short() { 250 | let data = [I_16, 0x01]; 251 | let result = read_unsigned_int(&data); 252 | 253 | assert!(result.is_err()); 254 | } 255 | 256 | #[test] 257 | fn cant_read_unsigned_int_32_too_short() { 258 | let data = [I_32, 0x01, 0x01, 0x01]; 259 | let result = read_unsigned_int(&data); 260 | 261 | assert!(result.is_err()); 262 | } 263 | } 264 | 265 | #[cfg(test)] 266 | mod float_tests { 267 | use crate::deserializer::{ 268 | constants::{I_16, I_32}, 269 | number::{read_double, read_float}, 270 | }; 271 | 272 | #[test] 273 | fn can_read_float_small() { 274 | let data = [0x01]; 275 | let result = read_float(&data).unwrap(); 276 | 277 | assert_eq!(result.value, 1.); 278 | assert_eq!(result.bytes_consumed, 1); 279 | } 280 | 281 | #[test] 282 | fn can_read_float_16() { 283 | let data = [I_16, 0x01, 0x01]; 284 | let result = read_float(&data).unwrap(); 285 | 286 | assert_eq!(result.value, 257.); 287 | assert_eq!(result.bytes_consumed, 3); 288 | } 289 | 290 | #[test] 291 | fn can_read_float_32() { 292 | let data = [I_32, 0x01, 0x01, 0x01, 0x01]; 293 | let result = read_float(&data).unwrap(); 294 | 295 | assert_eq!(result.value, 16843009.); 296 | assert_eq!(result.bytes_consumed, 5); 297 | } 298 | 299 | #[test] 300 | fn can_read_double_small() { 301 | let data = [0x01]; 302 | let result = read_double(&data).unwrap(); 303 | 304 | assert_eq!(result.value, 1.); 305 | assert_eq!(result.bytes_consumed, 1); 306 | } 307 | 308 | #[test] 309 | fn can_read_double_16() { 310 | let data = [I_16, 0x01, 0x01]; 311 | let result = read_double(&data).unwrap(); 312 | 313 | assert_eq!(result.value, 257.); 314 | assert_eq!(result.bytes_consumed, 3); 315 | } 316 | 317 | #[test] 318 | fn can_read_double_32() { 319 | let data = [I_32, 0x01, 0x01, 0x01, 0x01]; 320 | let result = read_double(&data).unwrap(); 321 | 322 | assert_eq!(result.value, 16843009.); 323 | assert_eq!(result.bytes_consumed, 5); 324 | } 325 | } 326 | -------------------------------------------------------------------------------- /src/deserializer/iter.rs: -------------------------------------------------------------------------------- 1 | //! Iterators for resolving properties in an [`Archived::Object`] 2 | 3 | use core::slice::Iter; 4 | 5 | use alloc::vec::Vec; 6 | 7 | use crate::models::{archived::Archived, class::Class, output_data::OutputData, types::Type}; 8 | 9 | /// A single resolved property from an [`Archived::Object`]. 10 | #[derive(Debug)] 11 | pub enum Property<'a, 'b> { 12 | /// An object with its class metadata, class name, and nested properties iterator. 13 | Object { 14 | /// The class of the object 15 | class: &'a Class, 16 | /// The name of the class, typically a string from the type table 17 | name: &'a str, 18 | /// An iterator over the properties of this object 19 | data: PropertyIterator<'a, 'b>, 20 | }, 21 | /// A group of properties (primitives or nested objects). 22 | Group(Vec>), 23 | /// A primitive value (string, number, byte, etc.). 24 | Primitive(&'b OutputData<'a>), 25 | } 26 | 27 | /// An iterator that resolves the top-level properties of a single [`Archived::Object`]. 28 | /// 29 | /// This iterator will yield `Property` items, which can be either nested objects or primitive values. 30 | /// It is created from an `Archived` object and its associated type table. 31 | /// 32 | /// It is designed to traverse the properties of an object, allowing you to access nested objects and their properties recursively. 33 | /// 34 | /// # Example 35 | /// 36 | /// ```no_run 37 | /// use crabstep::deserializer::typedstream::TypedStreamDeserializer; 38 | /// use crabstep::deserializer::iter::PropertyIterator; 39 | /// 40 | /// // Create a new `TypedStreamDeserializer` and oxidize the data to get the root index. 41 | /// let data: &[u8] = &[]; 42 | /// let mut deserializer = TypedStreamDeserializer::new(data); 43 | /// let root_idx = deserializer.oxidize().unwrap(); 44 | /// 45 | /// // This creates a `PropertyIterator` over the root object. 46 | /// let root_object = deserializer.resolve_properties(root_idx).unwrap(); 47 | /// 48 | /// // Create a property iterator for the root object. 49 | /// root_object.into_iter().for_each(|property| { 50 | /// println!("{:?}", property); 51 | /// }); 52 | /// ``` 53 | #[derive(Debug, Clone)] 54 | pub struct PropertyIterator<'a, 'b> { 55 | object_table: &'b [Archived<'a>], 56 | type_table: &'b [Vec>], 57 | property_groups: Iter<'b, Vec>>, 58 | } 59 | 60 | impl<'a, 'b> PropertyIterator<'a, 'b> { 61 | pub(crate) fn new( 62 | object_table: &'b [Archived<'a>], 63 | type_table: &'b [Vec>], 64 | root_object_index: usize, 65 | ) -> Option { 66 | let root_object = object_table.get(root_object_index)?; 67 | 68 | let Archived::Object { 69 | data: properties, .. 70 | } = root_object 71 | else { 72 | return None; 73 | }; 74 | 75 | Some(Self { 76 | object_table, 77 | type_table, 78 | property_groups: properties.iter(), 79 | }) 80 | } 81 | } 82 | 83 | impl<'a, 'b: 'a> PropertyIterator<'a, 'b> { 84 | /// Collects only primitive data values from a `typedstream` using a depth-first-search over the deserialized object graph. 85 | /// 86 | /// Note: There is a max depth of 100 and a max item limit of 1,000,000. 87 | /// 88 | /// # Examples 89 | /// 90 | /// ```no_run 91 | /// use crabstep::deserializer::typedstream::TypedStreamDeserializer; 92 | /// 93 | /// // Create a new `TypedStreamDeserializer` and oxidize the data to get the root index. 94 | /// let data: &[u8] = &[]; 95 | /// let mut deserializer = TypedStreamDeserializer::new(data); 96 | /// let root_idx = deserializer.oxidize().unwrap(); 97 | /// 98 | /// // This creates a `PropertyIterator` over the root object. 99 | /// let root_obj = deserializer.resolve_properties(root_idx).unwrap(); 100 | /// 101 | /// // Emit the primitive values from the root object. 102 | /// let primitives = root_obj.primitives(); 103 | /// primitives.into_iter().for_each(|primitive| { 104 | /// println!("{primitive}"); 105 | /// }); 106 | /// ``` 107 | #[must_use] 108 | pub fn primitives(self) -> Vec<&'b OutputData<'a>> { 109 | self.primitives_with_limits(100, 1_000_000) 110 | } 111 | 112 | /// Collects primitive data values with safety limits to prevent infinite loops. 113 | /// 114 | /// # Arguments 115 | /// 116 | /// * `max_depth` - Maximum depth to traverse (prevents infinite recursion on cycles) 117 | /// * `max_items` - Maximum total items to process (prevents runaway expansion) 118 | #[must_use] 119 | pub fn primitives_with_limits( 120 | self, 121 | max_depth: usize, 122 | max_items: usize, 123 | ) -> Vec<&'b OutputData<'a>> { 124 | let mut primitives = Vec::new(); 125 | let mut processed_items = 0; 126 | 127 | // Use an explicit stack for depth-first traversal with depth tracking 128 | let initial_props: Vec> = self.collect(); 129 | let mut stack: Vec<(Property<'a, 'b>, usize)> = 130 | initial_props.into_iter().map(|p| (p, 0)).collect(); 131 | 132 | while let Some((prop, depth)) = stack.pop() { 133 | // Safety checks to prevent infinite expansion 134 | if processed_items >= max_items { 135 | break; 136 | } 137 | if depth >= max_depth { 138 | continue; 139 | } 140 | 141 | processed_items += 1; 142 | 143 | match prop { 144 | Property::Primitive(p) => primitives.push(p), 145 | Property::Group(mut group) => { 146 | // push children in reverse to preserve order 147 | while let Some(child) = group.pop() { 148 | stack.push((child, depth + 1)); 149 | } 150 | } 151 | Property::Object { data, .. } => { 152 | // data is a PropertyIterator; collect its items 153 | let mut nested: Vec<_> = data.collect(); 154 | while let Some(child) = nested.pop() { 155 | stack.push((child, depth + 1)); 156 | } 157 | } 158 | } 159 | } 160 | primitives.reverse(); 161 | primitives 162 | } 163 | } 164 | 165 | impl<'a, 'b: 'a> Iterator for PropertyIterator<'a, 'b> { 166 | type Item = Property<'a, 'b>; 167 | 168 | fn next(&mut self) -> Option { 169 | let groups = self.property_groups.next()?; 170 | 171 | let mut resolved = Vec::with_capacity(groups.len()); 172 | 173 | for group in groups { 174 | match group { 175 | OutputData::Object(idx) => { 176 | if let Some(Archived::Object { 177 | class: cls, 178 | data: _, 179 | }) = self.object_table.get(*idx) 180 | && let Some(Archived::Class(cls)) = self.object_table.get(*cls) 181 | { 182 | let class_name = self 183 | .type_table 184 | .get(cls.name_index) 185 | .and_then(|types| types.first()) 186 | .and_then(|t| match t { 187 | Type::String(name) => Some(*name), 188 | _ => None, 189 | }) 190 | .unwrap_or("Unknown Class"); 191 | // recurse into that object’s own data 192 | let sub_iter = 193 | PropertyIterator::new(self.object_table, self.type_table, *idx)?; 194 | resolved.push(Property::Object { 195 | class: cls, 196 | name: class_name, 197 | data: sub_iter, 198 | }); 199 | } 200 | } 201 | prim => resolved.push(Property::Primitive(prim)), 202 | } 203 | } 204 | Some(Property::Group(resolved)) 205 | } 206 | } 207 | 208 | /// Print a resolved [`PropertyIterator`] in a human-readable tree format for debugging. 209 | /// 210 | /// This function iteratively prints all properties with proper indentation to show the nested structure 211 | /// of the deserialized object graph. Uses an explicit stack to avoid stack overflow for large structures. 212 | /// 213 | /// Note: There is a max depth of 100 and a max item limit of 1,000,000. 214 | /// 215 | /// # Arguments 216 | /// 217 | /// * `iter` - The property iterator to print 218 | /// * `indent` - Number of spaces to indent each level (typically `2` or `4`) 219 | /// 220 | /// # Examples 221 | /// ```no_run 222 | /// use crabstep::deserializer::iter::print_resolved; 223 | /// use crabstep::deserializer::typedstream::TypedStreamDeserializer; 224 | /// 225 | /// let mut ds = TypedStreamDeserializer::new(&[]); 226 | /// let root = ds.oxidize().unwrap(); 227 | /// 228 | /// if let Ok(iter) = ds.resolve_properties(root) { 229 | /// print_resolved(iter, 2); 230 | /// } 231 | /// ``` 232 | /// 233 | /// This function is intended for debugging purposes. Example output appears as follows: 234 | /// 235 | /// ```txt 236 | /// Group: 237 | /// Object: "NSMutableString" 238 | /// Group: 239 | /// Primitive: String("Noter test") 240 | /// Group: 241 | /// Primitive: SignedInteger(1) 242 | /// Primitive: UnsignedInteger(10) 243 | /// Group: 244 | /// Object: "NSDictionary" 245 | /// Group: 246 | /// Primitive: SignedInteger(1) 247 | /// Group: 248 | /// Object: "NSString" 249 | /// Group: 250 | /// Primitive: String("__kIMMessagePartAttributeName") 251 | /// Group: 252 | /// Object: "NSNumber" 253 | /// Group: 254 | /// Primitive: SignedInteger(0) 255 | /// ``` 256 | #[cfg(any(feature = "std", test))] 257 | pub fn print_resolved(iter: PropertyIterator<'_, '_>, indent: usize) { 258 | print_resolved_with_limits(iter, indent, 100, 1_000_000); 259 | } 260 | 261 | /// Print a resolved [`PropertyIterator`] with depth and item limits to prevent infinite expansion. 262 | /// 263 | /// # Arguments 264 | /// 265 | /// * `iter` - The property iterator to print 266 | /// * `indent` - Number of spaces to indent each level 267 | /// * `max_depth` - Maximum depth to traverse (prevents infinite recursion on cycles) 268 | /// * `max_items` - Maximum total items to print (prevents runaway output) 269 | #[cfg(any(feature = "std", test))] 270 | fn print_resolved_with_limits( 271 | iter: PropertyIterator<'_, '_>, 272 | indent: usize, 273 | max_depth: usize, 274 | max_items: usize, 275 | ) { 276 | extern crate std; 277 | use std::println; 278 | // Use an explicit stack to avoid recursion and potential stack overflow 279 | let mut stack: Vec<(Property<'_, '_>, usize)> = Vec::new(); 280 | let mut items_printed = 0; 281 | 282 | // Push all properties from the iterator onto the stack with their indent level 283 | for prop in iter { 284 | stack.push((prop, indent)); 285 | } 286 | 287 | // Process the stack 288 | while let Some((prop, current_indent)) = stack.pop() { 289 | // Safety checks to prevent infinite expansion 290 | if items_printed >= max_items { 291 | println!( 292 | "{:indent$}... (truncated after {max_items} items)", 293 | "", 294 | indent = current_indent 295 | ); 296 | break; 297 | } 298 | 299 | let depth = (current_indent - indent) / 2; 300 | if depth >= max_depth { 301 | println!( 302 | "{:indent$}... (max depth {max_depth} reached)", 303 | "", 304 | indent = current_indent 305 | ); 306 | continue; 307 | } 308 | 309 | items_printed += 1; 310 | 311 | match prop { 312 | Property::Object { 313 | class: _, 314 | name, 315 | data, 316 | } => { 317 | // Print the object itself 318 | println!("{:indent$}Object: {:?}", "", name, indent = current_indent); 319 | // Push its children onto the stack with increased indent (in reverse order) 320 | let children: Vec<_> = data.collect(); 321 | for child in children.into_iter().rev() { 322 | stack.push((child, current_indent + 2)); 323 | } 324 | } 325 | Property::Group(group) => { 326 | println!("{:indent$}Group:", "", indent = current_indent); 327 | // Push every slot in the group onto the stack with increased indent (in reverse order) 328 | for slot in group.into_iter().rev() { 329 | stack.push((slot, current_indent + 2)); 330 | } 331 | } 332 | Property::Primitive(p) => { 333 | println!("{:indent$}Primitive: {:?}", "", p, indent = current_indent); 334 | } 335 | } 336 | } 337 | } 338 | -------------------------------------------------------------------------------- /src/deserializer/typedstream.rs: -------------------------------------------------------------------------------- 1 | /*! 2 | Logic used to deserialize data from a `typedstream`. 3 | 4 | A writeup about the reverse engineering of `typedstream` can be found [here](https://chrissardegna.com/blog/reverse-engineering-apples-typedstream-format/). 5 | */ 6 | 7 | use alloc::{vec, vec::Vec}; 8 | 9 | use crate::{ 10 | deserializer::{ 11 | constants::{EMPTY, END, START}, 12 | header::validate_header, 13 | iter::PropertyIterator, 14 | number::{read_double, read_float, read_signed_int, read_unsigned_int}, 15 | read::{read_byte_at, read_exact_bytes, read_pointer}, 16 | string::read_string, 17 | }, 18 | error::{Result, TypedStreamError}, 19 | models::{archived::Archived, class::Class, output_data::OutputData, types::Type}, 20 | }; 21 | 22 | /// Contains logic and data used to deserialize data from a `typedstream`. 23 | /// 24 | /// `typedstream` is a binary serialization format developed by `NeXTSTEP` and later adopted by Apple. 25 | /// It's designed to serialize and deserialize complex object graphs and data structures in C and Objective-C. 26 | /// 27 | /// A `typedstream` begins with a header that includes format version and architecture information, 28 | /// followed by a stream of typed data elements. Each element is prefixed with type information, 29 | /// allowing the [`TypedStreamDeserializer`] to understand the original data structures. 30 | pub struct TypedStreamDeserializer<'a> { 31 | /// The `typedstream` we want to parse 32 | pub data: &'a [u8], 33 | /// The current index we are at in the stream 34 | pub(crate) position: usize, 35 | /// As we parse the `typedstream`, build a table of seen [`Type`]s to reference in the future 36 | /// 37 | /// The first time a [`Type`] is seen, it is present in the stream literally, 38 | /// but afterwards are only referenced by index in order of appearance. 39 | pub type_table: Vec>>, 40 | /// As we parse the `typedstream`, build a table of seen [`Archived`] data to reference in the future 41 | pub object_table: Vec>, 42 | /// We want to copy embedded types the first time they are seen, even if the types were resolved through references 43 | pub(crate) seen_embedded_types: Vec, 44 | } 45 | 46 | impl<'a> TypedStreamDeserializer<'a> { 47 | /// Create a new `TypedStreamDeserializer` for the provided byte slice. 48 | /// 49 | /// # Examples 50 | /// 51 | /// ```no_run 52 | /// use crabstep::deserializer::typedstream::TypedStreamDeserializer; 53 | /// 54 | /// let data: &[u8] = &[]; 55 | /// let deserializer = TypedStreamDeserializer::new(data); 56 | /// ``` 57 | #[must_use] 58 | pub fn new(data: &'a [u8]) -> Self { 59 | // Estimate initial capacities based on data size to reduce reallocations 60 | let estimated_size = data.len(); 61 | let type_capacity = (estimated_size / 64).clamp(16, 256); 62 | let object_capacity = (estimated_size / 32).clamp(32, 512); 63 | let embedded_capacity = (estimated_size / 128).clamp(8, 64); 64 | 65 | Self { 66 | data, 67 | position: 0, 68 | type_table: Vec::with_capacity(type_capacity), 69 | object_table: Vec::with_capacity(object_capacity), 70 | seen_embedded_types: Vec::with_capacity(embedded_capacity), 71 | } 72 | } 73 | 74 | /// Creates an iterator that resolves the properties of the root object in the `typedstream`. 75 | /// 76 | /// # Examples 77 | /// 78 | /// ```no_run 79 | /// use crabstep::deserializer::typedstream::TypedStreamDeserializer; 80 | /// 81 | /// let data: &[u8] = &[]; 82 | /// let mut deserializer = TypedStreamDeserializer::new(data); 83 | /// 84 | /// // Walk the object root, printing each primitive value 85 | /// deserializer.iter_root().into_iter().for_each(|prop| { 86 | /// prop.primitives().into_iter().for_each(|data| println!("{data}")); 87 | /// }); 88 | /// ``` 89 | pub fn iter_root(&mut self) -> Result> { 90 | let root = self.oxidize()?; 91 | self.resolve_properties(root) 92 | } 93 | 94 | /// Parse the `typedstream`, consuming header and objects, returning the index of the top-level archived object. 95 | /// 96 | /// # Errors 97 | /// 98 | /// Returns a [`TypedStreamError`] if parsing fails or the stream ends unexpectedly. 99 | /// 100 | /// # Examples 101 | /// 102 | /// ```no_run 103 | /// use crabstep::TypedStreamDeserializer; 104 | /// 105 | /// let mut deserializer = TypedStreamDeserializer::new(&[]); 106 | /// let result = deserializer.oxidize(); 107 | /// ``` 108 | pub fn oxidize(&mut self) -> Result { 109 | let mut obj = None; 110 | let validation = validate_header(self.data)?; 111 | 112 | // Advance by the number of bytes consumed by the header validation 113 | self.position += validation.bytes_consumed; 114 | 115 | // while self.position <= self.data.len() { 116 | let found_type = self.read_type(false)?; 117 | 118 | if let Some(type_index) = found_type { 119 | // Read the types at the specified index 120 | obj = self.read_types(type_index)?; 121 | } 122 | 123 | match obj 124 | .ok_or(TypedStreamError::InvalidObject)? 125 | .first() 126 | .ok_or(TypedStreamError::InvalidObject)? 127 | { 128 | OutputData::Object(idx) => Ok(*idx), 129 | _ => Err(TypedStreamError::InvalidObject), 130 | } 131 | } 132 | 133 | /// Creates an iterator that resolves the properties of an object 134 | /// at the specified index in the `object_table`, preserving nested structure. 135 | /// 136 | /// This should be called after [`oxidize()`](Self::oxidize). 137 | /// 138 | /// # Arguments 139 | /// 140 | /// * `root_object_index` - Index of the object in the deserializer's `object_table` to iterate. 141 | /// 142 | /// # Errors 143 | /// 144 | /// Returns [`TypedStreamError::InvalidPointer`] if the index is not a valid object reference. 145 | /// 146 | /// # Examples 147 | /// 148 | /// ```no_run 149 | /// use crabstep::TypedStreamDeserializer; 150 | /// 151 | /// let mut ts = TypedStreamDeserializer::new(&[]); 152 | /// let root = ts.oxidize().unwrap(); 153 | /// 154 | /// let iter = ts.resolve_properties(root).unwrap(); 155 | /// ``` 156 | pub fn resolve_properties(&self, root_object_index: usize) -> Result> { 157 | PropertyIterator::new(&self.object_table, &self.type_table, root_object_index) 158 | .ok_or(TypedStreamError::InvalidPointer(root_object_index as u8)) 159 | } 160 | 161 | /// Reads the next byte from the stream, advancing the position. 162 | #[inline(always)] 163 | fn consume_current_byte(&mut self) -> Result<&u8> { 164 | let byte = read_byte_at(self.data, self.position)?; 165 | self.position += 1; 166 | Ok(byte) 167 | } 168 | 169 | /// Reads an unsigned integer from the stream, advancing the position. 170 | #[inline(always)] 171 | fn read_unsigned_int(&mut self) -> Result { 172 | let unsigned_int = read_unsigned_int(&self.data[self.position..])?; 173 | self.position += unsigned_int.bytes_consumed; 174 | Ok(unsigned_int.value) 175 | } 176 | 177 | /// [`Archivable`] data can be embedded on a class or in a C String marked as [`Type::EmbeddedData`] 178 | fn read_embedded_type(&mut self) -> Result> { 179 | match *self.consume_current_byte()? { 180 | START => { 181 | // 0x84 indicates the start of embedded data 182 | self.read_type(true) 183 | } 184 | EMPTY => Ok(None), 185 | ptr => { 186 | let pointer = read_pointer(&ptr)?.map(|v| v as usize); 187 | if let Some(Archived::Type(idx)) = self.object_table.get(pointer.value) { 188 | Ok(Some(*idx)) 189 | } else { 190 | Err(TypedStreamError::InvalidPointer(pointer.value as u8)) 191 | } 192 | } 193 | } 194 | } 195 | 196 | fn read_string(&mut self) -> Result { 197 | let current_byte = *self.consume_current_byte()?; 198 | match current_byte { 199 | START => { 200 | let string_data = read_string(&self.data[self.position..])?; 201 | self.position += string_data.bytes_consumed; 202 | self.type_table 203 | .push(vec![Type::new_string(string_data.value)]); 204 | Ok(self.type_table.len() - 1) 205 | } 206 | EMPTY => Err(TypedStreamError::EmptyString), 207 | ptr => { 208 | let pointer = read_pointer(&ptr)?.map(|v| v as usize); 209 | if let Some(Type::String(_)) = self 210 | .type_table 211 | .get(pointer.value) 212 | .and_then(|inner| inner.first()) 213 | { 214 | Ok(pointer.value) 215 | } else { 216 | Err(TypedStreamError::InvalidPointer(pointer.value as u8)) 217 | } 218 | } 219 | } 220 | } 221 | 222 | fn read_class(&mut self) -> Result> { 223 | // Index of the first START we encounter (the bottom-most child) 224 | let mut first_new: Option = None; 225 | // Index of the most recently pushed class (current “child”) 226 | let mut prev_new: Option = None; 227 | // Parent for the outer-most new class (set by EMPTY or a pointer) 228 | let final_parent: Option; 229 | 230 | loop { 231 | match *self.consume_current_byte()? { 232 | START => { 233 | let name_idx = self.read_string()?; 234 | let version = self.read_unsigned_int()?; 235 | 236 | // Append the new class with no parent yet 237 | let idx = self.object_table.len(); 238 | self.object_table 239 | .push(Archived::Class(Class::new(name_idx, version, None))); 240 | 241 | // The class we just appended (*idx*) is the **parent** of the 242 | // class we appended in the previous iteration (*prev_new*) 243 | if let Some(child_idx) = prev_new 244 | && let Archived::Class(ref mut child_cls) = self.object_table[child_idx] 245 | { 246 | child_cls.parent_index = Some(idx); 247 | } 248 | 249 | // remember the first class we ever pushed 250 | first_new.get_or_insert(idx); 251 | // and mark the current class as “last pushed” 252 | prev_new = Some(idx); 253 | } 254 | EMPTY => { 255 | final_parent = None; 256 | break; 257 | } 258 | ptr => { 259 | let pointer = read_pointer(&ptr)?; 260 | 261 | final_parent = Some(pointer.value as usize); 262 | break; 263 | } 264 | } 265 | } 266 | 267 | // If we did not create any new classes, just return what we found. 268 | let Some(first_idx) = first_new else { 269 | return Ok(final_parent); 270 | }; 271 | 272 | // Patch the outer-most newly created class so that it points to the 273 | // already-existing parent (or to `None` if EMPTY terminated the list). 274 | if let Some(outer_idx) = prev_new 275 | && let Archived::Class(ref mut outer_cls) = self.object_table[outer_idx] 276 | { 277 | outer_cls.parent_index = final_parent; 278 | } 279 | 280 | // Return the index of the bottom-most child we created first. 281 | Ok(Some(first_idx)) 282 | } 283 | 284 | fn read_object(&mut self) -> Result> { 285 | match *read_byte_at(self.data, self.position)? { 286 | START => { 287 | let placeholder_index = self.object_table.len(); 288 | // This placeholder will be replaced with the actual object data once we read the class 289 | self.object_table.push(Archived::Placeholder); 290 | // Advance the position to the next byte, which should be the start of a class 291 | self.position += 1; 292 | 293 | if let Some(cls) = self.read_class()? { 294 | // Estimate initial capacity for object data to reduce reallocations 295 | let estimated_data_capacity = 296 | ((self.data.len() - self.position) / 64).clamp(8, 64); 297 | self.object_table[placeholder_index] = Archived::Object { 298 | class: cls, 299 | data: Vec::with_capacity(estimated_data_capacity), 300 | }; 301 | while self.position < self.data.len() 302 | && *read_byte_at(self.data, self.position)? != END 303 | { 304 | // Read the next type, which should be an object 305 | if let Some(next_index) = self.read_type(false)? { 306 | // Recursively read the types for this object 307 | if let Some(data) = self.read_types(next_index)? 308 | && let Some(Archived::Object { 309 | class: _, 310 | data: data_vec, 311 | }) = self.object_table.get_mut(placeholder_index) 312 | { 313 | // Add the data to the object 314 | data_vec.push(data); 315 | } 316 | } 317 | } 318 | } 319 | Ok(Some(placeholder_index)) 320 | } 321 | EMPTY => { 322 | self.position += 1; 323 | Ok(None) 324 | } 325 | ptr => { 326 | let pointer = read_pointer(&ptr)?; 327 | Ok(Some(pointer.value as usize)) 328 | } 329 | } 330 | } 331 | 332 | /// Reads numeric types (signed, unsigned, float, double) and returns the corresponding `OutputData` 333 | fn read_number(&mut self, table_index: usize, type_index: usize) -> Result> { 334 | match self.type_table[table_index][type_index] { 335 | Type::SignedInt => { 336 | let signed_int = read_signed_int(&self.data[self.position..])?; 337 | self.position += signed_int.bytes_consumed; 338 | Ok(OutputData::SignedInteger(signed_int.value as i64)) 339 | } 340 | Type::UnsignedInt => { 341 | let unsigned_int = read_unsigned_int(&self.data[self.position..])?; 342 | self.position += unsigned_int.bytes_consumed; 343 | Ok(OutputData::UnsignedInteger(unsigned_int.value)) 344 | } 345 | Type::Float => { 346 | let float = read_float(&self.data[self.position..])?; 347 | self.position += float.bytes_consumed; 348 | Ok(OutputData::Float(float.value as f32)) 349 | } 350 | Type::Double => { 351 | let double = read_double(&self.data[self.position..])?; 352 | self.position += double.bytes_consumed; 353 | Ok(OutputData::Double(double.value as f64)) 354 | } 355 | _ => unreachable!(), 356 | } 357 | } 358 | 359 | fn read_types(&mut self, types_index: usize) -> Result>>> { 360 | // Start reading types from the specified index in the type table 361 | 362 | let len = self.type_table[types_index].len(); 363 | let mut out_v = Vec::with_capacity(len); 364 | 365 | for i in 0..len { 366 | // Read the next type from the type table 367 | match self.type_table[types_index][i] { 368 | Type::Utf8String => { 369 | let str_data = read_string(&self.data[self.position..])?; 370 | self.position += str_data.bytes_consumed; 371 | out_v.push(OutputData::String(str_data.value)); 372 | } 373 | Type::EmbeddedData => { 374 | if let Some(idx) = self.read_embedded_type()? { 375 | self.position += 1; 376 | return self.read_types(idx); 377 | } 378 | return Ok(None); 379 | } 380 | Type::Object => { 381 | let obj_idx = self.read_object()?; 382 | self.position += 1; 383 | if let Some(obj_idx) = obj_idx { 384 | out_v.push(OutputData::Object(obj_idx)); 385 | } else { 386 | out_v.push(OutputData::Null); 387 | } 388 | } 389 | Type::String(s) => { 390 | out_v.push(OutputData::String(s)); 391 | } 392 | Type::Array(length) => { 393 | let array_data = read_exact_bytes(&self.data[self.position..], length)?; 394 | self.position += length; 395 | out_v.push(OutputData::Array(array_data)); 396 | } 397 | Type::Unknown(byte) => { 398 | // Read a single byte for unknown data 399 | out_v.push(OutputData::Byte(byte)); 400 | } 401 | // Handle all numeric types 402 | Type::SignedInt | Type::UnsignedInt | Type::Float | Type::Double => { 403 | let val = self.read_number(types_index, i)?; 404 | out_v.push(val); 405 | } 406 | } 407 | } 408 | 409 | Ok(Some(out_v)) 410 | } 411 | 412 | /// Gets the current type from the stream, either by reading it from the stream or reading it from 413 | /// the specified index of [`Self::type_table`]. Returns an index into the types table 414 | /// to avoid cloning large type vectors. 415 | fn read_type(&mut self, is_embedded_type: bool) -> Result> { 416 | let byte = *self.consume_current_byte()?; 417 | 418 | match byte { 419 | START => { 420 | // Get the type of the object 421 | let new_types = Type::read_new_type(&self.data[self.position..])?; 422 | let new_type_index = self.type_table.len(); 423 | // Embedded data is stored as a Type in the objects table 424 | if is_embedded_type { 425 | self.object_table.push(Archived::Type(new_type_index)); 426 | // We only want to include the first embedded reference tag, not subsequent references to the same embed 427 | self.seen_embedded_types 428 | .push(self.object_table.len().saturating_sub(1)); 429 | } 430 | 431 | self.type_table.push(new_types.value); 432 | self.position += new_types.bytes_consumed; 433 | Ok(Some(self.type_table.len() - 1)) 434 | } 435 | END | EMPTY => Ok(None), 436 | ptr => { 437 | let pointer = read_pointer(&ptr)?; 438 | let ref_tag = pointer.value as usize; 439 | 440 | // Optimize bounds checking 441 | if ref_tag >= self.type_table.len() { 442 | return Ok(None); 443 | } 444 | 445 | if is_embedded_type { 446 | // We only want to include the first embedded reference tag, not subsequent references to the same embed 447 | if !self.seen_embedded_types.contains(&ref_tag) { 448 | self.object_table.push(Archived::Type(ref_tag)); 449 | self.seen_embedded_types.push(ref_tag); 450 | } 451 | } 452 | 453 | Ok(Some(ref_tag)) 454 | } 455 | } 456 | } 457 | } 458 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and`show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------