Exemple #1
1
  /** @throws IOException */
  public void createJar() throws IOException {
    Manifest manifest = new Manifest();

    setDefaultAttributes(metaInfAttributes);

    for (String attrName : metaInfAttributes.keySet()) {
      manifest.getMainAttributes().putValue(attrName, metaInfAttributes.get(attrName));
    }

    removeOldJar();

    if (unpackaged) {
      for (File inputDir : inputDirectory) {
        FileUtils.copyFilesFromDir(inputDir, outputFile, getIncludes(), getExcludes());
      }
      File metaInfDir = new File(outputFile, "META-INF");
      metaInfDir.mkdirs();
      manifest.write(new FileOutputStream(new File(metaInfDir, "MANIFEST.MF")));
    } else {
      File parentFile = outputFile.getParentFile();
      if (parentFile != null && !parentFile.exists()) {
        parentFile.mkdirs();
      }

      JarOutputStream target = new JarOutputStream(new FileOutputStream(outputFile), manifest);

      if (inputDirectory != null) {
        Set<String> added = new HashSet<String>();
        for (File inputDir : inputDirectory) {
          addFile(inputDir, target, inputDir.getCanonicalPath().length(), added);
        }
      }
      target.close();
    }
  }
Exemple #2
0
  private static void writeSignatureFile(Manifest manifest, SignatureOutputStream out)
      throws IOException, GeneralSecurityException {
    Manifest sf = new Manifest();
    Attributes main = sf.getMainAttributes();
    main.putValue("Signature-Version", "1.0");
    main.putValue("Created-By", "1.0 (KApkSigner)");
    BASE64Encoder base64 = new BASE64Encoder();
    MessageDigest md = MessageDigest.getInstance("SHA1");
    PrintStream print =
        new PrintStream(new DigestOutputStream(new ByteArrayOutputStream(), md), true, "UTF-8");
    manifest.write(print);
    print.flush();
    main.putValue("SHA1-Digest-Manifest", base64.encode(md.digest()));
    Map<String, Attributes> entries = manifest.getEntries();
    for (Map.Entry<String, Attributes> entry : entries.entrySet()) {
      // Digest of the manifest stanza for this entry.
      print.print("Name: " + entry.getKey() + "\r\n");
      for (Map.Entry<Object, Object> att : entry.getValue().entrySet()) {
        print.print(att.getKey() + ": " + att.getValue() + "\r\n");
      }
      print.print("\r\n");
      print.flush();

      Attributes sfAttr = new Attributes();
      sfAttr.putValue("SHA1-Digest", base64.encode(md.digest()));
      sf.getEntries().put(entry.getKey(), sfAttr);
    }
    sf.write(out);
    if (out.size() % 1024 == 0) {
      out.write('\r');
      out.write('\n');
    }
  }
  /* transform manifest in an array of byte
      if any code error, exit
      else if any error, show dialog, then return nil
  */
  public static byte[] s_toByteArray(Manifest man, Frame frmOwner) {
    String strMethod = _f_s_strClass + "s_toByteArray(...)";

    if (man == null) {
      MySystem.s_printOutExit(strMethod, "nil man");
    }

    ByteArrayOutputStream baoBuffer = new ByteArrayOutputStream();

    try {
      man.write(baoBuffer);
      baoBuffer.flush();
      baoBuffer.close();
    } catch (IOException excIO) {
      excIO.printStackTrace();
      MySystem.s_printOutExit(strMethod, "excIO caught");

      String strBody = "Got IO exception";

      OPAbstract.s_showDialogError(frmOwner, strBody);

      return null;
    }

    return baoBuffer.toByteArray();
  }
