fs.mitm: experimental support for save redirection to sd.

This commit is contained in:
Michael Scire 2019-04-05 13:36:38 -07:00
parent fb5e02050b
commit 938169cd3c
15 changed files with 434 additions and 66 deletions

View file

@ -16,3 +16,9 @@ dmnt_cheats_enabled_by_default = u8!0x1
; for restoration on new game launch. 1 = always save toggles,
; 0 = only save toggles if toggle file exists.
dmnt_always_save_cheat_toggles = u8!0x0
; Controls whether fs.mitm should redirect save files
; to directories on the sd card.
; 0 = Do not redirect, 1 = Redirect.
; NOTE: EXPERIMENTAL
; If you do not know what you are doing, do not touch this yet.
fsmitm_redirect_saves_to_sd = u8!0x0

View file

@ -95,3 +95,39 @@ Result FsDirUtils::CopyDirectoryRecursively(IFileSystem *dst_fs, IFileSystem *sr
return CopyFile(dst_fs, src_fs, work_path, path, dir_ent, work_buf, work_buf_size);
});
}
Result FsDirUtils::EnsureDirectoryExists(IFileSystem *fs, const FsPath &path) {
FsPath normal_path;
size_t normal_path_len;
Result rc;
/* Normalize the path. */
if (R_FAILED((rc = FsPathUtils::Normalize(normal_path.str, sizeof(normal_path.str) - 1, path.str, &normal_path_len)))) {
return rc;
}
/* Repeatedly call CreateDirectory on each directory leading to the target. */
for (size_t i = 1; i < normal_path_len; i++) {
/* If we detect a separator, we're done. */
if (normal_path.str[i] == '/') {
normal_path.str[i] = 0;
{
rc = fs->CreateDirectory(normal_path);
if (rc == ResultFsPathAlreadyExists) {
rc = ResultSuccess;
}
if (R_FAILED(rc)) {
return rc;
}
}
normal_path.str[i] = '/';
}
}
/* Call CreateDirectory on the final path. */
rc = fs->CreateDirectory(normal_path);
if (rc == ResultFsPathAlreadyExists) {
rc = ResultSuccess;
}
return rc;
}

View file

