Search in sources :

Example 11 with JarFile

use of java.util.jar.JarFile in project hadoop by apache.

the class JarFinder method createJar.

private static void createJar(File dir, File jarFile) throws IOException {
    Preconditions.checkNotNull(dir, "dir");
    Preconditions.checkNotNull(jarFile, "jarFile");
    File jarDir = jarFile.getParentFile();
    if (!jarDir.exists()) {
        if (!jarDir.mkdirs()) {
            throw new IOException(MessageFormat.format("could not create dir [{0}]", jarDir));
        }
    }
    JarOutputStream zos = new JarOutputStream(new FileOutputStream(jarFile));
    jarDir(dir, "", zos);
}
Also used : FileOutputStream(java.io.FileOutputStream) JarOutputStream(java.util.jar.JarOutputStream) IOException(java.io.IOException) JarFile(java.util.jar.JarFile) File(java.io.File)

Example 12 with JarFile

use of java.util.jar.JarFile in project MinecraftForge by MinecraftForge.

the class FMLSanityChecker method call.

@Override
public Void call() throws Exception {
    CodeSource codeSource = getClass().getProtectionDomain().getCodeSource();
    boolean goodFML = false;
    boolean fmlIsJar = false;
    if (codeSource.getLocation().getProtocol().equals("jar")) {
        fmlIsJar = true;
        Certificate[] certificates = codeSource.getCertificates();
        if (certificates != null) {
            for (Certificate cert : certificates) {
                String fingerprint = CertificateHelper.getFingerprint(cert);
                if (fingerprint.equals(FMLFINGERPRINT)) {
                    FMLRelaunchLog.info("Found valid fingerprint for FML. Certificate fingerprint %s", fingerprint);
                    goodFML = true;
                } else if (fingerprint.equals(FORGEFINGERPRINT)) {
                    FMLRelaunchLog.info("Found valid fingerprint for Minecraft Forge. Certificate fingerprint %s", fingerprint);
                    goodFML = true;
                } else {
                    FMLRelaunchLog.severe("Found invalid fingerprint for FML: %s", fingerprint);
                }
            }
        }
    } else {
        goodFML = true;
    }
    // Server is not signed, so assume it's good - a deobf env is dev time so it's good too
    boolean goodMC = FMLLaunchHandler.side() == Side.SERVER || !liveEnv;
    int certCount = 0;
    try {
        Class<?> cbr = Class.forName("net.minecraft.client.ClientBrandRetriever", false, cl);
        codeSource = cbr.getProtectionDomain().getCodeSource();
    } catch (Exception e) {
        // Probably a development environment, or the server (the server is not signed)
        goodMC = true;
    }
    JarFile mcJarFile = null;
    if (fmlIsJar && !goodMC && codeSource.getLocation().getProtocol().equals("jar")) {
        try {
            String mcPath = codeSource.getLocation().getPath().substring(5);
            mcPath = mcPath.substring(0, mcPath.lastIndexOf('!'));
            mcPath = URLDecoder.decode(mcPath, Charsets.UTF_8.name());
            mcJarFile = new JarFile(mcPath, true);
            mcJarFile.getManifest();
            JarEntry cbrEntry = mcJarFile.getJarEntry("net/minecraft/client/ClientBrandRetriever.class");
            InputStream mcJarFileInputStream = mcJarFile.getInputStream(cbrEntry);
            try {
                ByteStreams.toByteArray(mcJarFileInputStream);
            } finally {
                IOUtils.closeQuietly(mcJarFileInputStream);
            }
            Certificate[] certificates = cbrEntry.getCertificates();
            certCount = certificates != null ? certificates.length : 0;
            if (certificates != null) {
                for (Certificate cert : certificates) {
                    String fingerprint = CertificateHelper.getFingerprint(cert);
                    if (fingerprint.equals(MCFINGERPRINT)) {
                        FMLRelaunchLog.info("Found valid fingerprint for Minecraft. Certificate fingerprint %s", fingerprint);
                        goodMC = true;
                    }
                }
            }
        } catch (Throwable e) {
            FMLRelaunchLog.log(Level.ERROR, e, "A critical error occurred trying to read the minecraft jar file");
        } finally {
            Java6Utils.closeZipQuietly(mcJarFile);
        }
    } else {
        goodMC = true;
    }
    if (!goodMC) {
        FMLRelaunchLog.severe("The minecraft jar %s appears to be corrupt! There has been CRITICAL TAMPERING WITH MINECRAFT, it is highly unlikely minecraft will work! STOP NOW, get a clean copy and try again!", codeSource.getLocation().getFile());
        if (!Boolean.parseBoolean(System.getProperty("fml.ignoreInvalidMinecraftCertificates", "false"))) {
            FMLRelaunchLog.severe("For your safety, FML will not launch minecraft. You will need to fetch a clean version of the minecraft jar file");
            FMLRelaunchLog.severe("Technical information: The class net.minecraft.client.ClientBrandRetriever should have been associated with the minecraft jar file, " + "and should have returned us a valid, intact minecraft jar location. This did not work. Either you have modified the minecraft jar file (if so " + "run the forge installer again), or you are using a base editing jar that is changing this class (and likely others too). If you REALLY " + "want to run minecraft in this configuration, add the flag -Dfml.ignoreInvalidMinecraftCertificates=true to the 'JVM settings' in your launcher profile.");
            FMLCommonHandler.instance().exitJava(1, false);
        } else {
            FMLRelaunchLog.severe("FML has been ordered to ignore the invalid or missing minecraft certificate. This is very likely to cause a problem!");
            FMLRelaunchLog.severe("Technical information: ClientBrandRetriever was at %s, there were %d certificates for it", codeSource.getLocation(), certCount);
        }
    }
    if (!goodFML) {
        FMLRelaunchLog.severe("FML appears to be missing any signature data. This is not a good thing");
    }
    return null;
}
Also used : InputStream(java.io.InputStream) CodeSource(java.security.CodeSource) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) Certificate(java.security.cert.Certificate)

