Class: HTTPX::Resolver::Native

Inherits:
Resolver
  • Object
show all
Extended by:
Forwardable
Includes:
_ToIO
Defined in:
lib/httpx/resolver/native.rb,
sig/resolver/native.rbs

Overview

Implements a pure ruby name resolver, which abides by the Selectable API. It delegates DNS payload encoding/decoding to the resolv stlid gem.

Constant Summary collapse

DEFAULTS =

Returns:

  • (Hash[Symbol, untyped])
{
  nameserver: nil,
  **Resolv::DNS::Config.default_config_hash,
  packet_size: 512,
  timeouts: Resolver::RESOLVE_TIMEOUT,
}.freeze
DNS_PORT =

Returns:

  • (Integer)
53

Constants inherited from Resolver

Resolver::FAMILY_TYPES, Resolver::RECORD_TYPES

Constants included from Loggable

Loggable::COLORS, Loggable::USE_DEBUG_LOG

Instance Attribute Summary collapse

Attributes inherited from Resolver

#current_selector, #current_session, #family, #multi, #options

Instance Method Summary collapse

Methods inherited from Resolver

#disconnect, #each_connection, #early_resolve, #emit_addresses, #emit_connection_error, #emit_resolve_error, #emit_resolved_connection, #empty?, #inflight?, #initial_call, #lazy_resolve, multi?, #on_error, #resolve_connection, #resolve_error

Methods included from Loggable

#log, #log_exception, log_identifiers, #log_redact, #log_redact_body, #log_redact_headers

Methods included from _Selectable

#initial_call, #on_error

Constructor Details

#initialize(family, options) ⇒ Native

Returns a new instance of Native.

Parameters:

  • family (ip_family)
  • options (options)


28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/httpx/resolver/native.rb', line 28

def initialize(family, options)
  super
  @ns_index = 0
  @resolver_options = DEFAULTS.merge(@options.resolver_options)
  @socket_type = @resolver_options.fetch(:socket_type, :udp)
  @nameserver = if (nameserver = @resolver_options[:nameserver])
    nameserver = nameserver[family] if nameserver.is_a?(Hash)
    Array(nameserver)
  end
  @ndots = @resolver_options.fetch(:ndots, 1)
  @search = Array(@resolver_options[:search]).map { |srch| srch.scan(/[^.]+/) }
  @_timeouts = Array(@resolver_options[:timeouts])
  @timeouts = Hash.new { |timeouts, host| timeouts[host] = @_timeouts.dup }
  @name = nil
  @queries = {}
  @read_buffer = "".b
  @write_buffer = Buffer.new(@resolver_options[:packet_size])
  @state = :idle
  @timer = nil
end

Instance Attribute Details

#stateSymbol (readonly)

Returns the value of attribute state.

Returns:

  • (Symbol)


26
27
28
# File 'lib/httpx/resolver/native.rb', line 26

def state
  @state
end

Instance Method Details

#<<(connection) ⇒ void

This method returns an undefined value.

Parameters:



102
103
104
105
106
107
108
109
110
111
112
# File 'lib/httpx/resolver/native.rb', line 102

def <<(connection)
  if @nameserver.nil?
    ex = ResolveError.new("No available nameserver")
    ex.set_backtrace(caller)
    connection.force_close
    throw(:resolve_error, ex)
  else
    @connections << connection
    resolve
  end
end

#build_socketUDP, TCP

Returns:



499
500
501
502
503
504
505
506
507
508
509
510
511
512
# File 'lib/httpx/resolver/native.rb', line 499

def build_socket
  ip, port = @nameserver[@ns_index]
  port ||= DNS_PORT

  case @socket_type
  when :udp
    log { "resolver #{FAMILY_TYPES[@record_type]}: server: udp://#{ip}:#{port}..." }
    UDP.new(ip, port, @options)
  when :tcp
    log { "resolver #{FAMILY_TYPES[@record_type]}: server: tcp://#{ip}:#{port}..." }
    origin = URI("tcp://#{ip}:#{port}")
    TCP.new(origin, [Resolver::Entry.new(ip)], @options)
  end
end

#calculate_interests:r, ...

Returns:

  • (:r, :w, nil)


145
146
147
148
149
150
151
152
153
154
155
# File 'lib/httpx/resolver/native.rb', line 145

