ctr_cart 0.3.0

3DS file header library and utilities.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
// SPDX-License-Identifier: LGPL-2.1-or-later OR GPL-2.0-or-later OR MPL-2.0
// SPDX-FileCopyrightText: 2024 Gabriel Marcano <gabemarcano@yahoo.com>

use crate::error::Error;
use crate::ncch::NCCH;
use crate::ncch::NCCHRead;

use std::fmt;
use std::fmt::Display;
use std::io::Read;
use std::io::Seek;
use std::io::SeekFrom;

use byteorder::ByteOrder;
use byteorder::LittleEndian;
use byteorder::ReadBytesExt;

/// Represents the type of encryption on the NCCH partition.
#[derive(Debug)]
pub enum NCCHPartitionCryptoType {
    /// No encryption used.
    None,
    /// Nintendo DS encryption.
    Twl,
    /// Nintendo 3DS encryption.
    Ctr,
    /// Nintendo 3DS dev encryption.
    Snake,
}

impl TryFrom<u8> for NCCHPartitionCryptoType {
    type Error = Error;

    fn try_from(data: u8) -> Result<Self, Error> {
        match data {
            0 => Ok(Self::None),
            1 => Ok(Self::Twl),
            2 => Ok(Self::Ctr),
            3 => Ok(Self::Snake),
            _ => Err(Error::Parse(
                "unable to parse NCCH partition crypt type".into(),
            )),
        }
    }
}

impl Display for NCCHPartitionCryptoType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::None => write!(f, "none"),
            Self::Twl => write!(f, "TWL"),
            Self::Ctr => write!(f, "CTR"),
            Self::Snake => write!(f, "SNAKE"),
        }
    }
}

/// The type of encryption used for the savegame partition.
#[derive(Debug)]
pub enum SavegameKeyYMethod {
    HashedKeyY,
    NewKeyY1,
    NewKeyY2,
}

impl TryFrom<u8> for SavegameKeyYMethod {
    type Error = Error;
    fn try_from(data: u8) -> Result<Self, Error> {
        match data {
            0 => Ok(Self::HashedKeyY),
            1 => Ok(Self::NewKeyY1),
            0x0A => Ok(Self::NewKeyY2),
            _ => Err(Error::Parse("failed to parse savegame key Y method".into())),
        }
    }
}

/// Crypto flags for an NCCH partittion.
#[derive(Debug)]
pub struct NCCHPartitionCryptoFlags {
    pub savegame_keyy_method: SavegameKeyYMethod,
    pub use_keyy_hash: bool,
    pub use_keyy_hash_method: bool,
}

impl TryFrom<[u8; 8]> for NCCHPartitionCryptoFlags {
    type Error = Error;

    fn try_from(data: [u8; 8]) -> Result<Self, Error> {
        Ok(Self {
            savegame_keyy_method: data[1].try_into()?,
            use_keyy_hash: data[3] != 0,
            use_keyy_hash_method: data[7] != 0,
        })
    }
}

/// Describes the flags associated with an NCCH partition.
#[derive(Debug)]
pub struct NCCHPartitionFlags {
    /// The number of seconds to wait to write save to backup after the card is recognized.
    pub backup_write_wait_time: u8,
    /// The type of save media used by the cartridge (?).
    pub media_card_device: MediaCardDevice,
    /// The platform the cartridge runs on.
    pub media_platform: MediaPlatform,
    /// The type of cartridge used.
    pub media_type: MediaType,
    /// The media unit size in bytes.
    pub media_unit_size: u32,
}

/// Represents the platform the media requires.
#[derive(Debug)]
pub enum MediaPlatform {
    /// Retail 3DS consoles.
    Ctr,
    /// Development 3DS consoles.
    Snake,
}

impl Display for MediaPlatform {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Ctr => write!(f, "Nintendo 3DS"),
            Self::Snake => write!(f, "development Nintendo 3DS"),
        }
    }
}

impl TryFrom<u8> for MediaPlatform {
    type Error = Error;

    fn try_from(data: u8) -> Result<Self, Error> {
        match data {
            1 => Ok(Self::Ctr),
            _ => Err(Error::Parse("could not parse media platform".into())),
        }
    }
}

/// Describes the filesystem of the NCCH partition.
#[derive(Debug)]
pub enum NCCHPartitionFilesystemType {
    None,
    Normal,
    Firm,
    AgbFirmSave,
}

