async-dns 1.2.6 → 1.4.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,115 +1,138 @@
1
- # Copyright, 2012, by Samuel G. D. Williams. <http://www.codeotaku.com>
2
- #
3
- # Permission is hereby granted, free of charge, to any person obtaining a copy
4
- # of this software and associated documentation files (the "Software"), to deal
5
- # in the Software without restriction, including without limitation the rights
6
- # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
- # copies of the Software, and to permit persons to whom the Software is
8
- # furnished to do so, subject to the following conditions:
9
- #
10
- # The above copyright notice and this permission notice shall be included in
11
- # all copies or substantial portions of the Software.
12
- #
13
- # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
- # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
- # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
- # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
- # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
- # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19
- # THE SOFTWARE.
1
+ # frozen_string_literal: true
20
2
 
21
- require_relative 'handler'
3
+ # Released under the MIT License.
4
+ # Copyright, 2015-2024, by Samuel Williams.
5
+ # Copyright, 2017, by Olle Jonsson.
6
+ # Copyright, 2024, by Sean Dilda.
22
7
 
23
- require 'securerandom'
24
- require 'async'
8
+ require_relative "handler"
9
+ require_relative "system"
10
+ require_relative "cache"
11
+
12
+ require "securerandom"
13
+ require "async"
14
+
15
+ require "io/endpoint/composite_endpoint"
16
+ require "io/endpoint/host_endpoint"
25
17
 
26
18
  module Async::DNS
19
+ # Represents a DNS connection which we don't know how to use.
27
20
  class InvalidProtocolError < StandardError
28
21
  end
29
22
 
30
- class InvalidResponseError < StandardError
31
- end
32
-
23
+ # Represents a failure to resolve a given name to an address.
33
24
  class ResolutionFailure < StandardError
34
25
  end
35
26
 
27
+ # Resolve names to addresses using the DNS protocol.
36
28
  class Resolver
37
- # Wait for up to 5 seconds for a response. Override with `options[:timeout]`
38
- DEFAULT_TIMEOUT = 5.0
39
-
40
- # 10ms wait between making requests. Override with `options[:delay]`
41
- DEFAULT_DELAY = 0.01
42
-
43
- # Try a given request 10 times before failing. Override with `options[:retries]`.
44
- DEFAULT_RETRIES = 10
29
+ # The default resolver for the system.
30
+ def self.default(**options)
31
+ System.resolver(**options)
32
+ end
45
33
 
46
34
  # Servers are specified in the same manor as options[:listen], e.g.
47
35
  # [:tcp/:udp, address, port]
48
36
  # In the case of multiple servers, they will be checked in sequence.
49
- def initialize(endpoints, origin: nil, logger: Console.logger, timeout: DEFAULT_TIMEOUT)
50
- @endpoints = endpoints
37
+ def initialize(endpoint, ndots: 1, search: nil, origin: nil, cache: Cache.new, **options)
38
+ @endpoint = endpoint
39
+
40
+ @ndots = ndots
41
+ if search
42
+ @search = search
43
+ else
44
+ @search = [nil]
45
+ end
46
+
47
+ if origin
48
+ @search = [origin] + @search
49
+ end
51
50
 
52
- @origin = origin
53
- @logger = logger
54
- @timeout = timeout
51
+ @cache = cache
52
+ @options = options
55
53
  end
56
54
 
57
- attr_accessor :origin
55
+ # The search domains, which are used to generate fully qualified names if required.
56
+ attr :search
58
57
 
59
- def fully_qualified_name(name)
60
- # If we are passed an existing deconstructed name:
61
- if Resolv::DNS::Name === name
62
- if name.absolute?
63
- return name
64
- else
65
- return name.with_origin(@origin)
66
- end
67
- end
58
+ # Generates a fully qualified name from a given name.
59
+ #
60
+ # @parameter name [String | Resolv::DNS::Name] The name to fully qualify.
61
+ def fully_qualified_names(name)
62
+ return to_enum(:fully_qualified_names, name) unless block_given?
63
+
64
+ name = Resolv::DNS::Name.create(name)
68
65
 