Exemple #4
0
  public static boolean extractJarDir(String jarfile, String outfile) throws Exception {
    long filesize = new File(jarfile).length();
    JarInputStream jar = new JarInputStream(new FileInputStream(jarfile));
    // while (true) {
    //	JarEntry jarentry = (JarEntry)jar.getNextJarEntry();
    //	if (jarentry==null) break;
    //	String maindir = jarentry.getName();
    //	// get rid of "./" and "/" prefix
    //	if (maindir.startsWith("."))
    //		maindir = maindir.substring(1);
    //	if (maindir.startsWith(File.separator))
    //		maindir = maindir.substring(1);
    //	// Find manifest
    //	System.out.println(maindir);
    //	if (maindir.equals("META-INF/MANIFEST.MF")) {
    //		java.io.InputStream ins = jar;

    java.io.FileOutputStream outs = new java.io.FileOutputStream(outfile);
    Manifest man = jar.getManifest();
    if (man == null) return false;
    man.write(outs);
    byte[] buf = ("MIDlet-Jar-Size: " + filesize).getBytes();
    outs.write(buf, 0, buf.length);
    outs.close();
    //		// copy buffered (is a lot faster than one byte at a time)
    //		byte[] buf = new byte[8192];
    //		int total_bytes=0;
    //		while (true) {
    //			//outs.write(ins.read());
    //			int len = ins.read(buf);
    //			if (len < 0) break;
    //			outs.write(buf,0,len);
    //			total_bytes += len;
    //		}
    //		buf = ("MIDlet-Jar-Size: "+total_bytes).getBytes();
    //		outs.write(buf,0,buf.length);
    //		outs.close();
    //		//ins.close();
    //	}
    // }
    // return false;
    // remove empty lines from the generated jad which may have been
    // introduced by manifest write.
    // some systems have trouble with empty lines
    List<String> lines = new ArrayList<String>();
    BufferedReader in = new BufferedReader(new FileReader(outfile));
    while (true) {
      String line = in.readLine();
      if (line == null) break;
      lines.add(line);
    }
    in.close();
    PrintWriter outp = new PrintWriter(outfile);
    for (String s : lines) {
      if (s.trim().equals("")) continue;
      outp.println(s);
    }
    outp.close();
    return true;
  }
  public void test_1562() throws Exception {
    Manifest man = new Manifest();
    Attributes att = man.getMainAttributes();
    att.put(Attributes.Name.MANIFEST_VERSION, "1.0");
    att.put(Attributes.Name.MAIN_CLASS, "foo.bar.execjartest.Foo");

    File outputZip = File.createTempFile("hyts_", ".zip");
    outputZip.deleteOnExit();
    ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(outputZip));
    File resources = Support_Resources.createTempFolder();

    for (String zipClass : new String[] {"Foo", "Bar"}) {
      zout.putNextEntry(new ZipEntry("foo/bar/execjartest/" + zipClass + ".class"));
      zout.write(getResource(resources, "hyts_" + zipClass + ".ser"));
    }

    zout.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF"));
    man.write(zout);
    zout.close();

    // set up the VM parameters
    String[] args = new String[] {"-jar", outputZip.getAbsolutePath()};

    // execute the JAR and read the result
    String res = Support_Exec.execJava(args, null, false);

    assertTrue("Error executing ZIP : result returned was incorrect.", res.startsWith("FOOBAR"));
  }
  public BundleDescription(
      URL systemLocation,
      URL serverLocation,
      Manifest manifest,
      boolean systemLibrary,
      String md5Digest) {
    if (systemLocation == null) {
      throw new IllegalArgumentException("systemLocation must not be null");
    }
    if (serverLocation == null) {
      throw new IllegalArgumentException("serverLocation must not be null");
    }
    if (manifest == null) {
      throw new IllegalArgumentException("manifest must not be null");
    }
    if (md5Digest == null) {
      throw new IllegalArgumentException("md5Digest must not be null");
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
      manifest.write(out);
    } catch (IOException ex) {
      throw new IllegalStateException("ByteArrayOutputStream never should throw IOException", ex);
    }

    this.location = serverLocation;
    this.manifestData = out.toByteArray();
    this.systemLibrary = systemLibrary;
    this.md5Digest = md5Digest;
  }
  public void execute() throws MojoExecutionException {
    try {
      File out = new File(project.getBasedir(), jars);
      for (Iterator i = getIncludedArtifacts().iterator(); i.hasNext(); ) {
        Artifact a = (Artifact) i.next();
        FileUtils.copyFileToDirectory(a.getFile(), out);
      }

      if (packageSources) {
        packageSources(getIncludedArtifacts());
      }

      Manifest manifest = getManifest();
      File metaInf = new File(project.getBasedir(), "META-INF");
      metaInf.mkdirs();
      BufferedOutputStream os =
          new BufferedOutputStream(new FileOutputStream(new File(metaInf, "MANIFEST.MF")));
      manifest.write(os);
      os.close();

      //			packageBundle();
    } catch (Exception e) {
      throw new MojoExecutionException(e.getMessage(), e);
    }
  }
  public static void transform(URL url, OutputStream os) throws Exception {
    // Build dom document
    Document doc = parse(url);
    // Heuristicly retrieve name and version
    String name = getPath(url);
    int idx = name.lastIndexOf('/');
    if (idx >= 0) {
      name = name.substring(idx + 1);
    }
    String[] str = DeployerUtils.extractNameVersionType(name);
    // Create manifest
    Manifest m = new Manifest();
    m.getMainAttributes().putValue("Manifest-Version", "2");
    m.getMainAttributes().putValue(Constants.BUNDLE_MANIFESTVERSION, "2");
    m.getMainAttributes().putValue(Constants.BUNDLE_SYMBOLICNAME, str[0]);
    m.getMainAttributes().putValue(Constants.BUNDLE_VERSION, str[1]);
    String importPkgs = getImportPackages(analyze(new DOMSource(doc)));
    if (importPkgs != null && importPkgs.length() > 0) {
      m.getMainAttributes().putValue(Constants.IMPORT_PACKAGE, importPkgs);
    }
    m.getMainAttributes().putValue(Constants.DYNAMICIMPORT_PACKAGE, "*");
    // Extract manifest entries from the DOM
    NodeList l = doc.getElementsByTagName("manifest");
    if (l != null) {
      for (int i = 0; i < l.getLength(); i++) {
        Element e = (Element) l.item(i);
        String text = e.getTextContent();
        Properties props = new Properties();
        props.load(new ByteArrayInputStream(text.trim().getBytes()));
        Enumeration en = props.propertyNames();
        while (en.hasMoreElements()) {
          String k = (String) en.nextElement();
          String v = props.getProperty(k);
          m.getMainAttributes().putValue(k, v);
        }
        e.getParentNode().removeChild(e);
      }
    }

    JarOutputStream out = new JarOutputStream(os);
    ZipEntry e = new ZipEntry(JarFile.MANIFEST_NAME);
    out.putNextEntry(e);
    m.write(out);
    out.closeEntry();
    e = new ZipEntry("OSGI-INF/");
    out.putNextEntry(e);
    e = new ZipEntry("OSGI-INF/blueprint/");
    out.putNextEntry(e);
    out.closeEntry();
    // check .xml file extension
    if (!name.endsWith(".xml")) {
      name += ".xml";
    }
    e = new ZipEntry("OSGI-INF/blueprint/" + name);
    out.putNextEntry(e);
    // Copy the new DOM
    XmlUtils.transform(new DOMSource(doc), new StreamResult(out));
    out.closeEntry();
    out.close();
  }
  /**
   * tests case when Main-Class is not in the zip launched but in another zip referenced by
   * Class-Path
   *
   * @throws Exception in case of troubles
   */
  public void test_main_class_in_another_zip() throws Exception {
    File fooZip = File.createTempFile("hyts_", ".zip");
    File barZip = File.createTempFile("hyts_", ".zip");
    fooZip.deleteOnExit();
    barZip.deleteOnExit();

    // create the manifest
    Manifest man = new Manifest();
    Attributes att = man.getMainAttributes();
    att.put(Attributes.Name.MANIFEST_VERSION, "1.0");
    att.put(Attributes.Name.MAIN_CLASS, "foo.bar.execjartest.Foo");
    att.put(Attributes.Name.CLASS_PATH, fooZip.getName());

    File resources = Support_Resources.createTempFolder();

    ZipOutputStream zoutFoo = new ZipOutputStream(new FileOutputStream(fooZip));
    zoutFoo.putNextEntry(new ZipEntry("foo/bar/execjartest/Foo.class"));
    zoutFoo.write(getResource(resources, "hyts_Foo.ser"));
    zoutFoo.close();

    ZipOutputStream zoutBar = new ZipOutputStream(new FileOutputStream(barZip));
    zoutBar.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF"));
    man.write(zoutBar);

    zoutBar.putNextEntry(new ZipEntry("foo/bar/execjartest/Bar.class"));
    zoutBar.write(getResource(resources, "hyts_Bar.ser"));
    zoutBar.close();

    String[] args = new String[] {"-jar", barZip.getAbsolutePath()};

    // execute the JAR and read the result
    String res = Support_Exec.execJava(args, null, false);

    assertTrue("Error executing JAR : result returned was incorrect.", res.startsWith("FOOBAR"));
  }
