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 post_task(task) synchronize { ns_post_task(task) } end
Post the task to the internal queue. @note This is intended as a callback method from ScheduledTask only. It is not intended to be used directly. Post a task by using the `SchedulesTask#execute` method. @!visibility private
post_task
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/executor/timer_set.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/executor/timer_set.rb
Apache-2.0
def remove_task(task) synchronize { @queue.delete(task) } end
Remove the given task from the queue. @note This is intended as a callback method from `ScheduledTask` only. It is not intended to be used directly. Cancel a task by using the `ScheduledTask#cancel` method. @!visibility private
remove_task
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/executor/timer_set.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/executor/timer_set.rb
Apache-2.0
def ns_shutdown_execution ns_reset_if_forked @queue.clear @timer_executor.kill stopped_event.set end
`ExecutorService` callback called during shutdown. @!visibility private
ns_shutdown_execution
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/executor/timer_set.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/executor/timer_set.rb
Apache-2.0
def process_tasks loop do task = synchronize { @condition.reset; @queue.peek } break unless task now = Concurrent.monotonic_time diff = task.schedule_time - now if diff <= 0 # We need to remove the task from the queue before passing # it to the executor, to avoid race conditions where we pass # the peek'ed task to the executor and then pop a different # one that's been added in the meantime. # # Note that there's no race condition between the peek and # this pop - this pop could retrieve a different task from # the peek, but that task would be due to fire now anyway # (because @queue is a priority queue, and this thread is # the only reader, so whatever timer is at the head of the # queue now must have the same pop time, or a closer one, as # when we peeked). task = synchronize { @queue.pop } task.executor.post { task.process_task } else @condition.wait([diff, 60].min) end end end
Run a loop and execute tasks in the scheduled order and at the approximate scheduled time. If no tasks remain the thread will exit gracefully so that garbage collection can occur. If there are no ready tasks it will sleep for up to 60 seconds waiting for the next scheduled task. @!visibility private
process_tasks
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/executor/timer_set.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/executor/timer_set.rb
Apache-2.0
def synchronize raise NotImplementedError end
@!macro synchronization_object_method_synchronize @yield runs the block synchronized against this object, equivalent of java's `synchronize(this) {}` @note can by made public in descendants if required by `public :synchronize`
synchronize
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/synchronization/abstract_lockable_object.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/synchronization/abstract_lockable_object.rb
Apache-2.0
def ns_wait_until(timeout = nil, &condition) if timeout wait_until = Concurrent.monotonic_time + timeout loop do now = Concurrent.monotonic_time condition_result = condition.call return condition_result if now >= wait_until || condition_result ns_wait wait_until - now end else ns_wait timeout until condition.call true end end
@!macro synchronization_object_method_ns_wait_until Wait until condition is met or timeout passes, protects against spurious wake-ups. @param [Numeric, nil] timeout in seconds, `nil` means no timeout @yield condition to be met @yieldreturn [true, false] @return [true, false] if condition met @note only to be used inside synchronized block @note to provide direct access to this method in a descendant add method ``` def wait_until(timeout = nil, &condition) synchronize { ns_wait_until(timeout, &condition) } end ```
ns_wait_until
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/synchronization/abstract_lockable_object.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/synchronization/abstract_lockable_object.rb
Apache-2.0
def ns_wait(timeout = nil) raise NotImplementedError end
@!macro synchronization_object_method_ns_wait Wait until another thread calls #signal or #broadcast, spurious wake-ups can happen. @param [Numeric, nil] timeout in seconds, `nil` means no timeout @return [self] @note only to be used inside synchronized block @note to provide direct access to this method in a descendant add method ``` def wait(timeout = nil) synchronize { ns_wait(timeout) } end ```
ns_wait
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/synchronization/abstract_lockable_object.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/synchronization/abstract_lockable_object.rb
Apache-2.0
def ns_signal raise NotImplementedError end
@!macro synchronization_object_method_ns_signal Signal one waiting thread. @return [self] @note only to be used inside synchronized block @note to provide direct access to this method in a descendant add method ``` def signal synchronize { ns_signal } end ```
ns_signal
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/synchronization/abstract_lockable_object.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/synchronization/abstract_lockable_object.rb
Apache-2.0
def ns_broadcast raise NotImplementedError end
@!macro synchronization_object_method_ns_broadcast Broadcast to all waiting threads. @return [self] @note only to be used inside synchronized block @note to provide direct access to this method in a descendant add method ``` def broadcast synchronize { ns_broadcast } end ```
ns_broadcast
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/synchronization/abstract_lockable_object.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/synchronization/abstract_lockable_object.rb
Apache-2.0
def initialize super __initialize_atomic_fields__ end
TODO make it a module if possible @!method self.attr_volatile(*names) Creates methods for reading and writing (as `attr_accessor` does) to a instance variable with volatile (Java) semantic. The instance variable should be accessed only through generated methods. @param [::Array<Symbol>] names of the instance variables to be volatile @return [::Array<Symbol>] names of defined method names Has to be called by children.
initialize
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/synchronization/object.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/synchronization/object.rb
Apache-2.0
def sum x = base if current_cells = cells current_cells.each do |cell| x += cell.value if cell end end x end
Returns the current sum. The returned value is _NOT_ an atomic snapshot: Invocation in the absence of concurrent updates returns an accurate result, but concurrent updates that occur while the sum is being calculated might not be incorporated.
sum
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/thread_safe/util/adder.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/thread_safe/util/adder.rb
Apache-2.0
def cheap_wait conditional_variable = @conditional_variable ||= ConditionVariable.new conditional_variable.wait(mutex) end
Releases this object's +cheap_synchronize+ lock and goes to sleep waiting for other threads to +cheap_broadcast+, reacquires the lock on wakeup. Must only be called in +cheap_broadcast+'s block.
cheap_wait
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/thread_safe/util/cheap_lockable.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/thread_safe/util/cheap_lockable.rb
Apache-2.0
def cheap_broadcast if conditional_variable = @conditional_variable conditional_variable.broadcast end end
Wakes up all threads waiting for this object's +cheap_synchronize+ lock. Must only be called in +cheap_broadcast+'s block.
cheap_broadcast
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/thread_safe/util/cheap_lockable.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/thread_safe/util/cheap_lockable.rb
Apache-2.0
def retry_update(x, hash_code, was_uncontended) # :yields: current_value hash = hash_code collided = false # True if last slot nonempty while true if current_cells = cells if !(cell = current_cells.volatile_get_by_hash(hash)) if busy? collided = false else # Try to attach new Cell if try_to_install_new_cell(Cell.new(x), hash) # Optimistically create and try to insert new cell break else redo # Slot is now non-empty end end elsif !was_uncontended # CAS already known to fail was_uncontended = true # Continue after rehash elsif cell.cas_computed {|current_value| yield current_value} break elsif current_cells.size >= CPU_COUNT || cells != current_cells # At max size or stale collided = false elsif collided && expand_table_unless_stale(current_cells) collided = false redo # Retry with expanded table else collided = true end hash = XorShiftRandom.xorshift(hash) elsif try_initialize_cells(x, hash) || cas_base_computed {|current_base| yield current_base} break end end self.hash_code = hash end
Handles cases of updates involving initialization, resizing, creating new Cells, and/or contention. See above for explanation. This method suffers the usual non-modularity problems of optimistic retry code, relying on rechecked sets of reads. Arguments: [+x+] the value [+hash_code+] hash code used [+x+] false if CAS failed before call
retry_update
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/thread_safe/util/striped64.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/thread_safe/util/striped64.rb
Apache-2.0
def hash_code Thread.current[THREAD_LOCAL_KEY] ||= XorShiftRandom.get end
A thread-local hash code accessor. The code is initially random, but may be set to a different value upon collisions.
hash_code
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/thread_safe/util/striped64.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/thread_safe/util/striped64.rb
Apache-2.0
def internal_reset(initial_value) current_cells = cells self.base = initial_value if current_cells current_cells.each do |cell| cell.value = initial_value if cell end end end
Sets base and all +cells+ to the given value.
internal_reset
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/thread_safe/util/striped64.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/thread_safe/util/striped64.rb
Apache-2.0
def attr_volatile(*attr_names) return if attr_names.empty? include(Module.new do atomic_ref_setup = attr_names.map {|attr_name| "@__#{attr_name} = Concurrent::AtomicReference.new"} initialize_copy_setup = attr_names.zip(atomic_ref_setup).map do |attr_name, ref_setup| "#{ref_setup}(other.instance_variable_get(:@__#{attr_name}).get)" end class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1 def initialize(*) super #{atomic_ref_setup.join('; ')} end def initialize_copy(other) super #{initialize_copy_setup.join('; ')} end RUBY_EVAL attr_names.each do |attr_name| class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1 def #{attr_name} @__#{attr_name}.get end def #{attr_name}=(value) @__#{attr_name}.set(value) end def compare_and_set_#{attr_name}(old_value, new_value) @__#{attr_name}.compare_and_set(old_value, new_value) end RUBY_EVAL alias_method :"cas_#{attr_name}", :"compare_and_set_#{attr_name}" alias_method :"lazy_set_#{attr_name}", :"#{attr_name}=" end end) end
Provides +volatile+ (in the JVM's sense) attribute accessors implemented atop of +Concurrent::AtomicReference+. Usage: class Foo extend Concurrent::ThreadSafe::Util::Volatile attr_volatile :foo, :bar def initialize(bar) super() # must super() into parent initializers before using the volatile attribute accessors self.bar = bar end def hello my_foo = foo # volatile read self.foo = 1 # volatile write cas_foo(1, 2) # => true | a strong CAS end end
attr_volatile
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/thread_safe/util/volatile.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/thread_safe/util/volatile.rb
Apache-2.0
def get Kernel.rand(MAX_XOR_SHIFTABLE_INT) + 1 # 0 can't be xorshifted end
Generates an initial non-zero positive +Fixnum+ via +Kernel.rand+.
get
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/thread_safe/util/xor_shift_random.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/thread_safe/util/xor_shift_random.rb
Apache-2.0
def monotonic_time(unit = :float_second) Process.clock_gettime(Process::CLOCK_MONOTONIC, unit) end
@!macro monotonic_get_time Returns the current time as tracked by the application monotonic clock. @param [Symbol] unit the time unit to be returned, can be either :float_second, :float_millisecond, :float_microsecond, :second, :millisecond, :microsecond, or :nanosecond default to :float_second. @return [Float] The current monotonic time since some unspecified starting point @!macro monotonic_clock_warning
monotonic_time
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/utility/monotonic_time.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/concurrent-ruby-1.2.2/lib/concurrent-ruby/concurrent/utility/monotonic_time.rb
Apache-2.0
def get_ns_domains(resolver, domain) ns_response = get_ns_response(resolver, domain) ns_answers = ns_response.answer.select { |r| r.type == 'NS'} ns_answers.map(&:domainname) end
Finds all the nameserver domains for the domain.
get_ns_domains
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/demo/check_soa.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/demo/check_soa.rb
Apache-2.0
def fatal_error(message) puts message exit -1 end
= NAME mx - Print a domain's MX records = SYNOPSIS mx domain = DESCRIPTION mx prints a domain's MX records, sorted by preference. = AUTHOR Michael Fuhr <[email protected]> (Ruby port AlexD, Nominet UK)
fatal_error
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/demo/mx.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/demo/mx.rb
Apache-2.0
def log_and_raise(object, error_class = RuntimeError) if object.is_a?(Exception) error = object Dnsruby.log.error(error.inspect) raise error else message = object.to_s Dnsruby.log.error(message) raise error_class.new(message) end end
Logs (error level) and raises an error.
log_and_raise
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby.rb
Apache-2.0
def to_binary_string(min_length = 0) BitMapping.number_to_binary_string(number, min_length) end
Instance methods to convert the data to the various representation types: Returns the instance's value as a binary string (e.g. "\x0C")
to_binary_string
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/bitmap.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/bitmap.rb
Apache-2.0
def binary_string_to_number(string) string = string.clone.force_encoding(Encoding::ASCII_8BIT) string.bytes.inject(0) do |number, byte| number * 256 + byte.ord end end
Converts from a binary string to a number, e.g. "\x01\x00" => 256
binary_string_to_number
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/bit_mapping.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/bit_mapping.rb
Apache-2.0
def number_to_binary_string(number, min_length = 0) assert_non_negative(number) binary_string = ''.force_encoding(Encoding::ASCII_8BIT) while number > 0 byte_value = number & 0xFF binary_string << byte_value number >>= 8 end binary_string.reverse.rjust(min_length, "\x00") end
Converts a number to a binary encoded string, e.g. 256 => "\x01\x00"
number_to_binary_string
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/bit_mapping.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/bit_mapping.rb
Apache-2.0
def number_to_place_value_array(number) assert_non_negative(number) array = [] bit_value = 1 while number > 0 array << ((number & 1 == 1) ? bit_value : 0) number >>= 1 bit_value <<= 1 end array.reverse end
Converts a number to an array of place values, e.g. 9 => [8, 0, 0, 1]
number_to_place_value_array
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/bit_mapping.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/bit_mapping.rb
Apache-2.0
def number_to_bit_array(number, minimum_binary_places = 0) assert_non_negative(number) array = [] while number > 0 array << (number & 1) number >>= 1 end array.reverse! zero_pad_count = minimum_binary_places - array.size zero_pad_count.times { array.unshift(0) } array end
Converts a number to an array of bit values, e.g. 9 => [1, 0, 0, 1]
number_to_bit_array
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/bit_mapping.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/bit_mapping.rb
Apache-2.0
def bit_array_to_number(bit_array) return nil if bit_array.empty? multiplier = 1 bit_array.reverse.inject(0) do |result, n| result += n * multiplier multiplier *= 2 result end end
Converts an array of bit values, e.g. [1, 0, 0, 1], to a number, e.g. 9
bit_array_to_number
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/bit_mapping.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/bit_mapping.rb
Apache-2.0
def number_to_set_bit_positions_array(number) assert_non_negative(number) array = [] position = 0 while number > 0 array << position if number & 1 == 1 position += 1 number >>= 1 end array end
Converts a number to a sparse array containing bit positions that are set/true/1. Note that these are bit positions, e.g. 76543210, and not bit column values such as 128/64/32/16/8/4/2/1.
number_to_set_bit_positions_array
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/bit_mapping.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/bit_mapping.rb
Apache-2.0
def set_bit_position_array_to_number(position_array) return nil if position_array.empty? position_array.inject(0) do |result, n| result += 2 ** n end end
Converts an array of bit position numbers to a numeric value, e.g. [0, 2] => 5
set_bit_position_array_to_number
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/bit_mapping.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/bit_mapping.rb
Apache-2.0
def binary_string_to_bit_array(string, minimum_binary_places = 0) number = binary_string_to_number(string) number_to_bit_array(number, minimum_binary_places) end
Converts a binary string to an array of bit values, e.g. "\x0C" => [1, 1, 0, 0]
binary_string_to_bit_array
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/bit_mapping.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/bit_mapping.rb
Apache-2.0
def assert_non_negative(number) unless number.is_a?(Integer) && number >= 0 raise ArgumentError.new( "Parameter must be a nonnegative Integer " + "but is #{number.inspect} (a #{number.class})") end end
If number is negative, raises an ArgumentError; else does nothing.
assert_non_negative
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/bit_mapping.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/bit_mapping.rb
Apache-2.0
def reverse_binary_string_bits(binary_string) binary_place_count = binary_string.size * 8 reversed_bit_array = binary_string_to_bit_array(binary_string, binary_place_count).reverse number = bit_array_to_number(reversed_bit_array) number_to_binary_string(number) end
Reverses a binary string. Note that it is not enough to reverse the string itself because although the bytes would be reversed, the bits within each byte would not.
reverse_binary_string_bits
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/bit_mapping.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/bit_mapping.rb
Apache-2.0
def find(qname, qtype, qclass = Classes.IN) # print "CACHE find : #{qname}, #{qtype}\n" qn = Name.create(qname) qn.absolute = true key = CacheKey.new(qn, qtype, qclass).to_s @mutex.synchronize { data = @cache[key] if (!data) # print "CACHE lookup failed\n" return nil end if (data.expiration <= Time.now.to_i) @cache.delete(key) TheLog.debug("CACHE lookup stale\n") return nil end m = data.message TheLog.debug("CACHE found\n") return m } end
This method "fixes up" the response, so that the header and ttls are OK The resolver will still need to copy the flags and ID across from the query
find
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/cache.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/cache.rb
Apache-2.0
def nameserver if (!@configured) parse_config end return @nameserver end
-- @TODO@ Switches for : -- single socket for all packets -- single new socket for individual client queries (including retries and multiple nameservers) ++ The list of nameservers to query
nameserver
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/config.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/config.rb
Apache-2.0
def ndots if (!@configured) parse_config end return @ndots end
The minimum number of labels in the query name (if it is not absolute) before it is considered complete
ndots
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/config.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/config.rb
Apache-2.0
def initialize() @mutex = Mutex.new @configured = false end
Create a new Config with system default values
initialize
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/config.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/config.rb
Apache-2.0
def add_nameserver(ns) @configured = true if (ns.kind_of?String) ns=[ns] end check_ns(ns) ns.reverse_each do |n| if ([email protected]?(n)) self.nameserver=[n]+@nameserver end end end
Add a nameserver to the list of nameservers. Can take either a single String or an array of Strings. The new nameservers are added at a higher priority.
add_nameserver
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/config.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/config.rb
Apache-2.0
def initialize(config_info=nil) @do_caching = true @config = Config.new() @config.set_config_info(config_info) @resolver = Resolver.new(@config) # if (@resolver.single_resolvers.length == 0) # raise ArgumentError.new("Must pass at least one valid resolver address") # end end
Creates a new DNS resolver +config_info+ can be: * nil:: Uses platform default (e.g. /etc/resolv.conf) * String:: Path to a file using /etc/resolv.conf's format * Hash:: Must contain :nameserver, :search and :ndots keys example : Dnsruby::DNS.new({:nameserver => ['210.251.121.21'], :search => ['ruby-lang.org'], :ndots => 1})
initialize
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/DNS.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/DNS.rb
Apache-2.0
def getaddress(name) each_address(name) {|address| return address} raise ResolvError.new("DNS result has no information for #{name}") end
Gets the first IP address of +name+ from the DNS resolver +name+ can be a Dnsruby::Name or a String. Retrieved address will be a Dnsruby::IPv4 or a Dnsruby::IPv6
getaddress
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/DNS.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/DNS.rb
Apache-2.0
def getaddresses(name) ret = [] each_address(name) {|address| ret << address} return ret end
Gets all IP addresses of +name+ from the DNS resolver +name+ can be a Dnsruby::Name or a String. Retrieved address will be a Dnsruby::IPv4 or a Dnsruby::IPv6
getaddresses
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/DNS.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/DNS.rb
Apache-2.0
def each_address(name) each_resource(name) {|resource| yield resource.address} end
Iterates over all IP addresses of +name+ retrieved from the DNS resolver +name+ can be a Dnsruby::Name or a String. Retrieved address will be a Dnsruby::IPv4 or a Dnsruby::IPv6
each_address
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/DNS.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/DNS.rb
Apache-2.0
def getname(address) each_name(address) {|name| return name} raise ResolvError.new("DNS result has no information for #{address}") end
Gets the first hostname for +address+ from the DNS resolver +address+ must be a Dnsruby::IPv4, Dnsruby::IPv6 or a String. Retrieved name will be a Dnsruby::Name.
getname
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/DNS.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/DNS.rb
Apache-2.0
def getnames(address) ret = [] each_name(address) {|name| ret << name} return ret end
Gets all hostnames for +address+ from the DNS resolver +address+ must be a Dnsruby::IPv4, Dnsruby::IPv6 or a String. Retrieved name will be a Dnsruby::Name.
getnames
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/DNS.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/DNS.rb
Apache-2.0
def each_name(address) case address when Name ptr = address when IPv4, IPv6 ptr = address.to_name when IPv4::Regex ptr = IPv4.create(address).to_name when IPv6::Regex ptr = IPv6.create(address).to_name else raise ResolvError.new("cannot interpret as address: #{address}") end each_resource(ptr, Types.PTR, Classes.IN) {|resource| yield resource.domainname} end
Iterates over all hostnames for +address+ retrieved from the DNS resolver +address+ must be a Dnsruby::IPv4, Dnsruby::IPv6 or a String. Retrieved name will be a Dnsruby::Name.
each_name
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/DNS.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/DNS.rb
Apache-2.0
def getresource(name, type=Types.A, klass=Classes.IN) each_resource(name, type, klass) {|resource| return resource} raise ResolvError.new("DNS result has no information for #{name}") end
Look up the first +type+, +klass+ resource for +name+ +type+ defaults to Dnsruby::Types.A +klass+ defaults to Dnsruby::Classes.IN Returned resource is represented as a Dnsruby::RR instance, e.g. Dnsruby::RR::IN::A
getresource
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/DNS.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/DNS.rb
Apache-2.0
def getresources(name, type=Types.A, klass=Classes.IN) ret = [] each_resource(name, type, klass) {|resource| ret << resource} return ret end
Look up all +type+, +klass+ resources for +name+ +type+ defaults to Dnsruby::Types.A +klass+ defaults to Dnsruby::Classes.IN Returned resource is represented as a Dnsruby::RR instance, e.g. Dnsruby::RR::IN::A
getresources
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/DNS.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/DNS.rb
Apache-2.0
def each_resource(name, type=Types.A, klass=Classes.IN, &proc) type = Types.new(type) klass = Classes.new(klass) reply, reply_name = send_query(name, type, klass) case reply.rcode.code when RCode::NOERROR extract_resources(reply, reply_name, type, klass, &proc) return # when RCode::NXDomain # Dnsruby.log.debug("RCode::NXDomain returned - raising error") # raise Config::NXDomain.new(reply_name.to_s) else Dnsruby.log.error{"Unexpected rcode : #{reply.rcode.string}"} raise Config::OtherResolvError.new(reply_name.to_s) end end
Iterates over all +type+, +klass+ resources for +name+ +type+ defaults to Dnsruby::Types.A +klass+ defaults to Dnsruby::Classes.IN Yielded resource is represented as a Dnsruby::RR instance, e.g. Dnsruby::RR::IN::A
each_resource
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/DNS.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/DNS.rb
Apache-2.0
def initialize(filename = DefaultFileName) @filename = filename @mutex = Mutex.new @initialized = nil end
Creates a new Dnsruby::Hosts using +filename+ for its data source
initialize
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/hosts.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/hosts.rb
Apache-2.0
def getaddress(name) each_address(name) {|address| return address} raise ResolvError.new("#{@filename} has no name: #{name}") end
Gets the first IP address for +name+ from the hosts file
getaddress
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/hosts.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/hosts.rb
Apache-2.0
def getaddresses(name) ret = [] each_address(name) {|address| ret << address} return ret end
Gets all IP addresses for +name+ from the hosts file
getaddresses
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/hosts.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/hosts.rb
Apache-2.0
def each_address(name, &proc) lazy_initialize if @name2addr.include?(name) @name2addr[name].each(&proc) end end
Iterates over all IP addresses for +name+ retrieved from the hosts file
each_address
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/hosts.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/hosts.rb
Apache-2.0
def getname(address) each_name(address) {|name| return name} raise ResolvError.new("#{@filename} has no address: #{address}") end
Gets the first hostname of +address+ from the hosts file
getname
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/hosts.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/hosts.rb
Apache-2.0
def getnames(address) ret = [] each_name(address) {|name| ret << name} return ret end
Gets all hostnames for +address+ from the hosts file
getnames
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/hosts.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/hosts.rb
Apache-2.0
def each_name(address, &proc) lazy_initialize if @addr2name.include?(address) @addr2name[address].each(&proc) end end
Iterates over all hostnames for +address+ retrieved from the hosts file
each_name
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/hosts.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/hosts.rb
Apache-2.0
def to_name return Name.create( # @address.unpack("H32")[0].split(//).reverse + ['ip6', 'arpa']) @address.unpack("H32")[0].split(//).reverse.join(".") + ".ip6.arpa") end
Turns this IPv6 address into a Dnsruby::Name -- ip6.arpa should be searched too. [RFC3152]
to_name
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/ipv6.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/ipv6.rb
Apache-2.0
def initialize(keys = nil) # Store key tag against [expiry, key] @keys = {} add(keys) end
Cache includes expiration time for keys Cache removes expired records
initialize
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/key_cache.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/key_cache.rb
Apache-2.0
def initialize(*args) arg=args[0] @ipv6 = false @packet_timeout = Resolver::DefaultPacketTimeout @port = Resolver::DefaultPort @udp_size = Resolver::DefaultUDPSize @dnssec = Resolver::DefaultDnssec @use_tcp = false @no_tcp = false @tsig = nil @ignore_truncation = false @src_address = '0.0.0.0' @src_address6 = '::' @src_port = [0] @recurse = true @tcp_pipelining = false @tcp_pipelining_max_queries = :infinite @use_counts = {} if arg.nil? elsif arg.kind_of? String @server = arg elsif arg.kind_of? Name @server = arg elsif arg.kind_of? Hash arg.keys.each do |attr| begin if ((attr.to_s == "src_address" || attr.to_s == "src_address6") && (arg[attr] == nil || arg[attr] == "")) else send(attr.to_s + "=", arg[attr]) end rescue Exception => e Dnsruby.log.error { "PacketSender : Argument #{attr}, #{arg[attr]} not valid : #{e}\n" } end end end # Check server is IP @server=Config.resolve_server(@server) check_ipv6 # ResolverRegister::register_single_resolver(self) end
Can take a hash with the following optional keys : * :server * :port * :use_tcp * :tcp_pipelining * :tcp_pipelining_max_queries * :no_tcp * :ignore_truncation * :src_address * :src_address6 * :src_port * :udp_size * :tsig * :packet_timeout * :recurse
initialize
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/packet_sender.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/packet_sender.rb
Apache-2.0
def send_async(*args) # msg, client_queue, client_query_id, use_tcp=@use_tcp) # @TODO@ Need to select a good Header ID here - see forgery-resilience RFC draft for details msg = args[0] client_query_id = nil client_queue = nil use_tcp = @use_tcp if (msg.kind_of? String) msg = Message.new(msg) if (@dnssec) msg.header.cd = @dnssec # we'll do our own validation by default if (Dnssec.no_keys?) msg.header.cd = false end end end if (args.length > 1) if (args[1].class==Queue) client_queue = args[1] elsif (args.length == 2) use_tcp = args[1] end if (args.length > 2) client_query_id = args[2] if (args.length > 3) use_tcp = args[3] end end end # Need to keep track of the request mac (if using tsig) so we can validate the response (RFC2845 4.1) # #Are we using EventMachine or native Dnsruby? # if (Resolver.eventmachine?) # return send_eventmachine(query_packet, msg, client_query_id, client_queue, use_tcp) # else if (!client_query_id) client_query_id = Time.now + rand(10000) # is this safe?! end begin query_packet = make_query_packet(msg, use_tcp) rescue EncodeError => err Dnsruby.log.error { "#{err}" } st = SelectThread.instance st.push_exception_to_select(client_query_id, client_queue, err, nil) return end if (msg.do_caching && (msg.class != Update)) # Check the cache!! cachedanswer = nil if (msg.header.rd) cachedanswer = @@recursive_cache.find(msg.question()[0].qname, msg.question()[0].type) else cachedanswer = @@authoritative_cache.find(msg.question()[0].qname, msg.question()[0].type) end if (cachedanswer) TheLog.debug("Sending cached answer to client\n") # @TODO@ Fix up the header - ID and flags cachedanswer.header.id = msg.header.id # If we can find the answer, send it to the client straight away # Post the result to the client using SelectThread st = SelectThread.instance st.push_response_to_select(client_query_id, client_queue, cachedanswer, msg, self) return client_query_id end end # Otherwise, run the query if (udp_packet_size < query_packet.length) if (@no_tcp) # Can't send the message - abort! err=IOError.new("Can't send message - too big for UDP and no_tcp=true") Dnsruby.log.error { "#{err}" } st.push_exception_to_select(client_query_id, client_queue, err, nil) return end Dnsruby.log.debug { "Query packet length exceeds max UDP packet size - using TCP" } use_tcp = true end send_dnsruby(query_packet, msg, client_query_id, client_queue, use_tcp) return client_query_id # end end
Asynchronously send a Message to the server. The send can be done using just Dnsruby. Support for EventMachine has been deprecated. == Dnsruby pure Ruby event loop : A client_queue is supplied by the client, along with an optional client_query_id to identify the response. The client_query_id is generated, if not supplied, and returned to the client. When the response is known, the tuple (query_id, response_message, response_exception) is put in the queue for the client to process. The query is sent synchronously in the caller's thread. The select thread is then used to listen for and process the response (up to pushing it to the client_queue). The client thread is then used to retrieve the response and deal with it. Takes : * msg - the message to send * client_queue - a Queue to push the response to, when it arrives * client_query_id - an optional ID to identify the query to the client * use_tcp - whether to use TCP (defaults to PacketSender.use_tcp) Returns : * client_query_id - to identify the query response to the client. This ID is generated if it is not passed in by the client If the native Dsnruby networking layer is being used, then this method returns the client_query_id id = res.send_async(msg, queue) NOT SUPPORTED : id = res.send_async(msg, queue, use_tcp) id = res.send_async(msg, queue, id) id = res.send_async(msg, queue, id, use_tcp) Use Message#send_raw to send the packet with an untouched header. Use Message#do_caching to tell dnsruby whether to check the cache before sending, and update the cache upon receiving a response. Use Message#do_validation to tell dnsruby whether or not to do DNSSEC validation for this particular packet (assuming SingleResolver#dnssec == true) Note that these options should not normally be used!
send_async
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/packet_sender.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/packet_sender.rb
Apache-2.0
def tcp_pipeline_socket(src_port) Dnsruby.log.debug("Using tcp_pipeline_socket") sockaddr = Socket.sockaddr_in(@port, @server) reuse_pipeline_socket = -> do begin max = @tcp_pipelining_max_queries use_count = @use_counts[@pipeline_socket] if use_count && max != :infinite && use_count >= max #we can't reuse the socket since max is reached @use_counts.delete(@pipeline_socket) @pipeline_socket = nil Dnsruby.log.debug("Max queries per connection attained - creating new socket") else @pipeline_socket.connect(sockaddr) end rescue Errno::EISCONN #already connected, do nothing and reuse! rescue IOError, Errno::ECONNRESET #close by remote host, reconnect @pipeline_socket = nil Dnsruby.log.debug("Connection closed - recreating socket") end end create_pipeline_socket = -> do @tcp_pipeline_local_port = src_port src_address = @ipv6 ? @src_address6 : @src_address begin @pipeline_socket = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0) @pipeline_socket.bind(Addrinfo.tcp(src_address, src_port)) @pipeline_socket.connect(sockaddr) Dnsruby.log.debug("Creating socket #{src_address}:#{src_port}") @use_counts[@pipeline_socket] = 0 rescue Exception => e @pipeline_socket = nil raise e end end # Don't combine the following 2 statements; the reuse lambda can set the # socket to nil and if so we'd want to call the create lambda to recreate it. reuse_pipeline_socket.() if @pipeline_socket new_socket = @pipeline_socket.nil? create_pipeline_socket.() unless @pipeline_socket @use_counts[@pipeline_socket] += 1 [@pipeline_socket, new_socket] end
This method returns the current tcp socket for pipelining If this is the first time the method is called then the socket is bound to @src_address:@src_port and connected to the remote dns server @server:@port. If the connection has been closed because of an EOF on recv_nonblock (closed by server) the function will recreate of the socket (since @pipeline_socket.connect will result in a IOError exception) In general, every subsequent call the function will either return the current tcp pipeline socket or a new connected socket if the current one was closed by the server
tcp_pipeline_socket
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/packet_sender.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/packet_sender.rb
Apache-2.0
def send_dnsruby(query_bytes, query, client_query_id, client_queue, use_tcp) #:nodoc: all endtime = Time.now + @packet_timeout # First send the query (synchronously) st = SelectThread.instance socket = nil runnextportloop = true numtries = 0 src_address = @src_address if (@ipv6) src_address = @src_address6 end while (runnextportloop) do begin numtries += 1 src_port = get_next_src_port if (use_tcp) begin if (@tcp_pipelining) socket, new_socket = tcp_pipeline_socket(src_port) src_port = @tcp_pipeline_local_port else socket = Socket.tcp(@server, @port, src_address, src_port, connect_timeout: @packet_timeout) new_socket = true end rescue Errno::EBADF, Errno::ENETUNREACH => e # Can't create a connection err=IOError.new("TCP connection error to #{@server}:#{@port} from #{src_address}:#{src_port}, use_tcp=#{use_tcp}, exception = #{e.class}, #{e}") Dnsruby.log.error { "#{err}" } st.push_exception_to_select(client_query_id, client_queue, err, nil) return end else socket = nil # JRuby UDPSocket only takes 0 parameters - no IPv6 support in JRuby... if (/java/ =~ RUBY_PLATFORM) socket = UDPSocket.new() else # ipv6 = @src_address =~ /:/ socket = UDPSocket.new(@ipv6 ? Socket::AF_INET6 : Socket::AF_INET) end new_socket = true socket.bind(src_address, src_port) socket.connect(@server, @port) end runnextportloop = false rescue Exception => e if (socket!=nil) begin #let the select thread close the socket if tcp_pipeli socket.close unless @tcp_pipelining && !new_socket rescue Exception end end # Try again if the error was EADDRINUSE and a random source port is used # Maybe try a max number of times? if ((e.class != Errno::EADDRINUSE) || (numtries > 50) || ((e.class == Errno::EADDRINUSE) && (src_port == @src_port[0]))) err_msg = "dnsruby can't connect to #{@server}:#{@port} from #{src_address}:#{src_port}, use_tcp=#{use_tcp}, exception = #{e.class}, #{e} #{e.backtrace}" err=IOError.new(err_msg) Dnsruby.log.error( "#{err}") Dnsruby.log.error(e.backtrace) if @tcp_pipelining st.push_exception_to_select(client_query_id, client_queue, SocketEofResolvError.new(err_msg), nil) else st.push_exception_to_select(client_query_id, client_queue, err, nil) end return end end end if (socket==nil) err=IOError.new("dnsruby can't connect to #{@server}:#{@port} from #{src_address}:#{src_port}, use_tcp=#{use_tcp}") Dnsruby.log.error { "#{err}" } st.push_exception_to_select(client_query_id, client_queue, err, nil) return end Dnsruby.log.debug { "Sending packet to #{@server}:#{@port} from #{src_address}:#{src_port}, use_tcp=#{use_tcp} : #{query.question()[0].qname}, #{query.question()[0].qtype}" } # print "#{Time.now} : Sending packet to #{@server} : #{query.question()[0].qname}, #{query.question()[0].qtype}\n" # Listen for the response before we send the packet (to avoid any race conditions) query_settings = SelectThread::QuerySettings.new(query_bytes, query, @ignore_truncation, client_queue, client_query_id, socket, @server, @port, endtime, udp_packet_size, self) query_settings.is_persistent_socket = @tcp_pipelining if use_tcp query_settings.tcp_pipelining_max_queries = @tcp_pipelining_max_queries if @tcp_pipelining begin if (use_tcp) lenmsg = [query_bytes.length].pack('n') socket.send(lenmsg, 0) end socket.send(query_bytes, 0) # The select thread will now wait for the response and send that or a # timeout back to the client_queue. st.add_to_select(query_settings) rescue Exception => e err_msg = "Send failed to #{@server}:#{@port} from #{src_address}:#{src_port}, use_tcp=#{use_tcp}, exception : #{e}" err=IOError.new(err_msg) Dnsruby.log.error { "#{err}" } Dnsruby.log.error(e.backtrace) if @tcp_pipelining st.push_exception_to_select(client_query_id, client_queue, SocketEofResolvError.new(err_msg), nil) if new_socket else st.push_exception_to_select(client_query_id, client_queue, err, nil) end begin #we let the select_thread close the socket when doing tcp #pipelining socket.close unless @tcp_pipelining && !new_socket rescue Exception end return end Dnsruby.log.debug { "Packet sent to #{@server}:#{@port} from #{src_address}:#{src_port}, use_tcp=#{use_tcp} : #{query.question()[0].qname}, #{query.question()[0].qtype}" } # print "Packet sent to #{@server}:#{@port} from #{@src_address}:#{src_port}, use_tcp=#{use_tcp} : #{query.question()[0].qname}, #{query.question()[0].qtype}\n" end
This method sends the packet using the built-in pure Ruby event loop, with no dependencies.
send_dnsruby
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/packet_sender.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/packet_sender.rb
Apache-2.0
def src_port if (@src_port.length == 1) return @src_port[0] end return @src_port end
The source port to send queries from Returns either a single Integer or an Array e.g. "0", or "[60001, 60002, 60007]" Defaults to 0 - random port
src_port
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/packet_sender.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/packet_sender.rb
Apache-2.0
def add_src_port(p) if (Resolver.check_port(p, @src_port)) a = Resolver.get_ports_from(p) a.each do |x| if ((@src_port.length > 0) && (x == 0)) raise ArgumentError.new("src_port of 0 only allowed as only src_port value (currently #{@src_port.length} values") end @src_port.push(x) end end end
Can be a single Integer or a Range or an Array If an invalid port is selected (one reserved by IANA), then an ArgumentError will be raised. "0" means "any valid port" - this is only a viable option if it is the only port in the list. An ArgumentError will be raised if "0" is added to an existing set of source ports. res.add_src_port(60000) res.add_src_port([60001,60005,60010]) res.add_src_port(60015..60115)
add_src_port
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/packet_sender.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/packet_sender.rb
Apache-2.0
def udp_packet_size # if @udp_size > DefaultUDPSize then we use EDNS and # @udp_size should be taken as the maximum packet_data length ret = (@udp_size > Resolver::DefaultUDPSize ? @udp_size : Resolver::DefaultUDPSize) return ret end
Return the packet size to use for UDP
udp_packet_size
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/packet_sender.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/packet_sender.rb
Apache-2.0
def initialize(*args) @hash = Hash.new # stores addresses against their expiration @mutex = Mutex.new # This class is thread-safe end
Like an array, but stores the expiration of each record.
initialize
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/recursor.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/recursor.rb
Apache-2.0
def query(name, type=Types.A, klass=Classes.IN, no_validation = false) # @TODO@ PROVIDE AN ASYNCHRONOUS SEND WHICH RETURNS MESSAGE WITH ERROR!!! # Make sure the hint servers are initialized. @@mutex.synchronize { self.hints=(Hash.new) unless @@hints } @resolver.recurse = false # Make sure the authority cache is clean. # It is only used to store A and AAAA records of # the suposedly authoritative name servers. # TTLs are respected @@mutex.synchronize { if (!@@zones_cache) Recursor.clear_caches(@resolver) end } # So we have normal hashes, but the array of addresses at the end is now an AddressCache # which respects the ttls of the A/AAAA records # Now see if we already know the zone in question # Otherwise, see if we know any of its parents (will know at least ".") known_zone, known_authorities = get_closest_known_zone_authorities_for(name) # ".", @hints if nothing else # Seed name servers with the closest known authority # ret = _dorecursion( name, type, klass, ".", @hints, 0) ret = _dorecursion( name, type, klass, known_zone, known_authorities, 0, no_validation) Dnssec.validate(ret) if !no_validation # print "\n\nRESPONSE:\n#{ret}\n" return ret end
This method is much like the normal query() method except it disables the recurse flag in the packet and explicitly performs the recursion. packet = res.query( "www.netscape.com.", "A") packet = res.query( "www.netscape.com.", "A", "IN", true) # no validation The Recursor maintains a cache of known nameservers. DNSSEC validation is performed unless true is passed as the fourth parameter.
query
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/recursor.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/recursor.rb
Apache-2.0
def initialize(resolvers=[Hosts.new, DNS.new]) @resolvers = resolvers end
Instance Methods: Creates a new Resolv using +resolvers+
initialize
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolv.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolv.rb
Apache-2.0
def getaddress(name) addresses = getaddresses(name) if addresses.empty? raise ResolvError.new("no address for #{name}") else addresses.first end end
Looks up the first IP address for +name+
getaddress
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolv.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolv.rb
Apache-2.0
def getaddresses(name) return [name] if ADDRESS_REGEX.match(name) @resolvers.each do |resolver| addresses = [] resolver.each_address(name) { |address| addresses << address } return addresses unless addresses.empty? end [] end
Looks up all IP addresses for +name+
getaddresses
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolv.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolv.rb
Apache-2.0
def each_address(name) getaddresses(name).each { |address| yield(address)} end
Iterates over all IP addresses for +name+
each_address
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolv.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolv.rb
Apache-2.0
def getname(address) names = getnames(address) if names.empty? raise ResolvError.new("no name for #{address}") else names.first end end
Looks up the first hostname of +address+
getname
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolv.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolv.rb
Apache-2.0
def getnames(address) @resolvers.each do |resolver| names = [] resolver.each_name(address) { |name| names << name } return names unless names.empty? end [] end
Looks up all hostnames of +address+
getnames
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolv.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolv.rb
Apache-2.0
def each_name(address) getnames(address).each { |address| yield(address) } end
Iterates over all hostnames of +address+
each_name
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolv.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolv.rb
Apache-2.0
def query(name, type=Types.A, klass=Classes.IN, set_cd=@dnssec) msg = Message.new msg.do_caching = @do_caching msg.header.rd = 1 msg.add_question(name, type, klass) msg.do_validation = @do_validation if @dnssec msg.header.cd = set_cd # We do our own validation by default end send_message(msg) end
-- @TODO@ add load_balance? i.e. Target nameservers in a random, rather than pre-determined, order? This is best done when configuring the Resolver, as it will re-order servers based on their response times. ++ Query for a name. If a valid Message is received, then it is returned to the caller. Otherwise an exception (a Dnsruby::ResolvError or Dnsruby::ResolvTimeout) is raised. require 'dnsruby' res = Dnsruby::Resolver.new response = res.query('example.com') # defaults to Types.A, Classes.IN response = res.query('example.com', Types.MX) response = res.query('208.77.188.166') # IPv4 address so PTR query will be made response = res.query('208.77.188.166', Types.PTR)
query
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
Apache-2.0
def query!(name, type=Types.A, klass=Classes.IN, set_cd=@dnssec) response = nil; error = nil begin response = query(name, type, klass, set_cd) rescue => e error = e end [response, error] end
Like query, but does not raise an error when an error occurs. Instead, it returns it. @return a 2 element array: [response, error]
query!
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
Apache-2.0
def send_message(message) Dnsruby.log.debug{'Resolver : sending message'} q = Queue.new send_async(message, q) _id, result, error = q.pop if error error.response = result if error.is_a?(ResolvError) raise error else result end end
Send a message, and wait for the response. If a valid Message is received, then it is returned to the caller. Otherwise an exception (a Dnsruby::ResolvError or Dnsruby::ResolvTimeout) is raised. send_async is called internally. example : require 'dnsruby' include Dnsruby res = Dnsruby::Resolver.new begin response = res.send_message(Message.new('example.com', Types.MX)) rescue ResolvError # ... rescue ResolvTimeout # ... end
send_message
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
Apache-2.0
def send_message!(message) response = nil; error = nil begin response = send_message(message) rescue => e error = e end [response, error] end
Like send_message, but does not raise an error when an error occurs. Instead, it returns it. @return a 2 element array: [response, error]
send_message!
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
Apache-2.0
def query_raw(message, error_strategy = :return) unless [:return, :raise].include?(error_strategy) raise ArgumentError.new('error_strategy should be one of [:return, :raise].') end response, error = send_plain_message(message) if error_strategy == :return [response, error] else raise error if error response end end
Sends a message with send_plain_message. Effectively a wrapper around send_plain_message, but adds the ability to configure whether an error will be raised or returned if it occurs. @param message the message to send to the DNS server @param error_strategy :return to return [response, error] (default), :raise to return response only, or raise an error if one occurs
query_raw
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
Apache-2.0
def send_plain_message(message) Dnsruby::TheLog.debug('Resolver : send_plain_message') message.do_caching = false message.do_validation = false message.send_raw = true q = Queue.new send_async(message, q) _id, result, error = q.pop error.response = result if !error.nil? && error.is_a?(ResolvError) [result, error] end
This method takes a Message (supplied by the client), and sends it to the configured nameservers. No changes are made to the Message before it is sent (TSIG signatures will be applied if configured on the Resolver). Retries are handled as the Resolver is configured to do. Incoming responses to the query are not cached or validated (although TCP fallback will be performed if the TC bit is set and the (Single)Resolver has ignore_truncation set to false). Note that the Message is left untouched - this means that no OPT records are added, even if the UDP transport for the server is specified at more than 512 bytes. If it is desired to use EDNS for this packet, then you should call the Dnsruby::PacketSender#prepare_for_dnssec(msg), or Dnsruby::PacketSender#add_opt_rr(msg) The return value from this method is the [response, error] tuple. Either of these values may be nil - it is up to the client to check. example : require 'dnsruby' include Dnsruby res = Dnsruby::Resolver.new response, error = res.send_plain_message(Message.new('example.com', Types.MX)) if error print "Error returned : #{error}\n" else process_response(response) end
send_plain_message
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
Apache-2.0
def send_async(msg, client_queue, client_query_id = nil) unless @configured add_config_nameservers end # @single_res_mutex.synchronize { unless @resolver_ruby # @TODO@ Synchronize this? @resolver_ruby = ResolverRuby.new(self) end # } client_query_id = @resolver_ruby.send_async(msg, client_queue, client_query_id) if @single_resolvers.length == 0 Thread.start { sleep(@query_timeout == 0 ? 1 : @query_timeout) client_queue.push([client_query_id, nil, ResolvTimeout.new('Query timed out - no nameservers configured')]) } end client_query_id end
Asynchronously send a Message to the server. The send can be done using just Dnsruby. Support for EventMachine has been deprecated. == Dnsruby pure Ruby event loop : A client_queue is supplied by the client, along with an optional client_query_id to identify the response. The client_query_id is generated, if not supplied, and returned to the client. When the response is known, a tuple of (query_id, response_message, exception) will be added to the client_queue. The query is sent synchronously in the caller's thread. The select thread is then used to listen for and process the response (up to pushing it to the client_queue). The client thread is then used to retrieve the response and deal with it. Takes : * msg - the message to send * client_queue - a Queue to push the response to, when it arrives * client_query_id - an optional ID to identify the query to the client * use_tcp - whether to use only TCP (defaults to SingleResolver.use_tcp) Returns : * client_query_id - to identify the query response to the client. This ID is generated if it is not passed in by the client === Example invocations : id = res.send_async(msg, queue) NOT SUPPORTED : id = res.send_async(msg, queue, use_tcp) id = res.send_async(msg, queue, id) id = res.send_async(msg, queue, id, use_tcp) === Example code : require 'dnsruby' res = Dnsruby::Resolver.newsend query_id = 10 # can be any object you like query_queue = Queue.new res.send_async(Message.new('example.com', Types.MX), query_queue, query_id) query_id_2 = res.send_async(Message.new('example.com', Types.A), query_queue) # ...do a load of other stuff here... 2.times do response_id, response, exception = query_queue.pop # You can check the ID to see which query has been answered if exception == nil # deal with good response else # deal with problem end end
send_async
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
Apache-2.0
def close @resolver_ruby.close if @resolver_ruby end
Close the Resolver. Unfinished queries are terminated with OtherResolvError.
close
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
Apache-2.0
def initialize(*args) # @TODO@ Should we allow :namesver to be an RRSet of NS records? Would then need to randomly order them? @resolver_ruby = nil @src_address = nil @src_address6 = nil @single_res_mutex = Mutex.new @configured = false @do_caching = true @config = Config.new() reset_attributes # Process args if args.length == 1 if args[0].class == Hash args[0].keys.each do |key| begin if key == :config_info @config.set_config_info(args[0][:config_info]) elsif key == :nameserver set_config_nameserver(args[0][:nameserver]) elsif key == :nameservers set_config_nameserver(args[0][:nameservers]) else send(key.to_s + '=', args[0][key]) end rescue Exception => e Dnsruby.log.error{"Argument #{key} not valid : #{e}\n"} end end elsif args[0].class == String set_config_nameserver(args[0]) elsif args[0].class == Config # also accepts a Config object from Dnsruby::Resolv @config = args[0] end else # Anything to do? end update end
Create a new Resolver object. If no parameters are passed in, then the default system configuration will be used. Otherwise, a Hash may be passed in with the following optional elements : * :port * :use_tcp * :tsig * :ignore_truncation * :src_address * :src_address6 * :src_port * :recurse * :udp_size * :config_info - see Config * :nameserver - can be either a String or an array of Strings * :packet_timeout * :query_timeout * :retry_times * :retry_delay * :do_caching * :tcp_pipelining * :tcp_pipelining_max_queries - can be a number or :infinite symbol
initialize
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
Apache-2.0
def add_server(server)# :nodoc: @configured = true res = PacketSender.new(server) Dnsruby.log_and_raise("Can't create server #{server}", ArgumentError) unless res update_internal_res(res) @single_res_mutex.synchronize { @single_resolvers.push(res) } end
# Add a new SingleResolver to the list of resolvers this Resolver object will # query. def add_resolver(internal) # :nodoc: # @TODO@ Make a new PacketSender from this SingleResolver!! @single_resolvers.push(internal) end
add_server
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
Apache-2.0
def src_port @src_port.length == 1 ? @src_port[0] : @src_port end
The source port to send queries from Returns either a single Integer or an Array e.g. '0', or '[60001, 60002, 60007]' Defaults to 0 - random port
src_port
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
Apache-2.0
def add_src_port(p) if Resolver.check_port(p, @src_port) a = Resolver.get_ports_from(p) a.each do |x| if (@src_port.length > 0) && (x == 0) Dnsruby.log_and_raise("src_port of 0 only allowed as only src_port value (currently #{@src_port.length} values", ArgumentError) end @src_port.push(x) end end update end
Can be a single Integer or a Range or an Array If an invalid port is selected (one reserved by IANA), then an ArgumentError will be raised. "0" means "any valid port" - this is only a viable option if it is the only port in the list. An ArgumentError will be raised if "0" is added to an existing set of source ports. res.add_src_port(60000) res.add_src_port([60001,60005,60010]) res.add_src_port(60015..60115)
add_src_port
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
Apache-2.0
def close # @mutex.synchronize { @parent.single_res_mutex.synchronize { @query_list.each do |client_query_id, values| _msg, client_queue, q, _outstanding = values send_result_and_stop_querying(client_queue, client_query_id, q, nil, OtherResolvError.new('Resolver closing!')) end } end
Close the Resolver. Unfinished queries are terminated with OtherResolvError.
close
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
Apache-2.0
def send_result_and_stop_querying(client_queue, client_query_id, select_queue, msg, error) # :nodoc: all stop_querying(client_query_id) send_result(client_queue, client_query_id, select_queue, msg, error) end
MUST BE CALLED IN A SYNCHRONIZED BLOCK! Send the result back to the client, and close the socket for that query by removing the query from the select thread.
send_result_and_stop_querying
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
Apache-2.0
def send_result(client_queue, client_query_id, select_queue, msg, error) # :nodoc: all stop_querying(client_query_id) # @TODO@ ! # We might still get some callbacks, which we should ignore st = SelectThread.instance st.remove_observer(select_queue, self) # @mutex.synchronize{ # Remove the query from all of the data structures @query_list.delete(client_query_id) # } # Return the response to the client client_queue.push([client_query_id, msg, error]) end
MUST BE CALLED IN A SYNCHRONIZED BLOCK! Sends the result to the client's queue, and removes the queue observer from the select thread
send_result
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
Apache-2.0
def tick # :nodoc: all # Handle the tick # Do we have any retries due to be sent yet? # @mutex.synchronize{ @parent.single_res_mutex.synchronize { time_now = Time.now @timeouts.keys.each do |client_query_id| msg, client_queue, select_queue, outstanding = @query_list[client_query_id] query_timeout, timeouts = @timeouts[client_query_id] if query_timeout < Time.now # Time the query out send_result_and_stop_querying(client_queue, client_query_id, select_queue, nil, ResolvTimeout.new('Query timed out')) next end timeouts_done = [] timeouts.keys.sort.each do |timeout| if timeout < time_now # Send the next query res, retry_count = timeouts[timeout] id = [res, msg, client_query_id, retry_count] Dnsruby.log.debug("Sending msg to #{res.server}") # We should keep a list of the queries which are outstanding outstanding.push(id) timeouts_done.push(timeout) timeouts.delete(timeout) # Pick a new QID here @TODO@ !!! # msg.header.id = rand(65535); # print "New query : #{new_msg}\n" res.send_async(msg, select_queue, id) else break end end timeouts_done.each { |t| timeouts.delete(t) } end } end
This method is called twice a second from the select loop, in the select thread. It should arguably be called from another worker thread... (which also handles the queue) Each tick, we check if any timeouts have occurred. If so, we take the appropriate action : Return a timeout to the client, or send a new query
tick
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
Apache-2.0
def handle_queue_event(queue, id) # :nodoc: all # Time to process a new queue event. # If we get a callback for an ID we don't know about, don't worry - # just ignore it. It may be for a query we've already completed. # # So, get the next response from the queue (presuming there is one!) # # @TODO@ Tick could poll the queue and then call this method if needed - no need for observer interface. # @TODO@ Currently, tick and handle_queue_event called from select_thread - could have thread chuck events in to tick_queue. But then, clients would have to call in on other thread! # # So - two types of response : # 1) we've got a coherent response (or error) - stop sending more packets for that query! # 2) we've validated the response - it's ready to be sent to the client # # so need two more methods : # handleValidationResponse : basically calls send_result_and_stop_querying and # handleValidationError : does the same as handleValidationResponse, but for errors # can leave handleError alone # but need to change handleResponse to stop sending, rather than send_result_and_stop_querying. # # @TODO@ Also, we could really do with a MaxValidationTimeout - if validation not OK within # this time, then raise Timeout (and stop validation)? # # @TODO@ Also, should there be some facility to stop validator following same chain # concurrently? # # @TODO@ Also, should have option to speak only to configured resolvers (not follow authoritative chain) # if queue.empty? Dnsruby.log_and_raise('Severe internal error - Queue empty in handle_queue_event') end event_id, event_type, response, error = queue.pop # We should remove this packet from the list of outstanding packets for this query _resolver, _msg, client_query_id, _retry_count = id if id != event_id Dnsruby.log_and_raise("Serious internal error!! #{id} expected, #{event_id} received") end # @mutex.synchronize{ @parent.single_res_mutex.synchronize { if @query_list[client_query_id] == nil # print "Dead query response - ignoring\n" Dnsruby.log.debug{'Ignoring response for dead query'} return end _msg, _client_queue, _select_queue, outstanding = @query_list[client_query_id] if event_type == Resolver::EventType::RECEIVED || event_type == Resolver::EventType::ERROR unless outstanding.include?(id) Dnsruby.log.error("Query id not on outstanding list! #{outstanding.length} items. #{id} not on #{outstanding}") end outstanding.delete(id) end # } if event_type == Resolver::EventType::RECEIVED # if (event.kind_of?(Exception)) if error handle_error_response(queue, event_id, error, response) else # if event.kind_of?(Message) handle_response(queue, event_id, response) # else # Dnsruby.log.error('Random object #{event.class} returned through queue to Resolver') end elsif event_type == Resolver::EventType::VALIDATED if error handle_validation_error(queue, event_id, error, response) else handle_validation_response(queue, event_id, response) end elsif event_type == Resolver::EventType::ERROR handle_error_response(queue, event_id, error, response) else # print "ERROR - UNKNOWN EVENT TYPE IN RESOLVER : #{event_type}\n" TheLog.error("ERROR - UNKNOWN EVENT TYPE IN RESOLVER : #{event_type}") end } end
This method is called by the SelectThread (in the select thread) when the queue has a new item on it. The queue interface is used to separate producer/consumer threads, but we're using it here in one thread. It's probably a good idea to create a new "worker thread" to take items from the select thread queue and call this method in the worker thread.
handle_queue_event
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
Apache-2.0
def increment_resolver_priority(res) TheLog.debug("Incrementing resolver priority for #{res.server}\n") # @parent.single_res_mutex.synchronize { index = @parent.single_resolvers.index(res) if index > 0 @parent.single_resolvers.delete(res) @parent.single_resolvers.insert(index-1,res) end # } end
TO BE CALLED IN A SYNCHRONIZED BLOCK
increment_resolver_priority
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
Apache-2.0
def decrement_resolver_priority(res) TheLog.debug("Decrementing resolver priority for #{res.server}\n") # @parent.single_res_mutex.synchronize { index = @parent.single_resolvers.index(res) if index < @parent.single_resolvers.length @parent.single_resolvers.delete(res) @parent.single_resolvers.insert(index+1,res) end # } end
TO BE CALLED IN A SYNCHRONIZED BLOCK
decrement_resolver_priority
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
Apache-2.0
def demote_resolver(res) TheLog.debug("Demoting resolver priority for #{res.server} to bottom\n") # @parent.single_res_mutex.synchronize { @parent.single_resolvers.delete(res) @parent.single_resolvers.push(res) # } end
TO BE CALLED IN A SYNCHRONIZED BLOCK
demote_resolver
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/resolver.rb
Apache-2.0
def initialize @@mutex = Mutex.new @@mutex.synchronize { @@in_select=false # @@notifier,@@notified=IO.pipe @@sockets = Set.new @@timeouts = Hash.new # @@mutex.synchronize do @@query_hash = Hash.new @@socket_hash = Hash.new @@socket_is_persistent = Hash.new @@observers = Hash.new @@tcp_buffers=Hash.new @@socket_remaining_queries = Hash.new @@tick_observers = [] @@queued_exceptions=[] @@queued_responses=[] @@queued_validation_responses=[] @@wakeup_sockets = get_socket_pair @@sockets << @@wakeup_sockets[1] # Suppress reverse lookups BasicSocket.do_not_reverse_lookup = true # end # Now start the select thread @@select_thread = Thread.new { do_select } # # Start the validator thread # @@validator = ValidatorThread.instance } end
This singleton class runs a continuous select loop which listens for responses on all of the in-use sockets. When a new query is sent, the thread is woken up, and the socket is added to the select loop (and the new timeout calculated). Note that a combination of the socket and the packet ID is sufficient to uniquely identify the query to the select thread. But how do we find the response queue for a particular query? Hash of client_id->[query, client_queue, socket] and socket->[client_id] @todo@ should we implement some of cancel function?
initialize
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/select_thread.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/select_thread.rb
Apache-2.0
def clean_up_closed_sockets @@mutex.synchronize do closed_sockets_in_hash = @@sockets.select(&:closed?).select { |s| @@socket_hash[s] } @@sockets.delete_if { | socket | socket.closed? } closed_sockets_in_hash.each_with_object([]) do |socket, exceptions| @@socket_hash[socket].each do | client_id | exceptions << [SocketEofResolvError.new("TCP socket closed before all answers received"), socket, client_id] end end end exceptions end
Removes closed sockets from @@sockets, and returns an array containing 1 exception for each closed socket contained in @@socket_hash.
clean_up_closed_sockets
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/select_thread.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/select_thread.rb
Apache-2.0
def initialize(*args) arg=args[0] @single_res_mutex = Mutex.new @packet_timeout = Resolver::DefaultPacketTimeout @query_timeout = @packet_timeout @port = Resolver::DefaultPort @udp_size = Resolver::DefaultUDPSize @dnssec = Resolver::DefaultDnssec @use_tcp = false @no_tcp = false @tsig = nil @ignore_truncation = false @src_address = nil @src_address6 = nil @src_port = [0] @recurse = true @persistent_udp = false @persistent_tcp = false @retry_times = 1 @retry_delay = 0 @single_resolvers = [] @configured = false @do_caching = true @config = Config.new if (arg==nil) # Get default config @config = Config.new @config.get_ready @server = @config.nameserver[0] elsif (arg.kind_of?String) @config.get_ready @configured= true @config.nameserver=[arg] @server = @config.nameserver[0] # @server=arg elsif (arg.kind_of?Name) @config.get_ready @configured= true @config.nameserver=arg @server = @config.nameserver[0] # @server=arg elsif (arg.kind_of?Hash) arg.keys.each do |attr| if (attr == :server) @config.get_ready @configured= true @config.nameserver=[arg[attr]] @server = @config.nameserver[0] else begin send(attr.to_s+"=", arg[attr]) rescue Exception Dnsruby.log.error{"Argument #{attr} not valid\n"} end end end end isr = PacketSender.new({:server=>@server, :port=>@port, :dnssec=>@dnssec, :use_tcp=>@use_tcp, :no_tcp=>@no_tcp, :packet_timeout=>@packet_timeout, :tsig => @tsig, :ignore_truncation=>@ignore_truncation, :src_address=>@src_address, :src_address6=>@src_address6, :src_port=>@src_port, :recurse=>@recurse, :udp_size=>@udp_size}) @single_resolvers = [isr] # ResolverRegister::register_single_resolver(self) end
Can take a hash with the following optional keys : * :server * :port * :use_tcp * :no_tcp * :ignore_truncation * :src_address * :src_address6 * :src_port * :udp_size * :persistent_tcp * :persistent_udp * :tsig * :packet_timeout * :recurse
initialize
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/single_resolver.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/single_resolver.rb
Apache-2.0
def add_opt_rr(m) @single_res_mutex.synchronize { @single_resolvers[0].add_opt_rr(m) } end
Add the appropriate EDNS OPT RR for the specified packet. This is done automatically, unless you are using Resolver#send_plain_message
add_opt_rr
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/single_resolver.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/single_resolver.rb
Apache-2.0
def clear_trust_anchors @trust_anchors = KeyCache.new end
Wipes the cache of trusted keys
clear_trust_anchors
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/single_verifier.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/single_verifier.rb
Apache-2.0
def check_rr_data(rrset, sigrec)#:nodoc: all # Each RR MUST have the same owner name as the RRSIG RR; if (rrset.name.canonical != sigrec.name.canonical) raise VerifyError.new("RRSET should have same owner name as RRSIG for verification (rrsert=#{rrset.name}, sigrec=#{sigrec.name}") end # Each RR MUST have the same class as the RRSIG RR; if (rrset.klass != sigrec.klass) raise VerifyError.new("RRSET should have same DNS class as RRSIG for verification") end # Each RR in the RRset MUST have the RR type listed in the # RRSIG RR's Type Covered field; if (rrset.type != sigrec.type_covered) raise VerifyError.new("RRSET should have same type as RRSIG for verification") end # #Each RR in the RRset MUST have the TTL listed in the # #RRSIG Original TTL Field; # if (rrset.ttl != sigrec.original_ttl) # raise VerifyError.new("RRSET should have same ttl as RRSIG original_ttl for verification (should be #{sigrec.original_ttl} but was #{rrset.ttl}") # end # Now check that we are in the validity period for the RRSIG now = Time.now.to_i if ((sigrec.expiration < now) || (sigrec.inception > now)) raise VerifyError.new("Signature record not in validity period") end end
Check that the RRSet and RRSIG record are compatible
check_rr_data
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/single_verifier.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/single_verifier.rb
Apache-2.0
def clear_trusted_keys @trusted_keys = KeyCache.new @res = nil @discovered_ds_store = [] @configured_ds_store = [] end
Wipes the cache of trusted keys
clear_trusted_keys
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/single_verifier.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/dnsruby-1.70.0/lib/dnsruby/single_verifier.rb
Apache-2.0