def calculate_interests
  if @queries.empty?
    return @io.interests if (@socket_type == :tcp) && (@state == :idle)

    return
  end

  return :r if @write_buffer.empty?

  :w
end

#callvoid

This method returns an undefined value.



76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/httpx/resolver/native.rb', line 76

def call
  case @state
  when :idle, :closed
    return if @connections.empty?

    transition(:idle) if @state == :closed
    transition(:open)

    consume if @state == :open
  when :open
    consume
  end
end

#closeObject



49
50
51
# File 'lib/httpx/resolver/native.rb', line 49

def close
  transition(:closed)
end

#close_or_resolvevoid

This method returns an undefined value.



588
589
590
591
592
593
594
595
596
597
# File 'lib/httpx/resolver/native.rb', line 588

def close_or_resolve
  # drop already closed connections
  @connections.shift until @connections.empty? || @connections.first.state != :closed

  if (@connections - @queries.values).empty?
    disconnect
  else
    resolve
  end
end

#closed?Boolean

Returns:

  • (Boolean)


68
69
70
# File 'lib/httpx/resolver/native.rb', line 68

def closed?
  @state == :idle || @state == :closed
end

#consumevoid

This method returns an undefined value.



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/httpx/resolver/native.rb', line 157

def consume
  loop do
    dread if calculate_interests == :r

    break unless calculate_interests == :w

    dwrite

    break unless calculate_interests == :r
  end
rescue Errno::EHOSTUNREACH => e
  @ns_index += 1
  nameserver = @nameserver
  if nameserver && @ns_index < nameserver.size
    log { "resolver #{FAMILY_TYPES[@record_type]}: failed resolving on nameserver #{@nameserver[@ns_index - 1]} (#{e.message})" }
    transition(:idle)
    @timeouts.clear
    retry
  else
    handle_error(e)
    disconnect
  end
rescue NativeResolveError => e
  handle_error(e)
  close_or_resolve
  retry unless closed?
end

#do_retry(h, connection, interval) ⇒ void

This method returns an undefined value.

Parameters:

  • host (String)
  • connection (Connection)
  • interval (interval)


204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/httpx/resolver/native.rb', line 204

def do_retry(h, connection, interval)
  timeouts = @timeouts[h]

  if !timeouts.empty?
    log { "resolver #{FAMILY_TYPES[@record_type]}: timeout after #{interval}s, retry (with #{timeouts.first}s) #{h}..." }
    # must downgrade to tcp AND retry on same host as last
    downgrade_socket
    resolve(connection, h)
  elsif @ns_index + 1 < @nameserver.size
    # try on the next nameserver
    @ns_index += 1
    log do
      "resolver #{FAMILY_TYPES[@record_type]}: failed resolving #{h} on nameserver #{@nameserver[@ns_index - 1]} (timeout error)"
    end
    transition(:idle)
    @timeouts.clear
    resolve(connection, h)
  else
    reset_hostname(h, reset_candidates: false)

    unless @queries.empty?
      resolve(connection)
      return
    end

    @connections.delete(connection)

    host = connection.peer.host

    # This loop_time passed to the exception is bogus. Ideally we would pass the total
    # resolve timeout, including from the previous retries.
    ex = ResolveTimeoutError.new(interval, "Timed out while resolving #{host}")
    ex.set_backtrace(ex ? ex.backtrace : caller)
    emit_resolve_error(connection, host, ex)

    close_or_resolve
  end
end

#downgrade_socketvoid

This method returns an undefined value.



514
515
516
517
518
519
520
# File 'lib/httpx/resolver/native.rb', line 514

def downgrade_socket
  return unless @socket_type == :tcp

  @socket_type = @resolver_options.fetch(:socket_type, :udp)
  transition(:idle)
  transition(:open)
end

#dread(arg0) ⇒ void #dreadvoid

Overloads:

  • #dread(arg0) ⇒ void

    This method returns an undefined value.

    Parameters:

    • arg0 (Integer)
  • #dreadvoid

    This method returns an undefined value.



243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# File 'lib/httpx/resolver/native.rb', line 243