Exemple #10
0
  /** Write the signature file to the given output stream. */
  private void generateSignatureFile(Manifest manifest, OutputStream out)
      throws IOException, GeneralSecurityException {
    out.write(("Signature-Version: 1.0\r\n").getBytes());
    out.write(("Created-By: 1.0 (Android SignApk)\r\n").getBytes());

    // BASE64Encoder base64 = new BASE64Encoder();
    MessageDigest md = MessageDigest.getInstance("SHA1");
    PrintStream print =
        new PrintStream(new DigestOutputStream(new ByteArrayOutputStream(), md), true, "UTF-8");

    // Digest of the entire manifest
    manifest.write(print);
    print.flush();

    out.write(("SHA1-Digest-Manifest: " + Base64.encode(md.digest()) + "\r\n\r\n").getBytes());

    Map<String, Attributes> entries = manifest.getEntries();
    for (Map.Entry<String, Attributes> entry : entries.entrySet()) {
      if (canceled) break;
      progressHelper.progress(ProgressEvent.PRORITY_NORMAL, "Generating signature file");
      // Digest of the manifest stanza for this entry.
      String nameEntry = "Name: " + entry.getKey() + "\r\n";
      print.print(nameEntry);
      for (Map.Entry<Object, Object> att : entry.getValue().entrySet()) {
        print.print(att.getKey() + ": " + att.getValue() + "\r\n");
      }
      print.print("\r\n");
      print.flush();

      out.write(nameEntry.getBytes());
      out.write(("SHA1-Digest: " + Base64.encode(md.digest()) + "\r\n\r\n").getBytes());
    }
  }