69
- # ..else if we have a string, we need to do some basic processing:
70
- if name.end_with? '.'
71
- return Resolv::DNS::Name.create(name)
66
+ if name.absolute?
67
+ yield name
72
68
  else
73
- return Resolv::DNS::Name.create(name).with_origin(@origin)
69
+ if @ndots <= name.length - 1
70
+ yield name
71
+ end
72
+
73
+ @search.each do |domain|
74
+ yield name.with_origin(domain)
75
+ end
74
76
  end
75
77
  end
76
-
78
+
77
79
  # Provides the next sequence identification number which is used to keep track of DNS messages.
78
80
  def next_id!
79
81
  # Using sequential numbers for the query ID is generally a bad thing because over UDP they can be spoofed. 16-bits isn't hard to guess either, but over UDP we also use a random port, so this makes effectively 32-bits of entropy to guess per request.
80
82
  SecureRandom.random_number(2**16)
81
83
  end
82
-
83
- # Look up a named resource of the given resource_class.
84
+
85
+ # Query a named resource and return the response.
86
+ #
87
+ # Bypasses the cache and always makes a new request.
88
+ #
89
+ # @returns [Resolv::DNS::Message] The response from the server.
84
90
  def query(name, resource_class = Resolv::DNS::Resource::IN::A)
85
- message = Resolv::DNS::Message.new(next_id!)
86
- message.rd = 1
87
- message.add_question fully_qualified_name(name), resource_class
91
+ response = nil
88
92
 
89
- dispatch_request(message)
93
+ self.fully_qualified_names(name) do |fully_qualified_name|
94
+ response = self.dispatch_query(fully_qualified_name, resource_class)
95
+
96
+ break if response.rcode == Resolv::DNS::RCode::NoError
97
+ end
98
+
99
+ return response
90
100
  end
91
101
 
92
- # Yields a list of `Resolv::IPv4` and `Resolv::IPv6` addresses for the given `name` and `resource_class`. Raises a ResolutionFailure if no severs respond.
93
- def addresses_for(name, resource_class = Resolv::DNS::Resource::IN::A, options = {})
94
- name = fully_qualified_name(name)
95
-
96
- cache = options.fetch(:cache, {})
97
- retries = options.fetch(:retries, DEFAULT_RETRIES)
98
- delay = options.fetch(:delay, DEFAULT_DELAY)
102
+ # Look up a named resource of the given resource_class.
103
+ def records_for(name, resource_classes)
104
+ Console.debug(self) {"Looking up records for #{name.inspect} with #{resource_classes.inspect}."}
105
+ resource_classes = Array(resource_classes)
106
+ resources = nil
99
107
 
100
- records = lookup(name, resource_class, cache) do |lookup_name, lookup_resource_class|
101
- response = nil
102
-
103
- retries.times do |i|
104
- # Wait 10ms before trying again:
105
- sleep delay if delay and i > 0
106
-
107
- response = query(lookup_name, lookup_resource_class)
108
-
109
- break if response
108
+ self.fully_qualified_names(name) do |fully_qualified_name|
109
+ resources = @cache.fetch(fully_qualified_name, resource_classes) do |name, resource_class|
110
+ if response = self.dispatch_query(name, resource_class)
111
+ response.answer.each do |name, ttl, record|
112
+ Console.debug(self) {"Caching record for #{name.inspect} with #{record.class} and TTL #{ttl}."}
113
+ @cache.store(name, resource_class, record)
114
+ end
115
+ end
110
116
  end
111
117
 