def dread(wsize = @resolver_options[:packet_size])
  loop do
    wsize = @large_packet.capacity if @large_packet

    siz = @io.read(wsize, @read_buffer)

    unless siz
      ex = EOFError.new("descriptor closed")
      ex.set_backtrace(caller)
      raise ex
    end

    return unless siz.positive?

    if @socket_type == :tcp
      # packet may be incomplete, need to keep draining from the socket
      if @large_packet
        # large packet buffer already exists, continue pumping
        @large_packet << @read_buffer

        next unless @large_packet.full?

        parse(@large_packet.to_s)
        @large_packet = nil
        # downgrade to udp again
        downgrade_socket
        return
      else
        size = @read_buffer[0, 2].unpack1("n")
        buffer = @read_buffer.byteslice(2..-1)

        if size > @read_buffer.bytesize
          # only do buffer logic if it's worth it, and the whole packet isn't here already
          @large_packet = Buffer.new(size)
          @large_packet << buffer

          next
        else
          parse(buffer)
        end
      end
    else # udp
      parse(@read_buffer)
    end

    return if @state == :closed || !@write_buffer.empty?
  end
end

#dwritevoid

This method returns an undefined value.



292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
# File 'lib/httpx/resolver/native.rb', line 292

def dwrite
  loop do
    return if @write_buffer.empty?

    siz = @io.write(@write_buffer)

    unless siz
      ex = EOFError.new("descriptor closed")
      ex.set_backtrace(caller)
      raise ex
    end

    return unless siz.positive?

    schedule_retry if @write_buffer.empty?

    return if @state == :closed
  end
end

#force_closeObject



53
54
55
56
57
58
59
60
61
62
# File 'lib/httpx/resolver/native.rb', line 53

def force_close(*)
  @timer.cancel if @timer
  @timer = @name = nil
  @queries.clear
  @timeouts.clear
  close
  super
ensure
  terminate
end

#generate_candidates(name) ⇒ Array[String]

Parameters:

  • (String)

Returns:

  • (Array[String])


485
486
487
488
489
490
491
492
493
494
495
496
497
# File 'lib/httpx/resolver/native.rb', line 485

def generate_candidates(name)
  return [name] if name.end_with?(".")

  name_parts = name.scan(/[^.]+/)
  candidates = @search.map { |domain| [*name_parts, *domain].join(".") }
  fname = "#{name}."
  if @ndots <= name_parts.size - 1
    candidates.unshift(fname)
  else
    candidates << fname
  end
  candidates
end

#handle_error(error) ⇒ Object



130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/httpx/resolver/native.rb', line 130

def handle_error(error)
  if error.respond_to?(:connection) &&
     error.respond_to?(:host)
    reset_hostname(error.host, connection: error.connection)
  else
    @queries.each do |host, connection|
      reset_hostname(host, connection: connection)
    end
  end

  super
end

#handle_socket_timeout(interval) ⇒ void

This method returns an undefined value.

Parameters:

  • interval (interval)


128
# File 'lib/httpx/resolver/native.rb', line 128

def handle_socket_timeout(interval); end

#interests:r, ...

Returns:

  • (:r, :w, nil)


90
91
92
93
94
95
96
97
98
99
100
# File 'lib/httpx/resolver/native.rb', line 90

def interests
  case @state
  when :idle
    transition(:open)
  when :closed
    transition(:idle)
    transition(:open)
  end

  calculate_interests
end

#on_io_errorvoid

This method returns an undefined value.

Parameters:

  • error (IOError)


40
# File 'sig/resolver/native.rbs', line 40

def on_io_error: (IOError error) -> void

#parse(buffer) ⇒ void

This method returns an undefined value.

Parameters:

  • (String)


312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
# File 'lib/httpx/resolver/native.rb', line 312

def parse(buffer)
  code, result = Resolver.decode_dns_answer(buffer)

  case code
  when :ok
    reset_query
    parse_addresses(result)
  when :no_domain_found
    reset_query
    # Indicates no such domain was found.
    hostname, connection = @queries.first
    reset_hostname(hostname, reset_candidates: false)

    other_candidate, _ = @queries.find { |_, conn| conn == connection }

    if other_candidate
      resolve(connection, other_candidate)
    else
      @connections.delete(connection)
      ex = NativeResolveError.new(connection, connection.peer.host, "name or service not known")
      ex.set_backtrace(ex ? ex.backtrace : caller)
      emit_resolve_error(connection, connection.peer.host, ex)
      close_or_resolve
    end
  when :message_truncated
    reset_query
    # TODO: what to do if it's already tcp??
    return if @socket_type == :tcp

    @socket_type = :tcp

    hostname, _ = @queries.first
    reset_hostname(hostname)
    transition(:closed)
  when :retriable_error
    if @name && @timer
      log { "resolver #{FAMILY_TYPES[@record_type]}: failed, but will retry..." }
      return
    end
    # retry now!
    # connection = @queries[@name].shift
    # @timer.fire
    reset_query
    hostname, connection = @queries.first
    reset_hostname(hostname)
    @connections.delete(connection)
    ex = NativeResolveError.new(connection, connection.peer.host, "unknown DNS error (error code #{result})")
    raise ex
  when :dns_error
    reset_query
    hostname, connection = @queries.first
    reset_hostname(hostname)
    @connections.delete(connection)
    ex = NativeResolveError.new(connection, connection.peer.host, "unknown DNS error (error code #{result})")
    raise ex
  when :decode_error
    reset_query
    hostname, connection = @queries.first
    reset_hostname(hostname)
    @connections.delete(connection)
    ex = NativeResolveError.new(connection, connection.peer.host, result.message)
    ex.set_backtrace(result.backtrace)
    raise ex
  end
