Launcher/LaunchServer/src/main/java/pro/gravit/launchserver/StarterAgent.java

67 lines
2.5 KiB
Java
Raw Normal View History

package pro.gravit.launchserver;
2018-09-17 10:07:32 +03:00
import java.io.IOException;
import java.lang.instrument.Instrumentation;
2019-10-19 19:46:04 +03:00
import java.nio.file.*;
2018-09-17 10:07:32 +03:00
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFilePermission;
2020-04-05 10:27:04 +03:00
import java.util.*;
2018-09-17 10:07:32 +03:00
import java.util.jar.JarFile;
2019-01-09 11:29:54 +03:00
public final class StarterAgent {
2018-09-17 10:07:32 +03:00
2020-04-05 10:27:04 +03:00
public static Instrumentation inst = null;
public static Path libraries = null;
private static boolean isStarted = false;
public static boolean isAgentStarted() {
return isStarted;
}
public static void premain(String agentArgument, Instrumentation inst) {
StarterAgent.inst = inst;
2020-09-25 18:44:39 +03:00
libraries = Paths.get(Optional.ofNullable(agentArgument).map(String::trim).filter(e -> !e.isEmpty()).orElse("libraries"));
2020-04-05 10:27:04 +03:00
isStarted = true;
try {
Files.walkFileTree(libraries, Collections.singleton(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new StarterVisitor());
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
2019-01-09 11:29:54 +03:00
private static final class StarterVisitor extends SimpleFileVisitor<Path> {
2019-05-15 14:11:22 +03:00
private static final Set<PosixFilePermission> DPERMS;
static {
Set<PosixFilePermission> perms = new HashSet<>(Arrays.asList(PosixFilePermission.values()));
perms.remove(PosixFilePermission.OTHERS_WRITE);
perms.remove(PosixFilePermission.GROUP_WRITE);
DPERMS = Collections.unmodifiableSet(perms);
}
2018-09-17 10:07:32 +03:00
2019-05-15 14:11:22 +03:00
private final boolean fixLib;
2019-05-15 14:11:22 +03:00
private StarterVisitor() {
2020-09-25 18:44:39 +03:00
Path filef = StarterAgent.libraries.resolve(".libraries_chmoded");
this.fixLib = !Files.exists(filef) && !Boolean.getBoolean("launcher.noLibrariesPosixPermsFix");
if (fixLib) {
2019-05-15 14:11:22 +03:00
try {
Files.deleteIfExists(filef);
Files.createFile(filef);
} catch (Throwable ignored) {
}
}
2018-09-22 17:33:00 +03:00
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
2019-05-15 14:11:22 +03:00
if (fixLib && Files.getFileAttributeView(file, PosixFileAttributeView.class) != null)
Files.setPosixFilePermissions(file, DPERMS);
2018-09-22 17:33:00 +03:00
if (file.toFile().getName().endsWith(".jar"))
inst.appendToSystemClassLoaderSearch(new JarFile(file.toFile()));
return super.visitFile(file, attrs);
}
}
2018-09-17 10:07:32 +03:00
}