112
- response or raise ResolutionFailure.new("Could not resolve #{name} after #{retries} attempt(s).")
118
+ break if resources.any?
119
+ end
120
+
121
+ return resources
122
+ end
123
+
124
+ if System.ipv6?
125
+ ADDRESS_RESOURCE_CLASSES = [Resolv::DNS::Resource::IN::A, Resolv::DNS::Resource::IN::AAAA]
126
+ else
127
+ ADDRESS_RESOURCE_CLASSES = [Resolv::DNS::Resource::IN::A]
128
+ end
129
+
130
+ # Yields a list of `Resolv::IPv4` and `Resolv::IPv6` addresses for the given `name` and `resource_class`. Raises a ResolutionFailure if no severs respond.
131
+ def addresses_for(name, resource_classes = ADDRESS_RESOURCE_CLASSES)
132
+ records = self.records_for(name, resource_classes)
133
+
134
+ if records.empty?
135
+ raise ResolutionFailure.new("Could not find any records for #{name.inspect}!")
113
136
  end
114
137
 
115
138
  addresses = []
@@ -119,74 +142,60 @@ module Async::DNS
119
142
  if record.respond_to? :address
120
143
  addresses << record.address
121
144
  else
122
- # The most common case here is that record.class is IN::CNAME and we need to figure out the address. Usually the upstream DNS server would have replied with this too, and this will be loaded from the response if possible without requesting additional information.
123
- addresses += addresses_for(record.name, record.class, options.merge(cache: cache))
145
+ # The most common case here is that record.class is IN::CNAME and we need to figure out the address. Usually the upstream DNS server would have replied with this too, and this will be loaded from the response if possible without requesting additional information:
146
+ addresses += addresses_for(record.name, resource_classes)
124
147
  end
125
148
  end
126
149
  end
127
150
 
128
- if addresses.size > 0
129
- return addresses
130
- else
131
- raise ResolutionFailure.new("Could not find any addresses for #{name}.")
151
+ if addresses.empty?
152
+ raise ResolutionFailure.new("Could not find any addresses for #{name.inspect}!")
132
153
  end
154
+
155
+ return addresses
156
+ end
157
+
158
+ private
159
+
160
+ # In general, DNS servers are only able to handle a single question at a time. This method is used to dispatch a single query to the server and wait for a response.
161
+ def dispatch_query(name, resource_class)
162
+ message = Resolv::DNS::Message.new(self.next_id!)
163
+ message.rd = 1
164
+
165
+ message.add_question(name, resource_class)
166
+
167
+ return dispatch_request(message)
133
168
  end
134
169
 
135
170
  # Send the message to available servers. If no servers respond correctly, nil is returned. This result indicates a failure of the resolver to correctly contact any server and get a valid response.
136
- def dispatch_request(message, task: Async::Task.current)
137
- request = Request.new(message, @endpoints)
171
+ def dispatch_request(message)
172
+ request = Request.new(message, @endpoint)
173
+ error = nil
138
174
 
139
175
  request.each do |endpoint|
140
- @logger.debug "[#{message.id}] Sending request #{message.question.inspect} to address #{endpoint.inspect}" if @logger
176
+ Console.debug "[#{message.id}] Sending request #{message.question.inspect} to address #{endpoint.inspect}"
141
177
 
142
178
  begin
143
- response = nil
144
-
145
- task.with_timeout(@timeout) do
146
- @logger.debug "[#{message.id}] -> Try address #{endpoint}" if @logger
147
- response = try_server(request, endpoint)
148
- @logger.debug "[#{message.id}] <- Try address #{endpoint} = #{response}" if @logger
149
- end
179
+ response = try_server(request, endpoint)
150
180
 
151
181
  if valid_response(message, response)
152
182
  return response
153
183
  end
154
- rescue Async::TimeoutError
155
- @logger.debug "[#{message.id}] Request timed out!" if @logger
156
- rescue InvalidResponseError
157
- @logger.warn "[#{message.id}] Invalid response from network: #{$!}!" if @logger
158
- rescue DecodeError
159
- @logger.warn "[#{message.id}] Error while decoding data from network: #{$!}!" if @logger
160
- rescue IOError, Errno::ECONNRESET
161
- @logger.warn "[#{message.id}] Error while reading from network: #{$!}!" if @logger
162
- rescue EOFError
163
- @logger.warn "[#{message.id}] Could not read complete response from network: #{$!}" if @logger
184
+ rescue => error
185
+ # Try the next server.
164
186
  end
