Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@
/.idea/
/runClient/
/runServer/
Command.bat
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i assume you forgot to remove this before commiting

Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,22 @@
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static com.diffusehyperion.inertiaanticheat.common.util.InertiaAntiCheatConstants.MODLOGGER;

Expand Down Expand Up @@ -62,27 +71,292 @@ public static Toml initializeConfig(String defaultConfigPath, Long currentConfig
}
}
Toml config = new Toml().read(configFile);
if (!Objects.equals(config.getLong("debug.version", 0L), currentConfigVersion)) {
warn("Looks like your config file is outdated! Backing up current config, then creating an updated config.");
boolean versionMismatch = !Objects.equals(config.getLong("debug.version", 0L), currentConfigVersion);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this feature isn't part of the main feature proposed in the pr (afaik), please open another pr instead

currently, i'm unwilling to add a config file patcher to avoid the possibility of the config file getting messed up without the user's knowledge.

boolean patched = patchTomlConfig(configFile, defaultConfigPath, currentConfigVersion, versionMismatch);
if (patched) {
config = new Toml().read(configFile);
info("Done! Your config was patched with new defaults (existing values preserved).");
}

return config;
}

private static boolean patchTomlConfig(File configFile, String defaultConfigPath,
Long currentConfigVersion, boolean versionMismatch) {
List<String> existingLines;
List<String> defaultLines;
try {
existingLines = Files.readAllLines(configFile.toPath(), StandardCharsets.UTF_8);
defaultLines = readDefaultConfigLines(defaultConfigPath);
} catch (IOException e) {
throw new RuntimeException("Couldn't read config file!", e);
}

ExistingToml existing = parseExistingToml(existingLines);
List<TomlTemplateSection> templateSections = parseTemplateSections(defaultLines);
List<String> additions = buildMissingBlocks(existing, templateSections, currentConfigVersion);

boolean modified = false;
if (!additions.isEmpty()) {
if (!existingLines.isEmpty() && !existingLines.get(existingLines.size() - 1).isBlank()) {
existingLines.add("");
}
existingLines.addAll(additions);
modified = true;
}

boolean versionUpdated = updateDebugVersion(existingLines, currentConfigVersion);
modified |= versionUpdated;

if (!modified) {
return false;
}

if (versionMismatch) {
warn("Looks like your config file is outdated! Backing up current config, then patching it.");
warn("Your config file will be backed up to \"BACKUP-InertiaAntiCheat.toml\".");
File backupFile = getConfigDir().resolve("BACKUP-InertiaAntiCheat.toml").toFile();
try {
Files.copy(configFile.toPath(), backupFile.toPath());
} catch (IOException e) {
throw new RuntimeException("Couldn't copy existing config file into a backup config file! Please do it manually.", e);
}
if (!configFile.delete()) {
throw new RuntimeException("Couldn't delete config file! Please delete it manually.");
}

try {
Files.write(configFile.toPath(), existingLines, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException("Couldn't write updated config file!", e);
}

return true;
}

private static List<String> readDefaultConfigLines(String defaultConfigPath) throws IOException {
try (InputStream stream = InertiaAntiCheatServer.class.getResourceAsStream(defaultConfigPath)) {
if (stream == null) {
throw new RuntimeException("Default config resource not found: " + defaultConfigPath);
}
return new String(stream.readAllBytes(), StandardCharsets.UTF_8).lines().toList();
}
}

private static ExistingToml parseExistingToml(List<String> lines) {
ExistingToml existing = new ExistingToml();
String currentSection = "";
for (String line : lines) {
String trimmed = line.trim();
if (trimmed.isEmpty() || trimmed.startsWith("#") || trimmed.startsWith("//")) {
continue;
}
try {
Files.copy(Objects.requireNonNull(InertiaAntiCheatServer.class.getResourceAsStream(defaultConfigPath)), configFile.toPath());
} catch (IOException e) {
throw new RuntimeException("Couldn't create a default config!", e);

if (isSectionHeader(trimmed)) {
currentSection = trimmed.substring(1, trimmed.length() - 1).trim();
existing.sections.add(currentSection);
continue;
}

int equalsIndex = trimmed.indexOf('=');
if (equalsIndex < 0) {
continue;
}
config = new Toml().read(configFile); // update config to new file
info("Done! Please readjust the configs in the new file accordingly.");

String key = trimmed.substring(0, equalsIndex).trim();
existing.keysBySection.computeIfAbsent(currentSection, ignored -> new HashSet<>()).add(key);
}
return existing;
}

private static List<TomlTemplateSection> parseTemplateSections(List<String> lines) {
List<TomlTemplateSection> sections = new ArrayList<>();
TomlTemplateSection current = new TomlTemplateSection("");
sections.add(current);
List<String> pending = new ArrayList<>();

for (String line : lines) {
String trimmed = line.trim();
if (isSectionHeader(trimmed)) {
String sectionName = trimmed.substring(1, trimmed.length() - 1).trim();
current = new TomlTemplateSection(sectionName);
current.headerComments.addAll(pending);
pending.clear();
sections.add(current);
continue;
}

if (trimmed.isEmpty() || trimmed.startsWith("#") || trimmed.startsWith("//")) {
pending.add(line);
continue;
}

int equalsIndex = trimmed.indexOf('=');
if (equalsIndex < 0) {
pending.add(line);
continue;
}

String key = trimmed.substring(0, equalsIndex).trim();
List<String> block = new ArrayList<>(pending);
pending.clear();
block.add(line);
current.keyBlocks.putIfAbsent(key, block);
}

return sections;
}

private static List<String> buildMissingBlocks(ExistingToml existing, List<TomlTemplateSection> sections,
Long currentConfigVersion) {
List<String> additions = new ArrayList<>();
for (TomlTemplateSection section : sections) {
String sectionName = section.name;
boolean sectionExists = sectionName.isEmpty() || existing.sections.contains(sectionName);

if (!sectionExists) {
appendSectionBlock(additions, section, currentConfigVersion);
continue;
}

Set<String> existingKeys = existing.keysBySection.getOrDefault(sectionName, Set.of());
List<String> missingBlocks = new ArrayList<>();
for (Map.Entry<String, List<String>> entry : section.keyBlocks.entrySet()) {
String key = entry.getKey();
if (existingKeys.contains(key)) {
continue;
}
List<String> block = new ArrayList<>(entry.getValue());
if ("debug".equals(sectionName) && "version".equals(key)) {
replaceVersionInBlock(block, currentConfigVersion);
}
missingBlocks.addAll(block);
}

if (!missingBlocks.isEmpty()) {
if (!additions.isEmpty() && !additions.get(additions.size() - 1).isBlank()) {
additions.add("");
}
if (!sectionName.isEmpty()) {
additions.add("[" + sectionName + "]");
}
additions.addAll(missingBlocks);
}
}
return additions;
}

private static void appendSectionBlock(List<String> additions, TomlTemplateSection section,
Long currentConfigVersion) {
if (!additions.isEmpty() && !additions.get(additions.size() - 1).isBlank()) {
additions.add("");
}
additions.addAll(section.headerComments);
if (!section.name.isEmpty()) {
additions.add("[" + section.name + "]");
}
for (Map.Entry<String, List<String>> entry : section.keyBlocks.entrySet()) {
List<String> block = new ArrayList<>(entry.getValue());
if ("debug".equals(section.name) && "version".equals(entry.getKey())) {
replaceVersionInBlock(block, currentConfigVersion);
}
additions.addAll(block);
}
}

private static boolean updateDebugVersion(List<String> lines, Long currentConfigVersion) {
String currentSection = "";
boolean updated = false;
for (int i = 0; i < lines.size(); i++) {
String line = lines.get(i);
String trimmed = line.trim();
if (trimmed.isEmpty() || trimmed.startsWith("#") || trimmed.startsWith("//")) {
continue;
}
if (isSectionHeader(trimmed)) {
currentSection = trimmed.substring(1, trimmed.length() - 1).trim();
continue;
}
int equalsIndex = trimmed.indexOf('=');
if (equalsIndex < 0) {
continue;
}
String key = trimmed.substring(0, equalsIndex).trim();
if ("debug".equals(currentSection) && "version".equals(key)) {
String newLine = replaceTomlValue(line, String.valueOf(currentConfigVersion));
if (!newLine.equals(line)) {
lines.set(i, newLine);
updated = true;
}
}
}
return updated;
}

private static void replaceVersionInBlock(List<String> block, Long currentConfigVersion) {
for (int i = 0; i < block.size(); i++) {
String line = block.get(i);
String trimmed = line.trim();
if (trimmed.startsWith("version") && trimmed.contains("=")) {
block.set(i, replaceTomlValue(line, String.valueOf(currentConfigVersion)));
return;
}
}
}

private static boolean isSectionHeader(String trimmed) {
return trimmed.startsWith("[") && trimmed.endsWith("]");
}

private static String replaceTomlValue(String line, String newValue) {
int equalsIndex = line.indexOf('=');
if (equalsIndex < 0) {
return line;
}
String prefix = line.substring(0, equalsIndex + 1);
String remainder = line.substring(equalsIndex + 1);
int commentIndex = findInlineCommentIndex(remainder);
String comment = commentIndex >= 0 ? remainder.substring(commentIndex).trim() : "";
String suffix = comment.isEmpty() ? "" : " " + comment;
return prefix + " " + newValue + suffix;
}

private static int findInlineCommentIndex(String text) {
boolean inQuotes = false;
char quoteChar = 0;
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (inQuotes) {
if (c == '\\') {
i++;
} else if (c == quoteChar) {
inQuotes = false;
}
} else {
if (c == '"' || c == '\'') {
inQuotes = true;
quoteChar = c;
} else if (c == '#') {
return i;
} else if (c == '/' && i + 1 < text.length() && text.charAt(i + 1) == '/') {
return i;
}
}
}
return -1;
}

private static final class ExistingToml {
private final Set<String> sections = new HashSet<>();
private final Map<String, Set<String>> keysBySection = new HashMap<>();
}

private static final class TomlTemplateSection {
private final String name;
private final List<String> headerComments = new ArrayList<>();
private final LinkedHashMap<String, List<String>> keyBlocks = new LinkedHashMap<>();

private TomlTemplateSection(String name) {
this.name = name;
}
return config;
}

public static Path getConfigDir() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.diffusehyperion.inertiaanticheat.common.interfaces;

import net.minecraft.network.ClientConnection;

public interface UpgradedServerCommonNetworkHandler {
ClientConnection inertiaAntiCheat$getConnection();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.diffusehyperion.inertiaanticheat.mixins.server;

import com.diffusehyperion.inertiaanticheat.common.interfaces.UpgradedServerCommonNetworkHandler;
import net.minecraft.network.ClientConnection;
import net.minecraft.server.network.ServerCommonNetworkHandler;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;

@Mixin(ServerCommonNetworkHandler.class)
public abstract class ServerCommonNetworkHandlerMixin implements UpgradedServerCommonNetworkHandler {
@Shadow @Final
ClientConnection connection;

@Override
public ClientConnection inertiaAntiCheat$getConnection() {
return this.connection;
}
}
Loading