Exemple #11
0
 /** Creates a new JAR file. */
 void create(OutputStream out, Manifest manifest) throws IOException {
   ZipOutputStream zos = new JarOutputStream(out);
   if (flag0) {
     zos.setMethod(ZipOutputStream.STORED);
   }
   if (manifest != null) {
     if (vflag) {
       output(getMsg("out.added.manifest"));
     }
     ZipEntry e = new ZipEntry(MANIFEST_DIR);
     e.setTime(System.currentTimeMillis());
     e.setSize(0);
     e.setCrc(0);
     zos.putNextEntry(e);
     e = new ZipEntry(MANIFEST_NAME);
     e.setTime(System.currentTimeMillis());
     if (flag0) {
       crc32Manifest(e, manifest);
     }
     zos.putNextEntry(e);
     manifest.write(zos);
     zos.closeEntry();
   }
   for (File file : entries) {
     addFile(zos, file);
   }
   zos.close();
 }
  /**
   * Write the manifest
   *
   * @throws Exception In case of error
   */
  public void write() throws Exception {
    File manifestFile = new File(manifestFolder.getAbsolutePath() + File.separator + manifestName);

    FileOutputStream outStream = new FileOutputStream(manifestFile, false);

    Attributes attributes = manifest.getMainAttributes();
    setAttributes(attributes);

    manifest.write(outStream);
  }