165
187
  end
166
188
 
167
- return nil
168
- end
169
-
170
- private
171
-
172
- # Lookup a name/resource_class record but use the records cache if possible reather than making a new request if possible.
173
- def lookup(name, resource_class = Resolv::DNS::Resource::IN::A, records = {})
174
- records.fetch(name) do
175
- response = yield(name, resource_class)
176
-
177
- if response
178
- response.answer.each do |name_in_answer, ttl, record|
179
- (records[name_in_answer] ||= []) << record
180
- end
181
- end
182
-
183
- records[name]
189
+ if error
190
+ raise error
184
191
  end
192
+
193
+ return nil
185
194
  end
186
195
 
187
196
  def try_server(request, endpoint)
188
197
  endpoint.connect do |socket|
189
- case socket.type
198
+ case socket.local_address.socktype
190
199
  when Socket::SOCK_DGRAM
191
200
  try_datagram_server(request, socket)
192
201
  when Socket::SOCK_STREAM
@@ -199,11 +208,11 @@ module Async::DNS
199
208
 
200
209
  def valid_response(message, response)
201
210
  if response.tc != 0
202
- @logger.warn "[#{message.id}] Received truncated response!" if @logger
211
+ Console.warn "Received truncated response!", message_id: message.id
203
212
  elsif response.id != message.id
204
- @logger.warn "[#{message.id}] Received response with incorrect message id: #{response.id}!" if @logger
213
+ Console.warn "Received response with incorrect message id: #{response.id}!", message_id: message.id
205
214
  else
206
- @logger.debug "[#{message.id}] Received valid response with #{response.answer.size} answer(s)." if @logger
215
+ Console.debug "Received valid response with #{response.answer.size} answer(s).", message_id: message.id
207
216
 
208
217
  return true
209
218
  end
@@ -214,9 +223,9 @@ module Async::DNS
214
223
  def try_datagram_server(request, socket)
215
224
  socket.sendmsg(request.packet, 0)
216
225
 
217
- data, peer = socket.recvmsg(UDP_TRUNCATION_SIZE)
226
+ data, peer = socket.recvfrom(UDP_MAXIMUM_SIZE)
218
227
 
219
- return Async::DNS::decode_message(data)
228
+ return ::Resolv::DNS::Message.decode(data)
220
229
  end
221
230
 
222
231
  def try_stream_server(request, socket)
@@ -224,31 +233,34 @@ module Async::DNS
224
233
 
225
234
  transport.write_chunk(request.packet)
226
235
 
227
- input_data = transport.read_chunk
236
+ data = transport.read_chunk
228
237
 
229
- return Async::DNS::decode_message(input_data)
238
+ return ::Resolv::DNS::Message.decode(data)
230
239
  end
231
240
 
232
241
  # Manages a single DNS question message across one or more servers.
233
242
  class Request
234
- def initialize(message, endpoints)
243
+ # Create a new request for the given message and endpoint.
244
+ #
245
+ # Encodes the message and stores it for later use.
246
+ #
247
+ # @parameter message [Resolv::DNS::Message] The message to send.
248
+ # @parameter endpoint [IO::Endpoint::Generic] The endpoint to send the message to.
249
+ def initialize(message, endpoint)
235
250
  @message = message
236
251
  @packet = message.encode
237
252
 
238
- @endpoints = endpoints.dup
239
-
240
- # We select the protocol based on the size of the data:
241
- if @packet.bytesize > UDP_TRUNCATION_SIZE
242
- @endpoints.delete_if{|server| server[0] == :udp}
243
- end
253
+ @endpoint = endpoint
244
254
  end