@ -133,6 +133,9 @@ class FsDirUtils {
return CopyDirectoryRecursively(fs, fs, dst_path, src_path, work_buf, work_buf_size);
}
/* Ensure directory existence. */
static Result EnsureDirectoryExists(IFileSystem *fs, const FsPath &path);
/* Other Utility. */
template<typename F>
static Result RetryUntilTargetNotLocked(F f) {

View file

@ -166,6 +166,27 @@ void DirectorySaveDataFileSystem::OnWritableFileClose() {
/* TODO: Abort if < 0? N does not. */
}
Result DirectorySaveDataFileSystem::CopySaveFromProxy() {
if (this->proxy_save_fs != nullptr) {
Result rc;
/* Get a buffer to work with. */
void *work_buf = nullptr;
size_t work_buf_size = 0;
if (R_FAILED((rc = this->AllocateWorkBuffer(&work_buf, &work_buf_size, IdealWorkBuffersize)))) {
return rc;
}
ON_SCOPE_EXIT { free(work_buf); };
rc = FsDirUtils::CopyDirectoryRecursively(this, this->proxy_save_fs.get(), FsPathUtils::RootPath, FsPathUtils::RootPath, work_buf, work_buf_size);
if (R_FAILED(rc)) {
return rc;
}
return this->Commit();
}
return ResultSuccess;
}
/* ================================================================================================ */
Result DirectorySaveDataFileSystem::CreateFileImpl(const FsPath &path, uint64_t size, int flags) {

View file

@ -35,12 +35,13 @@ class DirectorySaveDataFileSystem : public IFileSystem {
private:
std::shared_ptr<IFileSystem> shared_fs;
std::unique_ptr<IFileSystem> unique_fs;
std::unique_ptr<IFileSystem> proxy_save_fs;
IFileSystem *fs;
HosMutex lock;
size_t open_writable_files = 0;
public:
DirectorySaveDataFileSystem(IFileSystem *fs) : unique_fs(fs) {
DirectorySaveDataFileSystem(IFileSystem *fs, std::unique_ptr<IFileSystem> pfs) : unique_fs(fs), proxy_save_fs(std::move(pfs)) {
this->fs = this->unique_fs.get();
Result rc = this->Initialize();
if (R_FAILED(rc)) {
@ -48,7 +49,7 @@ class DirectorySaveDataFileSystem : public IFileSystem {
}
}
DirectorySaveDataFileSystem(std::unique_ptr<IFileSystem> fs) : unique_fs(std::move(fs)) {
DirectorySaveDataFileSystem(std::unique_ptr<IFileSystem> fs, std::unique_ptr<IFileSystem> pfs) : unique_fs(std::move(fs)), proxy_save_fs(std::move(pfs)) {
this->fs = this->unique_fs.get();
Result rc = this->Initialize();
if (R_FAILED(rc)) {
@ -56,7 +57,7 @@ class DirectorySaveDataFileSystem : public IFileSystem {
}
}
DirectorySaveDataFileSystem(std::shared_ptr<IFileSystem> fs) : shared_fs(fs) {
DirectorySaveDataFileSystem(std::shared_ptr<IFileSystem> fs, std::unique_ptr<IFileSystem> pfs) : shared_fs(fs), proxy_save_fs(std::move(pfs)) {
this->fs = this->shared_fs.get();
Result rc = this->Initialize();
if (R_FAILED(rc)) {
@ -64,7 +65,6 @@ class DirectorySaveDataFileSystem : public IFileSystem {
}
}
virtual ~DirectorySaveDataFileSystem() { }
private:
@ -79,6 +79,7 @@ class DirectorySaveDataFileSystem : public IFileSystem {
}
public:
void OnWritableFileClose();
Result CopySaveFromProxy();
public:
virtual Result CreateFileImpl(const FsPath &path, uint64_t size, int flags) override;
virtual Result DeleteFileImpl(const FsPath &path) override;

View file

@ -198,13 +198,18 @@ class IFileSystem {
class IFileSystemInterface : public IServiceObject {
private:
std::unique_ptr<IFileSystem> base_fs;
std::unique_ptr<IFileSystem> unique_fs;
std::shared_ptr<IFileSystem> shared_fs;
IFileSystem *base_fs;
public:
IFileSystemInterface(IFileSystem *fs) : base_fs(fs) {
/* ... */
IFileSystemInterface(IFileSystem *fs) : unique_fs(fs) {
this->base_fs = this->unique_fs.get();
};
IFileSystemInterface(std::unique_ptr<IFileSystem> fs) : base_fs(std::move(fs)) {
/* ... */
IFileSystemInterface(std::unique_ptr<IFileSystem> fs) : unique_fs(std::move(fs)) {
this->base_fs = this->unique_fs.get();
};
IFileSystemInterface(std::shared_ptr<IFileSystem> fs) : shared_fs(fs) {
this->base_fs = this->shared_fs.get();
};
private:

View file

@ -0,0 +1,127 @@
/*
* Copyright (c) 2018 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cstring>
#include <cstdlib>
#include <switch.h>
#include "fs_save_utils.hpp"
Result FsSaveUtils::GetSaveDataSpaceIdString(const char **out_str, u8 space_id) {
const char *str = nullptr;
switch (space_id) {
case FsSaveDataSpaceId_NandSystem:
case 100: /* ProperSystem */
case 101: /* SafeMode */
str = "sys";
break;
case FsSaveDataSpaceId_NandUser:
str = "user";
break;
case FsSaveDataSpaceId_SdCard:
str = "sd_sys";
break;
case FsSaveDataSpaceId_TemporaryStorage:
str = "temp";
break;
case 4: /* SdUser */
str = "sd_user";
break;
default: /* Unexpected */
str = nullptr;
break;
}
if (str == nullptr) {
return ResultFsInvalidSaveDataSpaceId;
}
if (out_str) {
*out_str = str;
}
return ResultSuccess;
}
Result FsSaveUtils::GetSaveDataTypeString(const char **out_str, u8 save_data_type) {
const char *str = nullptr;
switch (save_data_type) {
case FsSaveDataType_SystemSaveData:
str = "system";
break;
case FsSaveDataType_SaveData:
str = "account";
break;
case FsSaveDataType_BcatDeliveryCacheStorage:
str = "bcat";
break;
case FsSaveDataType_DeviceSaveData:
str = "device";
break;
case FsSaveDataType_TemporaryStorage:
str = "temp";
break;
case FsSaveDataType_CacheStorage:
str = "cache";
break;
case 6: /* System Bcat Save */
str = "bcat_sys";
break;
default: /* Unexpected */
str = nullptr;
break;
}
if (str == nullptr) {
/* TODO: Better result? */
return ResultFsInvalidArgument;
}
if (out_str) {
*out_str = str;
}
return ResultSuccess;
}
Result FsSaveUtils::GetSaveDataDirectoryPath(FsPath &out_path, u8 space_id, u8 save_data_type, u64 title_id, u128 user_id, u64 save_id) {
const char *space_id_str, *save_type_str;
Result rc;
/* Get space_id, save_data_type strings. */
if (R_FAILED((rc = GetSaveDataSpaceIdString(&space_id_str, space_id))) || R_FAILED((rc = GetSaveDataTypeString(&save_type_str, save_data_type)))) {
return rc;
}
/* Clear and initialize the path. */
std::memset(&out_path, 0, sizeof(out_path));
const bool is_system = (save_id != 0 && user_id == 0);
size_t out_path_len;
if (is_system) {
out_path_len = static_cast<size_t>(snprintf(out_path.str, sizeof(out_path.str), "/atmosphere/saves/sysnand/%s/%s/%016lx",
space_id_str, save_type_str, save_id));
} else {
out_path_len = static_cast<size_t>(snprintf(out_path.str, sizeof(out_path.str), "/atmosphere/saves/sysnand/%s/%s/%016lx/%016lx%016lx",
space_id_str, save_type_str, title_id, static_cast<u64>(user_id >> 64ul), static_cast<u64>(user_id)));
}
if (out_path_len >= sizeof(out_path)) {
/* TODO: Should we abort here? */
return ResultFsTooLongPath;
}
return ResultSuccess;
}

View file

@ -0,0 +1,29 @@
/*
* Copyright (c) 2018 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <switch.h>
#include "fs_path_utils.hpp"
#include "fs_ifilesystem.hpp"
class FsSaveUtils {
private:
static Result GetSaveDataSpaceIdString(const char **out_str, u8 space_id);
static Result GetSaveDataTypeString(const char **out_str, u8 save_data_type);
public:
static Result GetSaveDataDirectoryPath(FsPath &out_path, u8 space_id, u8 save_data_type, u64 title_id, u128 user_id, u64 save_id);
};

View file

@ -225,6 +225,46 @@ Result fsOpenFileSystemWithIdFwd(Service* s, FsFileSystem* out, u64 titleId, FsF
return rc;
}
Result fsOpenSaveDataFileSystemFwd(Service *s, FsFileSystem* out, u8 inval, FsSave *save) {
IpcCommand c;
ipcInitialize(&c);
struct {
u64 magic;
u64 cmd_id;
u64 inval;//Actually u8.
FsSave save;
} PACKED *raw;
raw = serviceIpcPrepareHeader(s, &c, sizeof(*raw));
raw->magic = SFCI_MAGIC;
raw->cmd_id = 51;
raw->inval = (u64)inval;
memcpy(&raw->save, save, sizeof(FsSave));
Result rc = serviceIpcDispatch(s);
if (R_SUCCEEDED(rc)) {
IpcParsedCommand r;
struct {
u64 magic;
u64 result;
} *resp;
serviceIpcParse(s, &r, sizeof(*resp));
resp = r.Raw;
rc = resp->result;
if (R_SUCCEEDED(rc)) {
serviceCreateSubservice(&out->s, s, &r, 0);
}
}
return rc;
}
/* Missing FS File commands. */
Result fsFileOperateRange(FsFile* f, u32 op_id, u64 off, u64 len, FsRangeInfo *out) {
IpcCommand c;

View file

@ -22,6 +22,7 @@ Result fsOpenDataStorageByCurrentProcessFwd(Service* s, FsStorage* out);
Result fsOpenDataStorageByDataIdFwd(Service* s, FsStorageId storage_id, u64 data_id, FsStorage* out);
Result fsOpenFileSystemWithPatchFwd(Service* s, FsFileSystem* out, u64 titleId, FsFileSystemType fsType);
Result fsOpenFileSystemWithIdFwd(Service* s, FsFileSystem* out, u64 titleId, FsFileSystemType fsType, const char* contentPath);
Result fsOpenSaveDataFileSystemFwd(Service* s, FsFileSystem* out, u8 inval, FsSave *save);
/* Missing FS File commands. */
Result fsFileOperateRange(FsFile* f, u32 op_id, u64 off, u64 len, FsRangeInfo *out);

View file

@ -28,6 +28,8 @@
#include "fsmitm_romstorage.hpp"
#include "fsmitm_layeredrom.hpp"
#include "fs_dir_utils.hpp"
#include "fs_save_utils.hpp"
#include "fs_subdirectory_filesystem.hpp"
#include "fs_directory_savedata_filesystem.hpp"
@ -101,7 +103,8 @@ Result FsMitmService::OpenHblWebContentFileSystem(Out<std::shared_ptr<IFileSyste
FsFileSystem sd_fs;
rc = fsMountSdcard(&sd_fs);
if (R_SUCCEEDED(rc)) {
fs = std::make_shared<IFileSystemInterface>(std::make_unique<SubDirectoryFileSystem>(std::make_shared<ProxyFileSystem>(sd_fs), AtmosphereHblWebContentDir));
std::unique_ptr<IFileSystem> web_ifs = std::make_unique<SubDirectoryFileSystem>(std::make_shared<ProxyFileSystem>(sd_fs), AtmosphereHblWebContentDir);
fs = std::make_shared<IFileSystemInterface>(std::move(web_ifs));
if (out_fs.IsDomain()) {
out_domain_id = sd_fs.s.object_id;
}
@ -158,6 +161,84 @@ Result FsMitmService::OpenFileSystemWithId(Out<std::shared_ptr<IFileSystemInterf
return this->OpenHblWebContentFileSystem(out_fs);
}
Result FsMitmService::OpenSaveDataFileSystem(Out<std::shared_ptr<IFileSystemInterface>> out_fs, u8 space_id, FsSave save_struct) {
bool should_redirect_saves = false;
if (R_FAILED(Utils::GetSettingsItemBooleanValue("atmosphere", "fsmitm_redirect_saves_to_sd", &should_redirect_saves))) {
return ResultAtmosphereMitmShouldForwardToSession;
}
/* For now, until we're sure this is robust, only intercept normal savedata. */
if (!should_redirect_saves || save_struct.SaveDataType != FsSaveDataType_SaveData) {
return ResultAtmosphereMitmShouldForwardToSession;
}
/* Verify we can open the save. */
FsFileSystem save_fs;
if (R_FAILED(fsOpenSaveDataFileSystemFwd(this->forward_service.get(), &save_fs, space_id, &save_struct))) {
return ResultAtmosphereMitmShouldForwardToSession;
}
std::unique_ptr<IFileSystem> save_ifs = std::make_unique<ProxyFileSystem>(save_fs);
{
std::shared_ptr<IFileSystemInterface> fs = nullptr;
u32 out_domain_id = 0;
Result rc = ResultSuccess;
ON_SCOPE_EXIT {
if (R_SUCCEEDED(rc)) {
out_fs.SetValue(std::move(fs));
if (out_fs.IsDomain()) {
out_fs.ChangeObjectId(out_domain_id);
}
}
};
/* Mount the SD card using fs.mitm's session. */
FsFileSystem sd_fs;
if (R_FAILED((rc = fsMountSdcard(&sd_fs)))) {
return rc;
}
std::shared_ptr<IFileSystem> sd_ifs = std::make_shared<ProxyFileSystem>(sd_fs);
/* Verify that we can open the save directory, and that it exists. */
const u64 target_tid = save_struct.titleID == 0 ? this->title_id : save_struct.titleID;
FsPath save_dir_path;
if (R_FAILED((rc = FsSaveUtils::GetSaveDataDirectoryPath(save_dir_path, space_id, save_struct.SaveDataType, target_tid, save_struct.userID, save_struct.saveID)))) {
return rc;
}
/* Check if this is the first time we're making the save. */
bool is_new_save = false;
{
DirectoryEntryType ent;
if (sd_ifs->GetEntryType(&ent, save_dir_path) == ResultFsPathNotFound) {
is_new_save = true;
}
}
/* Ensure the directory exists. */
if (R_FAILED((rc = FsDirUtils::EnsureDirectoryExists(sd_ifs.get(), save_dir_path)))) {
return rc;
}
std::shared_ptr<DirectorySaveDataFileSystem> dirsave_ifs = std::make_shared<DirectorySaveDataFileSystem>(new SubDirectoryFileSystem(sd_ifs, save_dir_path.str), std::move(save_ifs));
/* If it's the first time we're making the save, copy existing savedata over. */
if (is_new_save) {
/* TODO: Check error? */
dirsave_ifs->CopySaveFromProxy();
}
fs = std::make_shared<IFileSystemInterface>(static_cast<std::shared_ptr<IFileSystem>>(dirsave_ifs));
if (out_fs.IsDomain()) {
out_domain_id = sd_fs.s.object_id;
}
return rc;
}
}
/* Gate access to the BIS partitions. */
Result FsMitmService::OpenBisStorage(Out<std::shared_ptr<IStorageInterface>> out_storage, u32 bis_partition_id) {
std::shared_ptr<IStorageInterface> storage = nullptr;

View file

@ -29,6 +29,8 @@ enum FspSrvCmd : u32 {
FspSrvCmd_OpenFileSystemWithPatch = 7,
FspSrvCmd_OpenFileSystemWithId = 8,
FspSrvCmd_OpenSaveDataFileSystem = 51,
FspSrvCmd_OpenBisStorage = 12,
FspSrvCmd_OpenDataStorageByCurrentProcess = 200,
FspSrvCmd_OpenDataStorageByDataId = 202,
@ -73,6 +75,7 @@ class FsMitmService : public IMitmServiceObject {
/* Overridden commands. */
Result OpenFileSystemWithPatch(Out<std::shared_ptr<IFileSystemInterface>> out, u64 title_id, u32 filesystem_type);
Result OpenFileSystemWithId(Out<std::shared_ptr<IFileSystemInterface>> out, InPointer<char> path, u64 title_id, u32 filesystem_type);
Result OpenSaveDataFileSystem(Out<std::shared_ptr<IFileSystemInterface>> out, u8 space_id, FsSave save_struct);
Result OpenBisStorage(Out<std::shared_ptr<IStorageInterface>> out, u32 bis_partition_id);
Result OpenDataStorageByCurrentProcess(Out<std::shared_ptr<IStorageInterface>> out);
Result OpenDataStorageByDataId(Out<std::shared_ptr<IStorageInterface>> out, u64 data_id, u8 storage_id);
@ -81,6 +84,7 @@ class FsMitmService : public IMitmServiceObject {
/* TODO MakeServiceCommandMeta<FspSrvCmd_OpenFileSystemDeprecated, &FsMitmService::OpenFileSystemDeprecated>(), */
MakeServiceCommandMeta<FspSrvCmd_OpenFileSystemWithPatch, &FsMitmService::OpenFileSystemWithPatch, FirmwareVersion_200>(),
MakeServiceCommandMeta<FspSrvCmd_OpenFileSystemWithId, &FsMitmService::OpenFileSystemWithId, FirmwareVersion_200>(),
MakeServiceCommandMeta<FspSrvCmd_OpenSaveDataFileSystem, &FsMitmService::OpenSaveDataFileSystem>(),
MakeServiceCommandMeta<FspSrvCmd_OpenBisStorage, &FsMitmService::OpenBisStorage>(),
MakeServiceCommandMeta<FspSrvCmd_OpenDataStorageByCurrentProcess, &FsMitmService::OpenDataStorageByCurrentProcess>(),
MakeServiceCommandMeta<FspSrvCmd_OpenDataStorageByDataId, &FsMitmService::OpenDataStorageByDataId>(),

View file

@ -640,3 +640,15 @@ Result Utils::GetSettingsItemValueSize(const char *name, const char *key, u64 *o
Result Utils::GetSettingsItemValue(const char *name, const char *key, void *out, size_t max_size, u64 *out_size) {
return SettingsItemManager::GetValue(name, key, out, max_size, out_size);
}
Result Utils::GetSettingsItemBooleanValue(const char *name, const char *key, bool *out) {
u8 val = 0;
u64 out_size;
Result rc = Utils::GetSettingsItemValue(name, key, &val, sizeof(val), &out_size);
if (R_SUCCEEDED(rc)) {
if (out) {
*out = val != 0;
}
}
return rc;
}

View file

@ -85,6 +85,8 @@ class Utils {
/* Settings! */
static Result GetSettingsItemValueSize(const char *name, const char *key, u64 *out_size);
static Result GetSettingsItemValue(const char *name, const char *key, void *out, size_t max_size, u64 *out_size);
static Result GetSettingsItemBooleanValue(const char *name, const char *key, bool *out);
private:
static void RefreshConfiguration();
};

@ -1 +1 @@
Subproject commit b6ca2d89ae5106ea21454f332f07076159ad2e92
Subproject commit 8021b07eb82b9941c1820b211bbe6d898589e59b