Exemple #13
0
  public static void testSimple() throws Exception {
    Builder bmaker = new Builder();
    bmaker.addClasspath(IO.getFile("jar/mina.jar"));
    bmaker.set("Export-Package", "org.apache.mina.*;version=1");
    bmaker.set("DynamicImport-Package", "org.slf4j");
    Jar jar = bmaker.build();
    assertTrue(bmaker.check());

    Manifest m = jar.getManifest();
    m.write(System.err);
    assertTrue(m.getMainAttributes().getValue("Import-Package").indexOf("org.slf4j") >= 0);
    assertTrue(m.getMainAttributes().getValue("DynamicImport-Package").indexOf("org.slf4j") >= 0);
  }
  public void test_writeLjava_io_OutputStream() throws IOException {
    byte b[];
    Manifest manifest1 = null;
    Manifest manifest2 = null;
    try {
      manifest1 =
          new Manifest(new URL(Support_Resources.getURL("manifest/hyts_MANIFEST.MF")).openStream());
    } catch (MalformedURLException e) {
      fail("Malformed URL");
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    manifest1.write(baos);

    b = baos.toByteArray();

    File f = File.createTempFile("111", "111");
    FileOutputStream fos = new FileOutputStream(f);
    fos.close();
    try {
      manifest1.write(fos);
      fail("IOException expected");
    } catch (IOException e) {
      // expected
    }
    f.delete();

    ByteArrayInputStream bais = new ByteArrayInputStream(b);

    try {
      manifest2 = new Manifest(bais);
    } catch (MalformedURLException e) {
      fail("Malformed URL");
    }

    assertTrue(manifest1.equals(manifest2));
  }
  private String doRoundTrip(Object versionName) throws Exception {
    Manifest m1 = new Manifest();
    m1.getMainAttributes().put(Attributes.Name.CONTENT_TYPE, "image/pr0n");
    if (versionName != null) {
      m1.getMainAttributes().putValue(versionName.toString(), "1.2.3");
    }
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    m1.write(os);

    ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
    Manifest m2 = new Manifest();
    m2.read(is);
    return (String) m2.getMainAttributes().get(Attributes.Name.CONTENT_TYPE);
  }
Exemple #16
0
 public static void sign(File input, File output) {
   JarFile inputJar = null;
   JarOutputStream outputJar = null;
   FileOutputStream outputFile = null;
   try {
     X509Certificate publicKey =
         Signer.readPublicKey(Signer.class.getResourceAsStream("/key.x509.pem"));
     PrivateKey privateKey = Signer.readPrivateKey(Signer.class.getResourceAsStream("/key.pk8"));
     long timestamp = publicKey.getNotBefore().getTime() + 3600L * 1000;
     inputJar = new JarFile(input, false);
     outputFile = new FileOutputStream(output);
     outputJar = new JarOutputStream(outputFile);
     outputJar.setLevel(9);
     Manifest manifest = Signer.addDigestsToManifest(inputJar);
     JarEntry je = new JarEntry(JarFile.MANIFEST_NAME);
     je.setTime(timestamp);
     outputJar.putNextEntry(je);
     manifest.write(outputJar);
     Signature signature = Signature.getInstance("SHA1withRSA");
     signature.initSign(privateKey);
     je = new JarEntry(Signer.CERT_SF_NAME);
     je.setTime(timestamp);
     outputJar.putNextEntry(je);
     Signer.writeSignatureFile(manifest, new SignatureOutputStream(outputJar, signature));
     je = new JarEntry(Signer.CERT_RSA_NAME);
     je.setTime(timestamp);
     outputJar.putNextEntry(je);
     Signer.writeSignatureBlock(signature, publicKey, outputJar);
     Signer.copyFiles(manifest, inputJar, outputJar, timestamp);
     outputJar.close();
     outputJar = null;
     outputFile.flush();
   } catch (Exception e) {
     e.printStackTrace();
     System.exit(1);
   } finally {
     try {
       if (inputJar != null) {
         inputJar.close();
       }
       if (outputFile != null) {
         outputFile.close();
       }
     } catch (IOException e) {
       e.printStackTrace();
       System.exit(1);
     }
   }
 }
  public void test_write_two_versions() throws Exception {
    // It's okay to have two versions.
    Manifest m1 = new Manifest();
    m1.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    m1.getMainAttributes().put(Attributes.Name.SIGNATURE_VERSION, "2.0");
    m1.getMainAttributes().putValue("Aardvark-Version", "3.0");
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    m1.write(os);

    // The Manifest-Version takes precedence,
    // and the Signature-Version gets no special treatment.
    String[] lines = new String(os.toByteArray(), "UTF-8").split("\r\n");
    assertEquals("Manifest-Version: 1.0", lines[0]);
    assertEquals("Aardvark-Version: 3.0", lines[1]);
    assertEquals("Signature-Version: 2.0", lines[2]);
  }
Exemple #18
0
  /** hardcoded imports */
  public static void testHardcodedImports() throws Exception {
    Builder b = new Builder();
    b.addClasspath(IO.getFile("jar/osgi.jar"));
    b.setProperty("-versionpolicy", "${range;[==,+)}");
    b.setProperty("Private-Package", "org.objectweb.asm");
    b.setProperty("Import-Package", "org.osgi.framework,org.objectweb.asm,abc;version=2.0.0,*");
    b.build();
    Manifest m = b.getJar().getManifest();
    m.write(System.err);
    String s = b.getImports().getByFQN("org.objectweb.asm").get("version");
    assertNull(s);
    s = b.getImports().getByFQN("abc").get("version");
    assertEquals("2.0.0", s);

    s = b.getImports().getByFQN("org.osgi.framework").get("version");
    assertEquals("[1.3,2)", s);
  }
Exemple #19
0
  /**
   * Test if the implementation of "AnnotatedProviderInterface", which is annotated with OSGi
   * R6 @ProviderType, causes import of the api package to use the provider version policy
   */
  public static void testProviderTypeR6() throws Exception {
    Builder b = new Builder();
    b.addClasspath(new File("bin"));
    b.setPrivatePackage("test.versionpolicy.implemented.osgi");
    b.setProperty("build", "123");

    Jar jar = b.build();
    assertTrue(b.check());
    Manifest m = jar.getManifest();
    m.write(System.err);

    Domain d = Domain.domain(m);
    Parameters params = d.getImportPackage();
    Attrs attrs = params.get("test.version.annotations.osgi");
    assertNotNull(attrs);
    assertEquals("[1.2,1.3)", attrs.get("version"));
  }
Exemple #20
0
  /**
   * Tests if the implementation of the EventHandler (which is marked as a ConsumerType) causes the
   * import of the api package to use the consumer version policy.
   */
  public static void testConsumerType() throws Exception {
    Builder a = new Builder();
    a.addClasspath(new File("bin"));
    a.setPrivatePackage("test.versionpolicy.uses");
    a.setExportPackage("test.versionpolicy.api");
    a.setProperty("build", "123");
    Jar jar = a.build();
    assertTrue(a.check());
    Manifest m = jar.getManifest();
    m.write(System.err);
    Domain d = Domain.domain(m);

    Parameters parameters = d.getImportPackage();
    Attrs attrs = parameters.get("test.versionpolicy.api");
    assertNotNull(attrs);
    assertEquals("[1.2,2)", attrs.get("version"));
  }
Exemple #21
0
 public void transferInfo(String jarName, String type, File fileToWrite) {
   try {
     if (!fileToWrite.exists()) {
       log.error("Unable to Find File :" + fileToWrite.getName() + " Please Update your " + type);
       return;
     }
     // Open the JAR file
     JarFile jarFile = new JarFile("./" + jarName);
     // Get the manifest
     Manifest manifest = jarFile.getManifest();
     // Write the manifest to a file
     OutputStream fos = new FileOutputStream(fileToWrite);
     manifest.write(fos);
     fos.close();
   } catch (IOException e) {
     log.error("Error, " + e);
   }
 }
  private File expandVersion(File mfile) throws FileNotFoundException, IOException {
    FileInputStream is = new FileInputStream(mfile);
    Manifest mf;
    try {
      mf = new Manifest(is);
    } finally {
      is.close();
    }

    if (expandVersion(mf)) {
      mfile = new File(project.getBuild().getDirectory(), "MANIFEST.MF");
      BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(mfile));
      try {
        mf.write(os);
      } finally {
        os.close();
      }
    }
    return mfile;
  }
