Class: Masquito::DNS

Inherits:
Object
  • Object
show all
Defined in:
lib/masquito/dns.rb

Constant Summary collapse

ADDRESS =
'127.0.0.1'
PORT =
53532
@@resource =
{
  'A' => Resolv::DNS::Resource::IN::A.new(ADDRESS),
  'AAAA' => Resolv::DNS::Resource::IN::AAAA.new('::1')
}
@@ttl =

3 hours

10800

Instance Method Summary collapse

Constructor Details

#initialize(addr = ADDRESS, port = PORT, config_path = CONFIG_PATH) ⇒ DNS

Returns a new instance of DNS.



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/masquito/dns.rb', line 15

def initialize(addr = ADDRESS, port = PORT, config_path = CONFIG_PATH)
  puts "Starting Masquito on #{addr}:#{port}"
  @settings = Settings.new(config_path)

  # Bind port to receive requests
  socket = UDPSocket.new
  socket.bind(addr, port)

  loop do
    # Receive and parse query
    data, sender_addrinfo = socket.recvfrom(512)

    Thread.new(data, sender_addrinfo) do |data, sender_addrinfo|
      sender_port, sender_ip = sender_addrinfo[1], sender_addrinfo[2]
      query = Resolv::DNS::Message.decode(data)
      answer = setup_answer(query)
      socket.send(answer.encode, 0, sender_ip, sender_port) # Send the response
    end
  end
end

Instance Method Details

#each_question(query, answer) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/masquito/dns.rb', line 49

def each_question(query, answer)
  query.each_question do |name, typeclass|
    type = typeclass.name.split('::').last
    if type == 'A' || type == 'AAAA'                      # We need only A and AAAA records
      if @settings.include?(name)
        answer.add_answer(name, @@ttl, @@resource[type])  # Setup answer to this name
        answer.encode                                     # Don't forget encode it
      end
    end
  end
  answer
end

#setup_answer(query) ⇒ Object

Setup answer



37
38
39
40
41
42
43
44
45
46
47
# File 'lib/masquito/dns.rb', line 37

def setup_answer(query)
  # Standard fields
  answer = Resolv::DNS::Message.new(query.id)
  answer.qr = 1                 # 0 = Query, 1 = Response
  answer.opcode = query.opcode  # Type of Query; copy from query
  answer.aa = 1                 # Is this an authoritative response: 0 = No, 1 = Yes
  answer.rd = query.rd          # Is Recursion Desired, copied from query
  answer.ra = 0                 # Does name server support recursion: 0 = No, 1 = Yes
  answer.rcode = 0              # Response code: 0 = No errors
  each_question(query, answer)  # There may be multiple questions per query
end