From cfbec3467b830d86c5a1d7e3723ca67edd76b422 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pavel=20Rosick=C3=BD?= Date: Sat, 12 Jun 2021 18:49:57 +0200 Subject: [PATCH 1/2] import jruby version --- .github/workflows/ci.yml | 1 + .gitignore | 3 + Rakefile | 49 +- digest.gemspec | 30 +- ext/digest/lib/digest.rb | 2 +- .../org/jruby/ext/digest/BubbleBabble.java | 119 +++++ .../org/jruby/ext/digest/DigestLibrary.java | 44 ++ ext/java/org/jruby/ext/digest/MD5.java | 41 ++ ext/java/org/jruby/ext/digest/RMD160.java | 41 ++ ext/java/org/jruby/ext/digest/RubyDigest.java | 498 ++++++++++++++++++ ext/java/org/jruby/ext/digest/SHA1.java | 41 ++ ext/java/org/jruby/ext/digest/SHA2.java | 41 ++ test/lib/core_assertions.rb | 1 + 13 files changed, 897 insertions(+), 14 deletions(-) create mode 100644 ext/java/org/jruby/ext/digest/BubbleBabble.java create mode 100644 ext/java/org/jruby/ext/digest/DigestLibrary.java create mode 100644 ext/java/org/jruby/ext/digest/MD5.java create mode 100644 ext/java/org/jruby/ext/digest/RMD160.java create mode 100644 ext/java/org/jruby/ext/digest/RubyDigest.java create mode 100644 ext/java/org/jruby/ext/digest/SHA1.java create mode 100644 ext/java/org/jruby/ext/digest/SHA2.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e02190b..fbae97b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -30,6 +30,7 @@ jobs: - { os: ubuntu-20.04, ruby: head, ignore-pkg-error: true } - { os: windows-latest, ruby: mingw, ignore-pkg-error: true } - { os: windows-latest, ruby: mswin, ignore-pkg-error: true } + - { os: ubuntu-20.04, ruby: jruby-head, ignore-pkg-error: true } exclude: - { os: windows-latest, ruby: debug } diff --git a/.gitignore b/.gitignore index ed2d6bc..3e810e4 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,9 @@ /pkg/ /spec/reports/ /tmp/ +lib/*.jar +lib/digest +lib/digest/*.rb *.bundle *.so *.o diff --git a/Rakefile b/Rakefile index d5c2dab..daabba3 100644 --- a/Rakefile +++ b/Rakefile @@ -1,5 +1,6 @@ require "bundler/gem_tasks" require "rake/testtask" +require 'fileutils' Rake::TestTask.new(:test) do |t| t.libs << "test" << "test/lib" << "lib" @@ -7,14 +8,52 @@ Rake::TestTask.new(:test) do |t| t.test_files = FileList["test/**/test_*.rb"] end -require 'rake/extensiontask' -Rake::ExtensionTask.new("digest") -%w(bubblebabble md5 rmd160 sha1 sha2).each do |ext| - Rake::ExtensionTask.new("digest/#{ext}") +require 'rake/javaextensiontask' +Rake::JavaExtensionTask.new("digest") do |ext| + ext.source_version = '1.8' + ext.target_version = '1.8' + ext.ext_dir = 'ext/java' +end + +algorithms = %w(bubblebabble md5 rmd160 sha1 sha2) + +# copy library loaders +FileUtils.mkdir "./lib/digest" unless File.exist?("./lib/digest") +algorithms.each do |ext| + source = "./ext/digest/#{ext}/lib/#{ext}.rb" + if File.exist? source + FileUtils.cp source, "./lib/digest/#{ext}.rb" + end +end + +if RUBY_ENGINE == 'jruby' + File.write("./lib/digest/bubblebabble.rb", <<-FILE) +# frozen_string_literal: true +JRuby::Util.load_ext("org.jruby.ext.digest.BubbleBabble") +FILE + File.write("./lib/digest/md5.rb", <<-FILE) +# frozen_string_literal: true +JRuby::Util.load_ext("org.jruby.ext.digest.MD5") +FILE + File.write("./lib/digest/rmd160.rb", <<-FILE) +# frozen_string_literal: true +JRuby::Util.load_ext("org.jruby.ext.digest.RMD160") +FILE + File.write("./lib/digest/sha1.rb", <<-FILE) +# frozen_string_literal: true +JRuby::Util.load_ext("org.jruby.ext.digest.SHA1") +FILE + File.write("./lib/digest/sha2.rb", File.read("./lib/digest/sha2.rb").sub("require 'digest/sha2.so'", "JRuby::Util.load_ext('org.jruby.ext.digest.SHA2')")) + File.write("./lib/digest.rb", File.read("./lib/digest.rb").sub("require 'digest.so'", "JRuby::Util.load_ext('org.jruby.ext.digest.DigestLibrary')")) +else + require 'rake/extensiontask' + Rake::ExtensionTask.new("digest") + algorithms.each do |ext| + Rake::ExtensionTask.new("digest/#{ext}") + end end task :sync_tool do - require 'fileutils' FileUtils.cp "../ruby/tool/lib/test/unit/core_assertions.rb", "./test/lib" FileUtils.cp "../ruby/tool/lib/envutil.rb", "./test/lib" FileUtils.cp "../ruby/tool/lib/find_executable.rb", "./test/lib" diff --git a/digest.gemspec b/digest.gemspec index 381df92..f9357b0 100644 --- a/digest.gemspec +++ b/digest.gemspec @@ -46,13 +46,27 @@ Gem::Specification.new do |spec| spec.bindir = "exe" spec.executables = [] spec.require_paths = ["lib"] - spec.extensions = %w[ - ext/digest/extconf.rb - ext/digest/bubblebabble/extconf.rb - ext/digest/md5/extconf.rb - ext/digest/rmd160/extconf.rb - ext/digest/sha1/extconf.rb - ext/digest/sha2/extconf.rb - ] + + if Gem::Platform === spec.platform and spec.platform =~ 'java' or RUBY_ENGINE == 'jruby' + spec.platform = 'java' + spec.files.concat [ + "lib/digest.jar", + "lib/digest/md5.rb", + "lib/digest/sha1.rb", + "lib/digest/sha2.rb", + "lib/digest/rmd160.rb", + "lib/digest/bubblebabble.rb" + ] + else + spec.extensions = %w[ + ext/digest/extconf.rb + ext/digest/bubblebabble/extconf.rb + ext/digest/md5/extconf.rb + ext/digest/rmd160/extconf.rb + ext/digest/sha1/extconf.rb + ext/digest/sha2/extconf.rb + ] + end + spec.metadata["msys2_mingw_dependencies"] = "openssl" end diff --git a/ext/digest/lib/digest.rb b/ext/digest/lib/digest.rb index ba0637a..1a3eb7a 100644 --- a/ext/digest/lib/digest.rb +++ b/ext/digest/lib/digest.rb @@ -8,7 +8,7 @@ module Digest def self.const_missing(name) # :nodoc: case name when :SHA256, :SHA384, :SHA512 - lib = 'digest/sha2.so' + lib = 'digest/sha2' else lib = File.join('digest', name.to_s.downcase) end diff --git a/ext/java/org/jruby/ext/digest/BubbleBabble.java b/ext/java/org/jruby/ext/digest/BubbleBabble.java new file mode 100644 index 0000000..a16d165 --- /dev/null +++ b/ext/java/org/jruby/ext/digest/BubbleBabble.java @@ -0,0 +1,119 @@ +/* + **** BEGIN LICENSE BLOCK ***** + * BSD 2-Clause License + * + * Copyright (c) 2010, Charles Oliver Nutter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ***** END LICENSE BLOCK *****/ + +package org.jruby.ext.digest; + +import org.jruby.Ruby; +import org.jruby.runtime.load.Library; +import org.jruby.util.ByteList; + +import java.io.IOException; + +public class BubbleBabble implements Library { + + public void load(final Ruby runtime, boolean wrap) throws IOException { + RubyDigest.createDigestBubbleBabble(runtime); + } + + /** + * Ported from OpenSSH (https://github.com/openssh/openssh-portable/blob/957fbceb0f3166e41b76fdb54075ab3b9cc84cba/sshkey.c#L942-L987) + * + * OpenSSH License Notice + * + * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved. + * Copyright (c) 2008 Alexander von Gernler. All rights reserved. + * Copyright (c) 2010,2011 Damien Miller. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + public static ByteList bubblebabble(byte[] message, int begin, int length) { + char[] vowels = new char[]{'a', 'e', 'i', 'o', 'u', 'y'}; + char[] consonants = new char[]{'b', 'c', 'd', 'f', 'g', 'h', 'k', 'l', 'm', + 'n', 'p', 'r', 's', 't', 'v', 'z', 'x'}; + + long seed = 1; + + ByteList retval = new ByteList(); + + int rounds = (length / 2) + 1; + retval.append('x'); + for (int i = 0; i < rounds; i++) { + int idx0, idx1, idx2, idx3, idx4; + + if ((i + 1 < rounds) || (length % 2 != 0)) { + long b = message[begin + 2 * i] & 0xFF; + idx0 = (int) ((((b >> 6) & 3) + seed) % 6) & 0xFFFFFFFF; + idx1 = (int) (((b) >> 2) & 15) & 0xFFFFFFFF; + idx2 = (int) (((b & 3) + (seed / 6)) % 6) & 0xFFFFFFFF; + retval.append(vowels[idx0]); + retval.append(consonants[idx1]); + retval.append(vowels[idx2]); + if ((i + 1) < rounds) { + long b2 = message[begin + (2 * i) + 1] & 0xFF; + idx3 = (int) ((b2 >> 4) & 15) & 0xFFFFFFFF; + idx4 = (int) ((b2) & 15) & 0xFFFFFFFF; + retval.append(consonants[idx3]); + retval.append('-'); + retval.append(consonants[idx4]); + seed = ((seed * 5) + + ((b * 7) + + b2)) % 36; + } + } else { + idx0 = (int) (seed % 6) & 0xFFFFFFFF; + idx1 = 16; + idx2 = (int) (seed / 6) & 0xFFFFFFFF; + retval.append(vowels[idx0]); + retval.append(consonants[idx1]); + retval.append(vowels[idx2]); + } + } + retval.append('x'); + + return retval; + } +} diff --git a/ext/java/org/jruby/ext/digest/DigestLibrary.java b/ext/java/org/jruby/ext/digest/DigestLibrary.java new file mode 100644 index 0000000..cd46954 --- /dev/null +++ b/ext/java/org/jruby/ext/digest/DigestLibrary.java @@ -0,0 +1,44 @@ +/* + **** BEGIN LICENSE BLOCK ***** + * BSD 2-Clause License + * + * Copyright (C) 2006 Ola Bini + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ***** END LICENSE BLOCK *****/ + +package org.jruby.ext.digest; + +import java.io.IOException; + +import org.jruby.Ruby; +import org.jruby.runtime.load.Library; + +/** + * @author Ola Bini + */ +public class DigestLibrary implements Library { + public void load(final Ruby runtime, boolean wrap) throws IOException { + org.jruby.ext.digest.RubyDigest.createDigest(runtime); + } +}// DigestLibrary diff --git a/ext/java/org/jruby/ext/digest/MD5.java b/ext/java/org/jruby/ext/digest/MD5.java new file mode 100644 index 0000000..124d053 --- /dev/null +++ b/ext/java/org/jruby/ext/digest/MD5.java @@ -0,0 +1,41 @@ +/* + **** BEGIN LICENSE BLOCK ***** + * BSD 2-Clause License + * + * Copyright (c) 2010, Charles Oliver Nutter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ***** END LICENSE BLOCK *****/ + +package org.jruby.ext.digest; + +import java.io.IOException; +import org.jruby.Ruby; +import org.jruby.runtime.load.Library; + +public class MD5 implements Library { + + public void load(final Ruby runtime, boolean wrap) throws IOException { + org.jruby.ext.digest.RubyDigest.createDigestMD5(runtime); + } +} diff --git a/ext/java/org/jruby/ext/digest/RMD160.java b/ext/java/org/jruby/ext/digest/RMD160.java new file mode 100644 index 0000000..94b17ed --- /dev/null +++ b/ext/java/org/jruby/ext/digest/RMD160.java @@ -0,0 +1,41 @@ +/* + **** BEGIN LICENSE BLOCK ***** + * BSD 2-Clause License + * + * Copyright (c) 2010, Charles Oliver Nutter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ***** END LICENSE BLOCK *****/ + +package org.jruby.ext.digest; + +import java.io.IOException; +import org.jruby.Ruby; +import org.jruby.runtime.load.Library; + +public class RMD160 implements Library { + + public void load(final Ruby runtime, boolean wrap) throws IOException { + org.jruby.ext.digest.RubyDigest.createDigestRMD160(runtime); + } +} diff --git a/ext/java/org/jruby/ext/digest/RubyDigest.java b/ext/java/org/jruby/ext/digest/RubyDigest.java new file mode 100644 index 0000000..f10b8ca --- /dev/null +++ b/ext/java/org/jruby/ext/digest/RubyDigest.java @@ -0,0 +1,498 @@ + /* + **** BEGIN LICENSE BLOCK ***** + * BSD 2-Clause License + * + * Copyright (C) 2006, 2007 Ola Bini + * Copyright (C) 2007 Nick Sieger + * Copyright (C) 2008 Vladimir Sizikov + * Copyright (C) 2009 Joseph LaFata + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ***** END LICENSE BLOCK *****/ + +package org.jruby.ext.digest; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.Provider; +import java.util.HashMap; +import java.util.Map; + +import org.jcodings.specific.USASCIIEncoding; +import org.jruby.Ruby; +import org.jruby.RubyClass; +import org.jruby.RubyFixnum; +import org.jruby.RubyModule; +import org.jruby.RubyObject; +import org.jruby.RubyString; + +import org.jruby.anno.JRubyClass; +import org.jruby.anno.JRubyMethod; +import org.jruby.anno.JRubyModule; +import org.jruby.exceptions.RaiseException; +import org.jruby.runtime.Block; +import org.jruby.runtime.ThreadContext; +import org.jruby.runtime.Visibility; +import org.jruby.runtime.builtin.IRubyObject; +import org.jruby.util.ArraySupport; +import org.jruby.util.ByteList; +import org.jruby.util.log.Logger; +import org.jruby.util.log.LoggerFactory; + +/** + * @author Ola Bini + */ +@JRubyModule(name="Digest") +public class RubyDigest { + + private static final Map CLONEABLE_DIGESTS = new HashMap(8, 1); + static { + // standard digests from JCA specification; if we can retrieve and clone, save them + for (String name : new String[] {"MD2", "MD5", "SHA-1", "SHA-256", "SHA-384", "SHA-512"}) { + try { + MessageDigest digest = MessageDigest.getInstance(name); + digest.clone(); + CLONEABLE_DIGESTS.put(name, digest); + } + catch (Exception e) { + logger().debug(name + " not clonable", e); + } + } + } + + private static Logger logger() { return LoggerFactory.getLogger(RubyDigest.class); } + + private static final String PROVIDER = "org.bouncycastle.jce.provider.BouncyCastleProvider"; + private static Provider provider = null; + + public static void createDigest(Ruby runtime) { + try { + provider = (Provider) Class.forName(PROVIDER).getConstructor().newInstance(); + } + catch (Throwable t) { /* provider is not available */ } + + RubyModule mDigest = runtime.defineModule("Digest"); + mDigest.defineAnnotatedMethods(RubyDigest.class); + RubyModule mDigestInstance = mDigest.defineModuleUnder("Instance"); + mDigestInstance.defineAnnotatedMethods(DigestInstance.class); + RubyClass cDigestClass = mDigest.defineClassUnder("Class", runtime.getObject(), DigestClass::new); + cDigestClass.defineAnnotatedMethods(DigestClass.class); + cDigestClass.includeModule(mDigestInstance); + RubyClass cDigestBase = mDigest.defineClassUnder("Base", cDigestClass, DigestBase::new); + cDigestBase.defineAnnotatedMethods(DigestBase.class); + } + + private static MessageDigest createMessageDigest(final String name) throws NoSuchAlgorithmException { + MessageDigest cloneable = CLONEABLE_DIGESTS.get(name); + if (cloneable != null) { + try { + return (MessageDigest) cloneable.clone(); + } + catch (CloneNotSupportedException e) { + // should never happen, since we tested it in static init + } + } + + // fall back on JCA mechanisms for getting a digest + if (provider != null) { + try { + return MessageDigest.getInstance(name, provider); + } + catch (NoSuchAlgorithmException e) { + // bouncy castle doesn't support algorithm + } + } + + // fall back to default JCA providers + return MessageDigest.getInstance(name); + } + + private final static byte[] digits = { + '0', '1', '2', '3', '4', '5', + '6', '7', '8', '9', 'a', 'b', + 'c', 'd', 'e', 'f', 'g', 'h', + 'i', 'j', 'k', 'l', 'm', 'n', + 'o', 'p', 'q', 'r', 's', 't', + 'u', 'v', 'w', 'x', 'y', 'z' + }; + + private static ByteList toHex(byte[] val) { + ByteList byteList = new ByteList(val.length * 2); + for (int i = 0, j = val.length; i < j; i++) { + int b = val[i] & 0xFF; + byteList.append(digits[b >> 4]); + byteList.append(digits[b & 0xF]); + } + return byteList; + } + + private static RubyString toHexString(Ruby runtime, byte[] val) { + return RubyString.newStringNoCopy(runtime, new ByteList(ByteList.plain(toHex(val)), USASCIIEncoding.INSTANCE)); + } + + @JRubyMethod(name = "hexencode", required = 1, meta = true) + public static RubyString hexencode(IRubyObject self, IRubyObject arg) { + return toHexString(self.getRuntime(), arg.convertToString().getBytes()); + } + + @JRubyMethod(name = "bubblebabble", required = 1, meta = true) + public static RubyString bubblebabble(IRubyObject recv, IRubyObject arg) { + final ByteList bytes = arg.convertToString().getByteList(); + return RubyString.newString(recv.getRuntime(), BubbleBabble.bubblebabble(bytes.unsafeBytes(), bytes.begin(), bytes.length())); + } + + private static class Metadata { + + private final String name; + private final int blockLength; + + Metadata(String name, int blockLength) { + this.name = name; + this.blockLength = blockLength; + } + + String getName() { + return name; + } + + int getBlockLength() { + return blockLength; + } + } + + + @JRubyClass(name="Digest::MD5", parent="Digest::Base") + public static class MD5 {} + @JRubyClass(name="Digest::RMD160", parent="Digest::Base") + public static class RMD160 {} + @JRubyClass(name="Digest::SHA1", parent="Digest::Base") + public static class SHA1 {} + @JRubyClass(name="Digest::SHA256", parent="Digest::Base") + public static class SHA256 {} + @JRubyClass(name="Digest::SHA384", parent="Digest::Base") + public static class SHA384 {} + @JRubyClass(name="Digest::SHA512", parent="Digest::Base") + public static class SHA512 {} + + public static void createDigestMD5(Ruby runtime) { + runtime.getLoadService().require("digest"); + RubyModule Digest = runtime.getModule("Digest"); + RubyClass Base = Digest.getClass("Base"); + RubyClass MD5 = Digest.defineClassUnder("MD5", Base, Base.getAllocator()); + MD5.setInternalVariable("metadata", new Metadata("MD5", 64)); + } + + public static void createDigestRMD160(Ruby runtime) { + runtime.getLoadService().require("digest"); + if(provider == null) { + throw runtime.newLoadError("RMD160 not supported without BouncyCastle"); + } + RubyModule Digest = runtime.getModule("Digest"); + RubyClass Base = Digest.getClass("Base"); + RubyClass RMD160 = Digest.defineClassUnder("RMD160", Base, Base.getAllocator()); + RMD160.setInternalVariable("metadata", new Metadata("RIPEMD160", 64)); + } + + public static void createDigestSHA1(Ruby runtime) { + runtime.getLoadService().require("digest"); + RubyModule Digest = runtime.getModule("Digest"); + RubyClass Base = Digest.getClass("Base"); + RubyClass SHA1 = Digest.defineClassUnder("SHA1", Base, Base.getAllocator()); + SHA1.setInternalVariable("metadata", new Metadata("SHA1", 64)); + } + + public static void createDigestSHA2(Ruby runtime) { + runtime.getLoadService().require("digest"); + try { + createMessageDigest("SHA-256"); + } + catch (NoSuchAlgorithmException e) { + RaiseException ex = runtime.newLoadError("SHA2 not supported"); + ex.initCause(e); + throw ex; + } + final RubyModule Digest = runtime.getModule("Digest"); + final RubyClass Base = Digest.getClass("Base"); + RubyClass SHA256 = Digest.defineClassUnder("SHA256", Base, Base.getAllocator()); + SHA256.setInternalVariable("metadata", new Metadata("SHA-256", 64)); + RubyClass SHA384 = Digest.defineClassUnder("SHA384", Base, Base.getAllocator()); + SHA384.setInternalVariable("metadata", new Metadata("SHA-384", 128)); + RubyClass SHA512 = Digest.defineClassUnder("SHA512", Base, Base.getAllocator()); + SHA512.setInternalVariable("metadata", new Metadata("SHA-512", 128)); + } + + public static void createDigestBubbleBabble(Ruby runtime) { + runtime.getLoadService().require("digest"); + RubyModule Digest = runtime.getModule("Digest"); + RubyClass Base = Digest.getClass("Base"); + RubyClass MD5 = Digest.defineClassUnder("BubbleBabble", Base, Base.getAllocator()); + MD5.setInternalVariable("metadata", new Metadata("BubbleBabble", 64)); + } + + @JRubyModule(name = "Digest::Instance") + public static class DigestInstance { + + private static IRubyObject throwUnimplError(IRubyObject self, String name) { + throw self.getRuntime().newRuntimeError(String.format("%s does not implement %s()", self.getMetaClass().getRealClass().getName(), name)); + } + + /* instance methods that should be overridden */ + @JRubyMethod(name = {"update", "<<"}, required = 1) + public static IRubyObject update(ThreadContext context, IRubyObject self, IRubyObject arg) { + return throwUnimplError(self, "update"); + } + + @JRubyMethod() + public static IRubyObject finish(ThreadContext context, IRubyObject self) { + return throwUnimplError(self, "finish"); + } + + @JRubyMethod() + public static IRubyObject reset(ThreadContext context, IRubyObject self) { + return throwUnimplError(self, "reset"); + } + + @JRubyMethod() + public static IRubyObject digest_length(ThreadContext context, IRubyObject self) { + return digest(context, self, null).convertToString().bytesize(); + } + + @JRubyMethod() + public static IRubyObject block_length(ThreadContext context, IRubyObject self) { + return throwUnimplError(self, "block_length"); + } + + /* instance methods that may be overridden */ + @JRubyMethod(name = "==", required = 1) + public static IRubyObject op_equal(ThreadContext context, IRubyObject self, IRubyObject oth) { + if(oth.isNil()) return context.fals; + + RubyString str1, str2; + RubyModule instance = (RubyModule)context.runtime.getModule("Digest").getConstantAt("Instance"); + if (oth.getMetaClass().getRealClass().hasModuleInHierarchy(instance)) { + str1 = digest(context, self, null).convertToString(); + str2 = digest(context, oth, null).convertToString(); + } else { + str1 = to_s(context, self).convertToString(); + str2 = oth.convertToString(); + } + boolean ret = str1.bytesize().eql(str2.bytesize()) && (str1.eql(str2)); + return ret ? context.tru : context.fals; + } + + @JRubyMethod() + public static IRubyObject inspect(ThreadContext context, IRubyObject self) { + return RubyString.newStringNoCopy(self.getRuntime(), ByteList.plain("#<" + self.getMetaClass().getRealClass().getName() + ": " + hexdigest(context, self, null) + ">")); + } + + /* instance methods that need not usually be overridden */ + @JRubyMethod(name = "new") + public static IRubyObject newObject(ThreadContext context, IRubyObject self) { + return self.rbClone().callMethod(context, "reset"); + } + + @JRubyMethod(optional = 1) + public static IRubyObject digest(ThreadContext context, IRubyObject self, IRubyObject[] args) { + final IRubyObject value; + if (args != null && args.length > 0) { + self.callMethod(context, "reset"); + self.callMethod(context, "update", args[0]); + value = self.callMethod(context, "finish"); + self.callMethod(context, "reset"); + } else { + IRubyObject clone = self.rbClone(); + value = clone.callMethod(context, "finish"); + clone.callMethod(context, "reset"); + } + return value; + } + + @JRubyMethod(name = "digest!") + public static IRubyObject digest_bang(ThreadContext context, IRubyObject self) { + IRubyObject value = self.callMethod(context, "finish"); + self.callMethod(context, "reset"); + return value; + } + + @JRubyMethod(optional = 1) + public static IRubyObject hexdigest(ThreadContext context, IRubyObject self, IRubyObject[] args) { + return toHexString(context.runtime, digest(context, self, args).convertToString().getBytes()); + } + + @JRubyMethod(name = "hexdigest!") + public static IRubyObject hexdigest_bang(ThreadContext context, IRubyObject self) { + return toHexString(context.runtime, digest_bang(context, self).convertToString().getBytes()); + } + + @JRubyMethod(name = "bubblebabble", required = 1, optional = 1, meta = true) + public static IRubyObject bubblebabble(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block unusedBlock) { + byte[] digest = recv.callMethod(context, "digest", args, Block.NULL_BLOCK).convertToString().getBytes(); + return RubyString.newString(recv.getRuntime(), BubbleBabble.bubblebabble(digest, 0, digest.length)); + } + + @JRubyMethod() + public static IRubyObject to_s(ThreadContext context, IRubyObject self) { + return self.callMethod(context, "hexdigest"); + } + + @JRubyMethod(name = {"length", "size"}) + public static IRubyObject length(ThreadContext context, IRubyObject self) { + return self.callMethod(context, "digest_length"); + } + } + + + @JRubyClass(name="Digest::Class") + public static class DigestClass extends RubyObject { + public DigestClass(Ruby runtime, RubyClass type) { + super(runtime, type); + } + + @JRubyMethod(name = "digest", required = 1, rest = true, meta = true) + public static IRubyObject s_digest(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block unusedBlock) { + final Ruby runtime = context.runtime; + if (args.length < 1) { + throw runtime.newArgumentError("no data given"); + } + RubyString str = args[0].convertToString(); + args = ArraySupport.newCopy(args, 1, args.length - 1); // skip first arg + IRubyObject obj = ((RubyClass) recv).newInstance(context, args, Block.NULL_BLOCK); + return obj.callMethod(context, "digest", str); + } + + @JRubyMethod(name = "hexdigest", required = 1, optional = 1, meta = true) + public static IRubyObject s_hexdigest(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block unusedBlock) { + Ruby runtime = recv.getRuntime(); + byte[] digest = recv.callMethod(context, "digest", args, Block.NULL_BLOCK).convertToString().getBytes(); + return RubyDigest.toHexString(runtime, digest); + } + + @JRubyMethod(name = "bubblebabble", required = 1, meta = true) + public static RubyString bubblebabble(IRubyObject recv, IRubyObject arg) { + byte[] digest = recv.callMethod(recv.getRuntime().getCurrentContext(), "digest", arg).convertToString().getBytes(); + return RubyString.newString(recv.getRuntime(), BubbleBabble.bubblebabble(digest, 0, digest.length)); + } + } + + + @JRubyClass(name="Digest::Base") + public static class DigestBase extends RubyObject { + private MessageDigest algo; + private int blockLength = 0; + + public DigestBase(Ruby runtime, RubyClass type) { + super(runtime,type); + + if(type == runtime.getModule("Digest").getClass("Base")) { + throw runtime.newNotImplementedError("Digest::Base is an abstract class"); + } + + Metadata metadata = getMetadata(type); + if(metadata == null) { + throw runtime.newNotImplementedError("the " + type + "() function is unimplemented on this machine"); + } + + try { + setAlgorithm(metadata); + } catch(NoSuchAlgorithmException e) { + throw runtime.newNotImplementedError("the " + type + "() function is unimplemented on this machine"); + } + + } + + // if subclass extends particular digest we need to walk to find it...we should rearchitect digest to avoid walking type systems + private Metadata getMetadata(RubyModule type) { + for (RubyModule current = type; current != null; current = current.getSuperClass()) { + Metadata metadata = (Metadata) current.getInternalVariable("metadata"); + + if (metadata != null) return metadata; + } + + return null; + } + + @JRubyMethod(required = 1, visibility = Visibility.PRIVATE) + @Override + public IRubyObject initialize_copy(IRubyObject obj) { + if (this == obj) return this; + + DigestBase from = (DigestBase) obj; + from.checkFrozen(); + + try { + this.algo = (MessageDigest) from.algo.clone(); + } + catch (CloneNotSupportedException e) { + String name = from.algo.getAlgorithm(); + throw getRuntime().newTypeError("Could not initialize copy of digest (" + name + ")"); + } + return this; + } + + @JRubyMethod(name = {"update", "<<"}, required = 1) + public IRubyObject update(IRubyObject obj) { + ByteList bytes = obj.convertToString().getByteList(); + algo.update(bytes.getUnsafeBytes(), bytes.getBegin(), bytes.getRealSize()); + return this; + } + + @JRubyMethod() + public IRubyObject finish() { + IRubyObject digest = RubyString.newStringNoCopy(getRuntime(), algo.digest()); + algo.reset(); + return digest; + } + + @JRubyMethod() + public IRubyObject digest_length() { + return RubyFixnum.newFixnum(getRuntime(), algo.getDigestLength()); + } + + @JRubyMethod() + public IRubyObject block_length() { + if (blockLength == 0) { + throw getRuntime().newRuntimeError( + this.getMetaClass() + " doesn't implement block_length()"); + } + return RubyFixnum.newFixnum(getRuntime(), blockLength); + } + + @JRubyMethod() + public IRubyObject reset() { + algo.reset(); + return this; + } + + @JRubyMethod() + public IRubyObject bubblebabble(ThreadContext context) { + final byte[] digest = algo.digest(); + return RubyString.newString(context.runtime, BubbleBabble.bubblebabble(digest, 0, digest.length)); + } + + private void setAlgorithm(Metadata metadata) throws NoSuchAlgorithmException { + this.algo = createMessageDigest(metadata.getName()); + this.blockLength = metadata.getBlockLength(); + } + + } +}// RubyDigest diff --git a/ext/java/org/jruby/ext/digest/SHA1.java b/ext/java/org/jruby/ext/digest/SHA1.java new file mode 100644 index 0000000..f2a0043 --- /dev/null +++ b/ext/java/org/jruby/ext/digest/SHA1.java @@ -0,0 +1,41 @@ +/* + **** BEGIN LICENSE BLOCK ***** + * BSD 2-Clause License + * + * Copyright (c) 2010, Charles Oliver Nutter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ***** END LICENSE BLOCK *****/ + +package org.jruby.ext.digest; + +import java.io.IOException; +import org.jruby.Ruby; +import org.jruby.runtime.load.Library; + +public class SHA1 implements Library { + + public void load(final Ruby runtime, boolean wrap) throws IOException { + org.jruby.ext.digest.RubyDigest.createDigestSHA1(runtime); + } +} diff --git a/ext/java/org/jruby/ext/digest/SHA2.java b/ext/java/org/jruby/ext/digest/SHA2.java new file mode 100644 index 0000000..f9e58e3 --- /dev/null +++ b/ext/java/org/jruby/ext/digest/SHA2.java @@ -0,0 +1,41 @@ +/* + **** BEGIN LICENSE BLOCK ***** + * BSD 2-Clause License + * + * Copyright (c) 2010, Charles Oliver Nutter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ***** END LICENSE BLOCK *****/ + +package org.jruby.ext.digest; + +import java.io.IOException; +import org.jruby.Ruby; +import org.jruby.runtime.load.Library; + +public class SHA2 implements Library { + + public void load(final Ruby runtime, boolean wrap) throws IOException { + org.jruby.ext.digest.RubyDigest.createDigestSHA2(runtime); + } +} diff --git a/test/lib/core_assertions.rb b/test/lib/core_assertions.rb index ff78c2b..928af7b 100644 --- a/test/lib/core_assertions.rb +++ b/test/lib/core_assertions.rb @@ -291,6 +291,7 @@ def assert_separately(args, file = nil, line = nil, src, ignore_stderr: nil, **o eom args = args.dup args.insert((Hash === args.first ? 1 : 0), "-w", "--disable=gems", *$:.map {|l| "-I#{l}"}) + args << "--debug" if RUBY_ENGINE == 'jruby' # warning: tracing (e.g. set_trace_func) will not capture all events without --debug flag stdout, stderr, status = EnvUtil.invoke_ruby(args, src, capture_stdout, true, **opt) ensure if res_c From e9d0affea91d1b704fdd0d937322e9638f3c8d7a Mon Sep 17 00:00:00 2001 From: Nobuyoshi Nakada Date: Thu, 23 Sep 2021 23:19:10 +0200 Subject: [PATCH 2/2] Separate Java libraries --- .gitignore | 4 +-- Rakefile | 77 +++++++++++++++++++++++++++++++------------------- digest.gemspec | 17 ++++++----- 3 files changed, 59 insertions(+), 39 deletions(-) diff --git a/.gitignore b/.gitignore index 3e810e4..b26d37c 100644 --- a/.gitignore +++ b/.gitignore @@ -7,9 +7,7 @@ /pkg/ /spec/reports/ /tmp/ -lib/*.jar -lib/digest -lib/digest/*.rb +/lib/ *.bundle *.so *.o diff --git a/Rakefile b/Rakefile index daabba3..4e0477d 100644 --- a/Rakefile +++ b/Rakefile @@ -2,54 +2,59 @@ require "bundler/gem_tasks" require "rake/testtask" require 'fileutils' +helper = Bundler::GemHelper.instance + +lib_dir = RUBY_ENGINE == 'jruby' ? "lib/java" : "lib" + Rake::TestTask.new(:test) do |t| - t.libs << "test" << "test/lib" << "lib" + t.libs << "test" << "test/lib" << lib_dir t.ruby_opts << "-rhelper" t.test_files = FileList["test/**/test_*.rb"] end +algorithms = %w(BubbleBabble MD5 RMD160 SHA1 SHA2) + require 'rake/javaextensiontask' Rake::JavaExtensionTask.new("digest") do |ext| ext.source_version = '1.8' ext.target_version = '1.8' ext.ext_dir = 'ext/java' + ext.lib_dir = 'lib/java' end -algorithms = %w(bubblebabble md5 rmd160 sha1 sha2) - -# copy library loaders -FileUtils.mkdir "./lib/digest" unless File.exist?("./lib/digest") -algorithms.each do |ext| - source = "./ext/digest/#{ext}/lib/#{ext}.rb" - if File.exist? source - FileUtils.cp source, "./lib/digest/#{ext}.rb" - end +java_pkg = nil +task 'compile:java' => 'java:lib' do + java_pkg = Bundler::GemHelper.instance.build_java_gem end -if RUBY_ENGINE == 'jruby' - File.write("./lib/digest/bubblebabble.rb", <<-FILE) -# frozen_string_literal: true -JRuby::Util.load_ext("org.jruby.ext.digest.BubbleBabble") -FILE - File.write("./lib/digest/md5.rb", <<-FILE) -# frozen_string_literal: true -JRuby::Util.load_ext("org.jruby.ext.digest.MD5") -FILE - File.write("./lib/digest/rmd160.rb", <<-FILE) +task 'java:lib' do + FileUtils.mkdir_p "./lib/java/digest" + maps = algorithms.each.with_object({}) {|ext, map| map[ext.downcase] = ext} + maps.each do |lib, ext| + begin + source = File.read("#{__dir__}/ext/digest/#{lib}/lib/#{lib}.rb") + source["require 'digest/#{lib}.so'"] = "JRuby::Util.load_ext('org.jruby.ext.digest.#{ext}')" + rescue + source = <<-FILE # frozen_string_literal: true -JRuby::Util.load_ext("org.jruby.ext.digest.RMD160") +JRuby::Util.load_ext("org.jruby.ext.digest.#{ext}") FILE - File.write("./lib/digest/sha1.rb", <<-FILE) -# frozen_string_literal: true -JRuby::Util.load_ext("org.jruby.ext.digest.SHA1") -FILE - File.write("./lib/digest/sha2.rb", File.read("./lib/digest/sha2.rb").sub("require 'digest/sha2.so'", "JRuby::Util.load_ext('org.jruby.ext.digest.SHA2')")) - File.write("./lib/digest.rb", File.read("./lib/digest.rb").sub("require 'digest.so'", "JRuby::Util.load_ext('org.jruby.ext.digest.DigestLibrary')")) -else + end + File.write "./lib/java/digest/#{lib}.rb", source + end + source = File.read("#{__dir__}/ext/digest/lib/digest.rb") + source.gsub!(%r[require 'digest(?:/(\w+))?.so']) { + "JRuby::Util.load_ext('org.jruby.ext.digest.#{maps.fetch($1, 'DigestLibrary')}')" + } + source.gsub!(%r['digest/\w+\K.so(?=')], '') + File.write("./lib/java/digest.rb", source) +end + +unless RUBY_ENGINE == 'jruby' require 'rake/extensiontask' Rake::ExtensionTask.new("digest") algorithms.each do |ext| - Rake::ExtensionTask.new("digest/#{ext}") + Rake::ExtensionTask.new("digest/#{ext.downcase}") end end @@ -59,4 +64,18 @@ task :sync_tool do FileUtils.cp "../ruby/tool/lib/find_executable.rb", "./test/lib" end +def helper.build_java_gem + file_name = nil + sh([*gem_command, "build", "-V", "--platform=java", spec_path]) do + file_name = built_gem_path + pkg = File.join(base, "pkg") + FileUtils.mkdir_p(pkg) + FileUtils.mv(file_name, pkg) + file_name = File.basename(file_name) + Bundler.ui.confirm "#{name} #{version} built to pkg/#{file_name}." + file_name = File.join(pkg, file_name) + end + file_name +end + task :default => :test diff --git a/digest.gemspec b/digest.gemspec index f9357b0..46ad101 100644 --- a/digest.gemspec +++ b/digest.gemspec @@ -45,19 +45,22 @@ Gem::Specification.new do |spec| spec.bindir = "exe" spec.executables = [] - spec.require_paths = ["lib"] if Gem::Platform === spec.platform and spec.platform =~ 'java' or RUBY_ENGINE == 'jruby' spec.platform = 'java' + spec.require_paths = ["lib/java"] + spec.files.reject! {|path| path.start_with?("ext/")} spec.files.concat [ - "lib/digest.jar", - "lib/digest/md5.rb", - "lib/digest/sha1.rb", - "lib/digest/sha2.rb", - "lib/digest/rmd160.rb", - "lib/digest/bubblebabble.rb" + "lib/java/digest.jar", + "lib/java/digest.rb", + "lib/java/digest/md5.rb", + "lib/java/digest/sha1.rb", + "lib/java/digest/sha2.rb", + "lib/java/digest/rmd160.rb", + "lib/java/digest/bubblebabble.rb" ] else + spec.require_paths = ["lib"] spec.extensions = %w[ ext/digest/extconf.rb ext/digest/bubblebabble/extconf.rb