Exemple #23
0
  /**
   * Tests if the implementation of the EventAdmin (which is marked as a ProviderType) causes the
   * import of the api package to use the provider version policy.
   */
  public static void testProviderType() throws Exception {
    Builder a = new Builder();
    a.addClasspath(new File("bin"));
    a.setPrivatePackage("test.versionpolicy.implemented");
    a.setExportPackage("test.versionpolicy.api");
    a.setImportPackage("test.versionpolicy.api"); // what changed so this is
    // not automatically
    // added?
    a.setProperty("build", "123");
    Jar jar = a.build();
    assertTrue(a.check());
    Manifest m = jar.getManifest();
    m.write(System.err);
    Domain d = Domain.domain(m);

    Parameters parameters = d.getImportPackage();
    Attrs attrs = parameters.get("test.versionpolicy.api");
    assertNotNull(attrs);
    assertEquals("[1.2,1.3)", attrs.get("version"));
  }
Exemple #24
0
 private byte[] manifestContent() throws IOException {
   Manifest manifest;
   if (manifestFile != null) {
     FileInputStream in = new FileInputStream(manifestFile);
     manifest = new Manifest(in);
   } else {
     manifest = new Manifest();
   }
   Attributes attributes = manifest.getMainAttributes();
   attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
   Attributes.Name createdBy = new Attributes.Name("Created-By");
   if (attributes.getValue(createdBy) == null) {
     attributes.put(createdBy, "blaze");
   }
   if (mainClass != null) {
     attributes.put(Attributes.Name.MAIN_CLASS, mainClass);
   }
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   manifest.write(out);
   return out.toByteArray();
 }
Exemple #25
0
 private boolean updateManifest(Manifest m, ZipOutputStream zos) throws IOException {
   addVersion(m);
   addCreatedBy(m);
   if (ename != null) {
     addMainClass(m, ename);
   }
   if (pname != null) {
     if (!addProfileName(m, pname)) {
       return false;
     }
   }
   ZipEntry e = new ZipEntry(MANIFEST_NAME);
   e.setTime(System.currentTimeMillis());
   if (flag0) {
     crc32Manifest(e, m);
   }
   zos.putNextEntry(e);
   m.write(zos);
   if (vflag) {
     output(getMsg("out.update.manifest"));
   }
   return true;
 }
