Browse Source

initial commit

master
Ian Burgwin 2 years ago
commit
9d9d70a200
  1. 233
      .gitignore
  2. 21
      LICENSE.md
  3. 22
      README.md
  4. 156
      rebuild-title-database.py
  5. 2
      requirements.txt
  6. BIN
      title.db.gz

233
.gitignore

@ -0,0 +1,233 @@
movable.sed
# Created by .ignore support plugin (hsz.mobi)
### Python template
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
### JetBrains template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### macOS template
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk

21
LICENSE.md

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2020 Ian Burgwin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

22
README.md

@ -0,0 +1,22 @@
# rebuild-title-database
Rebuilds the contents of `title.db` for Nintendo 3DS.
This currently does not interact with `title.db` directly, [https://github.com/wwylele/save3ds](save3ds_fuse) must be used manually to extract and rebuild.
This had minimal testing, but it probably works in most cases. File an issue, send me an email, or contact me on Discord if there are problems.
## Summary
1. [Get boot9 and movable.sed.](https://ihaveamac.github.io/dump.html)
2. Run the script with the SD card. Example:
`<py3-cmd> rebuild-title-database.py -b boot9.bin -m movable.sed -s F: -o out`
3. Import into title.db with save3ds_fuse and the -i flag.
`<py3-cmd>` is often `python3` for *nix and Python from the Microsoft Store, and `py -3` for Windows when installed from python.org.
## `title.db.gz`
This is a gzip'd empty `title.db` file. This can be added manually with a tool like ninfs, or encrypting it in a script with pyctr. Eventually this tool might put it in place automatically.
Decompress with `gzip -d title.db.gz` or `<py3-cmd> -m gzip -d title.db.gz`.
## License
`rebuild-title-database.py` is under the MIT license.

156
rebuild-title-database.py

@ -0,0 +1,156 @@
#!/usr/bin/env python3
# This file is a part of rebuild-title-database.
#
# Copyright (c) 2020 Ian Burgwin
# This file is licensed under The MIT License (MIT).
# You can find the full license text in LICENSE.md in the root of this project.
from argparse import ArgumentParser
import lzma
from pathlib import Path
from random import randint
import sys
from pyctr.crypto import CryptoEngine, Keyslot
from pyctr.type.ncch import NCCHReader, NCCHSection
from pyctr.type.cia import CIAReader
from pyctr.type.tmd import TitleMetadataReader
from pyctr.util import roundup
# the size of each file and directory in a title's contents are rounded up to this
TITLE_ALIGN_SIZE = 0x8000
parser = ArgumentParser(description='Rebuilds 3DS Title Database.')
parser.add_argument('-b', '--boot9', help='boot9')
parser.add_argument('-m', '--movable', help='movable.sed', required=True)
parser.add_argument('-s', '--sd', help='SD card (containing "Nintendo 3DS")', required=True)
parser.add_argument('-o', '--output', help='output directory for title info entries', required=True)
args = parser.parse_args()
crypto = CryptoEngine(boot9=args.boot9)
crypto.setup_sd_key_from_file(args.movable)
out = Path(args.output)
out.mkdir(exist_ok=True)
id0 = Path(args.sd) / 'Nintendo 3DS' / crypto.id0.hex()
# Only continue if there is one id1 directory.
# If there isn't, the user needs to remove the unwanted ones.
id1_list = [x for x in id0.iterdir() if len(x.parts[-1]) == 32]
if len(id1_list) > 1:
print('There are multiple id1 directories in', id0, file=sys.stderr)
print('Please remove the rest.', file=sys.stderr)
sys.exit(1)
elif len(id1_list) < 1:
print('No id1 directory could be found in', id0, file=sys.stderr)
sys.exit(2)
id1 = id1_list[0]
for tmd_path in id1.rglob('*.tmd'):
tmd_id = int(tmd_path.name[0:8], 16)
tmd_path_for_cid = '/' + '/'.join(tmd_path.parts[len(id1.parts):])
with tmd_path.open('rb') as tmd_fh:
with crypto.create_ctr_io(Keyslot.SD, tmd_fh, crypto.sd_path_to_iv(tmd_path_for_cid)) as tmd_cfh:
tmd = TitleMetadataReader.load(tmd_cfh)
print('Parsing', tmd.title_id)
if tmd.title_id.startswith('0004008c'):
# DLC puts contents into different folders, the first content always goes in the first one
content0_path = tmd_path.parent / '00000000' / (tmd.chunk_records[0].id + '.app')
has_manual = False
else:
content0_path = tmd_path.parent / (tmd.chunk_records[0].id + '.app')
has_manual = any(x for x in tmd.chunk_records if x.cindex == 1)
content0_path_for_cid = '/' + '/'.join(content0_path.parts[len(id1.parts):])
with content0_path.open('rb') as ncch_fh:
with crypto.create_ctr_io(Keyslot.SD, ncch_fh, crypto.sd_path_to_iv(content0_path_for_cid)) as ncch_cfh:
ncch = NCCHReader(ncch_cfh, load_sections=False)
ncch_product_code = ncch.product_code
# NCCH version is required for DLP child to work I think. I remember something didn't work if it wasn't
# set in the title info entry.
ncch_version = ncch.version
try:
with ncch.open_raw_section(NCCHSection.ExtendedHeader) as e:
e.seek(0x200 + 0x30)
extdata_id = e.read(8)
except KeyError:
# not an executable title
extdata_id = b'\0' * 8
tidlow_path = tmd_path.parents[1]
# this is for the tidlow directory itself, which rglob doesn't include
sizes = [1]
# Get every file and include their size, except the directories for DLC content (the contents inside still count).
# This will also find the cmd file name.
# This is quite a lazy method to do things but it works!
# cmd_id should almost certainly be found. If not, the title will be skipped at the end of the loop.
cmd_id = None
for f in tmd_path.parents[1].rglob('*'):
if f.name.endswith('.cmd'):
cmd_id = int(f.name[0:8], 16)
# exclude DLC separate directories (00000000, etc) but include all others
# this won't match the tidlow directory which is not included in this search like above
try:
bytes.fromhex(f.name)
include_if_dir = False
except ValueError:
include_if_dir = True
if not (f.name.startswith('.') or (f.is_dir() and not include_if_dir)):
sizes.append(f.stat().st_size if f.is_file() else 1)
if cmd_id is None:
print(f'Could not find a cmd file for {tmd.title_id}, skipping.')
continue
title_size = sum(roundup(x, TITLE_ALIGN_SIZE) for x in sizes)
# this starts building the title info entry
title_info_entry_data = [
# title size
title_size.to_bytes(8, 'little'),
# title type, seems to usually be 0x40
0x40.to_bytes(4, 'little'),
# title version
int(tmd.title_version).to_bytes(2, 'little'),
# ncch version
ncch_version.to_bytes(2, 'little'),
# flags_0, only checking if there is a manual
(1 if has_manual else 0).to_bytes(4, 'little'),
# tmd content id
tmd_id.to_bytes(4, 'little'),
# cmd content id
cmd_id.to_bytes(4, 'little'),
# flags_1, only checking save data
(1 if tmd.save_size else 0).to_bytes(4, 'little'),
# extdataid low
extdata_id[0:4],
# reserved
b'\0' * 4,
# flags_2, only using a common value
0x100000000.to_bytes(8, 'little'),
# product code
ncch_product_code.encode('ascii').ljust(0x10, b'\0'),
# reserved
b'\0' * 0x10,
# unknown
randint(0, 0xFFFFFFFF).to_bytes(4, 'little'),
# reserved
b'\0' * 0x2c
]
title_info_entry = b''.join(title_info_entry_data)
tie_path = out / tmd.title_id
with tie_path.open('wb') as o:
o.write(title_info_entry)

2
requirements.txt

@ -0,0 +1,2 @@
pycryptodomex==3.9.4
pyctr==0.1.0

BIN
title.db.gz

Binary file not shown.
Loading…
Cancel
Save