245
255
 
256
+ # @attribute [Resolv::DNS::Message] The message to send.
246
257
  attr :message
258
+
259
+ # @attribute [String] The encoded message to send.
247
260
  attr :packet
248
- attr :logger
249
261
 
250
262
  def each(&block)
251
- Async::IO::Endpoint.each(@endpoints, &block)
263
+ @endpoint.each(&block)
252
264
  end
253
265
 
254
266
  def update_id!(id)
@@ -256,5 +268,7 @@ module Async::DNS
256
268
  @packet = @message.encode
257
269
  end
258
270
  end
271
+
272
+ private_constant :Request
259
273
  end
260
274
  end
@@ -1,59 +1,60 @@
1
- # Copyright, 2009, 2012, by Samuel G. D. Williams. <http://www.codeotaku.com>
2
- #
3
- # Permission is hereby granted, free of charge, to any person obtaining a copy
4
- # of this software and associated documentation files (the "Software"), to deal
5
- # in the Software without restriction, including without limitation the rights
6
- # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
- # copies of the Software, and to permit persons to whom the Software is
8
- # furnished to do so, subject to the following conditions:
9
- #
10
- # The above copyright notice and this permission notice shall be included in
11
- # all copies or substantial portions of the Software.
12
- #
13
- # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
- # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
- # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
- # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
- # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
- # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19
- # THE SOFTWARE.
1
+ # frozen_string_literal: true
20
2
 
21
- require 'async'
22
- require 'async/io'
3
+ # Released under the MIT License.
4
+ # Copyright, 2012-2014, by Tony Arcieri.
5
+ # Copyright, 2013, by Greg Thornton.
6
+ # Copyright, 2014, by Hendrik Beskow.
7
+ # Copyright, 2015-2025, by Samuel Williams.
8
+ # Copyright, 2023, by Hal Brodigan.
23
9
 
24
- require_relative 'transaction'
10
+ require "async"
11
+
12
+ require "io/endpoint/composite_endpoint"
13
+ require "io/endpoint/host_endpoint"
14
+
15
+ require_relative "transaction"
16
+ require_relative "handler"
25
17
 
26
18
  module Async::DNS
19
+ # A DNS server which can be used to resolve queries.
27
20
  class Server
28
- # The default server interfaces
29
- DEFAULT_ENDPOINTS = [[:udp, "0.0.0.0", 53], [:tcp, "0.0.0.0", 53]]
30
-
31
- # Instantiate a server with a block
21
+ # The default endpoint to listen on.
32
22
  #
33
- # server = Server.new do
34
- # match(/server.mydomain.com/, IN::A) do |transaction|
35
- # transaction.respond!("1.2.3.4")
36
- # end
37
- # end
23
+ # @parameter port [Integer] The port to listen on, defaults to 53.
24
+ def self.default_endpoint(port = 53)
25
+ ::IO::Endpoint.composite(
26
+ ::IO::Endpoint.udp("localhost", port),
27
+ ::IO::Endpoint.tcp("localhost", port)
28
+ )
29
+ end
30
+
31
+ # Instantiate a server with a block.
38
32
  #
39
- def initialize(endpoints = DEFAULT_ENDPOINTS, origin: '.', logger: Console.logger)
40
- @endpoints = endpoints
33
+ # @param endpoints [Array<(Symbol, String, Integer)>] The endpoints to listen on.
34
+ # @param origin [String] The default origin to resolve domains within.
35
+ # @param logger [Console::Logger] The logger to use.
36
+ def initialize(endpoint = self.class.default_endpoint, origin: ".")
37
+ @endpoint = endpoint
41
38
  @origin = origin
42
- @logger = logger
43
39
  end
44
-
45
- # Records are relative to this origin:
40
+
41
+ # Records are relative to this origin.
42
+ #
43
+ # @return [String]
46
44
  attr_accessor :origin
