public static Stream getInputStreamFromConfigFileEntry(URL mcoURL, string mcoName, string fileName) { JarFile mcoJarFile = getConfigJarfile(mcoURL); JarEntry entry = getConfigFileEntry(mcoJarFile, mcoName, fileName); try { if (entry == null) { throw new FileNotFoundException(); } return(mcoJarFile.getInputStream(entry)); } catch (FileNotFoundException e) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); } catch (IOException e) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); } return(null); }
public void SaveSettingsAction() { SectionOpacity = 1; ServerSectionCache.SSPath = ""; OnPropertyChanged(nameof(SectionOpacity)); ServerSectionCache.SectionObject = null; Complex.Title = Title; Complex.JarFile = JarFile; Complex.MinRam = MinRam; Complex.MaxRam = MaxRam; Complex.Parameter = Parameter; try { ServerPath = JarFile.Replace(JarFile.Split('\\').LastOrDefault(), ""); } catch { } Complex.StartFolder = ServerPath; CurrentHeight = 100; ChangeDate = DateTime.Now.ToString(); OnPropertyChanged(nameof(Title)); OnPropertyChanged(nameof(ChangeDate)); OnPropertyChanged(nameof(CurrentHeight)); Complex.ChangeDate = ChangeDate; ServerSave.SaveSettingsContainer(); ServerSectionCache.ChangeSection(); }
/// <summary> /// Asserts that the specified file is a jar file with a manifest containing a /// non-empty classpath attribute. /// </summary> /// <param name="file">File to check</param> /// <exception cref="System.IO.IOException">if there is an I/O error</exception> private static void AssertJar(FilePath file) { JarFile jarFile = null; try { jarFile = new JarFile(file); Manifest manifest = jarFile.GetManifest(); NUnit.Framework.Assert.IsNotNull(manifest); Attributes mainAttributes = manifest.GetMainAttributes(); NUnit.Framework.Assert.IsNotNull(mainAttributes); Assert.True(mainAttributes.Contains(Attributes.Name.ClassPath)); string classPathAttr = mainAttributes.GetValue(Attributes.Name.ClassPath); NUnit.Framework.Assert.IsNotNull(classPathAttr); NUnit.Framework.Assert.IsFalse(classPathAttr.IsEmpty()); } finally { // It's too bad JarFile doesn't implement Closeable. if (jarFile != null) { try { jarFile.Close(); } catch (IOException e) { Log.Warn("exception closing jarFile: " + jarFile, e); } } } }
private SourceFile(ApkFile apk, JarFile jar, ISpySettings settings, MapFile mapFile, string singleFilePath = null) { this.apk = apk; this.jar = jar; this.settings = settings; this.mapFile = mapFile; this.singleFilePath = singleFilePath; #if DEBUG classLoader = new AssemblyClassLoader(module.OnClassLoaded); var modParams = new ModuleParameters { AssemblyResolver = new AssemblyResolver(new[] { Frameworks.Instance.FirstOrDefault().Folder }, classLoader, module.OnAssemblyLoaded), Kind = ModuleKind.Dll }; assembly = AssemblyDefinition.CreateAssembly(new AssemblyNameDefinition("spy", Version.Parse("1.0.0.0")), "main", modParams); classLoader.LoadAssembly(assembly); var dot42Assembly = modParams.AssemblyResolver.Resolve("dot42"); // Force loading of classes if (jar != null) { foreach (var fileName in jar.ClassFileNames) { OpenClass(fileName); } } #endif }
public static List <String> getAllClassNames(String jarFilename) { try { var classes = new ArrayList <String>(); var pathToJar = jarFilename; var jarFile = new JarFile(pathToJar); foreach (var je in jarFile.entries().ToIterable()) { if (je.IsDirectory || !je.Name.endsWith(".class")) { continue; } String className = je.Name.substring(0, je.Name.length() - ".class".Length); className = className.replace('/', '.'); classes.add(className); } jarFile.close(); return(classes); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } }
/// <summary> /// Create wrapper for given jar file /// </summary> private void CreateAssembly(JarFile jf, string folder) { // Create java type wrappers var module = new NetModule(jf.Scope); var classTypeBuilders = jf.ClassNames.SelectMany(n => StandardTypeBuilder.Create(jf.LoadClass(n), target)); var typeBuilders = classTypeBuilders.OrderBy(x => x.Priority).ToList(); typeBuilders.ForEach(x => x.CreateType(null, module, target)); // Implement and finalize types Implement(typeBuilders, target); var assemblyAttributes = new List <NetCustomAttribute>(); if (!importAsStubs) { // Import code var attrType = new NetTypeDefinition(ClassFile.Empty, target, AttributeConstants.Dot42Scope) { Name = AttributeConstants.JavaCodeAttributeName, Namespace = AttributeConstants.Dot42AttributeNamespace }; string hash = JarReferenceHash.ComputeJarReferenceHash(jarFilePath); var attr = new NetCustomAttribute(attrType, hash, Path.GetFileName(jarFilePath)); assemblyAttributes.Add(attr); } // Save CodeGenerator.Generate(folder, module.Types, assemblyAttributes, target, this, target); }
private static string GetMainClassFromJarManifest(string mainClass) { JarFile jarFile = new JarFile(mainClass); string result; try { Manifest manifest = jarFile.getManifest(); if (manifest == null) { Console.Error.WriteLine("Jar file doesn't contain manifest"); result = null; return(result); } mainClass = manifest.getMainAttributes().getValue(java.util.jar.Attributes.Name.MAIN_CLASS); } finally { jarFile.close(); } if (mainClass == null) { Console.Error.WriteLine("Manifest doesn't contain a Main-Class."); result = null; } else { result = mainClass.Replace('/', '.'); } return(result); }
/// <summary>List directory contents for a resource folder.</summary> /// <remarks>List directory contents for a resource folder. Not recursive.</remarks> /// <author>Andrew Reslan</author> /// <param name="clazz">Any java class that lives in the same place as the resources folder /// </param> /// <param name="path">Should end with "/", but not start with one.</param> /// <returns>An array of the name of each member item, or null if path does not denote a directory /// </returns> /// <exception cref="Sharpen.URISyntaxException">Sharpen.URISyntaxException</exception> /// <exception cref="System.IO.IOException">System.IO.IOException</exception> public static string[] GetResourceListing(Type clazz, string path) { Uri dirURL = clazz.GetClassLoader().GetResource(path); if (dirURL != null && dirURL.Scheme.Equals("file")) { return(new FilePath(dirURL.ToURI()).List()); } if (dirURL != null && dirURL.Scheme.Equals("jar")) { string jarPath = Sharpen.Runtime.Substring(dirURL.AbsolutePath, 5, dirURL.AbsolutePath .IndexOf("!")); JarFile jar = new JarFile(URLDecoder.Decode(jarPath, "UTF-8")); Enumeration <JarEntry> entries = ((Enumeration <JarEntry>)jar.Entries()); ICollection <string> result = new HashSet <string>(); while (entries.MoveNext()) { string name = entries.Current.GetName(); if (name.StartsWith(path)) { string entry = Sharpen.Runtime.Substring(name, path.Length); int checkSubdir = entry.IndexOf("/"); if (checkSubdir >= 0) { // if it is a subdirectory, we just return the directory name entry = Sharpen.Runtime.Substring(entry, 0, checkSubdir); } result.AddItem(entry); } } return(Sharpen.Collections.ToArray(result, new string[result.Count])); } throw new NotSupportedException("Cannot list files for URL " + dirURL); }
private static ImmutableSet <string> getEntries(File jarFile, string rootPath) { ImmutableSet.Builder <string> builder = ImmutableSet.builder(); try { using (JarFile jar = new JarFile(jarFile)) { IEnumerator <JarEntry> jarEntries = jar.entries(); while (jarEntries.MoveNext()) { JarEntry entry = jarEntries.Current; string entryName = entry.Name; if (entryName.StartsWith(rootPath, StringComparison.Ordinal) && !entryName.Equals(rootPath)) { string relativeEntryPath = entryName.Substring(rootPath.Length + 1); if (relativeEntryPath.Trim().Length > 0) { builder.add(relativeEntryPath); } } } } } catch (Exception e) { throw new System.ArgumentException(Messages.format("Error scanning entries in JAR file: {}", jarFile), e); } return(builder.build()); }
/// <summary>List directory contents for a resource folder.</summary> /// <remarks>List directory contents for a resource folder. Not recursive.</remarks> /// <author>Andrew Reslan</author> /// <param name="clazz">Any java class that lives in the same place as the resources folder /// </param> /// <param name="path">Should end with "/", but not start with one.</param> /// <returns>An array of the name of each member item, or null if path does not denote a directory /// </returns> /// <exception cref="Sharpen.URISyntaxException">Sharpen.URISyntaxException</exception> /// <exception cref="System.IO.IOException">System.IO.IOException</exception> public static string[] GetResourceListing(Type clazz, string path) { Uri dirURL = clazz.GetClassLoader().GetResource(path); if (dirURL != null && dirURL.Scheme.Equals("file")) { return new FilePath(dirURL.ToURI()).List(); } if (dirURL != null && dirURL.Scheme.Equals("jar")) { string jarPath = Sharpen.Runtime.Substring(dirURL.AbsolutePath, 5, dirURL.AbsolutePath .IndexOf("!")); JarFile jar = new JarFile(URLDecoder.Decode(jarPath, "UTF-8")); Enumeration<JarEntry> entries = ((Enumeration<JarEntry>)jar.Entries()); ICollection<string> result = new HashSet<string>(); while (entries.MoveNext()) { string name = entries.Current.GetName(); if (name.StartsWith(path)) { string entry = Sharpen.Runtime.Substring(name, path.Length); int checkSubdir = entry.IndexOf("/"); if (checkSubdir >= 0) { // if it is a subdirectory, we just return the directory name entry = Sharpen.Runtime.Substring(entry, 0, checkSubdir); } result.AddItem(entry); } } return Sharpen.Collections.ToArray(result, new string[result.Count]); } throw new NotSupportedException("Cannot list files for URL " + dirURL); }
/// <summary> /// Try loading the jar file to see if we have a stub jar. /// </summary> private void jarLoader_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { importCode = true; libName = string.Empty; var jarPath = (string)e.Argument; try { var hasJarPath = !string.IsNullOrEmpty(jarPath) && File.Exists(jarPath); if (hasJarPath) { var jf = new JarFile(File.OpenRead(jarPath), jarPath, null); ClassFile result; if (jf.TryLoadClass("com/google/android/maps/MapActivity", out result)) { importCode = false; libName = "com.google.android.maps"; } } } catch (Exception) { // Ignore } }
/// <param name="args"/> public static void Main(string[] args) { try { using (JarFile jar_file = new JarFile(args[0])) { Manifest manifest = jar_file.GetManifest(); if (manifest != null) { string value = manifest.GetMainAttributes().GetValue("Main-Class"); if (value != null) { System.Console.Out.WriteLine(value.ReplaceAll("/", ".")); return; } } } } catch { } // ignore it System.Console.Out.WriteLine("UNKNOWN"); System.Environment.Exit(1); }
private static string GetMainClassFromJarManifest(string mainClass) { JarFile jf = new JarFile(mainClass); try { Manifest manifest = jf.getManifest(); if (manifest == null) { Console.Error.WriteLine("Jar file doesn't contain manifest"); return(null); } mainClass = manifest.getMainAttributes().getValue(Attributes.Name.MAIN_CLASS); } finally { jf.close(); } if (mainClass == null) { Console.Error.WriteLine("Manifest doesn't contain a Main-Class."); return(null); } return(mainClass.Replace('/', '.')); }
public override void FillTypemapXml(JarFile jf, XElement parent) { var element = new XElement("type"); element.Add(new XAttribute("fullname", TypeDefinition.FullName)); element.Add(new XAttribute("classname", TypeDefinition.OriginalJavaClassName)); parent.Add(element); }
void build() { List<String> lst = new ArrayList<String>(); //collect unit tests Console.WriteLine("Collecting unit tests from " + _testDir); collectTests(_testDir, _testDir, lst, ".+?\\.Test.+?\\.class$"); TestSuite suite = new TestSuite(); for (String arg : lst) { //ignore inner classes defined in tests if (arg.IndexOf('$') != -1) continue; String cls = arg.Replace(".class", ""); try { Class test = Class.forName(cls); suite.AddTestSuite(test); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } //run tests TestRunner.Run(suite); //see what classes from the ooxml-schemas.jar are loaded Console.WriteLine("Copying classes to " + _destDest); Map<String, Class<?>> classes = GetLoadedClasses(_ooxmlJar.getName()); for (Class<?> cls : classes.values()) { String className = cls.GetName(); String classRef = className.Replace('.', '/') + ".class"; File destFile = new File(_destDest, classRef); copyFile(cls.GetResourceAsStream('/' + classRef), destFile); if(cls.isInterface()){ /** * Copy classes and interfaces declared as members of this class */ for(Class fc : cls.GetDeclaredClasses()){ className = fc.GetName(); classRef = className.Replace('.', '/') + ".class"; destFile = new File(_destDest, classRef); copyFile(fc.GetResourceAsStream('/' + classRef), destFile); } } } //finally copy the compiled .xsb files Console.WriteLine("Copying .xsb resources"); JarFile jar = new JarFile(_ooxmlJar); for(Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements(); ){ JarEntry je = e.nextElement(); if(je.GetName().matches("schemaorg_apache_xmlbeans/system/\\w+/\\w+\\.xsb")) { File destFile = new File(_destDest, je.GetName()); copyFile(jar.GetInputStream(je), destFile); } } jar.close(); }
public void Test() { var jf = new JarFile(new MemoryStream(Resources.android), "test", null); foreach (var name in jf.ClassNames) { ClassFile cf; jf.TryLoadClass(name, out cf); } }
/// <summary> /// Create Dot42.dll /// </summary> private static void CreateFrameworkAssembly(JarFile jf, DocModel xmlModel, SourceProperties sourceProperties, string folder) { // Initialize all MappedTypeBuilder.Initialize(CompositionContainer); // Create java type wrappers var module = new NetModule(AttributeConstants.Dot42Scope); var classLoader = new AssemblyClassLoader(null); var target = new TargetFramework(null, classLoader, xmlModel, LogMissingParamNamesType, true, false, Enumerable.Empty <string>()); List <TypeBuilder> typeBuilders; using (Profiler.Profile(x => Console.WriteLine("{0:####} ms for Create()", x.TotalMilliseconds))) { var classTypeBuilders = jf.ClassNames.SelectMany(n => StandardTypeBuilder.Create(jf.LoadClass(n), target)); var customTypeBuilder = CompositionContainer.GetExportedValues <ICustomTypeBuilder>() .OrderBy(x => x.CustomTypeName) .Select(x => x.AsTypeBuilder()); typeBuilders = classTypeBuilders.Concat(customTypeBuilder) .OrderBy(x => x.Priority) .ToList(); typeBuilders.ForEach(x => x.CreateType(null, module, target)); } // Create JavaRef attribute //JavaRefAttributeBuilder.Build(asm.MainModule); // Implement and finalize types using (Profiler.Profile(x => Console.WriteLine("{0:####} ms for Implement()", x.TotalMilliseconds))) { JarImporter.Implement(typeBuilders, target); } // Save using (Profiler.Profile(x => Console.WriteLine("{0:####} ms for Generate()", x.TotalMilliseconds))) { CodeGenerator.Generate(folder, module.Types, new List <NetCustomAttribute>(), target, new FrameworkCodeGeneratorContext(), target); } // Create layout.xml var doc = new XDocument(new XElement("layout")); typeBuilders.ForEach(x => x.FillLayoutXml(jf, doc.Root)); doc.Save(Path.Combine(folder, "layout.xml")); // create dot42.typemap doc = new XDocument(new XElement("typemap")); typeBuilders.ForEach(x => x.FillTypemapXml(jf, doc.Root)); doc.Save(Path.Combine(folder, "dot42.typemap")); //using (var s = new FileStream(Path.Combine(folder, "dot42.typemap"), FileMode.Create)) // CompressedXml.WriteTo(doc, s, Encoding.UTF8); }
public static JarEntry getConfigFileEntry(JarFile mcoJarFile, string mcoName, string fileName) { JarEntry entry = mcoJarFile.getJarEntry(mcoName + '/' + fileName); if (entry == null) { entry = mcoJarFile.getJarEntry(mcoName + '\\' + fileName); } return(entry); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: private java.io.File extract(java.util.jar.JarFile jarFile, java.util.jar.JarEntry jarEntry) throws java.io.IOException private File Extract(JarFile jarFile, JarEntry jarEntry) { File extractedFile = CreateTempFile(jarEntry); using (Stream jarInputStream = jarFile.getInputStream(jarEntry)) { Files.copy(jarInputStream, extractedFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } return(extractedFile); }
protected override string GenerateCommandLineCommands() { List <string> argv = new List <string>(); argv.Add("-out:" + JarFile.GetMetadata("FullPath")); argv.AddRange(Namespaces.Select(x => "-namespace:" + x)); argv.AddRange(InputAssemblies.Select(x => x.GetMetadata("FullPath"))); return(string.Join(" ", argv.Select(x => $"\"{x}\""))); }
public void ShouldThrowExceptionOnMaxLimit() { using (var jarFileWriter = new JarFile(FileAccessMode.Write, jarFiledata, 2)) { jarFileWriter.AddFile(new JarFileItem(header, file1)); jarFileWriter.AddFile(new JarFileItem(header, file2)); Assert.Throws <JarFileReachedMaxLimitException>(() => jarFileWriter.AddFile(new JarFileItem(header, file2))); } }
/// <summary> /// Perform the import from jar to cs source. /// </summary> public void Import() { using (var jf = new JarFile(File.OpenRead(jarFilePath), jarFilePath, target.TypeNameMap)) { // Create output folder var folder = Path.GetFullPath(sourceOutputPath); Directory.CreateDirectory(folder); // Create mscorlib CreateAssembly(jf, folder); } }
private void startProcessor(JToken processor, Dictionary <string, string> mapData) { var name = processor["jar"]?.ToString(); if (name == null) { return; } // jar var jar = PackageName.Parse(name); var jarpath = Path.Combine(Minecraft.Library, jar.GetPath()); var jarfile = new JarFile(jarpath); var jarManifest = jarfile.GetManifest(); // mainclass string mainclass = null; var hasMainclass = jarManifest?.TryGetValue("Main-Class", out mainclass) ?? false; if (!hasMainclass || string.IsNullOrEmpty(mainclass)) { return; } // classpath var classpathObj = processor["classpath"]; var classpath = new List <string>(); if (classpathObj != null) { foreach (var libname in classpathObj) { var lib = Path.Combine(Minecraft.Library, PackageName.Parse(libname?.ToString()).GetPath()); classpath.Add(lib); } } classpath.Add(jarpath); // arg var argsArr = processor["args"] as JArray; string[] args = null; if (argsArr != null) { var arrStrs = argsArr.Select(x => x.ToString()).ToArray(); args = Mapper.Map(arrStrs, mapData, Minecraft.Library); } startJava(classpath.ToArray(), mainclass, args); }
private bool isArchive(File paramFile) { try { JarFile jarFile = new JarFile(paramFile); jarFile.close(); return(true); } catch (Exception) { return(false); } }
public void ShouldThrowExceptionForInvalidModeOpretion() { using (var jarFileWriter = new JarFile(FileAccessMode.Write, jarFiledata)) { jarFileWriter.AddFile(new JarFileItem(header, file1)); Assert.Throws <InvalidOperationException>(() => jarFileWriter.GetNextFile()); } using (var jarFileReader = new JarFile(FileAccessMode.Read, jarFiledata)) { Assert.Throws <InvalidOperationException>(() => jarFileReader.AddFile(new JarFileItem(header, file1))); } }
public override SignatureVerificationResult VerifySignature(string path, string parent) { if (VerifyJarSignatures) { var svr = new SignatureVerificationResult(path, parent); try { JarError.ClearErrors(); var jarFile = new JarFile(path); svr.IsSigned = jarFile.IsSigned(); if (!svr.IsSigned && JarError.HasErrors()) { svr.AddDetail(DetailKeys.Error, JarError.GetLastError()); } else { foreach (Timestamp timestamp in jarFile.Timestamps) { svr.AddDetail(DetailKeys.Misc, SignCheckResources.DetailTimestamp, timestamp.SignedOn, timestamp.SignatureAlgorithm); } IEnumerable <Timestamp> invalidTimestamps = from ts in jarFile.Timestamps where !ts.IsValid select ts; foreach (Timestamp ts in invalidTimestamps) { svr.AddDetail(DetailKeys.Error, SignCheckResources.DetailTimestampOutisdeCertValidity, ts.SignedOn, ts.EffectiveDate, ts.ExpiryDate); svr.IsSigned = false; } } svr.AddDetail(DetailKeys.File, SignCheckResources.DetailSigned, svr.IsSigned); } catch (Exception e) { svr.AddDetail(DetailKeys.Error, e.Message); } return(svr); } return(SignatureVerificationResult.UnsupportedFileTypeResult(path, parent)); }
public static JarFile getConfigJarfile(URL url) { JarFile mcoFile = null; try { JarURLConnection conn = (JarURLConnection)(new URL("jar:" + url.ToString() + "!/")).openConnection(); mcoFile = conn.JarFile; } catch (IOException e) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); } return(mcoFile); }
/// <summary> /// Add this type to the layout.xml file if needed. /// </summary> public override void FillLayoutXml(JarFile jf, XElement parent) { var baseName = GetLayoutBaseClassName(cf); if (baseName == null) { return; } string elementName; switch (baseName) { case SdkConstants.ViewClass: elementName = "view"; break; case SdkConstants.ViewGroupClass: elementName = "viewgroup"; break; default: return; } var shortName = GetShortName(cf.ClassName); var element = new XElement(elementName, new XAttribute("name", shortName)); if (cf.IsAbstract) { element.Add(new XAttribute("abstract", "true")); } ClassFile superClass; if (cf.TryGetSuperClass(out superClass)) { if ((superClass != null) && (GetLayoutBaseClassName(superClass) != null)) { element.Add(new XAttribute("super", GetShortName(superClass.ClassName))); } } parent.Add(element); }
/// <summary> /// Extract jar that is stored ad resource in a parent jar into temporary file </summary> /// <param name="resourceUrl"> resource jar resourceUrl </param> /// <param name="jar"> jar resource path </param> /// <returns> jar temporary file </returns> /// <exception cref="IOException"> on exception during jar extractions </exception> /// <exception cref="EmbeddedJarNotFoundException"> if jar not found or can't be extracted. </exception> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: private java.io.File extractJar(java.net.URL resourceUrl, String jar) throws java.io.IOException private File ExtractJar(URL resourceUrl, string jar) { URLConnection connection = resourceUrl.openConnection(); if (connection is JarURLConnection) { JarURLConnection urlConnection = ( JarURLConnection )connection; JarFile jarFile = urlConnection.JarFile; JarEntry jarEntry = urlConnection.JarEntry; if (jarEntry == null) { throw new EmbeddedJarNotFoundException("Jar file '" + jar + "' not found."); } return(Extract(jarFile, jarEntry)); } else { throw new EmbeddedJarNotFoundException("Jar file '" + jar + "' not found."); } }
public void ShouldAllowReadConcurrently() { using (var jarFileWriter = new JarFile(FileAccessMode.Write, jarFiledata)) { header["FileName"] = file1; jarFileWriter.AddFile(new JarFileItem(header, file1)); } using (var sourceStream = new FileStream( jarFiledata, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (var jarFileWriter = new JarFile(FileAccessMode.Write, jarFiledata)) { header["FileName"] = file2; jarFileWriter.AddFile(new JarFileItem(header, file2)); } } }
protected internal override ResourceLocator getResource(string subdirectoryName, string resourceName) { string fullLocation = string.format(Locale.ENGLISH, "%s%s/%s", rootPath, subdirectoryName, resourceName); try { using (JarFile jar = new JarFile(jarFile)) { JarEntry entry = jar.getJarEntry(fullLocation); if (entry == null) { return(null); } return(getEntryLocator(entry.Name)); } } catch (Exception e) { throw new System.ArgumentException(Messages.format("Error loading resource from JAR file: {}", jarFile), e); } }
/** Add the SHA1 of every file to the manifest, creating it if necessary. */ private static Manifest addDigestsToManifest(JarFile jar) { Manifest input = jar.Manifest; Manifest output = new Manifest(); Attributes main = output.MainAttributes; if (input != null) { main.AddAll(input.MainAttributes); } else { main.Add("Manifest-Version", "1.0"); main.Add("Created-By", "1.0 (Android SignApk)"); } byte[] buffer = new byte[4096]; int num; IEnumerable<JarEntry> jes; if (input == null) { jes = jar.OrderBy(j => j.Name); } else { var entries = jar.ToDictionary(j => j.Name); var sortedEntries = new List<JarEntry>(); foreach (var entry in input.Entries) sortedEntries.Add(entries[entry.Key]); jes = sortedEntries; } foreach (JarEntry entry in jes) { HashAlgorithm md = HashAlgorithm.Create("SHA1"); String name = entry.Name; if (!entry.IsDirectory && !name.Equals(JarFile.MANIFEST_NAME) && !name.Equals(CERT_SF_NAME) && !name.Equals(CERT_RSA_NAME) && !name.Equals(OTACERT_NAME) && (stripPattern == null || !stripPattern.IsMatch(name))) { Stream data = jar.GetInputStream(entry); while ((num = data.Read(buffer, 0, buffer.Length)) > 0) { md.TransformBlock(buffer, 0, num, null, 0); } md.TransformFinalBlock(buffer, 0, 0); Attributes attr = null; if (input != null) attr = input.GetAttributes(name); attr = attr != null ? new Attributes(attr) : new Attributes(); attr.Add("SHA1-Digest", Convert.ToBase64String(md.Hash)); output.Entries.Add(name, attr); } } return output; }
/** * Copy all the files in a manifest from input to output. We set * the modification times in the output to a fixed time, so as to * reduce variation in the output file and make incremental OTAs * more efficient. */ private static void copyFiles(Manifest manifest, JarFile in_, ZipOutputStream out_, DateTime timestamp) { byte[] buffer = new byte[4096]; int num; IDictionary<String, Attributes> entries = manifest.Entries; List<String> names = new List<String>(entries.Keys); names.Sort(); foreach (String name in names) { JarEntry inEntry = in_.GetJarEntry(name); JarEntry outEntry = null; if (inEntry.CompressionMethod == CompressionMethod.Stored) { // Preserve the STORED method of the input entry. outEntry = new JarEntry(inEntry); } else { // Create a new entry so that the compressed len is recomputed. outEntry = new JarEntry(name); if (inEntry.Size > -1) outEntry.Size = inEntry.Size; } outEntry.DateTime = timestamp; out_.PutNextEntry(outEntry); Stream data = in_.GetInputStream(inEntry); while ((num = data.Read(buffer, 0, buffer.Length)) > 0) { out_.Write(buffer, 0, num); } out_.Flush(); } }
public static void SignPackage(Stream input, X509Certificate2 certificate, Stream output, bool signWholeFile) { JarFile inputJar = null; ZipOutputStream outputJar = null; // Assume the certificate is valid for at least an hour. DateTime timestamp = DateTime.Parse(certificate.GetEffectiveDateString()).AddHours(1); inputJar = new JarFile(input); // Don't verify. Stream outputStream = null; if (signWholeFile) { outputStream = new MemoryStream(); } else { outputStream = output; } outputJar = new ZipOutputStream(outputStream); outputJar.SetComment(null); outputJar.SetLevel(9); JarEntry je; Manifest manifest = addDigestsToManifest(inputJar); // Everything else copyFiles(manifest, inputJar, outputJar, timestamp); // otacert if (signWholeFile) { addOtacert(outputJar, certificate, timestamp, manifest); } var buffer = new MemoryStream(); // MANIFEST.MF je = new JarEntry(JarFile.MANIFEST_NAME); je.DateTime = timestamp; manifest.Write(buffer); je.Size = buffer.Length; outputJar.PutNextEntry(je); buffer.WriteTo(outputJar); // CERT.SF var signature = new MemoryStream(); je = new JarEntry(CERT_SF_NAME); je.DateTime = timestamp; buffer.SetLength(0); writeSignatureFile(manifest, signature); signature.WriteTo(buffer); je.Size = buffer.Length; outputJar.PutNextEntry(je); buffer.WriteTo(outputJar); // CERT.RSA je = new JarEntry(CERT_RSA_NAME); je.DateTime = timestamp; buffer.SetLength(0); writeSignatureBlock(signature, certificate, buffer); je.Size = buffer.Length; outputJar.PutNextEntry(je); buffer.WriteTo(outputJar); outputJar.Close(); outputJar = null; if (signWholeFile) { signWholeOutputFile(((MemoryStream)outputStream).ToArray(), output, certificate); } }