Files
RetroArch/tasks/task_core_backup.c
davey 349a3ae780 core signatures: the last loaded core passes its reload until another core loads
The core loaded last keeps its pass after the unload, so its reload
after Close Content and menu or driver init pass without another hash
or warning. Where a file's identity can't bind the pass (Windows, and
Linux filesystems that don't keep ctime), its checked file stays open
to bind it. Loading another core ends the pass. So do the Core
Updater, Core Manager delete and core restore: on the main thread,
before they replace or delete a core file, they close every core file
the check keeps open for a pass or a refusal.
2026-11-16 07:12:21 +01:00

2226 lines
80 KiB
C

/* RetroArch - A frontend for libretro.
* Copyright (C) 2011-2017 - Daniel De Matteis
* Copyright (C) 2014-2017 - Jean-André Santoni
* Copyright (C) 2016-2019 - Brad Parker
* Copyright (C) 2019-2020 - James Leaver
*
* RetroArch is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Found-
* ation, either version 3 of the License, or (at your option) any later version.
*
* RetroArch is distributed in the hope that 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 RetroArch.
* If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <boolean.h>
#include <string/stdstring.h>
#include <file/file_path.h>
#include <streams/interface_stream.h>
#include <streams/file_stream.h>
#include <streams/rzip_stream.h>
#include "../retroarch.h"
#include "../paths.h"
#include "../command.h"
#include "../msg_hash.h"
#include "../verbosity.h"
#include "../core_info.h"
#include "../core_backup.h"
#include "tasks_internal.h"
#ifdef HAVE_CORE_LOAD_CHECK
#include "../core_load_check.h"
#endif
#ifdef HAVE_CORE_SIGNATURES
#include "../core_install_check.h"
#include "../core_trust_runtime.h"
#endif
#if defined(RARCH_INTERNAL) && defined(HAVE_MENU)
#include "../menu/menu_driver.h"
#endif
#if defined(ANDROID)
#include "../os/android/play_feature_delivery.h"
#endif
/* A low common denominator transfer quantum. On a slow (speed class
6) SD card we can write 6MB/s, which is roughly 100KB/frame, so a
single quantum is one syscall that fits inside one frame even on
the worst storage we support.
This is the size of one read/write call, NOT the amount of work a
tick may do. Tying the two together at 4096 bytes caps a backup
or restore at CORE_BACKUP_CHUNK_SIZE *
tick_rate == ~245KB/s regardless of the device: measured here, a
4MB core takes 1029 ticks at 4076 bytes each, i.e. 17.2s at 60Hz
to copy a file the same machine moves in well under a second. Cores
in the tens of megabytes are ordinary (mame, dolphin, ppsspp) and
an automatic backup runs on every core update, so this was the
common path rather than a corner.
The tick budget below is what bounds a tick now; the quantum only
bounds how far the handler can overshoot it, which is why it stays
sized for the slowest device rather than the fastest. Same shape
as SAVE_STATE_CHUNK in tasks/task_save.c. */
#define CORE_BACKUP_CHUNK_SIZE (100 * 1024)
/* Every CRC step and every transfer quantum of a backup or restore is
a work item of the shared per-frame I/O window (task_nbio_slice_*),
so a backup shares one frame's I/O allowance with every other
budgeted task instead of carrying a deadline of its own. The
window's floor grants one item per tick, so a device slow enough
that one quantum exceeds the window still makes progress, exactly
as when a tick was hardcoded to one quantum. */
/* Bytes hashed per step. Matches the read size inside
intfstream_crc_step(). */
#define CORE_BACKUP_CRC_CHUNK (256 * 1024)
enum core_backup_status
{
CORE_BACKUP_BEGIN = 0,
CORE_BACKUP_CHECK_CRC,
CORE_BACKUP_PRE_ITERATE,
CORE_BACKUP_ITERATE,
CORE_BACKUP_CHECK_HISTORY,
CORE_BACKUP_PRUNE_HISTORY,
CORE_BACKUP_END,
CORE_RESTORE_GET_CORE_CRC,
CORE_RESTORE_GET_BACKUP_CRC,
CORE_RESTORE_CHECK_CRC,
CORE_RESTORE_PRE_ITERATE,
CORE_RESTORE_ITERATE,
CORE_RESTORE_CHECK,
CORE_RESTORE_END
};
#ifdef HAVE_CORE_SIGNATURES
/* How a checked restore ended, for its callback on the main thread */
enum core_restore_outcome
{
CORE_RESTORE_OUTCOME_NONE = 0,
CORE_RESTORE_OUTCOME_INSTALLED,
CORE_RESTORE_OUTCOME_TRUSTED,
CORE_RESTORE_OUTCOME_WARN
};
#endif
typedef struct core_backup_handle
{
int64_t core_file_size;
int64_t backup_file_size;
int64_t file_data_read;
char *dir_core_assets;
char *core_path;
char *core_name;
char *backup_path;
/* Restore only: the file the core is written to - core_path with
* any symbolic link resolved - and the temporary beside it that
* the restore writes and then renames over it */
char *core_target_path;
char *core_tmp_path;
/* Install mode only: the new core, extracted beside core_path,
* which this task moves into place once the old core is backed up
* (task_push_core_backup_install()) */
char *staged_path;
intfstream_t *core_file;
intfstream_t *backup_file;
/* A copy that needs no decoding or encoding - restoring an
* uncompressed backup, or backing up where backups are not
* compressed - goes through the VFS copy instead of the two
* streams: the platform's own primitive, so on Linux and APFS no
* byte passes through the transfer buffer. NULL otherwise. */
struct retro_vfs_copy_handle *copy;
/* Transfer buffer, allocated once. CORE_BACKUP_CHUNK_SIZE is far
* too large to sit on the stack of a task handler, which may be
* running on the task thread. */
uint8_t *buffer;
/* Resumable CRC accumulator, so hashing a core is spread across
* ticks instead of consuming a whole stream in one call. */
uint32_t crc_accumulator;
bool crc_active;
/* Install mode: staged_path has been moved over core_path */
bool installed;
core_backup_list_t *backup_list;
/* The pusher's completion callback, chained from
* cb_task_core_backup() */
retro_task_callback_t done_cb;
size_t auto_backup_history_size;
size_t num_auto_backups_to_remove;
size_t backup_index;
uint32_t core_crc;
uint32_t backup_crc;
enum core_backup_type backup_type;
enum core_backup_mode backup_mode;
enum core_backup_status status;
bool crc_match;
bool success;
#ifdef HAVE_CORE_SIGNATURES
/* A checked restore: the store as the push saw it (NULL: today's
* restore), the folder it stages in, and for Install and Trust the
* check the user was warned about */
core_trust_set_t *trust;
struct core_check *warned;
char *dir_libretro;
char *staging_dir;
struct core_install_check check;
enum core_restore_outcome outcome;
bool check_begun;
bool own_backup;
#endif
} core_backup_handle_t;
/*********************/
/* Utility functions */
/*********************/
/* Closes the files and drops the buffers a finished task no longer
* needs. Done by the handler as it finishes, so the callback (a
* restore reloads core info from the file just written) sees them
* closed; the strings stay until cleanup, since finders read
* core_path for as long as the task is findable. */
static void core_backup_handle_release_io(core_backup_handle_t *backup_handle)
{
/* Cancels a copy still running and removes its partial file */
if (backup_handle->copy)
{
filestream_copy_close(backup_handle->copy);
backup_handle->copy = NULL;
}
if (backup_handle->core_file)
{
intfstream_close(backup_handle->core_file);
free(backup_handle->core_file);
backup_handle->core_file = NULL;
}
if (backup_handle->backup_file)
{
intfstream_close(backup_handle->backup_file);
free(backup_handle->backup_file);
backup_handle->backup_file = NULL;
}
if (backup_handle->backup_list)
{
core_backup_list_free(backup_handle->backup_list);
backup_handle->backup_list = NULL;
}
if (backup_handle->buffer)
{
free(backup_handle->buffer);
backup_handle->buffer = NULL;
}
}
/* Bytes offered to one step of the copy; the I/O window decides how
* many steps a tick gets. */
#define CORE_BACKUP_COPY_STEP (1024 * 1024)
/* Runs @backup_handle's copy while the shared I/O window allows.
* Returns RETRO_VFS_COPY_RUNNING to come back next tick, otherwise
* DONE or FAILED with the handle closed. */
static int core_backup_copy_run(core_backup_handle_t *backup_handle)
{
int status = RETRO_VFS_COPY_RUNNING;
int64_t done = 0;
nbio_budget_t budget;
task_nbio_slice_open(&budget);
while ( status == RETRO_VFS_COPY_RUNNING
&& task_nbio_slice_within_budget(&budget, 0, 0))
status = filestream_copy_step(backup_handle->copy,
CORE_BACKUP_COPY_STEP, &done, NULL);
task_nbio_slice_close(&budget);
backup_handle->file_data_read = done;
if (status == RETRO_VFS_COPY_RUNNING)
return status;
if (filestream_copy_close(backup_handle->copy) != 0)
status = RETRO_VFS_COPY_FAILED;
backup_handle->copy = NULL;
return status;
}
static void free_core_backup_handle(core_backup_handle_t *backup_handle)
{
if (!backup_handle)
return;
if (backup_handle->dir_core_assets)
{
free(backup_handle->dir_core_assets);
backup_handle->dir_core_assets = NULL;
}
if (backup_handle->core_path)
{
free(backup_handle->core_path);
backup_handle->core_path = NULL;
}
if (backup_handle->core_name)
{
free(backup_handle->core_name);
backup_handle->core_name = NULL;
}
if (backup_handle->backup_path)
{
free(backup_handle->backup_path);
backup_handle->backup_path = NULL;
}
free(backup_handle->core_target_path);
backup_handle->core_target_path = NULL;
free(backup_handle->core_tmp_path);
backup_handle->core_tmp_path = NULL;
free(backup_handle->staged_path);
backup_handle->staged_path = NULL;
#ifdef HAVE_CORE_SIGNATURES
core_install_check_free(&backup_handle->check);
if (backup_handle->trust)
core_trust_set_put(backup_handle->trust);
free(backup_handle->warned);
free(backup_handle->dir_libretro);
free(backup_handle->staging_dir);
#endif
core_backup_handle_release_io(backup_handle);
free(backup_handle);
backup_handle = NULL;
}
/* The restore writes a temporary beside the core and renames it over
* the core only once every byte is written, so a restore that fails
* part-way - a write error, a full disk, the task cancelled on quit -
* leaves the installed core intact instead of truncated. The rename
* swaps the directory entry, so a core reached through a symbolic link
* is resolved first: the link stays and the file it points to is
* replaced, as a write through the link did before. When resolution
* is unavailable or fails, the path is used as given. Heap buffers:
* the handler may run on the task thread's small stack. */
static bool core_restore_set_write_paths(core_backup_handle_t *backup_handle)
{
size_t _len;
if (!(backup_handle->core_target_path = (char*)malloc(PATH_MAX_LENGTH)))
return false;
strlcpy(backup_handle->core_target_path, backup_handle->core_path,
PATH_MAX_LENGTH);
path_resolve_realpath(backup_handle->core_target_path,
PATH_MAX_LENGTH, true);
_len = strlen(backup_handle->core_target_path);
if (!(backup_handle->core_tmp_path = (char*)malloc(
_len + sizeof(".tmp"))))
return false;
memcpy(backup_handle->core_tmp_path,
backup_handle->core_target_path, _len);
memcpy(backup_handle->core_tmp_path + _len, ".tmp", sizeof(".tmp"));
return true;
}
#if defined(ANDROID)
static bool core_restore_pfd_installed(
const core_backup_handle_t *backup_handle)
{
return play_feature_delivery_enabled()
&& play_feature_delivery_core_installed(
path_basename(backup_handle->core_path));
}
/* A Play Store build deletes a core installed through play feature
* delivery before replacing it. False, the task's error set, when it
* can't. */
static bool core_restore_pfd_delete(retro_task_t *task,
core_backup_handle_t *backup_handle)
{
if ( core_restore_pfd_installed(backup_handle)
&& !play_feature_delivery_delete(
path_basename(backup_handle->core_path)))
{
RARCH_ERR("[Core Restore] Failed to delete existing play feature delivery core: \"%s\".\n",
backup_handle->core_path);
task_free_error(task);
task_set_error(task, strdup("Failed to delete existing play feature delivery core."));
return false;
}
return true;
}
#endif
#ifdef HAVE_CORE_SIGNATURES
/* A checked restore's own folder beside the file it replaces, apart
* from the updater's .staging */
#define CORE_RESTORE_STAGING_EXT ".restore"
/* A checked restore writes the core under its own name, so its .sig's
* name matches, into .<core>.restore beside the file it replaces */
static bool core_restore_set_staged_paths(core_backup_handle_t *backup_handle)
{
size_t _len;
char *buf;
char *leaf;
const char *name = path_basename_nocompression(backup_handle->core_path);
#if defined(ANDROID)
/* A Play-installed core links into the read-only APK and is deleted
* only once this one passes: staged beside the link it replaces */
if (core_restore_pfd_installed(backup_handle))
{
if (!(backup_handle->core_target_path =
strdup(backup_handle->core_path)))
return false;
}
else
#endif
if (!core_restore_set_write_paths(backup_handle))
return false;
free(backup_handle->core_tmp_path);
backup_handle->core_tmp_path = NULL;
/* A link to a file of another name can't be checked as this core */
if (!string_is_equal(path_basename_nocompression(
backup_handle->core_target_path), name))
{
RARCH_ERR("[Core Restore] Cannot check \"%s\": it links to a file of another name.\n",
backup_handle->core_path);
return false;
}
if (!(buf = (char*)malloc(2 * PATH_MAX_LENGTH)))
return false;
leaf = buf + PATH_MAX_LENGTH;
leaf[0] = '.';
_len = 1 + strlcpy(leaf + 1, name, PATH_MAX_LENGTH - 1);
if (_len >= PATH_MAX_LENGTH)
{
free(buf);
return false;
}
strlcpy(leaf + _len, CORE_RESTORE_STAGING_EXT, PATH_MAX_LENGTH - _len);
fill_pathname_parent_dir(buf, backup_handle->core_target_path,
PATH_MAX_LENGTH);
if ((backup_handle->staging_dir = (char*)malloc(PATH_MAX_LENGTH)))
{
fill_pathname_join_special(backup_handle->staging_dir, buf, leaf,
PATH_MAX_LENGTH);
if ((backup_handle->core_tmp_path = (char*)malloc(PATH_MAX_LENGTH)))
fill_pathname_join_special(backup_handle->core_tmp_path,
backup_handle->staging_dir, name, PATH_MAX_LENGTH);
}
free(buf);
return backup_handle->core_tmp_path
&& path_mkdir(backup_handle->staging_dir);
}
#endif
/* Runs at retirement, on the thread that retires the queue, after the
* callback and once the task can no longer be found: the first point
* at which no finder can still be reading task->state. */
static void task_core_backup_cleanup(retro_task_t *task)
{
free_core_backup_handle((core_backup_handle_t*)task->state);
task->state = NULL;
}
/* Forward declarations, required for task_core_backup_finder() */
static void task_core_backup_handler(retro_task_t *task);
/* The backup task's callback: the main thread, at retrieval. Menu
* flags are a plain read-modify-write, so every writer must be
* here, racing nothing - never in the handler on the worker. */
static void cb_task_core_backup(
retro_task_t *task, void *task_data,
void *user_data, const char *err)
{
/* Still attached: task_core_backup_cleanup() runs after this */
core_backup_handle_t *backup_handle = (core_backup_handle_t*)task->state;
#ifdef HAVE_MENU
struct menu_state *menu_st = menu_state_get_ptr();
if (menu_st)
menu_st->flags |= MENU_ST_FLAG_ENTRIES_NEED_REFRESH
| MENU_ST_FLAG_PREVENT_POPULATE;
#endif
if (backup_handle && backup_handle->done_cb)
backup_handle->done_cb(task, task_data, user_data, err);
}
static void task_core_restore_handler(retro_task_t *task);
static bool task_core_backup_finder(retro_task_t *task, void *user_data)
{
core_backup_handle_t *backup_handle = NULL;
const char *core_filename_a = NULL;
const char *core_filename_b = NULL;
if (!task || !user_data)
return false;
if ( (task->handler != task_core_backup_handler)
&& (task->handler != task_core_restore_handler))
return false;
/* A finished backup or restore has done its file work, though it
* stays in the queue until its callback has run: a second one of
* the same core pushed meanwhile was refused without a word. Passed
* over before its handle is read, which may already be gone. */
if (task_get_flags(task) & RETRO_TASK_FLG_FINISHED)
return false;
backup_handle = (core_backup_handle_t*)task->state;
if (!backup_handle)
return false;
if (!backup_handle->core_path || !*backup_handle->core_path)
return false;
core_filename_a = path_basename((const char*)user_data);
core_filename_b = path_basename(backup_handle->core_path);
if ( (!core_filename_a || !*core_filename_a)
|| (!core_filename_b || !*core_filename_b))
return false;
return string_is_equal(core_filename_a, core_filename_b);
}
/* Concurrent backup/restore tasks for the same core are not allowed:
* true when one is running, and the user is told rather than the
* Backup or Restore entry doing nothing. */
static bool task_core_backup_busy(const char *core_path)
{
task_finder_data_t find_data;
find_data.func = task_core_backup_finder;
find_data.userdata = (void*)core_path;
if (task_queue_find(&find_data))
{
char msg[128];
size_t _len = strlcpy(msg,
msg_hash_to_str(MSG_CORE_BACKUP_IN_PROGRESS), sizeof(msg));
strlcpy(msg + _len, path_basename(core_path), sizeof(msg) - _len);
RARCH_LOG("[Core Backup] %s\n", msg);
runloop_msg_queue_push(msg, strlen(msg), 1, 100, true, NULL,
MESSAGE_QUEUE_ICON_DEFAULT, MESSAGE_QUEUE_CATEGORY_INFO);
return true;
}
return false;
}
/***************/
/* Core Backup */
/***************/
static void task_core_backup_handler(retro_task_t *task)
{
uint8_t flg;
core_backup_handle_t *backup_handle = NULL;
if (!task)
goto task_finished;
backup_handle = (core_backup_handle_t*)task->state;
flg = task_get_flags(task);
if (!backup_handle || ((flg & RETRO_TASK_FLG_CANCELLED) > 0))
goto task_finished;
switch (backup_handle->status)
{
case CORE_BACKUP_BEGIN:
/* Get current list of backups */
backup_handle->backup_list = core_backup_list_init(
backup_handle->core_path, backup_handle->dir_core_assets);
/* Open core file */
backup_handle->core_file = intfstream_open_file(
backup_handle->core_path,
RETRO_VFS_FILE_ACCESS_READ,
RETRO_VFS_FILE_ACCESS_HINT_SEQUENTIAL_BULK);
if (!backup_handle->core_file)
{
RARCH_ERR("[Core Backup] Failed to open core file: \"%s\".\n",
backup_handle->core_path);
task_free_error(task);
task_set_error(task, strdup("Failed to open core file."));
backup_handle->status = CORE_BACKUP_END;
break;
}
/* Get core file size */
backup_handle->core_file_size = intfstream_get_size(backup_handle->core_file);
if (backup_handle->core_file_size <= 0)
{
RARCH_ERR("[Core Backup] Core file is empty/invalid: \"%s\".\n",
backup_handle->core_path);
task_free_error(task);
task_set_error(task, strdup("Core file is empty/invalid."));
backup_handle->status = CORE_BACKUP_END;
break;
}
/* Go to CRC checking phase */
backup_handle->status = CORE_BACKUP_CHECK_CRC;
break;
case CORE_BACKUP_CHECK_CRC:
/* Check whether we need to calculate CRC value */
if (backup_handle->core_crc == 0)
{
/* Hash a bounded slice per tick and stay in this state
* until done. intfstream_get_crc() consumes the whole
* stream in one call, so the cost of the tick that
* invoked it was a function of core size and nothing
* else -- 43ms for a 40MB core measured cold on NVMe,
* an order of magnitude worse on the SD-card and
* spinning-disk targets, and an automatic backup runs on
* every core update. Same treatment
* tasks/task_core_updater.c already applies. */
int64_t hashed = 1;
nbio_budget_t budget;
if (!backup_handle->crc_active)
{
backup_handle->crc_accumulator = 0;
backup_handle->crc_active = true;
intfstream_rewind(backup_handle->core_file);
}
task_nbio_slice_open(&budget);
while (task_nbio_slice_within_budget(&budget, 0, 0))
{
hashed = intfstream_crc_step(backup_handle->core_file,
&backup_handle->crc_accumulator,
CORE_BACKUP_CRC_CHUNK);
if (hashed < 0)
{
RARCH_ERR("[Core Backup] Failed to determine CRC of core file: \"%s\".\n",
backup_handle->core_path);
task_free_error(task);
task_set_error(task, strdup("Failed to determine CRC of core file."));
backup_handle->crc_active = false;
backup_handle->status = CORE_BACKUP_END;
task_nbio_slice_close(&budget);
return;
}
if (hashed == 0)
break;
}
task_nbio_slice_close(&budget);
/* Not finished: resume on the next tick. */
if (hashed > 0)
break;
backup_handle->core_crc = backup_handle->crc_accumulator;
backup_handle->crc_active = false;
/* Rewind: CORE_BACKUP_ITERATE copies from this same
* handle, and intfstream_get_crc() -- which this
* replaced -- rewound on the way out as well as on the
* way in. Without this the transfer phase starts at EOF
* and writes an empty backup. */
intfstream_rewind(backup_handle->core_file);
}
/* Check whether a backup with this CRC already
* exists */
if (backup_handle->backup_list)
{
const core_backup_list_entry_t *entry = NULL;
if (core_backup_list_get_crc(
backup_handle->backup_list,
backup_handle->core_crc,
backup_handle->backup_mode,
&entry))
{
RARCH_LOG("[Core Backup] Current version of core is already backed up: \"%s\".\n",
entry->backup_path);
backup_handle->crc_match = true;
backup_handle->success = true;
backup_handle->status = CORE_BACKUP_END;
break;
}
}
/* Go to pre-iteration phase */
backup_handle->status = CORE_BACKUP_PRE_ITERATE;
break;
case CORE_BACKUP_PRE_ITERATE:
{
size_t _len;
char task_title[128];
char backup_path[PATH_MAX_LENGTH];
backup_path[0] = '\0';
/* Get backup path */
if (!core_backup_get_backup_path(
backup_handle->core_path,
backup_handle->core_crc,
backup_handle->backup_mode,
backup_handle->dir_core_assets,
backup_path, sizeof(backup_path)))
{
RARCH_ERR("[Core Backup] Failed to generate backup path for core file: \"%s\".\n",
backup_handle->core_path);
task_free_error(task);
task_set_error(task, strdup("Failed to open core backup file."));
backup_handle->status = CORE_BACKUP_END;
break;
}
backup_handle->backup_path = strdup(backup_path);
/* Install mode: the old core is about to be replaced, so it
* becomes the backup as it is - moved, not read, compressed
* and written. The rzip reader takes an uncompressed file
* as it stands, and the CRC is in the name. Only if either
* move fails is the old core put back and copied below. */
if (backup_handle->staged_path)
{
/* An open file cannot be renamed everywhere */
if (backup_handle->core_file)
{
intfstream_close(backup_handle->core_file);
free(backup_handle->core_file);
backup_handle->core_file = NULL;
}
if (filestream_rename(backup_handle->core_path,
backup_handle->backup_path) == 0)
{
bool moved;
#ifdef HAVE_CORE_SIGNATURES
/* The replaced core's .sig goes with it, and is set
* aside before the new core goes in, so a crash never
* leaves it beside the new one */
core_install_copy_sig(backup_handle->core_path,
backup_handle->backup_path);
core_install_set_aside_sig(backup_handle->core_path);
#endif
moved = filestream_rename(backup_handle->staged_path,
backup_handle->core_path) == 0;
#ifdef HAVE_CORE_SIGNATURES
core_install_end_aside_sig(backup_handle->core_path,
moved);
/* The copy below takes it again once it is done */
if (!moved)
core_install_drop_sig(backup_handle->backup_path);
#endif
if (moved)
{
backup_handle->installed = true;
backup_handle->success = true;
backup_handle->status =
(backup_handle->backup_mode == CORE_BACKUP_MODE_AUTO)
? CORE_BACKUP_CHECK_HISTORY : CORE_BACKUP_END;
break;
}
filestream_rename(backup_handle->backup_path,
backup_handle->core_path);
}
RARCH_LOG("[Core Backup] Cannot move \"%s\" into the backups; copying it instead.\n",
backup_handle->core_path);
if (!(backup_handle->core_file = intfstream_open_file(
backup_handle->core_path,
RETRO_VFS_FILE_ACCESS_READ,
RETRO_VFS_FILE_ACCESS_HINT_SEQUENTIAL_BULK)))
{
backup_handle->status = CORE_BACKUP_END;
break;
}
}
/* Open backup file */
#if defined(HAVE_COMPRESSION)
backup_handle->backup_file = intfstream_open_rzip_file(
backup_handle->backup_path, RETRO_VFS_FILE_ACCESS_WRITE);
#else
/* An uncompressed backup is a plain copy of the core */
if ((backup_handle->copy = filestream_copy_begin(
backup_handle->core_path, backup_handle->backup_path,
RETRO_VFS_COPY_OVERWRITE)))
{
if (backup_handle->core_file)
{
intfstream_close(backup_handle->core_file);
free(backup_handle->core_file);
backup_handle->core_file = NULL;
}
}
else
backup_handle->backup_file = intfstream_open_file(
backup_handle->backup_path, RETRO_VFS_FILE_ACCESS_WRITE,
RETRO_VFS_FILE_ACCESS_HINT_SEQUENTIAL_BULK);
#endif
if (!backup_handle->backup_file && !backup_handle->copy)
{
RARCH_ERR("[Core Backup] Failed to open core backup file: \"%s\".\n",
backup_handle->backup_path);
task_free_error(task);
task_set_error(task, strdup("Failed to open core backup file."));
backup_handle->status = CORE_BACKUP_END;
break;
}
/* Update task title */
task_free_title(task);
_len = strlcpy(task_title, msg_hash_to_str(MSG_BACKING_UP_CORE),
sizeof(task_title));
strlcpy(task_title + _len,
backup_handle->core_name,
sizeof(task_title) - _len);
task_set_title(task, strdup(task_title));
/* Go to iteration phase */
backup_handle->status = CORE_BACKUP_ITERATE;
}
break;
case CORE_BACKUP_ITERATE:
{
int64_t data_written = 0;
int64_t data_read = 0;
nbio_budget_t budget;
bool failed_read = false;
bool failed_write = false;
if (backup_handle->copy)
{
int status = core_backup_copy_run(backup_handle);
if (status == RETRO_VFS_COPY_FAILED)
{
RARCH_ERR("[Core Backup] Failed to copy core file: \"%s\".\n",
backup_handle->core_path);
task_free_error(task);
task_set_error(task, strdup("Failed to write to core backup file."));
backup_handle->status = CORE_BACKUP_END;
}
else if (status == RETRO_VFS_COPY_DONE)
{
backup_handle->success = true;
#ifdef HAVE_CORE_SIGNATURES
core_install_copy_sig(backup_handle->core_path,
backup_handle->backup_path);
#endif
backup_handle->status = (backup_handle->backup_mode ==
CORE_BACKUP_MODE_AUTO) ?
CORE_BACKUP_CHECK_HISTORY : CORE_BACKUP_END;
}
else
task_set_progress(task, (int8_t)((backup_handle->file_data_read * 100)
/ backup_handle->core_file_size));
break;
}
if (!backup_handle->buffer)
{
if (!(backup_handle->buffer = (uint8_t*)malloc(
CORE_BACKUP_CHUNK_SIZE)))
{
RARCH_ERR("[Core Backup] Failed to allocate transfer buffer.\n");
task_free_error(task);
task_set_error(task, strdup("Failed to allocate transfer buffer."));
backup_handle->status = CORE_BACKUP_END;
break;
}
}
/* Transfer quanta while the shared I/O window allows */
task_nbio_slice_open(&budget);
while (task_nbio_slice_within_budget(&budget, 0, 0))
{
data_read = intfstream_read(backup_handle->core_file,
backup_handle->buffer, CORE_BACKUP_CHUNK_SIZE);
if (data_read < 0)
{
failed_read = true;
break;
}
backup_handle->file_data_read += data_read;
if (data_read == 0)
break;
data_written = intfstream_write(backup_handle->backup_file,
backup_handle->buffer, data_read);
if (data_written != data_read)
{
failed_write = true;
break;
}
}
task_nbio_slice_close(&budget);
if (failed_read)
{
RARCH_ERR("[Core Backup] Failed to read from core file: \"%s\".\n",
backup_handle->core_path);
task_free_error(task);
task_set_error(task, strdup("Failed to read from core file."));
backup_handle->status = CORE_BACKUP_END;
break;
}
if (failed_write)
{
RARCH_ERR("[Core Backup] Failed to write to core backup file: \"%s\".\n",
backup_handle->backup_path);
task_free_error(task);
task_set_error(task, strdup("Failed to write to core backup file."));
backup_handle->status = CORE_BACKUP_END;
break;
}
/* Check whether we have reached the end of the file */
if (data_read == 0)
{
/* Close core file */
intfstream_close(backup_handle->core_file);
free(backup_handle->core_file);
backup_handle->core_file = NULL;
/* Close backup file */
intfstream_flush(backup_handle->backup_file);
intfstream_close(backup_handle->backup_file);
free(backup_handle->backup_file);
backup_handle->backup_file = NULL;
backup_handle->success = true;
#ifdef HAVE_CORE_SIGNATURES
core_install_copy_sig(backup_handle->core_path,
backup_handle->backup_path);
#endif
/* If this is an automatic backup, check whether
* any old backup files should be deleted.
* In all other cases, backup is complete */
backup_handle->status = (backup_handle->backup_mode ==
CORE_BACKUP_MODE_AUTO) ?
CORE_BACKUP_CHECK_HISTORY : CORE_BACKUP_END;
break;
}
/* Update progress display */
task_set_progress(task,
(int8_t)((backup_handle->file_data_read * 100) / backup_handle->core_file_size));
}
break;
case CORE_BACKUP_CHECK_HISTORY:
{
size_t num_backups;
/* Sanity check: We can only reach this stage
* when performing automatic backups, but verify
* that this is true (i.e. don't inadvertently
* delete backups of the wrong type if someone
* edits the CORE_BACKUP_ITERATE case statement...) */
if (backup_handle->backup_mode != CORE_BACKUP_MODE_AUTO)
{
backup_handle->status = CORE_BACKUP_END;
break;
}
/* This is an automated backup
* > Fetch number of existing auto backups
* in the list
* > If we reach this stage then a new backup
* has been created successfully -> increment
* count by one */
num_backups = core_backup_list_get_num_backups(
backup_handle->backup_list,
CORE_BACKUP_MODE_AUTO);
num_backups++;
/* Check whether we have exceeded the backup
* history size limit */
if (num_backups > backup_handle->auto_backup_history_size)
{
size_t _len;
char task_title[128];
/* Get number of old backups to remove */
backup_handle->num_auto_backups_to_remove = num_backups -
backup_handle->auto_backup_history_size;
/* Update task title */
task_free_title(task);
_len = strlcpy(task_title,
msg_hash_to_str(MSG_PRUNING_CORE_BACKUP_HISTORY),
sizeof(task_title));
strlcpy(task_title + _len,
backup_handle->core_name,
sizeof(task_title) - _len);
task_set_title(task, strdup(task_title));
/* Go to history clean-up phase */
backup_handle->status = CORE_BACKUP_PRUNE_HISTORY;
}
/* No backups to remove - task is complete */
else
backup_handle->status = CORE_BACKUP_END;
}
break;
case CORE_BACKUP_PRUNE_HISTORY:
{
size_t list_size = core_backup_list_size(backup_handle->backup_list);
/* The core backup list is automatically sorted
* by timestamp - simply loop from start to end
* and delete automatic backups until the required
* number have been removed */
while ( (backup_handle->backup_index < list_size)
&& (backup_handle->num_auto_backups_to_remove > 0))
{
const core_backup_list_entry_t *entry = NULL;
if (core_backup_list_get_index(
backup_handle->backup_list,
backup_handle->backup_index,
&entry)
&& entry
&& (entry->backup_mode == CORE_BACKUP_MODE_AUTO))
{
/* Delete backup file (if it exists) */
if (path_is_valid(entry->backup_path))
filestream_delete(entry->backup_path);
#ifdef HAVE_CORE_SIGNATURES
core_install_drop_sig(entry->backup_path);
#endif
backup_handle->num_auto_backups_to_remove--;
backup_handle->backup_index++;
/* Break here - only remove one file per
* iteration of the task */
break;
}
backup_handle->backup_index++;
}
/* Check whether all old backups have been
* removed (also handle error conditions by
* ensuring we quit if end of backup list is
* reached...) */
if ((backup_handle->num_auto_backups_to_remove < 1) ||
(backup_handle->backup_index >= list_size))
backup_handle->status = CORE_BACKUP_END;
}
break;
case CORE_BACKUP_END:
{
size_t _len;
char task_title[128];
/* Install mode: the new core goes in whatever happened to
* the backup - an identical backup already existing, the
* copy, or no backup at all - unless the task was
* cancelled. Here the task's error means the install
* failed, and nothing else. */
if (backup_handle->staged_path && !backup_handle->installed)
{
bool cancelled = (task_get_flags(task)
& RETRO_TASK_FLG_CANCELLED) > 0;
core_backup_handle_release_io(backup_handle);
task_free_error(task);
#ifdef HAVE_CORE_SIGNATURES
/* Set aside, as in the move */
if (!cancelled)
core_install_set_aside_sig(backup_handle->core_path);
#endif
if ( !cancelled
&& filestream_rename(backup_handle->staged_path,
backup_handle->core_path) == 0)
backup_handle->installed = true;
else
{
RARCH_ERR("[Core Backup] Failed to install core: \"%s\".\n",
backup_handle->core_path);
task_set_error(task, strdup("Failed to install core."));
}
#ifdef HAVE_CORE_SIGNATURES
if (!cancelled)
core_install_end_aside_sig(backup_handle->core_path,
backup_handle->installed);
#endif
}
else if (backup_handle->staged_path)
task_free_error(task);
/* Set final task title */
task_free_title(task);
if (backup_handle->success)
{
if (backup_handle->crc_match)
_len = strlcpy(task_title,
msg_hash_to_str(MSG_CORE_BACKUP_ALREADY_EXISTS),
sizeof(task_title));
else
_len = strlcpy(task_title,
msg_hash_to_str(MSG_CORE_BACKUP_COMPLETE),
sizeof(task_title));
}
else
_len = strlcpy(task_title, msg_hash_to_str(MSG_CORE_BACKUP_FAILED),
sizeof(task_title));
strlcpy(task_title + _len,
backup_handle->core_name,
sizeof(task_title) - _len);
task_set_title(task, strdup(task_title));
}
/* fall-through */
default:
task_set_progress(task, 100);
goto task_finished;
}
return;
task_finished:
/* Menu refresh happens in the task's callback: the main
* thread, where menu flags are written. The handle itself is
* released by task_core_backup_cleanup(). */
if (backup_handle)
core_backup_handle_release_io(backup_handle);
if (task)
task_set_flags(task, RETRO_TASK_FLG_FINISHED, true);
}
/* Note 1: If CRC is set to 0, CRC of core_path file will
* be calculated automatically
* Note 2: If core_display_name is set to NULL, display
* name will be determined automatically
* > core_display_name *must* be set to a non-empty
* string if task_push_core_backup() is *not* called
* on the main thread */
static void *task_push_core_backup_internal(
const char *core_path, const char *staged_path,
const char *core_display_name,
uint32_t crc, enum core_backup_mode backup_mode,
size_t auto_backup_history_size,
const char *dir_core_assets, bool mute,
retro_task_callback_t cb, void *user_data)
{
size_t _len;
const char *core_name = NULL;
retro_task_t *task = NULL;
core_backup_handle_t *backup_handle = NULL;
char task_title[128];
/* Sanity check */
if ( (!core_path || !*core_path)
|| !path_is_valid(core_path))
goto error;
/* Concurrent backup/restore tasks for the same core
* are not allowed */
if (task_core_backup_busy(core_path))
goto error;
/* Get core name */
if (core_display_name && *core_display_name)
core_name = core_display_name;
else
{
core_info_t *core_info = NULL;
/* If core is found, use display name */
if ( core_info_find(core_path, &core_info)
&& core_info->display_name)
core_name = core_info->display_name;
else
{
/* If not, use core file name */
core_name = path_basename(core_path);
if (!core_name || !*core_name)
goto error;
}
}
/* Configure handle */
if (!(backup_handle = (core_backup_handle_t*)calloc(1,
sizeof(core_backup_handle_t))))
goto error;
backup_handle->dir_core_assets = (!dir_core_assets || !*dir_core_assets) ? NULL : strdup(dir_core_assets);
backup_handle->core_path = strdup(core_path);
backup_handle->core_name = strdup(core_name);
backup_handle->backup_path = NULL;
backup_handle->backup_type = CORE_BACKUP_TYPE_ARCHIVE;
backup_handle->backup_mode = backup_mode;
backup_handle->auto_backup_history_size = auto_backup_history_size;
backup_handle->num_auto_backups_to_remove = 0;
backup_handle->backup_index = 0;
backup_handle->core_file_size = 0;
backup_handle->backup_file_size = 0;
backup_handle->file_data_read = 0;
backup_handle->core_crc = crc;
backup_handle->backup_crc = 0;
backup_handle->crc_match = false;
backup_handle->success = false;
backup_handle->core_file = NULL;
backup_handle->backup_file = NULL;
backup_handle->backup_list = NULL;
backup_handle->done_cb = cb;
backup_handle->staged_path = (staged_path && *staged_path)
? strdup(staged_path) : NULL;
backup_handle->installed = false;
backup_handle->status = CORE_BACKUP_BEGIN;
/* Create task */
if (!(task = task_init()))
goto error;
/* Get initial task title */
_len = strlcpy(task_title, msg_hash_to_str(MSG_CORE_BACKUP_SCANNING_CORE),
sizeof(task_title));
strlcpy(task_title + _len,
backup_handle->core_name,
sizeof(task_title) - _len);
/* Configure task */
task->handler = task_core_backup_handler;
task->callback = cb_task_core_backup;
task->cleanup = task_core_backup_cleanup;
task->user_data = user_data;
task->state = backup_handle;
task->title = strdup(task_title);
task->progress = 0;
task->progress_cb = task_window_progress_cb;
if (mute)
task->flags |= RETRO_TASK_FLG_MUTE;
else
task->flags &= ~RETRO_TASK_FLG_MUTE;
task->flags |= RETRO_TASK_FLG_ALTERNATIVE_LOOK;
/* Push task */
task_queue_push(task);
return task;
error:
/* Clean up task */
if (task)
{
free(task);
task = NULL;
}
/* Clean up handle */
free_core_backup_handle(backup_handle);
return NULL;
}
void *task_push_core_backup(
const char *core_path, const char *core_display_name,
uint32_t crc, enum core_backup_mode backup_mode,
size_t auto_backup_history_size,
const char *dir_core_assets, bool mute,
retro_task_callback_t cb, void *user_data)
{
return task_push_core_backup_internal(core_path, NULL,
core_display_name, crc, backup_mode, auto_backup_history_size,
dir_core_assets, mute, cb, user_data);
}
void *task_push_core_backup_install(
const char *core_path, const char *staged_path,
const char *core_display_name, uint32_t crc,
size_t auto_backup_history_size,
const char *dir_core_assets, bool mute,
retro_task_callback_t cb, void *user_data)
{
if (!staged_path || !*staged_path || !path_is_valid(staged_path))
return NULL;
return task_push_core_backup_internal(core_path, staged_path,
core_display_name, crc, CORE_BACKUP_MODE_AUTO,
auto_backup_history_size, dir_core_assets, mute, cb, user_data);
}
/****************/
/* Core Restore */
/****************/
#ifdef HAVE_CORE_SIGNATURES
/* What Install and Trust needs to run the restore again */
typedef struct
{
struct core_check warned;
char *backup_path;
char *dir_libretro;
char *core_name;
enum core_backup_type backup_type;
bool own_backup;
} core_restore_request_t;
static void core_restore_request_free(core_restore_request_t *req)
{
free(req->backup_path);
free(req->dir_libretro);
free(req->core_name);
free(req);
}
static void core_restore_failed_msg(enum core_backup_type backup_type,
const char *core_name, bool flush)
{
size_t _len;
char msg[128];
_len = strlcpy(msg,
(backup_type == CORE_BACKUP_TYPE_ARCHIVE)
? msg_hash_to_str(MSG_CORE_RESTORATION_FAILED)
: msg_hash_to_str(MSG_CORE_INSTALLATION_FAILED),
sizeof(msg));
_len += strlcpy(msg + _len, core_name, sizeof(msg) - _len);
runloop_msg_queue_push(msg, _len, 1, 100, flush, NULL,
MESSAGE_QUEUE_ICON_DEFAULT, MESSAGE_QUEUE_CATEGORY_INFO);
}
/* Main thread. CANCEL only lets go. */
static void core_restore_warning_cb(enum core_warning_choice choice,
const struct core_check *c, const char *core_path, void *userdata)
{
core_restore_request_t *req = (core_restore_request_t*)userdata;
(void)c;
(void)core_path;
if (choice == CORE_WARNING_INSTALL_AND_TRUST)
{
bool core_loaded = false;
/* Unflushed: a refusal may have put its reason up already */
if (!task_push_core_restore(req->backup_path, req->dir_libretro,
&core_loaded, req->own_backup, &req->warned))
core_restore_failed_msg(req->backup_type, req->core_name, false);
}
core_restore_request_free(req);
}
static void core_restore_warn(core_backup_handle_t *backup_handle)
{
core_restore_request_t *req = (core_restore_request_t*)
calloc(1, sizeof(*req));
if (req)
{
req->warned = backup_handle->check.c;
req->own_backup = backup_handle->own_backup;
req->backup_type = backup_handle->backup_type;
req->backup_path = strdup(backup_handle->backup_path);
req->dir_libretro = strdup(backup_handle->dir_libretro);
req->core_name = strdup(backup_handle->core_name);
if ( req->backup_path
&& req->dir_libretro
&& req->core_name
&& core_warning_push(&req->warned, CORE_WARNING_INSTALL,
backup_handle->core_path, core_restore_warning_cb, req))
return;
core_restore_request_free(req);
}
/* No screen to ask on: not installed */
core_restore_failed_msg(backup_handle->backup_type,
backup_handle->core_name, true);
}
#endif
static void cb_task_core_restore(
retro_task_t *task, void *task_data,
void *user_data, const char *err)
{
/* Reload core info files
* > This must be done on the main thread
* > Forced: a core file changed on disk */
bool refresh = true;
#ifdef HAVE_CORE_SIGNATURES
/* Still attached: task_core_backup_cleanup() runs after this */
core_backup_handle_t *backup_handle = (core_backup_handle_t*)task->state;
#endif
command_event(CMD_EVENT_CORE_INFO_INIT, &refresh);
#if defined(RARCH_INTERNAL) && defined(HAVE_MENU)
/* Force reload of contentless cores icons */
menu_contentless_cores_free();
#endif
#ifdef HAVE_CORE_SIGNATURES
if (backup_handle)
switch (backup_handle->outcome)
{
case CORE_RESTORE_OUTCOME_INSTALLED:
core_trust_runtime_apply(&backup_handle->check.c);
break;
case CORE_RESTORE_OUTCOME_TRUSTED:
core_trust_runtime_always(&backup_handle->check.c);
break;
case CORE_RESTORE_OUTCOME_WARN:
core_restore_warn(backup_handle);
break;
default:
break;
}
#endif
}
#ifdef HAVE_CORE_SIGNATURES
/* Installs what passed, or what Install and Trust was asked for; leaves
* anything else to the Security Warning, from the callback */
static void core_restore_checked(retro_task_t *task,
core_backup_handle_t *backup_handle)
{
const struct core_check *c = &backup_handle->check.c;
enum core_restore_outcome outcome = CORE_RESTORE_OUTCOME_INSTALLED;
backup_handle->status = CORE_RESTORE_END;
if (c->result != CORE_CHECK_OK)
{
/* The user decides on the main thread; nothing waits here */
if (!backup_handle->warned)
{
backup_handle->outcome = CORE_RESTORE_OUTCOME_WARN;
task_set_flags(task, RETRO_TASK_FLG_MUTE, true);
return;
}
if ( c->result == CORE_CHECK_ERROR
|| !core_warning_same_core(backup_handle->warned, c))
{
RARCH_ERR("[Core Restore] Not the core the warning was about: \"%s\".\n",
backup_handle->backup_path);
task_free_error(task);
task_set_error(task, strdup("Core changed since the warning."));
return;
}
outcome = CORE_RESTORE_OUTCOME_TRUSTED;
/* Trusted by its hash: a .sig that failed would read as changed
* once the hash leaves the store */
if (c->result != CORE_CHECK_OLDER)
core_install_drop_sig(backup_handle->core_tmp_path);
}
#if defined(ANDROID)
/* Only once it passed: a refusal keeps the Play-installed core */
if (!core_restore_pfd_delete(task, backup_handle))
return;
#endif
if (!core_install_commit(backup_handle->core_tmp_path,
backup_handle->core_target_path, &backup_handle->check.c))
{
RARCH_ERR("[Core Restore] Failed to replace core file: \"%s\".\n",
backup_handle->core_target_path);
task_free_error(task);
task_set_error(task, strdup("Failed to replace core file."));
return;
}
backup_handle->outcome = outcome;
backup_handle->success = true;
}
/* A trusted restore is checked before it replaces the core, with the
* .sig kept beside what was picked */
static bool core_restore_to_check(core_backup_handle_t *backup_handle)
{
if (!backup_handle->trust)
return false;
core_install_drop_sig(backup_handle->core_tmp_path);
core_install_copy_sig(backup_handle->backup_path,
backup_handle->core_tmp_path);
backup_handle->status = CORE_RESTORE_CHECK;
return true;
}
#endif
static void task_core_restore_handler(retro_task_t *task)
{
uint8_t flg;
core_backup_handle_t *backup_handle = NULL;
if (!task)
goto task_finished;
backup_handle = (core_backup_handle_t*)task->state;
flg = task_get_flags(task);
if (!backup_handle || ((flg & RETRO_TASK_FLG_CANCELLED) > 0))
goto task_finished;
switch (backup_handle->status)
{
case CORE_RESTORE_GET_CORE_CRC:
/* If core file already exists, get its current
* CRC value */
if (path_is_valid(backup_handle->core_path))
{
/* Get CRC value, a bounded slice per tick; see the
* matching comment in CORE_BACKUP_CHECK_CRC. */
{
int64_t hashed = 1;
nbio_budget_t budget;
if (!backup_handle->crc_active)
{
/* Keep the stream open while CRC resumes on later
* task ticks. */
backup_handle->core_file = intfstream_open_file(
backup_handle->core_path, RETRO_VFS_FILE_ACCESS_READ,
RETRO_VFS_FILE_ACCESS_HINT_SEQUENTIAL_BULK);
if (!backup_handle->core_file)
{
RARCH_ERR("[Core Restore] Failed to open core file: \"%s\".\n",
backup_handle->core_path);
task_free_error(task);
task_set_error(task, strdup("Failed to open core file."));
backup_handle->status = CORE_RESTORE_END;
break;
}
backup_handle->crc_accumulator = 0;
backup_handle->crc_active = true;
intfstream_rewind(backup_handle->core_file);
}
task_nbio_slice_open(&budget);
while (task_nbio_slice_within_budget(&budget, 0, 0))
{
hashed = intfstream_crc_step(backup_handle->core_file,
&backup_handle->crc_accumulator,
CORE_BACKUP_CRC_CHUNK);
if (hashed < 0)
{
RARCH_ERR("[Core Restore] Failed to determine CRC of core file: \"%s\".\n",
backup_handle->core_path);
task_free_error(task);
task_set_error(task, strdup("Failed to determine CRC of core file."));
backup_handle->crc_active = false;
backup_handle->status = CORE_RESTORE_END;
task_nbio_slice_close(&budget);
return;
}
if (hashed == 0)
break;
}
task_nbio_slice_close(&budget);
/* Not finished: resume on the next tick. The core
* file stays open across ticks, which is what the
* close below is deferred for. */
if (hashed > 0)
break;
backup_handle->core_crc = backup_handle->crc_accumulator;
backup_handle->crc_active = false;
intfstream_rewind(backup_handle->core_file);
}
/* Close core file */
intfstream_close(backup_handle->core_file);
free(backup_handle->core_file);
backup_handle->core_file = NULL;
}
/* Go to next CRC gathering phase */
backup_handle->status = CORE_RESTORE_GET_BACKUP_CRC;
break;
case CORE_RESTORE_GET_BACKUP_CRC:
/* For a .lcbk archive the CRC is a field in the filename, so
* core_backup_get_backup_crc() is a string split and costs
* nothing. For a plain library it hashes the whole file in
* one call, which is the same unbounded tick this handler
* has just stopped doing twice over -- so that case is
* sliced here instead, leaving the helper's API intact for
* the archive path and for any future caller. */
if (core_backup_get_backup_type(backup_handle->backup_path)
== CORE_BACKUP_TYPE_LIB)
{
int64_t hashed = 1;
nbio_budget_t budget;
if (!backup_handle->crc_active)
{
if (!(backup_handle->backup_file = intfstream_open_file(
backup_handle->backup_path,
RETRO_VFS_FILE_ACCESS_READ,
RETRO_VFS_FILE_ACCESS_HINT_FREQUENT_ACCESS)))
{
RARCH_ERR("[Core Restore] Failed to determine CRC of core backup file: \"%s\".\n",
backup_handle->backup_path);
task_free_error(task);
task_set_error(task, strdup("Failed to determine CRC of core backup file."));
backup_handle->status = CORE_RESTORE_END;
break;
}
backup_handle->crc_accumulator = 0;
backup_handle->crc_active = true;
intfstream_rewind(backup_handle->backup_file);
}
task_nbio_slice_open(&budget);
while (task_nbio_slice_within_budget(&budget, 0, 0))
{
hashed = intfstream_crc_step(backup_handle->backup_file,
&backup_handle->crc_accumulator,
CORE_BACKUP_CRC_CHUNK);
if (hashed < 0)
{
RARCH_ERR("[Core Restore] Failed to determine CRC of core backup file: \"%s\".\n",
backup_handle->backup_path);
intfstream_close(backup_handle->backup_file);
free(backup_handle->backup_file);
backup_handle->backup_file = NULL;
backup_handle->crc_active = false;
task_free_error(task);
task_set_error(task, strdup("Failed to determine CRC of core backup file."));
backup_handle->status = CORE_RESTORE_END;
task_nbio_slice_close(&budget);
return;
}
if (hashed == 0)
break;
}
task_nbio_slice_close(&budget);
/* Not finished: resume on the next tick. */
if (hashed > 0)
break;
backup_handle->backup_crc = backup_handle->crc_accumulator;
backup_handle->crc_active = false;
intfstream_close(backup_handle->backup_file);
free(backup_handle->backup_file);
backup_handle->backup_file = NULL;
/* A zero CRC is what the helper reports as failure, and
* the comparison below cannot distinguish it from a real
* match, so keep that contract. */
if (backup_handle->backup_crc == 0)
{
RARCH_ERR("[Core Restore] Failed to determine CRC of core backup file: \"%s\".\n",
backup_handle->backup_path);
task_free_error(task);
task_set_error(task, strdup("Failed to determine CRC of core backup file."));
backup_handle->status = CORE_RESTORE_END;
break;
}
}
else if (!core_backup_get_backup_crc(
backup_handle->backup_path, &backup_handle->backup_crc))
{
RARCH_ERR("[Core Restore] Failed to determine CRC of core backup file: \"%s\".\n",
backup_handle->backup_path);
task_free_error(task);
task_set_error(task, strdup("Failed to determine CRC of core backup file."));
backup_handle->status = CORE_RESTORE_END;
break;
}
/* Go to CRC comparison phase */
backup_handle->status = CORE_RESTORE_CHECK_CRC;
break;
case CORE_RESTORE_CHECK_CRC:
/* Check whether current core matches backup CRC */
if (backup_handle->core_crc == backup_handle->backup_crc)
{
RARCH_LOG("[Core Restore] Selected backup core file is already installed: \"%s\".\n",
backup_handle->backup_path);
backup_handle->crc_match = true;
backup_handle->success = true;
backup_handle->status = CORE_RESTORE_END;
break;
}
/* Go to pre-iteration phase */
backup_handle->status = CORE_RESTORE_PRE_ITERATE;
break;
case CORE_RESTORE_PRE_ITERATE:
{
size_t _len;
char task_title[128];
/* Open backup file */
#if defined(HAVE_COMPRESSION)
backup_handle->backup_file = intfstream_open_rzip_file(
backup_handle->backup_path, RETRO_VFS_FILE_ACCESS_READ);
#else
backup_handle->backup_file = intfstream_open_file(
backup_handle->backup_path, RETRO_VFS_FILE_ACCESS_READ,
RETRO_VFS_FILE_ACCESS_HINT_SEQUENTIAL_BULK);
#endif
if (!backup_handle->backup_file)
{
RARCH_ERR("[Core Restore] Failed to open core backup file: \"%s\".\n",
backup_handle->backup_path);
task_free_error(task);
task_set_error(task, strdup("Failed to open core backup file."));
backup_handle->status = CORE_RESTORE_END;
break;
}
/* Get backup file size */
backup_handle->backup_file_size = intfstream_get_size(backup_handle->backup_file);
if (backup_handle->backup_file_size <= 0)
{
RARCH_ERR("[Core Restore] Core backup file is empty/invalid: \"%s\".\n",
backup_handle->backup_path);
task_free_error(task);
task_set_error(task, strdup("Core backup file is empty/invalid."));
backup_handle->status = CORE_RESTORE_END;
break;
}
#if defined(ANDROID)
/* If this is a Play Store build and the
* core is currently installed via
* play feature delivery, must delete
* the existing core before attempting
* to write any data */
if (
#ifdef HAVE_CORE_SIGNATURES
!backup_handle->trust &&
#endif
!core_restore_pfd_delete(task, backup_handle))
{
backup_handle->status = CORE_RESTORE_END;
break;
}
#endif
/* Open the temporary beside the core for writing; a
* stale one left by an interrupted restore goes first.
* An uncompressed backup - what installing a core update
* leaves, or any backup where they are not compressed - is
* a plain copy, done by the VFS copy into that temporary. */
#ifdef HAVE_CORE_SIGNATURES
if (backup_handle->trust
? core_restore_set_staged_paths(backup_handle)
: core_restore_set_write_paths(backup_handle))
#else
if (core_restore_set_write_paths(backup_handle))
#endif
{
if (path_is_valid(backup_handle->core_tmp_path))
filestream_delete(backup_handle->core_tmp_path);
if ( !intfstream_is_compressed(backup_handle->backup_file)
&& (backup_handle->copy = filestream_copy_begin(
backup_handle->backup_path,
backup_handle->core_tmp_path,
RETRO_VFS_COPY_OVERWRITE)))
{
intfstream_close(backup_handle->backup_file);
free(backup_handle->backup_file);
backup_handle->backup_file = NULL;
}
else
backup_handle->core_file = intfstream_open_file(
backup_handle->core_tmp_path,
RETRO_VFS_FILE_ACCESS_WRITE,
RETRO_VFS_FILE_ACCESS_HINT_SEQUENTIAL_BULK);
}
if (!backup_handle->core_file && !backup_handle->copy)
{
RARCH_ERR("[Core Restore] Failed to open core file: \"%s\".\n",
backup_handle->core_tmp_path
? backup_handle->core_tmp_path
: backup_handle->core_path);
task_free_error(task);
task_set_error(task, strdup("Failed to open core file."));
backup_handle->status = CORE_RESTORE_END;
break;
}
/* Update task title */
task_free_title(task);
_len = strlcpy(task_title,
(backup_handle->backup_type == CORE_BACKUP_TYPE_ARCHIVE)
? msg_hash_to_str(MSG_RESTORING_CORE)
: msg_hash_to_str(MSG_INSTALLING_CORE),
sizeof(task_title));
strlcpy(task_title + _len,
backup_handle->core_name,
sizeof(task_title) - _len);
task_set_title(task, strdup(task_title));
/* Go to iteration phase */
backup_handle->status = CORE_RESTORE_ITERATE;
}
break;
case CORE_RESTORE_ITERATE:
{
int64_t data_read = 0;
int64_t data_written = 0;
nbio_budget_t budget;
bool failed_read = false;
bool failed_write = false;
if (backup_handle->copy)
{
int status = core_backup_copy_run(backup_handle);
if (status == RETRO_VFS_COPY_RUNNING)
{
task_set_progress(task, (int8_t)((backup_handle->file_data_read * 100)
/ backup_handle->backup_file_size));
break;
}
if (status == RETRO_VFS_COPY_FAILED)
{
RARCH_ERR("[Core Restore] Failed to write to core file: \"%s\".\n",
backup_handle->core_path);
task_free_error(task);
task_set_error(task, strdup("Failed to open core file."));
}
#ifdef HAVE_CORE_SIGNATURES
else if (core_restore_to_check(backup_handle))
break;
#endif
/* Complete: only now does it replace the core */
else if (filestream_rename(backup_handle->core_tmp_path,
backup_handle->core_target_path) != 0)
{
RARCH_ERR("[Core Restore] Failed to replace core file: \"%s\".\n",
backup_handle->core_target_path);
task_free_error(task);
task_set_error(task, strdup("Failed to replace core file."));
}
else
backup_handle->success = true;
backup_handle->status = CORE_RESTORE_END;
break;
}
if (!backup_handle->buffer)
{
if (!(backup_handle->buffer = (uint8_t*)malloc(
CORE_BACKUP_CHUNK_SIZE)))
{
RARCH_ERR("[Core Restore] Failed to allocate transfer buffer.\n");
task_free_error(task);
task_set_error(task, strdup("Failed to allocate transfer buffer."));
backup_handle->status = CORE_RESTORE_END;
break;
}
}
/* Same windowed quanta as the backup handler */
task_nbio_slice_open(&budget);
while (task_nbio_slice_within_budget(&budget, 0, 0))
{
data_read = intfstream_read(backup_handle->backup_file,
backup_handle->buffer, CORE_BACKUP_CHUNK_SIZE);
if (data_read < 0)
{
failed_read = true;
break;
}
backup_handle->file_data_read += data_read;
if (data_read == 0)
break;
data_written = intfstream_write(backup_handle->core_file,
backup_handle->buffer, data_read);
if (data_written != data_read)
{
failed_write = true;
break;
}
}
task_nbio_slice_close(&budget);
if (failed_read)
{
RARCH_ERR("[Core Restore] Failed to read from core backup file: \"%s\".\n",
backup_handle->backup_path);
task_free_error(task);
task_set_error(task, strdup("Failed to open core file."));
backup_handle->status = CORE_RESTORE_END;
break;
}
if (failed_write)
{
RARCH_ERR("[Core Restore] Failed to write to core file: \"%s\".\n",
backup_handle->core_path);
task_free_error(task);
task_set_error(task, strdup("Failed to open core file."));
backup_handle->status = CORE_RESTORE_END;
break;
}
/* Check whether we have reached the end of the file */
if (data_read == 0)
{
/* Close backup file */
intfstream_close(backup_handle->backup_file);
free(backup_handle->backup_file);
backup_handle->backup_file = NULL;
/* Close core file */
intfstream_flush(backup_handle->core_file);
intfstream_close(backup_handle->core_file);
free(backup_handle->core_file);
backup_handle->core_file = NULL;
#ifdef HAVE_CORE_SIGNATURES
if (core_restore_to_check(backup_handle))
break;
#endif
/* Complete: only now does it replace the core */
if (filestream_rename(backup_handle->core_tmp_path,
backup_handle->core_target_path) != 0)
{
RARCH_ERR("[Core Restore] Failed to replace core file: \"%s\".\n",
backup_handle->core_target_path);
task_free_error(task);
task_set_error(task, strdup("Failed to replace core file."));
backup_handle->status = CORE_RESTORE_END;
break;
}
backup_handle->success = true;
backup_handle->status = CORE_RESTORE_END;
break;
}
/* Update progress display */
task_set_progress(task,
(int8_t)((backup_handle->file_data_read * 100) / backup_handle->backup_file_size));
}
break;
#ifdef HAVE_CORE_SIGNATURES
case CORE_RESTORE_CHECK:
{
nbio_budget_t budget;
bool done = false;
if (!backup_handle->check_begun)
{
backup_handle->check_begun = true;
if (!core_install_check_begin(&backup_handle->check,
backup_handle->trust, backup_handle->core_tmp_path,
backup_handle->core_target_path))
{
core_restore_checked(task, backup_handle);
break;
}
}
task_nbio_slice_open(&budget);
while (!done && task_nbio_slice_within_budget(&budget, 0, 0))
done = core_install_check_step(&backup_handle->check);
task_nbio_slice_close(&budget);
if (!done)
break; /* resume next tick */
core_install_check_end(&backup_handle->check,
backup_handle->trust, backup_handle->core_tmp_path,
backup_handle->own_backup ? CORE_CHECK_ALLOW_OLDER : 0);
core_restore_checked(task, backup_handle);
}
break;
#endif
case CORE_RESTORE_END:
{
size_t _len;
char task_title[128];
#ifdef HAVE_CORE_SIGNATURES
/* The Security Warning says what happened */
if (backup_handle->outcome == CORE_RESTORE_OUTCOME_WARN)
{
task_set_progress(task, 100);
goto task_finished;
}
#endif
/* Set final task title */
task_free_title(task);
if (backup_handle->success)
{
if (backup_handle->crc_match)
_len = strlcpy(task_title,
(backup_handle->backup_type == CORE_BACKUP_TYPE_ARCHIVE)
? msg_hash_to_str(MSG_CORE_RESTORATION_ALREADY_INSTALLED)
: msg_hash_to_str(MSG_CORE_INSTALLATION_ALREADY_INSTALLED),
sizeof(task_title));
else
_len = strlcpy(task_title,
(backup_handle->backup_type == CORE_BACKUP_TYPE_ARCHIVE)
? msg_hash_to_str(MSG_CORE_RESTORATION_COMPLETE)
: msg_hash_to_str(MSG_CORE_INSTALLATION_COMPLETE),
sizeof(task_title));
}
else
_len = strlcpy(task_title,
(backup_handle->backup_type == CORE_BACKUP_TYPE_ARCHIVE)
? msg_hash_to_str(MSG_CORE_RESTORATION_FAILED)
: msg_hash_to_str(MSG_CORE_INSTALLATION_FAILED),
sizeof(task_title));
strlcpy(task_title + _len,
backup_handle->core_name,
sizeof(task_title) - _len);
task_set_title(task, strdup(task_title));
}
/* fall-through */
default:
task_set_progress(task, 100);
goto task_finished;
}
return;
task_finished:
/* The handle itself is released by task_core_backup_cleanup() */
if (backup_handle)
{
core_backup_handle_release_io(backup_handle);
#ifdef HAVE_CORE_SIGNATURES
/* Closed before its files go (Windows) */
core_install_check_free(&backup_handle->check);
#endif
/* Failed or cancelled part-way: the core was never touched,
* and the partial temporary (closed above) goes */
if ( !backup_handle->success
&& backup_handle->core_tmp_path
&& path_is_valid(backup_handle->core_tmp_path))
filestream_delete(backup_handle->core_tmp_path);
#ifdef HAVE_CORE_SIGNATURES
/* Whatever a checked restore left staged goes, and its folder */
if (backup_handle->staging_dir)
{
if ( backup_handle->core_tmp_path
&& path_is_valid(backup_handle->core_tmp_path))
filestream_delete(backup_handle->core_tmp_path);
if (backup_handle->core_tmp_path)
core_install_drop_sig(backup_handle->core_tmp_path);
path_rmdir(backup_handle->staging_dir);
}
#endif
}
if (task)
task_set_flags(task, RETRO_TASK_FLG_FINISHED, true);
}
bool task_push_core_restore(const char *backup_path, const char *dir_libretro,
bool *core_loaded, bool own_backup, const struct core_check *warned)
{
size_t _len;
enum core_backup_type backup_type;
core_info_t *core_info = NULL;
const char *core_name = NULL;
retro_task_t *task = NULL;
core_backup_handle_t *backup_handle = NULL;
char task_title[128];
char core_path[PATH_MAX_LENGTH];
core_path[0] = '\0';
/* Sanity check */
if ( (!backup_path || !*backup_path)
|| !path_is_valid(backup_path)
|| (!dir_libretro || !*dir_libretro)
|| !core_loaded)
goto error;
/* Ensure core directory is valid */
if (!path_is_directory(dir_libretro))
{
if (!path_mkdir(dir_libretro))
{
RARCH_ERR("[Core Restore] Failed to create core directory: \"%s\".\n", dir_libretro);
goto error;
}
}
/* Get core path */
backup_type = core_backup_get_core_path(
backup_path, dir_libretro, core_path, sizeof(core_path));
if (backup_type == CORE_BACKUP_TYPE_INVALID)
{
const char *backup_filename = path_basename(backup_path);
char msg[128];
_len = strlcpy(msg,
msg_hash_to_str(MSG_CORE_RESTORATION_INVALID_CONTENT),
sizeof(msg));
if (backup_filename)
_len += strlcpy(msg + _len,
backup_filename,
sizeof(msg) - _len);
/* TODO/FIXME - localize */
RARCH_ERR("[Core Restore] Invalid core file selected: \"%s\".\n", backup_path);
runloop_msg_queue_push(msg, _len, 1, 100, true, NULL,
MESSAGE_QUEUE_ICON_DEFAULT, MESSAGE_QUEUE_CATEGORY_INFO);
goto error;
}
/* Get core name
* > If core is found, use display name */
if ( core_info_find(core_path, &core_info)
&& core_info->display_name)
core_name = core_info->display_name;
else
{
/* > If not, use core file name */
core_name = path_basename(core_path);
if (!core_name || !*core_name)
goto error;
}
/* Check whether core is locked */
if (core_info_get_core_lock(core_path, true))
{
char msg[128];
_len = strlcpy(msg,
(backup_type == CORE_BACKUP_TYPE_ARCHIVE)
? msg_hash_to_str(MSG_CORE_RESTORATION_DISABLED)
: msg_hash_to_str(MSG_CORE_INSTALLATION_DISABLED),
sizeof(msg));
_len += strlcpy(msg + _len,
core_name,
sizeof(msg) - _len);
/* TODO/FIXME - localize */
RARCH_ERR("[Core Restore] Restoration disabled - core is locked: \"%s\".\n", core_path);
runloop_msg_queue_push(msg, _len, 1, 100, true, NULL,
MESSAGE_QUEUE_ICON_DEFAULT, MESSAGE_QUEUE_CATEGORY_INFO);
goto error;
}
/* Concurrent backup/restore tasks for the same core
* are not allowed */
if (task_core_backup_busy(core_path))
goto error;
/* Configure handle */
if (!(backup_handle = (core_backup_handle_t*)calloc(1, sizeof(core_backup_handle_t))))
goto error;
backup_handle->dir_core_assets = NULL;
backup_handle->core_path = strdup(core_path);
backup_handle->core_name = strdup(core_name);
backup_handle->backup_path = strdup(backup_path);
backup_handle->backup_type = backup_type;
backup_handle->backup_mode = CORE_BACKUP_MODE_MANUAL;
backup_handle->auto_backup_history_size = 0;
backup_handle->num_auto_backups_to_remove = 0;
backup_handle->backup_index = 0;
backup_handle->core_file_size = 0;
backup_handle->backup_file_size = 0;
backup_handle->file_data_read = 0;
backup_handle->core_crc = 0;
backup_handle->backup_crc = 0;
backup_handle->crc_match = false;
backup_handle->success = false;
backup_handle->core_file = NULL;
backup_handle->backup_file = NULL;
backup_handle->backup_list = NULL;
backup_handle->status = CORE_RESTORE_GET_CORE_CRC;
#ifdef HAVE_CORE_SIGNATURES
/* Read here, on the main thread; NULL with the feature inactive */
backup_handle->own_backup = own_backup;
if ((backup_handle->trust = core_trust_runtime_get()))
{
if (!(backup_handle->dir_libretro = strdup(dir_libretro)))
goto error;
if (warned)
{
if (!(backup_handle->warned = (struct core_check*)
malloc(sizeof(*warned))))
goto error;
*backup_handle->warned = *warned;
}
}
else if (core_trust_runtime_active())
goto error;
#else
(void)own_backup;
(void)warned;
#endif
/* Create task */
if (!(task = task_init()))
goto error;
/* Get initial task title */
_len = strlcpy(task_title,
msg_hash_to_str(MSG_CORE_BACKUP_SCANNING_CORE),
sizeof(task_title));
strlcpy(task_title + _len,
backup_handle->core_name,
sizeof(task_title) - _len);
/* Configure task */
task->handler = task_core_restore_handler;
task->state = backup_handle;
task->title = strdup(task_title);
task->progress = 0;
task->progress_cb = task_window_progress_cb;
task->callback = cb_task_core_restore;
task->cleanup = task_core_backup_cleanup;
task->flags |= RETRO_TASK_FLG_ALTERNATIVE_LOOK;
/* If core to be restored is currently loaded, must
* unload it before pushing the task */
if (retroarch_ctl(RARCH_CTL_IS_CORE_LOADED, (void*)core_path))
{
command_event(CMD_EVENT_UNLOAD_CORE, NULL);
*core_loaded = true;
}
else
*core_loaded = false;
#ifdef HAVE_CORE_LOAD_CHECK
core_load_check_release_held();
#endif
/* Push task */
task_queue_push(task);
return true;
error:
/* Clean up task */
if (task)
{
free(task);
task = NULL;
}
/* Clean up handle */
free_core_backup_handle(backup_handle);
return false;
}