47
-
48
- attr_accessor :logger
49
-
50
- # Fire the named event as part of running the server.
51
- def fire(event_name)
45
+
46
+ # @deprecated Use {Console} instead.
47
+ def logger
48
+ Console
52
49
  end
53
50
 
54
51
  # Give a name and a record type, try to match a rule and use it for processing the given arguments.
52
+ #
53
+ # @param name [String] The resource name.
54
+ # @param resource_class [Class<Resolv::DNS::Resource>] The requested resource class.
55
+ # @param transaction [Transaction] The transaction object.
55
56
  def process(name, resource_class, transaction)
56
- raise NotImplementedError.new
57
+ transaction.fail!(:NXDomain)
57
58
  end
58
59
 
59
60
  # Process an incoming DNS message. Returns a serialized message to be sent back to the client.
@@ -76,55 +77,47 @@ module Async::DNS
76
77
  begin
77
78
  question = question.without_origin(@origin)
78
79
 
79
- @logger.debug(query) {"Processing question #{question} #{resource_class}..."}
80
+ Console.debug(query) {"Processing question #{question} #{resource_class}..."}
80
81
 
81
- transaction = Transaction.new(self, query, question, resource_class, response, options)
82
+ transaction = Transaction.new(self, query, question, resource_class, response, **options)
82
83
 
83
84
  transaction.process
84
- rescue Resolv::DNS::OriginError
85
+ rescue Resolv::DNS::OriginError => error
85
86
  # This is triggered if the question is not part of the specified @origin:
86
- @logger.debug(query) {"Skipping question #{question} #{resource_class} because #{$!}"}
87
+ Console.error(self, "Failed to process question #{question} #{resource_class}!", error: error)
87
88
  end
88
89
  end
89
90
  rescue StandardError => error
90
- @logger.error(query) {error}
91
+ Console.error(query) {error}
91
92
 
92
93
  response.rcode = Resolv::DNS::RCode::ServFail
93
94
  end
94
95
 
95
96
  end_time = Time.now
96
- @logger.debug(query) {"Time to process request: #{end_time - start_time}s"}
97
+ Console.debug(query) {"Time to process request: #{end_time - start_time}s"}
97
98
 
98
99
  return response
99
100
  end
100
101
 
101
102
  # Setup all specified interfaces and begin accepting incoming connections.
102
- def run(*args)
103
- @logger.info "Starting Async::DNS server (v#{Async::DNS::VERSION})..."
103
+ def run
104
+ Console.info "Starting Async::DNS server (v#{Async::DNS::VERSION})..."
104
105
 
105
- Async::Reactor.run do |task|
106
- fire(:setup)
106
+ Async do |task|
107
+ wrapper = @endpoint.wrapper
107
108
 
108
- Async::IO::Endpoint.each(@endpoints) do |endpoint|
109
- task.async do
110
- endpoint.bind do |socket|
111
- case socket.type
112
- when Socket::SOCK_DGRAM
113
- @logger.info "<> Listening for datagrams on #{socket.local_address.inspect}"
114
- DatagramHandler.new(self, socket).run
115
- when Socket::SOCK_STREAM
116
- @logger.info "<> Listening for connections on #{socket.local_address.inspect}"
117
- StreamHandler.new(self, socket).run
118
- else
119
- raise ArgumentError.new("Don't know how to handle #{address}")
120
- end
121
- end
109
+ @endpoint.bind do |server|
110
+ Console.info "<> Listening for connections on #{server.local_address.inspect}"
111
+ case server.local_address.socktype
112
+ when Socket::SOCK_DGRAM
113
+ DatagramHandler.new(self, server).run(wrapper)
114
+ when Socket::SOCK_STREAM
115
+ StreamHandler.new(self, server).run(wrapper)
116
+ else
117
+ raise ArgumentError.new("Don't know how to handle #{server}")
122
118
  end
123
119
  end
124
-
125
- fire(:start)
126
120
  end
127
121
  end
128
-
129
122
  end
130
123
  end