Example 13 with JarFile

use of java.util.jar.JarFile in project MinecraftForge by MinecraftForge.

the class GenDiffSet method main.

public static void main(String[] args) throws IOException {
    //Clean Vanilla jar minecraft.jar or minecraft_server.jar
    String sourceJar = args[0];
    //Directory containing obfed output classes, typically mcp/reobf/minecraft
    String targetDir = args[1];
    //Path to FML's deobfusication_data.lzma
    String deobfData = args[2];
    //Path to place generated .binpatch
    String outputDir = args[3];
    //"true" if we should destroy the target file if it generated a successful .binpatch
    String killTarget = args[4];
    LogManager.getLogger("GENDIFF").log(Level.INFO, String.format("Creating patches at %s for %s from %s", outputDir, sourceJar, targetDir));
    Delta delta = new Delta();
    FMLDeobfuscatingRemapper remapper = FMLDeobfuscatingRemapper.INSTANCE;
    remapper.setupLoadOnly(deobfData, false);
    JarFile sourceZip = new JarFile(sourceJar);
    boolean kill = killTarget.equalsIgnoreCase("true");
    File f = new File(outputDir);
    f.mkdirs();
    for (String name : remapper.getObfedClasses()) {
        //            Logger.getLogger("GENDIFF").info(String.format("Evaluating path for data :%s",name));
        String fileName = name;
        String jarName = name;
        if (RESERVED_NAMES.contains(name.toUpperCase(Locale.ENGLISH))) {
            fileName = "_" + name;
        }
        File targetFile = new File(targetDir, fileName.replace('/', File.separatorChar) + ".class");
        jarName = jarName + ".class";
        if (targetFile.exists()) {
            String sourceClassName = name.replace('/', '.');
            String targetClassName = remapper.map(name).replace('/', '.');
            JarEntry entry = sourceZip.getJarEntry(jarName);
            byte[] vanillaBytes = toByteArray(sourceZip, entry);
            byte[] patchedBytes = Files.toByteArray(targetFile);
            byte[] diff = delta.compute(vanillaBytes, patchedBytes);
            ByteArrayDataOutput diffOut = ByteStreams.newDataOutput(diff.length + 50);
            // Original name
            diffOut.writeUTF(name);
            // Source name
            diffOut.writeUTF(sourceClassName);
            // Target name
            diffOut.writeUTF(targetClassName);
            // exists at original
            diffOut.writeBoolean(entry != null);
            if (entry != null) {
                diffOut.writeInt(Hashing.adler32().hashBytes(vanillaBytes).asInt());
            }
            // length of patch
            diffOut.writeInt(diff.length);
            // patch
            diffOut.write(diff);
            File target = new File(outputDir, targetClassName + ".binpatch");
            target.getParentFile().mkdirs();
            Files.write(diffOut.toByteArray(), target);
            Logger.getLogger("GENDIFF").info(String.format("Wrote patch for %s (%s) at %s", name, targetClassName, target.getAbsolutePath()));
            if (kill) {
                targetFile.delete();
                Logger.getLogger("GENDIFF").info(String.format("  Deleted target: %s", targetFile.toString()));
            }
        }
    }
    sourceZip.close();
}
Also used : FMLDeobfuscatingRemapper(net.minecraftforge.fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper) Delta(net.minecraftforge.fml.repackage.com.nothome.delta.Delta) ByteArrayDataOutput(com.google.common.io.ByteArrayDataOutput) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) JarFile(java.util.jar.JarFile) File(java.io.File)