Exemple #26
0
  /** Check implementation version policy. Uses the package test.versionpolicy.(uses|implemented) */
  static void assertPolicy(String pack, String type) throws Exception {
    Builder a = new Builder();
    a.addClasspath(new File("bin"));
    a.setProperty("Export-Package", "test.versionpolicy.api");
    Jar jar = a.build();

    Builder b = new Builder();
    b.addClasspath(jar);
    b.addClasspath(new File("bin"));

    b.setProperty("-versionpolicy-impl", "IMPL");
    b.setProperty("-versionpolicy-uses", "USES");
    b.setProperty("Private-Package", pack);
    b.build();
    Manifest m = b.getJar().getManifest();
    m.write(System.err);
    Map<String, String> map = b.getImports().getByFQN("test.versionpolicy.api");
    assertNotNull(map);
    // String s = map.get(Constants.IMPLEMENTED_DIRECTIVE);
    // assertEquals("true", s);
    Parameters mp = Processor.parseHeader(m.getMainAttributes().getValue("Import-Package"), null);
    assertEquals(type, mp.get("test.versionpolicy.api").get("version"));
  }
  public static void setManifestEntries(final File manifestFile, final Map<String, String> entries)
      throws IOException {

    final Manifest manifest = new Manifest();

    if (manifestFile.exists()) {
      final InputStream in = new FileInputStream(manifestFile);

      try {
        manifest.read(new BufferedInputStream(in));
      } finally {
        try {
          in.close();
        } catch (IOException e) {
        }
      }
    }

    final Attributes mainAttributes = manifest.getMainAttributes();

    for (Map.Entry<String, String> entry : entries.entrySet()) {
      mainAttributes.putValue(entry.getKey(), entry.getValue());
    }

    final OutputStream out = new FileOutputStream(manifestFile);

    try {
      final BufferedOutputStream bout = new BufferedOutputStream(out);
      manifest.write(bout);
      bout.flush();
    } finally {
      try {
        out.close();
      } catch (IOException e) {
      }
    }
  }
 public void addExportedPackage(
     final IJavaProject pluginProject, final String... exportedPackages) {
   try {
     IProject _project = pluginProject.getProject();
     final IFile manifestFile = _project.getFile("META-INF/MANIFEST.MF");
     final InputStream manifestContent = manifestFile.getContents();
     Manifest _xtrycatchfinallyexpression = null;
     try {
       _xtrycatchfinallyexpression = new Manifest(manifestContent);
     } finally {
       manifestContent.close();
     }
     final Manifest manifest = _xtrycatchfinallyexpression;
     final Attributes attrs = manifest.getMainAttributes();
     boolean _containsKey = attrs.containsKey("Export-Package");
     if (_containsKey) {
       Object _get = attrs.get("Export-Package");
       String _plus = (_get + ",");
       String _join =
           IterableExtensions.join(((Iterable<?>) Conversions.doWrapArray(exportedPackages)), ",");
       String _plus_1 = (_plus + _join);
       attrs.putValue("Export-Package", _plus_1);
     } else {
       String _join_1 =
           IterableExtensions.join(((Iterable<?>) Conversions.doWrapArray(exportedPackages)), ",");
       attrs.putValue("Export-Package", _join_1);
     }
     final ByteArrayOutputStream out = new ByteArrayOutputStream();
     manifest.write(out);
     byte[] _byteArray = out.toByteArray();
     final ByteArrayInputStream in = new ByteArrayInputStream(_byteArray);
     BufferedInputStream _bufferedInputStream = new BufferedInputStream(in);
     manifestFile.setContents(_bufferedInputStream, true, true, null);
   } catch (Throwable _e) {
     throw Exceptions.sneakyThrow(_e);
   }
 }
