-
Notifications
You must be signed in to change notification settings - Fork 9
/
jsondnsd.rb
206 lines (172 loc) · 5.8 KB
/
jsondnsd.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
# encoding: UTF-8
# A DNS server that services requests by asking an HTTP server for the answer.
print <<DANGER # USE WEBDNS INSTEAD
This code was a proof of concept. It works, but is VERY UNSTABLE.
If you want a solid DNS server that proxies request to an HTTP server. Use "webdns" instead!
http://github.com/progrium/webdns
DANGER
exit
require 'rubygems'
require 'logging'
require 'eventmachine'
require 'dnsruby'
require 'open-uri'
require 'yajl'
require 'pp'
include Dnsruby
$LOAD_PATH.push(File.dirname(__FILE__))
require 'lib/hash-to-dnsruby'
require 'lib/simplecache'
require 'lib/dnsruby-jsonquery'
require 'lib/dnsruby-valid'
# daemonize changes the directory to "/"
Dir.chdir(File.dirname(__FILE__))
# CONFIG = YAML.load_file('config.yml')
CONFIG = {
:bind_address => '127.0.0.1',
:bind_port => 1053,
:log_level => :debug,
:log_file => 'errors'
}
logfile = File.new(CONFIG[:log_file], 'a') # Always append
$logger = Logging.logger(logfile)
$logger.level = CONFIG[:log_level]
class DnsrubyError
def initialize(message = Message.new)
@message = message
@message.header.qr = true
end
def format_error
rv = @message
rv.header.rcode = 'FORMERR'
rv.encode
end
def server_failure
rv = @message
rv.header.rcode = 'SERVFAIL'
rv.encode
end
end
class JsonDns < EventMachine::Connection
attr_accessor :host, :port
def initialize
$logger.debug "Started"
@cache = SimpleCache.new
end
def new_connection
# http://nhw.pl/wp/2007/12/07/eventmachine-how-to-get-clients-ip-address
host = get_peername[2,6].unpack("nC4")
@port = host.shift
@host = host.join(".")
end
def process(data)
begin
message = Dnsruby::Message.decode(data).to_hash
rescue Exception => e
$logger.error "Error decoding message: #{e.inspect}"
error = DnsrubyError.new
return error.format_error
end
error = DnsrubyError.new(message.to_dnsruby_message)
return error.format_error unless message.valid?
# We can only handle one question per query right now.
# This is what djbdns does ... but I'm not married to the idea.
# The current URL structure only supports one question per query.
q = message[:question][0]
$logger.debug "#{@host}:#{@port.to_s} requested an #{q[:qtype]} record for #{q[:qname]}"
#url = "http://dig.jsondns.org/IN/#{q[:qname]}/#{q[:qtype]}" # lol
url = "http://bananatest.nfshost.com/IN/#{q[:qname]}/#{q[:qtype]}" # lol
if cached_answer = @cache.get(url)
message.overlay!(cached_answer)
return message.to_dnsruby_message.encode
end
begin
string = open(url).read
rescue Exception => e
$logger.error "Error reading #{url} (#{e.inspect})"
# set the rcode to match the HTTP response code as approprate
return error.server_failure
end
begin
server_reply = Yajl::Parser.new(:symbolize_keys => true).parse(string)
rescue Exception => e
$logger.error "Error parsing JSON reply from #{url} (#{e.inspect})"
return error.server_failure
end
reply_json = '{"header": {"aa": true}}'
reply = Yajl::Parser.new(:symbolize_keys => true).parse(reply_json)
reply_required_json = '{"header": {"qr": true,"opcode": "Query"}}'
reply_required = Yajl::Parser.new(:symbolize_keys => true).parse(reply_required_json)
begin
reply.overlay!(server_reply)
reply.overlay!(reply_required)
message.overlay!(reply)
rescue
$logger.error "Error merging reply with query (#{e.inspect})"
return error.server_failure
end
# Catch messages rendered invalid by the modifications above (A SOA reply with the AA flag set for example)
return error.format_error unless message.valid?
# TODO: Make sure that message.encode or message.valid? throw errors on messages that are too large, see also:
# http://eventmachine.rubyforge.org/EventMachine/Connection.html#M000298
begin
answer = message.to_dnsruby_message.encode
rescue Exception => e
$logger.error "Error encoding reply (#{e.inspect})"
return error.server_failure
end
# Only cache the message if it encodes without error
ttl = message[:answer][0][:ttl]
ttl = 10 unless ttl
$logger.debug "cache miss for #{q[:qname]}/#{q[:qtype]} - caching reply for #{ttl} seconds"
@cache.set(url,message,ttl)
answer
end
def receive_data(data)
new_connection
begin
reply = process(data)
rescue
# Handle unhandled exceptions ... we should never get this.
$logger.error "Encountered unknown error while processing packet data"
error = DnsrubyError.new
reply = error.server_failure
end
begin
send_datagram(reply, @host, @port)
rescue Exception => e
$logger.error "Error sending reply from #{url} (#{e.inspect})"
end
end # receive_data
def shutdown
# raise RuntimeError, "pid_file not defined in configuration" unless CONFIG[:pid_file]
# File.delete(CONFIG[:pid_file])
end # shutdown
end # JsonDns
#FIXME: On OS X (1Ghz PPC), queries take over 2000 miliseconds to complete. WTF?
EventMachine.run {
connection = nil
trap("INT") {
$logger.info "ctrl+c caught, stopping server"
connection.shutdown
EventMachine.stop_event_loop
}
trap("TERM") {
$logger.info "TERM caught, stopping server"
connection.shutdown
EventMachine.stop_event_loop
}
begin
# These options are supposed to help things run better on Linux?
# http://eventmachine.rubyforge.org/docs/EPOLL.html
EventMachine.epoll
EventMachine.kqueue
connection = EventMachine.open_datagram_socket(CONFIG[:bind_address], CONFIG[:bind_port], JsonDns)
$logger.info "jsondnsd started"
rescue Exception => e
$logger.fatal "#{e.inspect}"
$logger.fatal e.backtrace.join("\r\n")
$logger.fatal "Do you need root access?"
EventMachine.stop_event_loop
end
}