impl Display for NCCHPartitionFilesystemType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::None => write!(f, "none"),
            Self::Normal => write!(f, "normal"),
            Self::Firm => write!(f, "FIRM"),
            Self::AgbFirmSave => write!(f, "AGB_FIRM save"),
        }
    }
}

impl TryFrom<u8> for NCCHPartitionFilesystemType {
    type Error = Error;

    fn try_from(data: u8) -> Result<Self, Error> {
        match data {
            0 => Ok(Self::None),
            1 => Ok(Self::Normal),
            3 => Ok(Self::Firm),
            4 => Ok(Self::AgbFirmSave),
            _ => Err(Error::Parse(
                "could not parse the NCCH FS partition type".into(),
            )),
        }
    }
}

/// Represents all the NCSD metadata associated with a single NCCH partition.
#[derive(Debug)]
pub struct NCCHPartitionHeader {
    /// The index of the partition in the [`NCSD`] partition table.
    pub index: usize,
    /// The offset of the partition in the [`NCSD`] container in bytes from the beginning of the
    /// [`NCSD`] container..
    pub offset: u32,
    /// The size of the partition in bytes.
    pub size: u32,
    /// The title ID of the partition.
    pub title_id: u64,
    pub crypt_type: NCCHPartitionCryptoType,
    /// The type of the NCCH partition.
    pub filesystem_type: NCCHPartitionFilesystemType,
}

/// The type of media (for saves?) in the cartridge
#[derive(Debug)]
pub enum MediaCardDevice {
    /// Some games appear to have this set to zero? It's not documented anywhere.
    Null,
    NORFlash,
    None,
    BT,
}

/// Represents the type of cartridge used.
#[derive(Debug)]
pub enum MediaType {
    InnerDevice,
    /// Apparently a cart type that uses an external media for save storage.
    Card1,
    /// Apparently a cart type that allows saves to be saved to the same device as the ROM.
    Card2,
    ExtendedDevice,
}

impl Display for MediaType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::InnerDevice => write!(f, "inner device"),
            Self::Card1 => write!(f, "card1"),
            Self::Card2 => write!(f, "card2"),
            Self::ExtendedDevice => write!(f, "extended device"),
        }
    }
}

impl TryFrom<u8> for MediaType {
    type Error = Error;

    fn try_from(data: u8) -> Result<Self, Error> {
        match data {
            0 => Ok(Self::InnerDevice),
            1 => Ok(Self::Card1),
            2 => Ok(Self::Card2),
            3 => Ok(Self::ExtendedDevice),
            _ => Err(Error::Parse("could not parse media type".into())),
        }
    }
}

impl Display for MediaCardDevice {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Null => write!(f, "null"),
            Self::NORFlash => write!(f, "NOR flash"),
            Self::None => write!(f, "none"),
            Self::BT => write!(f, "BT"),
        }
    }
}

impl TryFrom<u8> for MediaCardDevice {
    type Error = Error;
    fn try_from(data: u8) -> Result<Self, Error> {
        match data {
            0 => Ok(Self::Null),
            1 => Ok(Self::NORFlash),
            2 => Ok(Self::None),
            3 => Ok(Self::BT),
            _ => Err(Self::Error::Parse(
                "could not parse media card device".into(),
            )),
        }
    }
}

impl TryFrom<[u8; 8]> for NCCHPartitionFlags {
    type Error = Error;
    fn try_from(data: [u8; 8]) -> Result<Self, Error> {
        let media_card_device: MediaCardDevice = if data[3] == 0 {
            data[7].try_into()?
        } else {
            data[3].try_into()?
        };
        Ok(Self {
            backup_write_wait_time: data[0],
            media_card_device,
            media_platform: data[4].try_into()?,
            media_type: data[5].try_into()?,
            media_unit_size: 0x200 * (1 << data[6]),
        })
    }
}

/// Describes where an NCCH partition is located, and its size.
#[derive(Debug, Copy, Clone)]
pub struct NCCHPartitionEntry {
    /// Offset to the partition in media units (512 bytes).
    pub offset: u32,
    /// Size of the partition in media units (512 bytes).
    pub size: u32,
}