end

#reset_hostname(hostname, connection: @queries.delete(hostname), reset_candidates: true) ⇒ void

This method returns an undefined value.

Parameters:

  • hostname (String)
  • connection: (Connection) (defaults to: @queries.delete(hostname))
  • reset_candidates: (Boolean) (defaults to: true)


576
577
578
579
580
581
582
583
584
585
586
# File 'lib/httpx/resolver/native.rb', line 576

def reset_hostname(hostname, connection: @queries.delete(hostname), reset_candidates: true)
  @timeouts.delete(hostname)

  return unless connection && reset_candidates

  # eliminate other candidates
  candidates = @queries.select { |_, conn| connection == conn }.keys
  @queries.delete_if { |h, _| candidates.include?(h) }
  # reset timeouts
  @timeouts.delete_if { |h, _| candidates.include?(h) }
end

#reset_queryvoid

This method returns an undefined value.



570
571
572
573
574
# File 'lib/httpx/resolver/native.rb', line 570

def reset_query
  @timer.cancel

  @timer = @name = nil
end

#schedule_retryvoid

This method returns an undefined value.



185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/httpx/resolver/native.rb', line 185

def schedule_retry
  h = @name

  return unless h

  connection = @queries[h]

  timeouts = @timeouts[h]
  timeout = timeouts.shift

  @timer = @current_selector.after(timeout) do
    next unless @connections.include?(connection)

    @timer = @name = nil

    do_retry(h, connection, timeout)
  end
end

#terminateObject



64
65
66
# File 'lib/httpx/resolver/native.rb', line 64

def terminate
  disconnect
end

#timeoutinterval?

Returns:

  • (interval, nil)


114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/httpx/resolver/native.rb', line 114

def timeout
  return unless @name

  @start_timeout = Utils.now

  timeouts = @timeouts[@name]

  return if timeouts.empty?

  log(level: 2) { "resolver #{FAMILY_TYPES[@record_type]}: next timeout #{timeouts.first} secs... (#{timeouts.size - 1} left)" }

  timeouts.first
end

#to_ioObject



72
73
74
# File 'lib/httpx/resolver/native.rb', line 72

def to_io
  @io.to_io
end

#transition(nextstate) ⇒ void

This method returns an undefined value.

moves the resolver state machine to the nextstate state (if all conditions are met)-

Parameters:

  • nextstate (Symbol)


523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
# File 'lib/httpx/resolver/native.rb', line 523

def transition(nextstate)
  case nextstate
  when :idle
    if (io = @io)
      @io = nil
      io.close

      # @fiber-switch-guard
      return if @io
    end
  when :open
    return unless @state == :idle

    @io ||= build_socket

    @io.connect
    return unless @io.connected?

    resolve if @queries.empty? && !@connections.empty?
  when :closed
    return if @state == :closed

    if (io = @io)
      @io = nil
      io.close

      # @fiber-switch-guard
      return if @io
    end

    @start_timeout = nil
    @write_buffer.clear
    @read_buffer.clear
  end
  log(level: 3) { "#{@state} -> #{nextstate}" }
  @state = nextstate
rescue Errno::ECONNREFUSED,
       Errno::EADDRNOTAVAIL,
       Errno::EHOSTUNREACH,
       SocketError,
       IOError,
       ConnectTimeoutError => e
  # these errors may happen during TCP handshake
  # treat them as resolve errors.
  on_error(e)
end