Example 14 with JarFile

use of java.util.jar.JarFile in project atlas by alibaba.

the class ProcessAwoAndroidResources method doFullTaskAction.

@Override
protected void doFullTaskAction() throws IOException {
    // we have to clean the source folder output in case the package name changed.
    File srcOut = getSourceOutputDir();
    if (srcOut != null) {
        // FileUtils.emptyFolder(srcOut);
        srcOut.delete();
        srcOut.mkdirs();
    }
    @Nullable File resOutBaseNameFile = getPackageOutputFile();
    // If are in instant run mode and we have an instant run enabled manifest
    File instantRunManifest = getInstantRunManifestFile();
    File manifestFileToPackage = instantRunBuildContext.isInInstantRunMode() && instantRunManifest != null && instantRunManifest.exists() ? instantRunManifest : getManifestFile();
    // 增加awb模块编译所需要的额外参数
    addAaptOptions();
    AaptPackageProcessBuilder aaptPackageCommandBuilder = new AaptPackageProcessBuilder(manifestFileToPackage, getAaptOptions()).setAssetsFolder(getAssetsDir()).setResFolder(getResDir()).setLibraries(getLibraries()).setPackageForR(getPackageForR()).setSourceOutputDir(absolutePath(srcOut)).setSymbolOutputDir(absolutePath(getTextSymbolOutputDir())).setResPackageOutput(absolutePath(resOutBaseNameFile)).setProguardOutput(absolutePath(getProguardOutputFile())).setType(getType()).setDebuggable(getDebuggable()).setPseudoLocalesEnabled(getPseudoLocalesEnabled()).setResourceConfigs(getResourceConfigs()).setSplits(getSplits()).setPreferredDensity(getPreferredDensity());
    @NonNull AtlasBuilder builder = (AtlasBuilder) getBuilder();
    // MergingLog mergingLog = new MergingLog(getMergeBlameLogFolder());
    //
    // ProcessOutputHandler processOutputHandler = new ParsingProcessOutputHandler(
    // new ToolOutputParser(new AaptOutputParser(), getILogger()),
    // builder.getErrorReporter());
    ProcessOutputHandler processOutputHandler = new LoggedProcessOutputHandler(getILogger());
    try {
        builder.processAwbResources(aaptPackageCommandBuilder, getEnforceUniquePackageName(), processOutputHandler, getMainSymbolFile());
        if (resOutBaseNameFile != null) {
            if (instantRunBuildContext.isInInstantRunMode()) {
                instantRunBuildContext.addChangedFile(InstantRunBuildContext.FileType.RESOURCES, resOutBaseNameFile);
                // get the new manifest file CRC
                JarFile jarFile = new JarFile(resOutBaseNameFile);
                String currentIterationCRC = null;
                try {
                    ZipEntry entry = jarFile.getEntry(SdkConstants.ANDROID_MANIFEST_XML);
                    if (entry != null) {
                        currentIterationCRC = String.valueOf(entry.getCrc());
                    }
                } finally {
                    jarFile.close();
                }
                // check the manifest file binary format.
                File crcFile = new File(instantRunSupportDir, "manifest.crc");
                if (crcFile.exists() && currentIterationCRC != null) {
                    // compare its content with the new binary file crc.
                    String previousIterationCRC = Files.readFirstLine(crcFile, Charsets.UTF_8);
                    if (!currentIterationCRC.equals(previousIterationCRC)) {
                        instantRunBuildContext.close();
                        instantRunBuildContext.setVerifierResult(InstantRunVerifierStatus.BINARY_MANIFEST_FILE_CHANGE);
                    }
                }
                // write the new manifest file CRC.
                Files.createParentDirs(crcFile);
                Files.write(currentIterationCRC, crcFile, Charsets.UTF_8);
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } catch (ProcessException e) {
        throw new RuntimeException(e);
    }
}
Also used : LoggedProcessOutputHandler(com.android.ide.common.process.LoggedProcessOutputHandler) ProcessOutputHandler(com.android.ide.common.process.ProcessOutputHandler) ZipEntry(java.util.zip.ZipEntry) IOException(java.io.IOException) JarFile(java.util.jar.JarFile) ProcessException(com.android.ide.common.process.ProcessException) AaptPackageProcessBuilder(com.android.builder.core.AaptPackageProcessBuilder) NonNull(com.android.annotations.NonNull) AtlasBuilder(com.android.builder.core.AtlasBuilder) LoggedProcessOutputHandler(com.android.ide.common.process.LoggedProcessOutputHandler) JarFile(java.util.jar.JarFile) OutputFile(org.gradle.api.tasks.OutputFile) File(java.io.File) InputFile(org.gradle.api.tasks.InputFile) Nullable(com.android.annotations.Nullable)

Example 15 with JarFile

use of java.util.jar.JarFile in project buck by facebook.

the class StubJarIntegrationTest method abiJarManifestShouldContainHashesOfItsFiles.

@Test
public void abiJarManifestShouldContainHashesOfItsFiles() throws IOException {
    Path out = Paths.get("junit-abi.jar");
    Path regularJar = testDataDir.resolve("junit.jar");
    new StubJar(regularJar).writeTo(filesystem, out);
    try (JarFile stubJar = new JarFile(filesystem.resolve(out).toFile())) {
        Manifest manifest = stubJar.getManifest();
        Enumeration<JarEntry> entries = stubJar.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            if (JarFile.MANIFEST_NAME.equals(entry.getName())) {
                continue;
            }
            String seenDigest = manifest.getAttributes(entry.getName()).getValue("Murmur3-128-Digest");
            String expectedDigest;
            try (InputStream inputStream = stubJar.getInputStream(entry)) {
                ByteSource byteSource = ByteSource.wrap(ByteStreams.toByteArray(inputStream));
                expectedDigest = byteSource.hash(Hashing.murmur3_128()).toString();
            }
            assertEquals(String.format("Digest mismatch for %s", entry.getName()), expectedDigest, seenDigest);
        }
    }
}
Also used : Path(java.nio.file.Path) InputStream(java.io.InputStream) ByteSource(com.google.common.io.ByteSource) JarFile(java.util.jar.JarFile) Manifest(java.util.jar.Manifest) JarEntry(java.util.jar.JarEntry) Test(org.junit.Test)

Aggregations

JarFile (java.util.jar.JarFile)1366 File (java.io.File)720 JarEntry (java.util.jar.JarEntry)616 IOException (java.io.IOException)587 URL (java.net.URL)272 InputStream (java.io.InputStream)271 ZipEntry (java.util.zip.ZipEntry)203 Manifest (java.util.jar.Manifest)186 ArrayList (java.util.ArrayList)158 Test (org.junit.Test)131 JarURLConnection (java.net.JarURLConnection)123 FileOutputStream (java.io.FileOutputStream)122 ZipFile (java.util.zip.ZipFile)121 FileInputStream (java.io.FileInputStream)111 Attributes (java.util.jar.Attributes)110 MalformedURLException (java.net.MalformedURLException)94 Enumeration (java.util.Enumeration)67 JarOutputStream (java.util.jar.JarOutputStream)65 HashSet (java.util.HashSet)58 URLClassLoader (java.net.URLClassLoader)55