/// This is the NCSD header specifically for carts, not for NAND.
#[derive(Debug)]
pub struct NCSD {
    /// RSA-2048 SHA256 signature of the header.
    pub signature: [u8; 0x100],
    /// Magic number that should equal to "NCSD'
    pub magic: [u8; 4],
    /// The size of the NCSD image/cartridge, in media units (media units == 512 byte).
    pub size: u32,
    /// The title ID of the main application partition.
    pub main_title_id: u64,
    /// Extended header SHA-256 hash.
    pub exheader_hash: [u8; 0x20],
    /// The size of the additional header.
    pub header_size: u32,
    /// The offset from sector zero of the header (?).
    pub sector_zero_offset: u32,
    /// Partition flags.
    pub partition_flags: NCCHPartitionFlags,
    pub partition_crypto_flags: NCCHPartitionCryptoFlags,
    /// Metadata of all NCCH partitions.
    pub ncch: Vec<(NCCHPartitionHeader, NCCH)>,
}

impl From<[u8; 8]> for NCCHPartitionEntry {
    fn from(data: [u8; 8]) -> Self {
        let offset = LittleEndian::read_u32(&data[..4]);
        let size = LittleEndian::read_u32(&data[4..8]);
        Self { offset, size }
    }
}

pub trait NCSDRead {
    /// Parses the 3DS ROM NCSD metadata from the object provided, returning a NCSD object with the
    /// header metadata.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Parse`] if the header cannot be found or if a field in the header contains
    /// an unexpected value.
    /// Returns [`Error::Io`] if an IO error took place while reading from the file.
    fn read_ncsd(&mut self) -> Result<NCSD, Error>;
}

impl<T: Read + Seek> NCSDRead for T {
    fn read_ncsd(&mut self) -> Result<NCSD, Error> {
        self.seek(SeekFrom::Start(0))?;

        let mut signature = [0u8; 0x100];
        self.read_exact(&mut signature)?;
        let mut magic = [0u8; 4];
        self.read_exact(&mut magic)?;
        let size = self.read_u32::<LittleEndian>()?;
        let main_title_id = self.read_u64::<LittleEndian>()?;
        let mut partition_fs_type = [0u8; 0x8];
        self.read_exact(&mut partition_fs_type)?;
        let mut partition_crypt_type = [0u8; 0x8];
        self.read_exact(&mut partition_crypt_type)?;
        let mut partition_table = [NCCHPartitionEntry { offset: 0, size: 0 }; 8];
        for entry in &mut partition_table {
            let mut data = [0u8; 8];
            self.read_exact(&mut data)?;
            *entry = data.into();
        }

        self.seek(SeekFrom::Start(0x160))?;
        let mut exheader_hash = [0u8; 0x20];
        self.read_exact(&mut exheader_hash)?;
        let header_size = self.read_u32::<LittleEndian>()?;
        let sector_zero_offset = self.read_u32::<LittleEndian>()?;

        let mut partition_flags = [0u8; 8];
        self.read_exact(&mut partition_flags)?;
        let partition_crypto_flags: NCCHPartitionCryptoFlags = partition_flags.try_into()?;
        let partition_flags: NCCHPartitionFlags = partition_flags.try_into()?;

        let mut partition_title_id_table = [0u64; 8];
        for elem in &mut partition_title_id_table {
            *elem = self.read_u64::<LittleEndian>()?;
        }
        let mut ncch = vec![];
        for index in 0..8 {
            if partition_table[index].size == 0 {
                continue;
            }

            let ncch_partition = self.read_ncch(partition_table[index])?.unwrap();

            ncch.push((
                NCCHPartitionHeader {
                    index,
                    offset: partition_table[index].offset,
                    size: partition_table[index].size,
                    title_id: partition_title_id_table[index],
                    filesystem_type: partition_fs_type[index].try_into()?,
                    crypt_type: partition_crypt_type[index].try_into()?,
                },
                ncch_partition,
            ));
        }

        Ok(NCSD {
            signature,
            magic,
            size,
            main_title_id,
            exheader_hash,
            header_size,
            sector_zero_offset,
            partition_flags,
            partition_crypto_flags,
            ncch,
        })
    }
}

impl NCSD {
    /// Returns the `NCCH` that contains the `ExeFs` section.
    #[must_use]
    pub fn find_exefs_ncch(&self) -> Option<&NCCH> {
        if let Some(ncch) = self.ncch.iter().find(|&ncch| ncch.1.exefs_size != 0) {
            return Some(&ncch.1);
        }
        None
    }
}