Class: VagrantAutoDNS::Cap::RedirectDNS

Inherits:
Object
  • Object
show all
Extended by:
Common
Defined in:
lib/vagrant-autodns/cap/redirect_dns.rb

Constant Summary collapse

PRIVATE_IP =
/^(192\.168|10\.|169\.254|172\.(1[6-9]|2\d|3[0-1]))/

Class Method Summary collapse

Methods included from Common

iptables_location, run_command

Class Method Details

.redirect_dns(machine) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/vagrant-autodns/cap/redirect_dns.rb', line 17

def self.redirect_dns(machine)
  #Get guest nameserver
  get_nameserver = [
    'grep nameserver /etc/resolv.conf',
    "awk '{print $2}'",
    'head -n1'
  ].join(' | ')
  nameserver = run_command(machine, get_nameserver)

  #Default to use resolvconf if installed
  update_search_domain = if !run_command(machine, 'command -v resolvconf').empty?
    [
      'echo "search $(hostname -d)" >> /etc/resolvconf/resolv.conf.d/base',
      'resolvconf -u'
    ].join(' && ')
  #Else check if dhclient is installed and try that
  elsif !run_command(machine, 'command -v dhclient').empty?
    #Find dhclient.conf location, consider doing this more intelligently
    dhclient_conf_loc = [
      '/etc/dhclient.conf',
      '/etc/dhcp/dhclient.conf',
      '/etc/dhcp3/dhclient.conf',
      #Dump to /dev/null if no conf can be found
      '/dev/null'
    ].map{|v| "ls #{v} 2>/dev/null"}.join(' || ')

    [
      "dhclient_conf_loc=$( #{dhclient_conf_loc} )",
      #Use dhclient to persist changes across reboots
      'echo "prepend domain-search $(hostname -d);" >> $dhclient_conf_loc',
      'sed "s/^search \(.*\)/search $(hostname -d) \1/" /etc/resolv.conf > /tmp/resolv.conf',
      'mv -f /tmp/resolv.conf /etc/resolv.conf'
    ].join(' && ')
  #Else overwrite resolv.conf directly
  else
    [
      'sed "s/^search \(.*\)/search $(hostname -d) \1/" /etc/resolv.conf > /tmp/resolv.conf',
      'mv -f /tmp/resolv.conf /etc/resolv.conf'
    ].join(' && ')
  end
  run_command(machine, update_search_domain)

  #Iptables redirect
  if nameserver =~ PRIVATE_IP
    daemon_port = Daemon.listen_port
    iptables_options_udp = [
      '-t nat', #Type nat
      '-A OUTPUT', #Append to output chain
      '-p udp', #Protocol udp (required to use dport)
      "-d #{nameserver}", #Destination ip
      '--dport 53', #Destination port
      '-j DNAT', #Target DNAT
      "--to-destination #{nameserver}:#{daemon_port}" #New destination
    ].join(' ')
    iptables_options_tcp = iptables_options_udp.gsub('-p udp', '-p tcp')
    run_command(machine, "#{iptables_location(machine)} #{iptables_options_udp}")
    run_command(machine, "#{iptables_location(machine)} #{iptables_options_tcp}")
  end
end