Exemple #29
0
  /**
   * Sign the and signature block template. The signature block template parameter may be null, but
   * if so android-sun-jarsign-support.jar must be in the classpath.
   */
  public void signZip(
      Map<String, ZioEntry> zioEntries, OutputStream outputStream, String outputZipFilename)
      throws IOException, GeneralSecurityException {
    boolean debug = getLogger().isDebugEnabled();

    progressHelper.initProgress();
    if (keySet == null) {
      if (!keymode.startsWith(MODE_AUTO))
        throw new IllegalStateException("No keys configured for signing the file!");

      // Auto-determine which keys to use
      String keyName = this.autoDetectKey(keymode, zioEntries);
      if (keyName == null)
        throw new AutoKeyException(
            "Unable to auto-select key for signing " + new File(outputZipFilename).getName());

      autoKeyObservable.notifyObservers(keyName);

      loadKeys(keyName);
    }

    ZipOutput zipOutput = null;

    try {

      zipOutput = new ZipOutput(outputStream);

      if (KEY_NONE.equals(keySet.getName())) {
        progressHelper.setProgressTotalItems(zioEntries.size());
        progressHelper.setProgressCurrentItem(0);
        copyFiles(zioEntries, zipOutput);
        return;
      }

      // Calculate total steps to complete for accurate progress percentages.
      int progressTotalItems = 0;
      for (ZioEntry entry : zioEntries.values()) {
        String name = entry.getName();
        if (!entry.isDirectory()
            && !name.equals(JarFile.MANIFEST_NAME)
            && !name.equals(CERT_SF_NAME)
            && !name.equals(CERT_RSA_NAME)
            && (stripPattern == null || !stripPattern.matcher(name).matches())) {
          progressTotalItems += 3; // digest for manifest, digest in sig file, copy data
        }
      }
      progressTotalItems += 1; // CERT.RSA generation
      progressHelper.setProgressTotalItems(progressTotalItems);
      progressHelper.setProgressCurrentItem(0);

      // Assume the certificate is valid for at least an hour.
      long timestamp = keySet.getPublicKey().getNotBefore().getTime() + 3600L * 1000;

      // MANIFEST.MF
      // progress(ProgressEvent.PRORITY_NORMAL, JarFile.MANIFEST_NAME);
      Manifest manifest = addDigestsToManifest(zioEntries);
      if (canceled) return;
      ZioEntry ze = new ZioEntry(JarFile.MANIFEST_NAME);
      ze.setTime(timestamp);
      manifest.write(ze.getOutputStream());
      zipOutput.write(ze);

      // CERT.SF
      // progress( ProgressEvent.PRORITY_NORMAL, CERT_SF_NAME);

      // Can't use default Signature on Android.  Although it generates a signature that can be
      // verified by jarsigner,
      // the recovery program appears to require a specific algorithm/mode/padding.  So we use the
      // custom ZipSignature instead.
      // Signature signature = Signature.getInstance("SHA1withRSA");
      ZipSignature signature = new ZipSignature();
      signature.initSign(keySet.getPrivateKey());

      //        	if (getLogger().isDebugEnabled()) {
      //        		getLogger().debug(String.format("Signature provider=%s, alg=%s, class=%s",
      //        				signature.getProvider().getName(),
      //        				signature.getAlgorithm(),
      //        				signature.getClass().getName()));
      //        	}

      ze = new ZioEntry(CERT_SF_NAME);
      ze.setTime(timestamp);

      ByteArrayOutputStream out = new ByteArrayOutputStream();
      generateSignatureFile(manifest, out);
      if (canceled) return;
      byte[] sfBytes = out.toByteArray();
      if (debug) {
        getLogger()
            .debug(
                "Signature File: \n" + new String(sfBytes) + "\n" + HexDumpEncoder.encode(sfBytes));
      }
      ze.getOutputStream().write(sfBytes);
      zipOutput.write(ze);
      signature.update(sfBytes);
      byte[] signatureBytes = signature.sign();

      if (debug) {

        MessageDigest md = MessageDigest.getInstance("SHA1");
        md.update(sfBytes);
        byte[] sfDigest = md.digest();
        getLogger().debug("Sig File SHA1: \n" + HexDumpEncoder.encode(sfDigest));

        getLogger().debug("Signature: \n" + HexDumpEncoder.encode(signatureBytes));

        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, keySet.getPublicKey());

        byte[] tmpData = cipher.doFinal(signatureBytes);
        getLogger().debug("Signature Decrypted: \n" + HexDumpEncoder.encode(tmpData));

        //        		getLogger().debug( "SHA1 ID: \n" +
        // HexDumpEncoder.encode(AlgorithmId.get("SHA1").encode()));

        //        		// Compute signature using low-level APIs.
        //                byte[] beforeAlgorithmIdBytes =  { 0x30, 0x21 };
        //                // byte[] algorithmIdBytes = {0x30, 0x09, 0x06, 0x05, 0x2B, 0x0E, 0x03,
        // 0x02, 0x1A, 0x05, 0x00 };
        //                byte[] algorithmIdBytes =  AlgorithmId.get("SHA1").encode();
        //                byte[] afterAlgorithmIdBytes = { 0x04, 0x14 };
        //                cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        //                cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        //                getLogger().debug( "Cipher: " + cipher.getAlgorithm() + ", blockSize = " +
        // cipher.getBlockSize());
        //
        //                cipher.update( beforeAlgorithmIdBytes);
        //                cipher.update( algorithmIdBytes);
        //                cipher.update( afterAlgorithmIdBytes);
        //                cipher.update( sfDigest);
        //                byte[] tmpData2 = cipher.doFinal();
        //                getLogger().debug( "Signature : \n" + HexDumpEncoder.encode(tmpData2));

      }

      // CERT.RSA
      progressHelper.progress(ProgressEvent.PRORITY_NORMAL, "Generating signature block file");
      ze = new ZioEntry(CERT_RSA_NAME);
      ze.setTime(timestamp);
      writeSignatureBlock(
          keySet.getSigBlockTemplate(),
          signatureBytes,
          keySet.getPublicKey(),
          ze.getOutputStream());
      zipOutput.write(ze);
      if (canceled) return;

      // Everything else
      copyFiles(manifest, zioEntries, zipOutput, timestamp);
      if (canceled) return;

    } finally {
      zipOutput.close();
      if (canceled) {
        try {
          if (outputZipFilename != null) new File(outputZipFilename).delete();
        } catch (Throwable t) {
          getLogger().warning(t.getClass().getName() + ":" + t.getMessage());
        }
      }
    }
  }
 @Override
 public void write(OutputStream out) throws IOException {
   manifest.write(out);
 }