ltouroumov

RubyDNS Server

Jun 17th, 2011
78
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. require 'rubygems'
  2.  
  3. require 'rexec'
  4. require 'rexec/daemon'
  5.  
  6. require 'rubydns'
  7.  
  8. require 'timeout'
  9.  
  10. RUN_AS="daemon"
  11.  
  12. # Cache DNS entries for 5 minutes
  13. CACHE_TIME=60*5
  14.  
  15. # We need to be root in order to bind to privileged port
  16. if RExec.current_user != "root"
  17.     $stderr.puts "Sorry, this command needs to be run as root!"
  18.     exit 1
  19. end
  20.  
  21. # Helper
  22. Name = Resolv::DNS::Name
  23.  
  24. Google = '8.8.8.8'
  25. Servers = {
  26.     :php => '192.168.10.1',
  27.     :ror => '192.168.10.2',
  28.     :sql => '192.168.10.3',
  29.     # ...
  30. }
  31.  
  32. # The Daemon itself
  33. class Server < RExec::Daemon::Base
  34.     @@var_directory = File.dirname(__FILE__)
  35.  
  36.     def self.run
  37.         # Don't buffer output (for debug purposes)
  38.         $stderr.sync = true
  39.        
  40.         # Use upstream DNS for name resolution
  41.         $R = Resolv::DNS.new(:nameserver => Google)
  42.  
  43.         $CACHE = {}
  44.  
  45.         # Start the RubyDNS server
  46.         RubyDNS::run_server do
  47.             on(:start) do
  48.                 RExec.change_user(RUN_AS)
  49.             end
  50.            
  51.             Servers.each do |name, addr|
  52.               match(/(.+).#{name.to_s}.dev$/, :A) do |match, transaction|
  53.                   transaction.respond!(addr)
  54.               end
  55.             end
  56.  
  57.             # Default DNS handler
  58.             otherwise do |transaction|
  59.                 transaction.passthrough!($R)
  60.             end
  61.         end
  62.     end
  63. end
  64.  
  65. # RExec daemon runner
  66. Server.daemonize
RAW Paste Data