Remove log4j-patch (#1860)

* Remove log4j-patch

* Update I18N
This commit is contained in:
Glavo 2022-11-23 17:20:15 +08:00 committed by GitHub
parent 4c9f8d3dca
commit c76b562705
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 8 additions and 380 deletions

3
.gitignore vendored
View File

@ -20,7 +20,6 @@ minecraft-exported-crash-info*
/HMCLCore/build/ /HMCLCore/build/
/HMCLTransformerDiscoveryService/build/ /HMCLTransformerDiscoveryService/build/
/minecraft/libraries/HMCLTransformerDiscoveryService/build/ /minecraft/libraries/HMCLTransformerDiscoveryService/build/
/minecraft/libraries/log4j-patch/build/
# idea # idea
.idea .idea
@ -28,14 +27,12 @@ minecraft-exported-crash-info*
/HMCL/out/ /HMCL/out/
/HMCLCore/out/ /HMCLCore/out/
/minecraft/libraries/HMCLTransformerDiscoveryService/out/ /minecraft/libraries/HMCLTransformerDiscoveryService/out/
/minecraft/libraries/log4j-patch/out/
# eclipse # eclipse
/bin/ /bin/
/HMCL/bin/ /HMCL/bin/
/HMCLCore/bin/ /HMCLCore/bin/
/minecraft/libraries/HMCLTransformerDiscoveryService/bin/ /minecraft/libraries/HMCLTransformerDiscoveryService/bin/
/minecraft/libraries/log4j-patch/bin/
.classpath .classpath
.project .project
.settings .settings

View File

@ -21,7 +21,6 @@ import com.jfoenix.controls.JFXButton;
import javafx.application.Platform; import javafx.application.Platform;
import javafx.stage.Stage; import javafx.stage.Stage;
import org.jackhuang.hmcl.Launcher; import org.jackhuang.hmcl.Launcher;
import org.jackhuang.hmcl.Metadata;
import org.jackhuang.hmcl.auth.*; import org.jackhuang.hmcl.auth.*;
import org.jackhuang.hmcl.auth.authlibinjector.AuthlibInjectorDownloadException; import org.jackhuang.hmcl.auth.authlibinjector.AuthlibInjectorDownloadException;
import org.jackhuang.hmcl.download.DefaultDependencyManager; import org.jackhuang.hmcl.download.DefaultDependencyManager;
@ -47,13 +46,9 @@ import org.jackhuang.hmcl.util.versioning.VersionNumber;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.net.SocketTimeoutException; import java.net.SocketTimeoutException;
import java.net.URL; import java.net.URL;
import java.nio.file.AccessDeniedException; import java.nio.file.AccessDeniedException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.*; import java.util.*;
import java.util.concurrent.CancellationException; import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@ -134,8 +129,6 @@ public final class LauncherHelper {
AtomicReference<JavaVersion> javaVersionRef = new AtomicReference<>(); AtomicReference<JavaVersion> javaVersionRef = new AtomicReference<>();
getLog4jPatch(version.get()).ifPresent(javaAgents::add);
TaskExecutor executor = checkGameState(profile, setting, version.get()) TaskExecutor executor = checkGameState(profile, setting, version.get())
.thenComposeAsync(javaVersion -> { .thenComposeAsync(javaVersion -> {
javaVersionRef.set(Objects.requireNonNull(javaVersion)); javaVersionRef.set(Objects.requireNonNull(javaVersion));
@ -663,47 +656,6 @@ public final class LauncherHelper {
}); });
} }
private static Optional<String> getLog4jPatch(Version version) {
Optional<String> log4jVersion = version.getLibraries().stream()
.filter(it -> it.is("org.apache.logging.log4j", "log4j-core")
&& (VersionNumber.VERSION_COMPARATOR.compare(it.getVersion(), "2.17") < 0 || "2.0-beta9".equals(it.getVersion())))
.map(Library::getVersion)
.findFirst();
if (log4jVersion.isPresent()) {
final String agentFileName = "log4j-patch-agent-1.0.jar";
Path agentFile = Metadata.HMCL_DIRECTORY.resolve(agentFileName).toAbsolutePath();
String agentFilePath = agentFile.toString();
if (agentFilePath.indexOf('=') >= 0) {
LOG.warning("Invalid character '=' in the HMCL directory path, unable to attach log4j-patch");
return Optional.empty();
}
if (Files.notExists(agentFile)) {
try (InputStream input = DefaultLauncher.class.getResourceAsStream("/assets/game/" + agentFileName)) {
LOG.info("Extract log4j patch to " + agentFilePath);
Files.createDirectories(agentFile.getParent());
Files.copy(input, agentFile, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
LOG.log(Level.WARNING, "Failed to extract log4j patch");
try {
Files.deleteIfExists(agentFile);
} catch (IOException ex) {
LOG.log(Level.WARNING, "Failed to delete incomplete log4j patch", ex);
}
return Optional.empty();
}
}
boolean isBeta = log4jVersion.get().startsWith("2.0-beta");
return Optional.of(agentFilePath + "=" + isBeta);
} else {
LOG.info("No log4j with security vulnerabilities found");
return Optional.empty();
}
}
private void checkExit() { private void checkExit() {
switch (launcherVisibility) { switch (launcherVisibility) {
case HIDE_AND_REOPEN: case HIDE_AND_REOPEN:

View File

@ -369,8 +369,7 @@ fatal.apply_update_failure=We are sorry, but Hello Minecraft\! Launcher is unabl
You can update manually by downloading a newer version of the launcher from %s.\n\ You can update manually by downloading a newer version of the launcher from %s.\n\
If the problem persists, please consider reporting this to us. If the problem persists, please consider reporting this to us.
fatal.samba=If you launched HMCL from a Samba network drive, some features might not be working. Please try updating your Java version or copy and run the launcher in a local folder. fatal.samba=If you launched HMCL from a Samba network drive, some features might not be working. Please try updating your Java version or copy and run the launcher in a local folder.
fatal.illegal_char=Your user path contains an illegal character '\=', so some features might not function properly.\n\ fatal.illegal_char=Your user path contains an illegal character '\=', you will not be able to use authlib-injector or change the skin of your offline account.
For example, you will not be able to use authlib-injector or change the skin of your offline account. Besides, this may cause security issues during multiplayer.
fatal.unsupported_platform=Minecraft is not yet fully supported for your platform, so you may experience missing functionality, \nor even be unable to launch the game.\n\ fatal.unsupported_platform=Minecraft is not yet fully supported for your platform, so you may experience missing functionality, \nor even be unable to launch the game.\n\
\n\ \n\
If you can't start Minecraft 1.17 and above, you can try turning on the "Use OpenGL software renderer" option\n\ If you can't start Minecraft 1.17 and above, you can try turning on the "Use OpenGL software renderer" option\n\

View File

@ -354,7 +354,7 @@ Usted puede actualizar manualmente mediante la descarga de una versión más rec
Si el problema persiste, por favor considere reportarlo a nosotros. Si el problema persiste, por favor considere reportarlo a nosotros.
fatal.samba=Si ha iniciado HMCL desde una unidad de red Samba, es posible que algunas funciones no funcionen. Por favor, intente actualizar su versión de Java o copie y ejecute el launcher en una carpeta local. fatal.samba=Si ha iniciado HMCL desde una unidad de red Samba, es posible que algunas funciones no funcionen. Por favor, intente actualizar su versión de Java o copie y ejecute el launcher en una carpeta local.
fatal.illegal_char=Su ruta de usuario contiene un carácter ilegal '\=', por lo que algunas características podrían no funcionar correctamente.\n\ fatal.illegal_char=Su ruta de usuario contiene un carácter ilegal '\=', por lo que algunas características podrían no funcionar correctamente.\n\
Por ejemplo, no podrá utilizar authlib-injector o cambiar el skin de su cuenta offline. Además, esto puede causar problemas de seguridad durante el multijugador. Por ejemplo, no podrá utilizar authlib-injector o cambiar el skin de su cuenta offline.
feedback=Comentarios feedback=Comentarios
feedback.add=Añadir un comentario feedback.add=Añadir un comentario

View File

@ -320,7 +320,7 @@ fatal.config_loading_failure=構成にアクセスできません。\nHelloMinec
fatal.migration_requires_manual_reboot=更新が完了しました。 Hello Minecraftを再開してくださいランチャー。 fatal.migration_requires_manual_reboot=更新が完了しました。 Hello Minecraftを再開してくださいランチャー。
fatal.apply_update_failure=ごめんなさい、Hello Minecraft! Launcher 何か問題が発生したため、ランチャーは更新を完了できませんでした。\nただし、Hello Minecraftをダウンロードすることで、手動で更新を終了できます。 %s からのランチャー。\nこの問題を報告することを検討してください。 fatal.apply_update_failure=ごめんなさい、Hello Minecraft! Launcher 何か問題が発生したため、ランチャーは更新を完了できませんでした。\nただし、Hello Minecraftをダウンロードすることで、手動で更新を終了できます。 %s からのランチャー。\nこの問題を報告することを検討してください。
fatal.samba=If you are trying to run HMCL in a shared folder by Samba, HMCL may not working, please try updating your Java or running HMCL in a local folder. fatal.samba=If you are trying to run HMCL in a shared folder by Samba, HMCL may not working, please try updating your Java or running HMCL in a local folder.
fatal.illegal_char=ユーザーフォルダーのパスに不正な文字'='が含まれています。hmclは動作しますが、一部の機能が正しく動作しません。 \nログインアカウントやオフラインログインではスキンの変更ができなくなり、多人数参加型ゲームをプレイする際のセキュリティリスクが高くなる可能性があります fatal.illegal_char=ユーザーフォルダーのパスに不正な文字'='が含まれています, ログインアカウントやオフラインログインではスキンの変更ができなくなり。
feedback=フィードバック feedback=フィードバック
Feedback.add=フィードバックを追加 Feedback.add=フィードバックを追加

View File

@ -321,7 +321,7 @@ fatal.config_loading_failure=Конфигурация недоступна.\nП
fatal.migration_requires_manual_reboot=Обновление завершено. Перезапустите лаунчер. fatal.migration_requires_manual_reboot=Обновление завершено. Перезапустите лаунчер.
fatal.apply_update_failure=Мы сожалеем, лаунчер не смог завершить обновление, потому что что-то пошло не так.\nНо вы все ещё можете вручную завершить обновление, загрузив Hлаунчер с %s.\nВы можете сообщить нам об этой проблеме. fatal.apply_update_failure=Мы сожалеем, лаунчер не смог завершить обновление, потому что что-то пошло не так.\nНо вы все ещё можете вручную завершить обновление, загрузив Hлаунчер с %s.\nВы можете сообщить нам об этой проблеме.
fatal.samba=Если вы пытаетесь запустить лаунчер в общей папке Samba, он может не работать, попробуйте обновить Java или запустить лаунчер из локальной папки. fatal.samba=Если вы пытаетесь запустить лаунчер в общей папке Samba, он может не работать, попробуйте обновить Java или запустить лаунчер из локальной папки.
fatal.illegal_char=Недопустимый символ '=' в пути к папке пользователя. Лаунчер может работать, но некоторые функции не будут работать.\nВы не сможете использовать аккаунт authlib-injector или изменить офлайн скин. Также в сетевой игре могут возникнуть большие риски для безопасности. fatal.illegal_char=Недопустимый символ '=' в пути к папке пользователя. Лаунчер может работать, но некоторые функции не будут работать.\nВы не сможете использовать аккаунт authlib-injector или изменить офлайн скин.
feedback=Обратная связь feedback=Обратная связь
feedback.add=Добавить отзыв (на английском или китайском) feedback.add=Добавить отзыв (на английском или китайском)

View File

@ -337,7 +337,7 @@ fatal.config_loading_failure.unix=Hello Minecraft! Launcher 無法載入設定
fatal.migration_requires_manual_reboot=Hello Minecraft! Launcher 即將升級完成,請重新開啟 Hello Minecraft! Launcher。 fatal.migration_requires_manual_reboot=Hello Minecraft! Launcher 即將升級完成,請重新開啟 Hello Minecraft! Launcher。
fatal.apply_update_failure=我們很抱歉 Hello Minecraft! Launcher 無法自動完成升級程式,因為出現了一些問題。\n但你依然可以從 %s 處手動下載 Hello Minecraft! Launcher 來完成升級。\n請考慮向我們回報該問題。 fatal.apply_update_failure=我們很抱歉 Hello Minecraft! Launcher 無法自動完成升級程式,因為出現了一些問題。\n但你依然可以從 %s 處手動下載 Hello Minecraft! Launcher 來完成升級。\n請考慮向我們回報該問題。
fatal.samba=如果您正在通過 Samba 共亯的資料夾中運行 HMCLHMCL 可能無法正常工作,請嘗試更新您的 Java 或在本地資料夾內運行 HMCL。 fatal.samba=如果您正在通過 Samba 共亯的資料夾中運行 HMCLHMCL 可能無法正常工作,請嘗試更新您的 Java 或在本地資料夾內運行 HMCL。
fatal.illegal_char=您的用戶資料夾路徑中存在非法字元‘=。HMCL 能够運行但一些功能無法正常使用。 \n您將無法使用外置登入帳戶以及離線登入更換皮膚功能,並且在進行多人遊戲時可能存在更大的安全隱患 fatal.illegal_char=由於您的用戶資料夾路徑中存在非法字元‘=’,您將無法使用外置登入帳戶以及離線登入更換皮膚功能。
fatal.unsupported_platform=Minecraft 尚未你您的平臺提供完善支持,所以可能影響遊戲體驗或無法啟動遊戲。\n若無法啟動 Minecraft 1.17 及以上版本,可以嘗試在版本設定中打開“使用 OpenGL 軟渲染器”選項,使用 CPU 渲染以獲得更好的相容性。 fatal.unsupported_platform=Minecraft 尚未你您的平臺提供完善支持,所以可能影響遊戲體驗或無法啟動遊戲。\n若無法啟動 Minecraft 1.17 及以上版本,可以嘗試在版本設定中打開“使用 OpenGL 軟渲染器”選項,使用 CPU 渲染以獲得更好的相容性。
fatal.unsupported_platform.osx_arm64=HMCL 已為 Apple Silicon 平臺提供支援,使用 ARM 原生 Java 啟動遊戲以獲得更流暢的遊戲體驗。\n如果你在遊戲中遭遇問題使用 x86-64 架構的 Java 啟動遊戲可能有更好的相容性。 fatal.unsupported_platform.osx_arm64=HMCL 已為 Apple Silicon 平臺提供支援,使用 ARM 原生 Java 啟動遊戲以獲得更流暢的遊戲體驗。\n如果你在遊戲中遭遇問題使用 x86-64 架構的 Java 啟動遊戲可能有更好的相容性。
fatal.unsupported_platform.windows_arm64=HMCL 已為 Windows on Arm 平臺提供原生支持。如果你在遊戲中遭遇問題,請嘗試使用 x86 架構的 Java 啟動遊戲。\n\n如果你正在使用<b>高通</b>平臺,你可能需要安裝 <a href="ms-windows-store://pdp/?productid=9NQPSL29BFFF">OpenGL 相容包</a>後才能進行遊戲。點擊連結前往 Microsoft Store 安裝相容包。 fatal.unsupported_platform.windows_arm64=HMCL 已為 Windows on Arm 平臺提供原生支持。如果你在遊戲中遭遇問題,請嘗試使用 x86 架構的 Java 啟動遊戲。\n\n如果你正在使用<b>高通</b>平臺,你可能需要安裝 <a href="ms-windows-store://pdp/?productid=9NQPSL29BFFF">OpenGL 相容包</a>後才能進行遊戲。點擊連結前往 Microsoft Store 安裝相容包。

View File

@ -337,7 +337,7 @@ fatal.config_loading_failure.unix=Hello Minecraft! Launcher 无法加载配置
fatal.migration_requires_manual_reboot=Hello Minecraft! Launcher 即将完成升级,请重新打开 Hello Minecraft! Launcher。 fatal.migration_requires_manual_reboot=Hello Minecraft! Launcher 即将完成升级,请重新打开 Hello Minecraft! Launcher。
fatal.apply_update_failure=我们很抱歉 Hello Minecraft! Launcher 无法自动完成升级,因为出现了一些问题……\n但你依可以从 %s 处手动下载 Hello Minecraft! Launcher 来完成升级\n请考虑向我们反馈该问题 fatal.apply_update_failure=我们很抱歉 Hello Minecraft! Launcher 无法自动完成升级,因为出现了一些问题……\n但你依可以从 %s 处手动下载 Hello Minecraft! Launcher 来完成升级\n请考虑向我们反馈该问题
fatal.samba=如果您正在通过 Samba 共享的文件夹中运行 HMCLHMCL 可能无法正常工作,请尝试更新您的 Java 或在本地文件夹内运行 HMCL。 fatal.samba=如果您正在通过 Samba 共享的文件夹中运行 HMCLHMCL 可能无法正常工作,请尝试更新您的 Java 或在本地文件夹内运行 HMCL。
fatal.illegal_char=的用户文件夹路径中存在非法字符‘=。HMCL 能够运行但可能某些功能无法正常使用!\n你将无法使用外置登录账户以及离线登录更换皮肤功能,并且在进行多人游戏时可能存在更大的安全隐患! fatal.illegal_char=由于你的用户文件夹路径中存在非法字符‘=’,你将无法使用外置登录账户以及离线登录更换皮肤功能
fatal.unsupported_platform=Minecraft 尚未为您的平台提供完善支持,所以可能影响游戏体验或无法启动游戏。\n若无法启动 Minecraft 1.17 及以上版本,可以尝试在版本设置中打开“使用 OpenGL 软渲染器”选项,使用 CPU 渲染以获得更好的兼容性。 fatal.unsupported_platform=Minecraft 尚未为您的平台提供完善支持,所以可能影响游戏体验或无法启动游戏。\n若无法启动 Minecraft 1.17 及以上版本,可以尝试在版本设置中打开“使用 OpenGL 软渲染器”选项,使用 CPU 渲染以获得更好的兼容性。
fatal.unsupported_platform.osx_arm64=HMCL 已为 Apple Silicon 平台提供支持,使用 ARM 原生 Java 启动游戏以获得更流畅的游戏体验。\n如果你在游戏中遭遇问题使用 x86-64 架构的 Java 启动游戏可能有更好的兼容性。 fatal.unsupported_platform.osx_arm64=HMCL 已为 Apple Silicon 平台提供支持,使用 ARM 原生 Java 启动游戏以获得更流畅的游戏体验。\n如果你在游戏中遭遇问题使用 x86-64 架构的 Java 启动游戏可能有更好的兼容性。
fatal.unsupported_platform.windows_arm64=HMCL 已为 Windows on Arm 平台提供原生支持。如果你在游戏中遭遇问题,请尝试使用 x86 架构的 Java 启动游戏。\n\n如果你正在使用<b>高通</b>平台,你可能需要安装 <a href="ms-windows-store://pdp/?productid=9NQPSL29BFFF">OpenGL 兼容包</a>后才能进行游戏。点击链接前往 Microsoft Store 安装兼容包。 fatal.unsupported_platform.windows_arm64=HMCL 已为 Windows on Arm 平台提供原生支持。如果你在游戏中遭遇问题,请尝试使用 x86 架构的 Java 启动游戏。\n\n如果你正在使用<b>高通</b>平台,你可能需要安装 <a href="ms-windows-store://pdp/?productid=9NQPSL29BFFF">OpenGL 兼容包</a>后才能进行游戏。点击链接前往 Microsoft Store 安装兼容包。

View File

@ -17,11 +17,3 @@ dependencies {
api("org.apache.commons:commons-lang3:3.12.0") api("org.apache.commons:commons-lang3:3.12.0")
compileOnlyApi("org.jetbrains:annotations:16.0.3") compileOnlyApi("org.jetbrains:annotations:16.0.3")
} }
tasks.processResources {
dependsOn(":log4j-patch:jar")
into("assets/game") {
from(project(":log4j-patch").file("build/libs"))
}
}

View File

@ -1,13 +0,0 @@
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.

View File

@ -1,6 +0,0 @@
# Log4j Patch
Copy from [Glavo/log4j-patch](https://github.com/Glavo/log4j-patch/).
`org.apache.logging.log4j.core.lookup.JndiLookup` is licensed under the WTFPL 2.0 license,
and `org.apache.logging.log4j.core.lookup.Interpolator` is licensed under the Apache 2.0 license.

View File

@ -1,53 +0,0 @@
import java.io.RandomAccessFile
version = "1.0"
sourceSets.create("agent") {
java {
srcDir("src/main/agent")
}
}
dependencies {
compileOnly("org.apache.logging.log4j:log4j-core:2.0-beta9")
}
tasks.withType<JavaCompile> {
sourceCompatibility = "1.8"
targetCompatibility = "1.8"
doLast {
val tree = fileTree(destinationDirectory)
tree.include("**/*.class")
tree.exclude("module-info.class")
tree.forEach {
RandomAccessFile(it, "rw").use { rf ->
rf.seek(7) // major version
rf.write(50) // java 6
rf.close()
}
}
}
}
val agentJar = tasks.create<Jar>("agentJar") {
dependsOn(tasks.compileJava)
archiveBaseName.set("log4j-patch-agent")
manifest {
attributes("Premain-Class" to "org.glavo.log4j.patch.agent.Log4jAgent")
}
from(sourceSets["agent"].output)
from(sourceSets["main"].output) {
includeEmptyDirs = false
eachFile { path = "org/glavo/log4j/patch/agent/$name.bin" }
}
}
tasks.jar {
enabled = false
dependsOn(agentJar)
}

View File

@ -1,71 +0,0 @@
package org.glavo.log4j.patch.agent;
import java.io.InputStream;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.ProtectionDomain;
import java.util.Arrays;
public final class Log4jAgent {
static final String JNDI_LOOKUP_CLASS_NAME = "org/apache/logging/log4j/core/lookup/JndiLookup";
static final String INTERPOLATOR_CLASS_NAME = "org/apache/logging/log4j/core/lookup/Interpolator";
static final byte[] INTERPOLATOR_CLASS_SHA = {53, 103, 16, 123, 51, 29, 65, -70, -32, 71, -11, 7, 114, -15, 72, 127, 40, -38, 35, 18};
static boolean isBeta = false;
private static byte[] loadResource(String name) {
try {
try (InputStream input = Log4jAgent.class.getResourceAsStream(name)) {
if (input == null) {
throw new AssertionError(name + " not found");
}
int available = input.available();
if (available <= 0) {
throw new AssertionError();
}
byte[] res = new byte[available];
if (input.read(res) != available) {
throw new AssertionError();
}
return res;
}
} catch (Exception ex) {
throw new InternalError(ex);
}
}
public static void premain(String agentArgs, Instrumentation inst) throws Exception {
if ("true".equals(agentArgs)) {
isBeta = true;
}
inst.addTransformer(new Transformer());
}
private static final class Transformer implements ClassFileTransformer {
@Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
if (!isBeta && JNDI_LOOKUP_CLASS_NAME.equals(className)) {
return loadResource("JndiLookup.class.bin");
}
if (isBeta && INTERPOLATOR_CLASS_NAME.equals(className)) {
try {
MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
sha1.update(classfileBuffer);
if (Arrays.equals(INTERPOLATOR_CLASS_SHA, sha1.digest())) {
return loadResource("Interpolator.class.bin");
}
} catch (NoSuchAlgorithmException e) {
throw new InternalError(e);
}
}
return null;
}
}
}

View File

@ -1,155 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache license, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the license for the specific language governing permissions and
* limitations under the license.
*/
package org.apache.logging.log4j.core.lookup;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.plugins.PluginManager;
import org.apache.logging.log4j.core.config.plugins.PluginType;
import org.apache.logging.log4j.status.StatusLogger;
import java.util.HashMap;
import java.util.Map;
/**
* The Interpolator is a StrLookup that acts as a proxy for all the other StrLookups.
*/
public class Interpolator implements StrLookup {
private static final Logger LOGGER = StatusLogger.getLogger();
/** Constant for the prefix separator. */
private static final char PREFIX_SEPARATOR = ':';
private final Map<String, StrLookup> lookups = new HashMap<String, StrLookup>();
private final StrLookup defaultLookup;
@SuppressWarnings("deprecation")
public Interpolator(final StrLookup defaultLookup) {
this.defaultLookup = defaultLookup == null ? new MapLookup(new HashMap<String, String>()) : defaultLookup;
final PluginManager manager = new PluginManager("Lookup");
manager.collectPlugins();
final Map<String, PluginType<?>> plugins = manager.getPlugins();
for (final Map.Entry<String, PluginType<?>> entry : plugins.entrySet()) {
@SuppressWarnings("unchecked")
final Class<? extends StrLookup> clazz = (Class<? extends StrLookup>) entry.getValue().getPluginClass();
try {
lookups.put(entry.getKey(), clazz.newInstance());
} catch (final Exception ex) {
LOGGER.error("Unable to create Lookup for " + entry.getKey(), ex);
}
}
}
/**
* Create the default Interpolator using only Lookups that work without an event.
*/
public Interpolator() {
this.defaultLookup = new MapLookup(new HashMap<String, String>());
lookups.put("sys", new SystemPropertiesLookup());
lookups.put("env", new EnvironmentLookup());
// lookups.put("jndi", new JndiLookup());
LOGGER.warn("Log4j patch works, JNDI lookup is disabled. This message is not a warning, it represents the successful elimination of some security risks. You should be able to play safely.");
try {
if (Class.forName("javax.servlet.ServletContext") != null) {
lookups.put("web", new WebLookup());
}
} catch (ClassNotFoundException ex) {
LOGGER.debug("ServletContext not present - WebLookup not added");
} catch (Exception ex) {
LOGGER.error("Unable to locate ServletContext", ex);
}
}
/**
* Resolves the specified variable. This implementation will try to extract
* a variable prefix from the given variable name (the first colon (':') is
* used as prefix separator). It then passes the name of the variable with
* the prefix stripped to the lookup object registered for this prefix. If
* no prefix can be found or if the associated lookup object cannot resolve
* this variable, the default lookup object will be used.
*
* @param var the name of the variable whose value is to be looked up
* @return the value of this variable or <b>null</b> if it cannot be
* resolved
*/
@Override
public String lookup(final String var) {
return lookup(null, var);
}
/**
* Resolves the specified variable. This implementation will try to extract
* a variable prefix from the given variable name (the first colon (':') is
* used as prefix separator). It then passes the name of the variable with
* the prefix stripped to the lookup object registered for this prefix. If
* no prefix can be found or if the associated lookup object cannot resolve
* this variable, the default lookup object will be used.
*
* @param event The current LogEvent or null.
* @param var the name of the variable whose value is to be looked up
* @return the value of this variable or <b>null</b> if it cannot be
* resolved
*/
@Override
public String lookup(final LogEvent event, String var) {
if (var == null) {
return null;
}
final int prefixPos = var.indexOf(PREFIX_SEPARATOR);
if (prefixPos >= 0) {
final String prefix = var.substring(0, prefixPos);
final String name = var.substring(prefixPos + 1);
final StrLookup lookup = lookups.get(prefix);
String value = null;
if (lookup != null) {
value = event == null ? lookup.lookup(name) : lookup.lookup(event, name);
}
if (value != null) {
return value;
}
var = var.substring(prefixPos + 1);
}
if (defaultLookup != null) {
return event == null ? defaultLookup.lookup(var) : defaultLookup.lookup(event, var);
}
return null;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
for (final String name : lookups.keySet()) {
if (sb.length() == 0) {
sb.append("{");
} else {
sb.append(", ");
}
sb.append(name);
}
if (sb.length() > 0) {
sb.append("}");
}
return sb.toString();
}
}

View File

@ -1,13 +0,0 @@
/*
* Copyright © 2021 Glavo <zjx001202@gmail.com>
* This work is free. You can redistribute it and/or modify it under the
* terms of the Do What The Fuck You Want To Public License, Version 2,
* as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
*/
package org.apache.logging.log4j.core.lookup;
public class JndiLookup {
public JndiLookup() {
throw new NoClassDefFoundError("JNDI lookup is disabled. This is not an error. We are blocking some vulnerabilities through it. You should be able to play safely.");
}
}

View File

@ -2,11 +2,10 @@ rootProject.name = "HMCL3"
include( include(
"HMCL", "HMCL",
"HMCLCore", "HMCLCore",
"HMCLTransformerDiscoveryService", "HMCLTransformerDiscoveryService"
"log4j-patch"
) )
val minecraftLibraries = listOf("log4j-patch", "HMCLTransformerDiscoveryService") val minecraftLibraries = listOf("HMCLTransformerDiscoveryService")
for (library in minecraftLibraries) { for (library in minecraftLibraries) {
project(":$library").projectDir = file("minecraft/libraries/$library") project(":$library").projectDir = file("minecraft/libraries/$library")