minecraft-pi-reborn/mods/src/override/override.c

88 lines
2.1 KiB
C
Raw Normal View History

2020-11-28 01:49:13 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <unistd.h>
#include <fcntl.h>
2021-01-27 21:26:19 +00:00
#include <libreborn/libreborn.h>
2020-11-28 01:49:13 +00:00
2021-06-17 21:32:24 +00:00
#include "../home/home.h"
2022-03-09 23:47:31 +00:00
// Check If String Starts With Prefix
2020-11-28 01:49:13 +00:00
static int starts_with(const char *s, const char *t) {
return strncmp(s, t, strlen(t)) == 0;
}
2022-03-09 23:47:31 +00:00
// Get Override Path For File (If It Exists)
2021-09-12 03:18:12 +00:00
char *override_get_path(const char *filename) {
2021-06-17 21:32:24 +00:00
// Get MCPI Home Path
char *home_path = home_get();
2020-11-28 01:49:13 +00:00
// Get Asset Override Path
char *overrides = NULL;
2021-06-17 21:32:24 +00:00
safe_asprintf(&overrides, "%s/overrides", home_path);
2021-09-12 03:18:12 +00:00
2021-06-17 21:32:24 +00:00
// Get Data Path
2020-11-28 01:49:13 +00:00
char *data = NULL;
2022-03-09 23:47:31 +00:00
char *binary_directory = get_mcpi_directory();
2021-09-12 03:18:12 +00:00
safe_asprintf(&data, "%s/data", binary_directory);
int data_length = strlen(data);
2020-11-28 01:49:13 +00:00
// Get Full Path
2021-09-12 03:18:12 +00:00
char *full_path;
if (strlen(filename) > 0 && filename[0] == '/') {
// Absolute Path
full_path = strdup(filename);
} else {
// Relative Path
full_path = realpath(filename, NULL);
}
// Check For Override
2020-11-28 01:49:13 +00:00
char *new_path = NULL;
if (full_path != NULL) {
if (starts_with(full_path, data)) {
2021-09-12 03:18:12 +00:00
safe_asprintf(&new_path, "%s%s", overrides, &full_path[data_length]);
2020-11-28 01:49:13 +00:00
if (access(new_path, F_OK) == -1) {
free(new_path);
new_path = NULL;
}
}
free(full_path);
}
2021-09-12 03:18:12 +00:00
2020-11-28 01:49:13 +00:00
// Free Variables
free(overrides);
free(data);
2021-09-12 03:18:12 +00:00
2020-11-28 01:49:13 +00:00
// Return
return new_path;
}
HOOK(fopen, FILE *, (const char *filename, const char *mode)) {
2021-09-12 03:18:12 +00:00
char *new_path = override_get_path(filename);
2020-11-28 01:49:13 +00:00
// Open File
ensure_fopen();
FILE *file = (*real_fopen)(new_path != NULL ? new_path : filename, mode);
// Free Data
if (new_path != NULL) {
free(new_path);
}
// Return File
return file;
}
HOOK(fopen64, FILE *, (const char *filename, const char *mode)) {
2021-09-12 03:18:12 +00:00
char *new_path = override_get_path(filename);
2020-11-28 01:49:13 +00:00
// Open File
ensure_fopen64();
FILE *file = (*real_fopen64)(new_path != NULL ? new_path : filename, mode);
// Free Data
if (new_path != NULL) {
free(new_path);
}
// Return File
return file;
2021-06-17 21:32:24 +00:00
}