| 1 | // Copyright 2022 Dolphin Emulator Project |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | |
| 4 | #include "Common/FatFsUtil.h" |
| 5 | |
| 6 | #include <algorithm> |
| 7 | #include <cstdlib> |
| 8 | #include <mutex> |
| 9 | #include <string> |
| 10 | #include <string_view> |
| 11 | #include <vector> |
| 12 | |
| 13 | #include <fmt/format.h> |
| 14 | |
| 15 | // Does not compile if diskio.h is included first. |
| 16 | // clang-format off |
| 17 | #include "ff.h" |
| 18 | #include "diskio.h" |
| 19 | // clang-format on |
| 20 | |
| 21 | #include "Common/Align.h" |
| 22 | #include "Common/FileUtil.h" |
| 23 | #include "Common/IOFile.h" |
| 24 | #include "Common/Logging/Log.h" |
| 25 | #include "Common/ScopeGuard.h" |
| 26 | #include "Common/StringUtil.h" |
| 27 | #include "Common/TimeUtil.h" |
| 28 | |
| 29 | #include "Core/Config/MainSettings.h" |
| 30 | |
| 31 | enum : u32 |
| 32 | { |
| 33 | SECTOR_SIZE = 512, |
| 34 | MAX_CLUSTER_SIZE = 64 * SECTOR_SIZE, |
| 35 | }; |
| 36 | |
| 37 | static std::mutex s_fatfs_mutex; |
| 38 | static Common::FatFsCallbacks* s_callbacks; |
| 39 | |
| 40 | namespace |
| 41 | { |
| 42 | int SDCardDiskRead(File::IOFile* image, u8 pdrv, u8* buff, u32 sector, unsigned int count) |
| 43 | { |
| 44 | const u64 offset = static_cast<u64>(sector) * SECTOR_SIZE; |
| 45 | if (!image->Seek(offset, File::SeekOrigin::Begin)) |
| 46 | { |
| 47 | ERROR_LOG_FMT(COMMON, "SD image seek failed (offset={})", offset); |
| 48 | return RES_ERROR; |
| 49 | } |
| 50 | |
| 51 | const size_t size = static_cast<size_t>(count) * SECTOR_SIZE; |
| 52 | if (!image->ReadBytes(buff, size)) |
| 53 | { |
| 54 | ERROR_LOG_FMT(COMMON, "SD image read failed (offset={}, size={})", offset, size); |
| 55 | return RES_ERROR; |
| 56 | } |
| 57 | |
| 58 | return RES_OK; |
| 59 | } |
| 60 | |
| 61 | int SDCardDiskWrite(File::IOFile* image, u8 pdrv, const u8* buff, u32 sector, unsigned int count) |
| 62 | { |
| 63 | const u64 offset = static_cast<u64>(sector) * SECTOR_SIZE; |
| 64 | if (!image->Seek(offset, File::SeekOrigin::Begin)) |
| 65 | { |
| 66 | ERROR_LOG_FMT(COMMON, "SD image seek failed (offset={})", offset); |
| 67 | return RES_ERROR; |
| 68 | } |
| 69 | |
| 70 | const size_t size = static_cast<size_t>(count) * SECTOR_SIZE; |
| 71 | if (!image->WriteBytes(buff, size)) |
| 72 | { |
| 73 | ERROR_LOG_FMT(COMMON, "SD image write failed (offset={}, size={})", offset, size); |
| 74 | return RES_ERROR; |
| 75 | } |
| 76 | |
| 77 | return RES_OK; |
| 78 | } |
| 79 | |
| 80 | int SDCardDiskIOCtl(File::IOFile* image, u8 pdrv, u8 cmd, void* buff) |
| 81 | { |
| 82 | switch (cmd) |
| 83 | { |
| 84 | case CTRL_SYNC: |
| 85 | return RES_OK; |
| 86 | case GET_SECTOR_COUNT: |
| 87 | *static_cast<LBA_t*>(buff) = image->GetSize() / SECTOR_SIZE; |
| 88 | return RES_OK; |
| 89 | default: |
| 90 | WARN_LOG_FMT(COMMON, "Unexpected SD image ioctl {}", cmd); |
| 91 | return RES_OK; |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | u32 GetSystemTimeFAT() |
| 96 | { |
| 97 | const std::time_t time = std::time(nullptr); |
| 98 | std::tm tm = *Common::LocalTime(time); |
| 99 | |
| 100 | DWORD fattime = 0; |
| 101 | fattime |= (tm.tm_year - 80) << 25; |
| 102 | fattime |= (tm.tm_mon + 1) << 21; |
| 103 | fattime |= tm.tm_mday << 16; |
| 104 | fattime |= tm.tm_hour << 11; |
| 105 | fattime |= tm.tm_min << 5; |
| 106 | fattime |= std::min(tm.tm_sec, 59) >> 1; |
| 107 | return fattime; |
| 108 | } |
| 109 | } // namespace |
| 110 | |
| 111 | namespace Common |
| 112 | { |
| 113 | FatFsCallbacks::FatFsCallbacks() = default; |
| 114 | FatFsCallbacks::~FatFsCallbacks() = default; |
| 115 | |
| 116 | u8 FatFsCallbacks::DiskInitialize(u8 pdrv) |
| 117 | { |
| 118 | return 0; |
| 119 | } |
| 120 | |
| 121 | u8 FatFsCallbacks::DiskStatus(u8 pdrv) |
| 122 | { |
| 123 | return 0; |
| 124 | } |
| 125 | |
| 126 | u32 FatFsCallbacks::GetCurrentTimeFAT() |
| 127 | { |
| 128 | return GetSystemTimeFAT(); |
| 129 | } |
| 130 | } // namespace Common |
| 131 | |
| 132 | namespace |
| 133 | { |
| 134 | class SDCardFatFsCallbacks : public Common::FatFsCallbacks |
| 135 | { |
| 136 | public: |
| 137 | int DiskRead(u8 pdrv, u8* buff, u32 sector, unsigned int count) override |
| 138 | { |
| 139 | return SDCardDiskRead(m_image, pdrv, buff, sector, count); |
| 140 | } |
| 141 | |
| 142 | int DiskWrite(u8 pdrv, const u8* buff, u32 sector, unsigned int count) override |
| 143 | { |
| 144 | return SDCardDiskWrite(m_image, pdrv, buff, sector, count); |
| 145 | } |
| 146 | |
| 147 | int DiskIOCtl(u8 pdrv, u8 cmd, void* buff) override |
| 148 | { |
| 149 | return SDCardDiskIOCtl(m_image, pdrv, cmd, buff); |
| 150 | } |
| 151 | |
| 152 | u32 GetCurrentTimeFAT() override |
| 153 | { |
| 154 | if (m_deterministic) |
| 155 | return 0; |
| 156 | |
| 157 | return GetSystemTimeFAT(); |
| 158 | } |
| 159 | |
| 160 | File::IOFile* m_image = nullptr; |
| 161 | bool m_deterministic = false; |
| 162 | }; |
| 163 | } // namespace |
| 164 | |
| 165 | extern "C" DSTATUS disk_status(BYTE pdrv) |
| 166 | { |
| 167 | return static_cast<DSTATUS>(s_callbacks->DiskStatus(pdrv)); |
| 168 | } |
| 169 | |
| 170 | extern "C" DSTATUS disk_initialize(BYTE pdrv) |
| 171 | { |
| 172 | return static_cast<DSTATUS>(s_callbacks->DiskInitialize(pdrv)); |
| 173 | } |
| 174 | |
| 175 | extern "C" DRESULT disk_read(BYTE pdrv, BYTE* buff, LBA_t sector, UINT count) |
| 176 | { |
| 177 | return static_cast<DRESULT>(s_callbacks->DiskRead(pdrv, buff, sector, count)); |
| 178 | } |
| 179 | |
| 180 | extern "C" DRESULT disk_write(BYTE pdrv, const BYTE* buff, LBA_t sector, UINT count) |
| 181 | { |
| 182 | return static_cast<DRESULT>(s_callbacks->DiskWrite(pdrv, buff, sector, count)); |
| 183 | } |
| 184 | |
| 185 | extern "C" DRESULT disk_ioctl(BYTE pdrv, BYTE cmd, void* buff) |
| 186 | { |
| 187 | return static_cast<DRESULT>(s_callbacks->DiskIOCtl(pdrv, cmd, buff)); |
| 188 | } |
| 189 | |
| 190 | extern "C" DWORD get_fattime(void) |
| 191 | { |
| 192 | return static_cast<DWORD>(s_callbacks->GetCurrentTimeFAT()); |
| 193 | } |
| 194 | |
| 195 | #if FF_USE_LFN == 3 // match ff.h; currently unused by Dolphin |
| 196 | extern "C" void* ff_memalloc(UINT msize) |
| 197 | { |
| 198 | return std::malloc(msize); |
| 199 | } |
| 200 | |
| 201 | extern "C" void ff_memfree(void* mblock) |
| 202 | { |
| 203 | return std::free(mblock); |
| 204 | } |
| 205 | #endif |
| 206 | |
| 207 | #if FF_FS_REENTRANT |
| 208 | extern "C" int ff_cre_syncobj(BYTE vol, FF_SYNC_t* sobj) |
| 209 | { |
| 210 | *sobj = new std::recursive_mutex(); |
| 211 | return *sobj != nullptr; |
| 212 | } |
| 213 | |
| 214 | extern "C" int ff_req_grant(FF_SYNC_t sobj) |
| 215 | { |
| 216 | std::recursive_mutex* m = reinterpret_cast<std::recursive_mutex*>(sobj); |
| 217 | m->lock(); |
| 218 | return 1; |
| 219 | } |
| 220 | |
| 221 | extern "C" void ff_rel_grant(FF_SYNC_t sobj) |
| 222 | { |
| 223 | std::recursive_mutex* m = reinterpret_cast<std::recursive_mutex*>(sobj); |
| 224 | m->unlock(); |
| 225 | } |
| 226 | |
| 227 | extern "C" int ff_del_syncobj(FF_SYNC_t sobj) |
| 228 | { |
| 229 | delete reinterpret_cast<std::recursive_mutex*>(sobj); |
| 230 | return 1; |
| 231 | } |
| 232 | #endif |
| 233 | |
| 234 | static const char* FatFsErrorToString(FRESULT error_code) |
| 235 | { |
| 236 | // These are taken from the comment next to each value in ff.h |
| 237 | switch (error_code) |
| 238 | { |
| 239 | case FR_OK: |
| 240 | return "Succeeded"; |
| 241 | case FR_DISK_ERR: |
| 242 | return "A hard error occurred in the low level disk I/O layer"; |
| 243 | case FR_INT_ERR: |
| 244 | return "Assertion failed"; |
| 245 | case FR_NOT_READY: |
| 246 | return "The physical drive cannot work"; |
| 247 | case FR_NO_FILE: |
| 248 | return "Could not find the file"; |
| 249 | case FR_NO_PATH: |
| 250 | return "Could not find the path"; |
| 251 | case FR_INVALID_NAME: |
| 252 | return "The path name format is invalid"; |
| 253 | case FR_DENIED: |
| 254 | return "Access denied due to prohibited access or directory full"; |
| 255 | case FR_EXIST: |
| 256 | return "Access denied due to prohibited access"; |
| 257 | case FR_INVALID_OBJECT: |
| 258 | return "The file/directory object is invalid"; |
| 259 | case FR_WRITE_PROTECTED: |
| 260 | return "The physical drive is write protected"; |
| 261 | case FR_INVALID_DRIVE: |
| 262 | return "The logical drive number is invalid"; |
| 263 | case FR_NOT_ENABLED: |
| 264 | return "The volume has no work area"; |
| 265 | case FR_NO_FILESYSTEM: |
| 266 | return "There is no valid FAT volume"; |
| 267 | case FR_MKFS_ABORTED: |
| 268 | return "The f_mkfs() aborted due to any problem"; |
| 269 | case FR_TIMEOUT: |
| 270 | return "Could not get a grant to access the volume within defined period"; |
| 271 | case FR_LOCKED: |
| 272 | return "The operation is rejected according to the file sharing policy"; |
| 273 | case FR_NOT_ENOUGH_CORE: |
| 274 | return "LFN working buffer could not be allocated"; |
| 275 | case FR_TOO_MANY_OPEN_FILES: |
| 276 | return "Number of open files > FF_FS_LOCK"; |
| 277 | case FR_INVALID_PARAMETER: |
| 278 | return "Given parameter is invalid"; |
| 279 | default: |
| 280 | return "Unknown error"; |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | namespace Common |
| 285 | { |
| 286 | static constexpr u64 MebibytesToBytes(u64 mebibytes) |
| 287 | { |
| 288 | return mebibytes * 1024 * 1024; |
| 289 | } |
| 290 | |
| 291 | static constexpr u64 GibibytesToBytes(u64 gibibytes) |
| 292 | { |
| 293 | return gibibytes * 1024 * 1024 * 1024; |
| 294 | } |
| 295 | |
| 296 | static bool CheckIfFATCompatible(const File::FSTEntry& entry) |
| 297 | { |
| 298 | if (!entry.isDirectory) |
| 299 | return true; |
| 300 | |
| 301 | if (entry.children.size() > 65536) |
| 302 | { |
| 303 | ERROR_LOG_FMT(COMMON, "Directory {} has too many entries ({})", entry.physicalName, |
| 304 | entry.children.size()); |
| 305 | return false; |
| 306 | } |
| 307 | |
| 308 | for (const File::FSTEntry& child : entry.children) |
| 309 | { |
| 310 | const size_t size = UTF8ToUTF16(child.virtualName).size(); |
| 311 | if (size > 255) |
| 312 | { |
| 313 | ERROR_LOG_FMT(COMMON, "Filename {0} (in directory {1}) is too long ({2})", child.virtualName, |
| 314 | entry.physicalName, size); |
| 315 | return false; |
| 316 | } |
| 317 | |
| 318 | if (child.size >= GibibytesToBytes(4)) |
| 319 | { |
| 320 | ERROR_LOG_FMT(COMMON, "File {0} (in directory {1}) is too large ({2})", child.virtualName, |
| 321 | entry.physicalName, child.size); |
| 322 | return false; |
| 323 | } |
| 324 | |
| 325 | if (!CheckIfFATCompatible(child)) |
| 326 | return false; |
| 327 | } |
| 328 | |
| 329 | return true; |
| 330 | } |
| 331 | |
| 332 | static u64 GetSize(const File::FSTEntry& entry) |
| 333 | { |
| 334 | if (!entry.isDirectory) |
| 335 | return AlignUp(entry.size, MAX_CLUSTER_SIZE); |
| 336 | |
| 337 | u64 size = 0; |
| 338 | for (const File::FSTEntry& child : entry.children) |
| 339 | { |
| 340 | size += 32; |
| 341 | // For simplicity, assume that all names are LFN. |
| 342 | const u64 num_lfn_entries = (UTF8ToUTF16(child.virtualName).size() + 13 - 1) / 13; |
| 343 | size += num_lfn_entries * 32; |
| 344 | } |
| 345 | size = AlignUp(size, MAX_CLUSTER_SIZE); |
| 346 | |
| 347 | for (const File::FSTEntry& child : entry.children) |
| 348 | size += GetSize(child); |
| 349 | |
| 350 | return size; |
| 351 | } |
| 352 | |
| 353 | static bool Pack(const std::function<bool()>& cancelled, const File::FSTEntry& entry, bool is_root, |
| 354 | std::vector<u8>& tmp_buffer) |
| 355 | { |
| 356 | if (cancelled()) |
| 357 | return false; |
| 358 | |
| 359 | if (!entry.isDirectory) |
| 360 | { |
| 361 | File::IOFile src(entry.physicalName, "rb"); |
| 362 | if (!src) |
| 363 | { |
| 364 | ERROR_LOG_FMT(COMMON, "Failed to open file {}", entry.physicalName); |
| 365 | return false; |
| 366 | } |
| 367 | |
| 368 | FIL dst{}; |
| 369 | const auto open_error_code = |
| 370 | f_open(&dst, entry.virtualName.c_str(), FA_CREATE_ALWAYS | FA_WRITE); |
| 371 | if (open_error_code != FR_OK) |
| 372 | { |
| 373 | ERROR_LOG_FMT(COMMON, "Failed to open file {} in SD image: {}", entry.physicalName, |
| 374 | FatFsErrorToString(open_error_code)); |
| 375 | return false; |
| 376 | } |
| 377 | |
| 378 | const size_t src_size = src.GetSize(); |
| 379 | if (src.GetSize() != entry.size) |
| 380 | { |
| 381 | ERROR_LOG_FMT(COMMON, "File at {} does not match previously read filesize ({} != {})", |
| 382 | entry.physicalName, entry.size, src_size); |
| 383 | return false; |
| 384 | } |
| 385 | |
| 386 | if (entry.size >= GibibytesToBytes(4)) |
| 387 | { |
| 388 | ERROR_LOG_FMT(COMMON, "File at {} is too large to fit into FAT ({} >= 4GiB)", |
| 389 | entry.physicalName, entry.size); |
| 390 | return false; |
| 391 | } |
| 392 | |
| 393 | u64 size = entry.size; |
| 394 | while (size > 0) |
| 395 | { |
| 396 | if (cancelled()) |
| 397 | return false; |
| 398 | |
| 399 | u32 chunk_size = static_cast<u32>(std::min(size, static_cast<u64>(tmp_buffer.size()))); |
| 400 | if (!src.ReadBytes(tmp_buffer.data(), chunk_size)) |
| 401 | { |
| 402 | ERROR_LOG_FMT(COMMON, "Failed to read data from file at {}", entry.physicalName); |
| 403 | return false; |
| 404 | } |
| 405 | |
| 406 | u32 written_size; |
| 407 | const auto write_error_code = f_write(&dst, tmp_buffer.data(), chunk_size, &written_size); |
| 408 | if (write_error_code != FR_OK) |
| 409 | { |
| 410 | ERROR_LOG_FMT(COMMON, "Failed to write file {} to SD image: {}", entry.physicalName, |
| 411 | FatFsErrorToString(write_error_code)); |
| 412 | return false; |
| 413 | } |
| 414 | |
| 415 | if (written_size != chunk_size) |
| 416 | { |
| 417 | ERROR_LOG_FMT(COMMON, "Failed to write bytes of file {} to SD image ({} != {})", |
| 418 | entry.physicalName, written_size, chunk_size); |
| 419 | return false; |
| 420 | } |
| 421 | |
| 422 | size -= chunk_size; |
| 423 | } |
| 424 | |
| 425 | const auto close_error_code = f_close(&dst); |
| 426 | if (close_error_code != FR_OK) |
| 427 | { |
| 428 | ERROR_LOG_FMT(COMMON, "Failed to close file {} in SD image: {}", entry.physicalName, |
| 429 | FatFsErrorToString(close_error_code)); |
| 430 | return false; |
| 431 | } |
| 432 | |
| 433 | if (!src.Close()) |
| 434 | { |
| 435 | ERROR_LOG_FMT(COMMON, "Failed to close file {}", entry.physicalName); |
| 436 | return false; |
| 437 | } |
| 438 | |
| 439 | return true; |
| 440 | } |
| 441 | |
| 442 | if (!is_root) |
| 443 | { |
| 444 | const auto mkdir_error_code = f_mkdir(entry.virtualName.c_str()); |
| 445 | if (mkdir_error_code != FR_OK) |
| 446 | { |
| 447 | ERROR_LOG_FMT(COMMON, "Failed to make directory {} in SD image: {}", entry.physicalName, |
| 448 | FatFsErrorToString(mkdir_error_code)); |
| 449 | return false; |
| 450 | } |
| 451 | |
| 452 | const auto chdir_error_code = f_chdir(entry.virtualName.c_str()); |
| 453 | if (chdir_error_code != FR_OK) |
| 454 | { |
| 455 | ERROR_LOG_FMT(COMMON, "Failed to entry directory {} in SD image: {}", entry.physicalName, |
| 456 | FatFsErrorToString(chdir_error_code)); |
| 457 | return false; |
| 458 | } |
| 459 | } |
| 460 | |
| 461 | for (const File::FSTEntry& child : entry.children) |
| 462 | { |
| 463 | if (!Pack(cancelled, child, false, tmp_buffer)) |
| 464 | return false; |
| 465 | } |
| 466 | |
| 467 | if (!is_root) |
| 468 | { |
| 469 | const auto chdir_up_error_code = f_chdir(".."); |
| 470 | if (chdir_up_error_code != FR_OK) |
| 471 | { |
| 472 | ERROR_LOG_FMT(COMMON, "Failed to leave directory {} in SD image: {}", entry.physicalName, |
| 473 | FatFsErrorToString(chdir_up_error_code)); |
| 474 | return false; |
| 475 | } |
| 476 | } |
| 477 | |
| 478 | return true; |
| 479 | } |
| 480 | |
| 481 | static void SortFST(File::FSTEntry* root) |
| 482 | { |
| 483 | std::ranges::sort(root->children, {}, &File::FSTEntry::virtualName); |
| 484 | for (auto& child : root->children) |
| 485 | SortFST(&child); |
| 486 | } |
| 487 | |
| 488 | bool SyncSDFolderToSDImage(const std::function<bool()>& cancelled, bool deterministic) |
| 489 | { |
| 490 | const std::string source_dir = File::GetUserPath(D_WIISDCARDSYNCFOLDER_IDX); |
| 491 | const std::string image_path = File::GetUserPath(F_WIISDCARDIMAGE_IDX); |
| 492 | if (source_dir.empty() || image_path.empty()) |
| 493 | return false; |
| 494 | |
| 495 | INFO_LOG_FMT(COMMON, "Starting SD card conversion from folder {} to file {}", source_dir, |
| 496 | image_path); |
| 497 | |
| 498 | if (!File::IsDirectory(source_dir)) |
| 499 | { |
| 500 | ERROR_LOG_FMT(COMMON, "{} is not a directory, not converting", source_dir); |
| 501 | return false; |
| 502 | } |
| 503 | |
| 504 | File::FSTEntry root = File::ScanDirectoryTree(source_dir, true); |
| 505 | if (deterministic) |
| 506 | SortFST(&root); |
| 507 | if (!CheckIfFATCompatible(root)) |
| 508 | return false; |
| 509 | |
| 510 | u64 size = Config::Get(Config::MAIN_WII_SD_CARD_FILESIZE); |
| 511 | if (size == 0) |
| 512 | { |
| 513 | size = GetSize(root); |
| 514 | // Allocate a reasonable amount of free space |
| 515 | size += std::clamp(size / 2, MebibytesToBytes(512), GibibytesToBytes(8)); |
| 516 | } |
| 517 | size = AlignUp(size, MAX_CLUSTER_SIZE); |
| 518 | |
| 519 | std::lock_guard lk(s_fatfs_mutex); |
| 520 | SDCardFatFsCallbacks callbacks; |
| 521 | s_callbacks = &callbacks; |
| 522 | Common::ScopeGuard callbacks_guard{[] { s_callbacks = nullptr; }}; |
| 523 | |
| 524 | File::IOFile image; |
| 525 | callbacks.m_image = ℑ |
| 526 | callbacks.m_deterministic = deterministic; |
| 527 | |
| 528 | const std::string temp_image_path = File::GetTempFilenameForAtomicWrite(image_path); |
| 529 | if (!image.Open(temp_image_path, "w+b")) |
| 530 | { |
| 531 | ERROR_LOG_FMT(COMMON, "Failed to create or overwrite SD image at {}", image_path); |
| 532 | return false; |
| 533 | } |
| 534 | |
| 535 | // delete temp file in failure case |
| 536 | Common::ScopeGuard image_delete_guard{[&] { |
| 537 | image.Close(); |
| 538 | File::Delete(temp_image_path); |
| 539 | }}; |
| 540 | |
| 541 | if (!image.Resize(size)) |
| 542 | { |
| 543 | ERROR_LOG_FMT(COMMON, "Failed to allocate {} bytes for SD image at {}", size, image_path); |
| 544 | return false; |
| 545 | } |
| 546 | |
| 547 | MKFS_PARM options = {}; |
| 548 | options.fmt = FM_FAT32 | FM_SFD; |
| 549 | options.n_fat = 0; // Number of FATs: automatic |
| 550 | options.align = 1; // Alignment of the data region (in sectors) |
| 551 | options.n_root = 0; // Number of root directory entries: automatic (and unused for FAT32) |
| 552 | options.au_size = 0; // Cluster size: automatic |
| 553 | |
| 554 | std::vector<u8> tmp_buffer(MAX_CLUSTER_SIZE); |
| 555 | const auto mkfs_error_code = |
| 556 | f_mkfs("", &options, tmp_buffer.data(), static_cast<UINT>(tmp_buffer.size())); |
| 557 | if (mkfs_error_code != FR_OK) |
| 558 | { |
| 559 | ERROR_LOG_FMT(COMMON, "Failed to initialize SD image filesystem: {}", |
| 560 | FatFsErrorToString(mkfs_error_code)); |
| 561 | return false; |
| 562 | } |
| 563 | |
| 564 | FATFS fs{}; |
| 565 | const auto mount_error_code = f_mount(&fs, "", 0); |
| 566 | if (mount_error_code != FR_OK) |
| 567 | { |
| 568 | ERROR_LOG_FMT(COMMON, "Failed to mount SD image filesystem: {}", |
| 569 | FatFsErrorToString(mount_error_code)); |
| 570 | return false; |
| 571 | } |
| 572 | Common::ScopeGuard unmount_guard{[] { f_unmount(""); }}; |
| 573 | |
| 574 | if (!Pack(cancelled, root, true, tmp_buffer)) |
| 575 | { |
| 576 | ERROR_LOG_FMT(COMMON, "Failed to pack folder {} to SD image at {}", source_dir, |
| 577 | temp_image_path); |
| 578 | return false; |
| 579 | } |
| 580 | |
| 581 | unmount_guard.Exit(); // unmount before closing the image |
| 582 | |
| 583 | if (!image.Close()) |
| 584 | { |
| 585 | ERROR_LOG_FMT(COMMON, "Failed to close SD image at {}", temp_image_path); |
| 586 | return false; |
| 587 | } |
| 588 | |
| 589 | if (!File::Rename(temp_image_path, image_path)) |
| 590 | { |
| 591 | ERROR_LOG_FMT(COMMON, "Failed to rename SD image from {} to {}", temp_image_path, image_path); |
| 592 | return false; |
| 593 | } |
| 594 | |
| 595 | image_delete_guard.Dismiss(); // no need to delete the temp file anymore after the rename |
| 596 | |
| 597 | INFO_LOG_FMT(COMMON, "Successfully packed folder {} to SD image at {}", source_dir, image_path); |
| 598 | return true; |
| 599 | } |
| 600 | |
| 601 | static bool Unpack(const std::function<bool()>& cancelled, const std::string& path, |
| 602 | bool is_directory, const char* name, std::vector<u8>& tmp_buffer) |
| 603 | { |
| 604 | if (cancelled()) |
| 605 | return false; |
| 606 | |
| 607 | if (!is_directory) |
| 608 | { |
| 609 | FIL src{}; |
| 610 | const auto open_error_code = f_open(&src, name, FA_READ); |
| 611 | if (open_error_code != FR_OK) |
| 612 | { |
| 613 | ERROR_LOG_FMT(COMMON, "Failed to open file {} in SD image: {}", path, |
| 614 | FatFsErrorToString(open_error_code)); |
| 615 | return false; |
| 616 | } |
| 617 | |
| 618 | File::IOFile dst(path, "wb"); |
| 619 | if (!dst) |
| 620 | { |
| 621 | ERROR_LOG_FMT(COMMON, "Failed to open file {}", path); |
| 622 | return false; |
| 623 | } |
| 624 | |
| 625 | u32 size = f_size(&src); |
| 626 | while (size > 0) |
| 627 | { |
| 628 | if (cancelled()) |
| 629 | return false; |
| 630 | |
| 631 | u32 chunk_size = std::min(size, static_cast<u32>(tmp_buffer.size())); |
| 632 | u32 read_size; |
| 633 | const auto read_error_code = f_read(&src, tmp_buffer.data(), chunk_size, &read_size); |
| 634 | if (read_error_code != FR_OK) |
| 635 | { |
| 636 | ERROR_LOG_FMT(COMMON, "Failed to read from file {} in SD image: {}", path, |
| 637 | FatFsErrorToString(read_error_code)); |
| 638 | return false; |
| 639 | } |
| 640 | |
| 641 | if (read_size != chunk_size) |
| 642 | { |
| 643 | ERROR_LOG_FMT(COMMON, "Failed to read bytes of file {} in SD image ({} != {})", path, |
| 644 | read_size, chunk_size); |
| 645 | return false; |
| 646 | } |
| 647 | |
| 648 | if (!dst.WriteBytes(tmp_buffer.data(), chunk_size)) |
| 649 | { |
| 650 | ERROR_LOG_FMT(COMMON, "Failed to write to file {}", path); |
| 651 | return false; |
| 652 | } |
| 653 | |
| 654 | size -= chunk_size; |
| 655 | } |
| 656 | |
| 657 | if (!dst.Close()) |
| 658 | { |
| 659 | ERROR_LOG_FMT(COMMON, "Failed to close file {}", path); |
| 660 | return false; |
| 661 | } |
| 662 | |
| 663 | const auto close_error_code = f_close(&src); |
| 664 | if (close_error_code != FR_OK) |
| 665 | { |
| 666 | ERROR_LOG_FMT(COMMON, "Failed to close file {} in SD image: {}", path, |
| 667 | FatFsErrorToString(close_error_code)); |
| 668 | return false; |
| 669 | } |
| 670 | |
| 671 | return true; |
| 672 | } |
| 673 | |
| 674 | if (!File::CreateDir(path)) |
| 675 | { |
| 676 | ERROR_LOG_FMT(COMMON, "Failed to create directory {}", path); |
| 677 | return false; |
| 678 | } |
| 679 | |
| 680 | const auto chdir_error_code = f_chdir(name); |
| 681 | if (chdir_error_code != FR_OK) |
| 682 | { |
| 683 | ERROR_LOG_FMT(COMMON, "Failed to enter directory {} in SD image: {}", path, |
| 684 | FatFsErrorToString(chdir_error_code)); |
| 685 | return false; |
| 686 | } |
| 687 | |
| 688 | DIR directory{}; |
| 689 | const auto opendir_error_code = f_opendir(&directory, "."); |
| 690 | if (opendir_error_code != FR_OK) |
| 691 | { |
| 692 | ERROR_LOG_FMT(COMMON, "Failed to open directory {} in SD image: {}", path, |
| 693 | FatFsErrorToString(opendir_error_code)); |
| 694 | return false; |
| 695 | } |
| 696 | |
| 697 | FILINFO entry{}; |
| 698 | while (true) |
| 699 | { |
| 700 | const auto readdir_error_code = f_readdir(&directory, &entry); |
| 701 | if (readdir_error_code != FR_OK) |
| 702 | { |
| 703 | ERROR_LOG_FMT(COMMON, "Failed to read directory {} in SD image: {}", path, |
| 704 | FatFsErrorToString(readdir_error_code)); |
| 705 | return false; |
| 706 | } |
| 707 | |
| 708 | if (entry.fname[0] == '\0') |
| 709 | break; |
| 710 | |
| 711 | if (entry.fname[0] == '?' && entry.fname[1] == '\0' && entry.altname[0] == '\0') |
| 712 | { |
| 713 | // FATFS indicates entries that have neither a short nor a long filename this way. |
| 714 | // These are likely corrupted file entries so just skip them. |
| 715 | continue; |
| 716 | } |
| 717 | |
| 718 | const std::string_view childname = entry.fname; |
| 719 | |
| 720 | // Check for path traversal attacks. |
| 721 | const bool is_path_traversal_attack = |
| 722 | childname.contains('\\') || childname.contains('/') || |
| 723 | std::ranges::all_of(childname, [](char c) { return c == '.'; }); |
| 724 | if (is_path_traversal_attack) |
| 725 | { |
| 726 | ERROR_LOG_FMT( |
| 727 | COMMON, |
| 728 | "Path traversal attack detected in directory {} in SD image, child filename is {}", path, |
| 729 | childname); |
| 730 | return false; |
| 731 | } |
| 732 | |
| 733 | if (!Unpack(cancelled, fmt::format("{}/{}", path, childname), entry.fattrib & AM_DIR, |
| 734 | entry.fname, tmp_buffer)) |
| 735 | { |
| 736 | return false; |
| 737 | } |
| 738 | } |
| 739 | |
| 740 | const auto closedir_error_code = f_closedir(&directory); |
| 741 | if (closedir_error_code != FR_OK) |
| 742 | { |
| 743 | ERROR_LOG_FMT(COMMON, "Failed to close directory {} in SD image: {}", path, |
| 744 | FatFsErrorToString(closedir_error_code)); |
| 745 | return false; |
| 746 | } |
| 747 | |
| 748 | const auto chdir_up_error_code = f_chdir(".."); |
| 749 | if (chdir_up_error_code != FR_OK) |
| 750 | { |
| 751 | ERROR_LOG_FMT(COMMON, "Failed to leave directory {} in SD image: {}", path, |
| 752 | FatFsErrorToString(chdir_up_error_code)); |
| 753 | return false; |
| 754 | } |
| 755 | |
| 756 | return true; |
| 757 | } |
| 758 | |
| 759 | bool SyncSDImageToSDFolder(const std::function<bool()>& cancelled) |
| 760 | { |
| 761 | const std::string image_path = File::GetUserPath(F_WIISDCARDIMAGE_IDX); |
| 762 | const std::string target_dir = File::GetUserPath(D_WIISDCARDSYNCFOLDER_IDX); |
| 763 | if (image_path.empty() || target_dir.empty()) |
| 764 | return false; |
| 765 | |
| 766 | std::lock_guard lk(s_fatfs_mutex); |
| 767 | SDCardFatFsCallbacks callbacks; |
| 768 | s_callbacks = &callbacks; |
| 769 | Common::ScopeGuard callbacks_guard{[] { s_callbacks = nullptr; }}; |
| 770 | |
| 771 | INFO_LOG_FMT(COMMON, "Starting SD card conversion from file {} to folder {}", image_path, |
| 772 | target_dir); |
| 773 | |
| 774 | File::IOFile image; |
| 775 | callbacks.m_image = ℑ |
| 776 | |
| 777 | // this shouldn't matter since we're not modifying the SD image here, but initialize it to |
| 778 | // something consistent just in case |
| 779 | callbacks.m_deterministic = true; |
| 780 | |
| 781 | if (!image.Open(image_path, "r+b")) |
| 782 | { |
| 783 | ERROR_LOG_FMT(COMMON, "Failed to open SD image at {}", image_path); |
| 784 | return false; |
| 785 | } |
| 786 | |
| 787 | FATFS fs{}; |
| 788 | const auto mount_error_code = f_mount(&fs, "", 0); |
| 789 | if (mount_error_code != FR_OK) |
| 790 | { |
| 791 | ERROR_LOG_FMT(COMMON, "Failed to mount SD image file system: {}", |
| 792 | FatFsErrorToString(mount_error_code)); |
| 793 | return false; |
| 794 | } |
| 795 | Common::ScopeGuard unmount_guard{[] { f_unmount(""); }}; |
| 796 | |
| 797 | // Unpack() and GetTempFilenameForAtomicWrite() don't want the trailing separator. |
| 798 | const std::string target_dir_without_slash = target_dir.substr(0, target_dir.length() - 1); |
| 799 | |
| 800 | // Most systems don't offer atomic directory renaming, so it's simpler to directly work on the |
| 801 | // actual one and rollback if needed. |
| 802 | const bool target_dir_exists = File::IsDirectory(target_dir); |
| 803 | const std::string backup_target_dir_without_slash = |
| 804 | File::GetTempFilenameForAtomicWrite(target_dir_without_slash); |
| 805 | |
| 806 | if (target_dir_exists) |
| 807 | { |
| 808 | if (!File::Rename(target_dir_without_slash, backup_target_dir_without_slash)) |
| 809 | { |
| 810 | ERROR_LOG_FMT(COMMON, "Failed to move old SD folder to {}", backup_target_dir_without_slash); |
| 811 | return false; |
| 812 | } |
| 813 | } |
| 814 | |
| 815 | std::vector<u8> tmp_buffer(MAX_CLUSTER_SIZE); |
| 816 | if (!Unpack(cancelled, target_dir_without_slash, true, "", tmp_buffer)) |
| 817 | { |
| 818 | ERROR_LOG_FMT(COMMON, "Failed to unpack SD image {} to {}", image_path, target_dir); |
| 819 | File::DeleteDirRecursively(target_dir_without_slash); |
| 820 | if (target_dir_exists) |
| 821 | File::Rename(backup_target_dir_without_slash, target_dir_without_slash); |
| 822 | return false; |
| 823 | } |
| 824 | |
| 825 | unmount_guard.Exit(); // unmount before closing the image |
| 826 | |
| 827 | if (target_dir_exists) |
| 828 | File::DeleteDirRecursively(backup_target_dir_without_slash); |
| 829 | |
| 830 | // even if this fails the conversion has already succeeded, so we still return true |
| 831 | if (!image.Close()) |
| 832 | ERROR_LOG_FMT(COMMON, "Failed to close SD image {}", image_path); |
| 833 | |
| 834 | INFO_LOG_FMT(COMMON, "Successfully unpacked SD image {} to {}", image_path, target_dir); |
| 835 | return true; |
| 836 | } |
| 837 | |
| 838 | void RunInFatFsContext(FatFsCallbacks& callbacks, const std::function<void()>& function) |
| 839 | { |
| 840 | std::lock_guard lk(s_fatfs_mutex); |
| 841 | s_callbacks = &callbacks; |
| 842 | Common::ScopeGuard callbacks_guard{[] { s_callbacks = nullptr; }}; |
| 843 | function(); |
| 844 | } |
| 845 | } // namespace Common |