-
Notifications
You must be signed in to change notification settings - Fork 9
/
jsondns.rb
83 lines (75 loc) · 2.48 KB
/
jsondns.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
#
# jsondns.rb
# Sinatra web application that provides a REST based DNS interface.
#
# Copyright 2009 Joel Franusic
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
$LOAD_PATH.push(File.dirname(__FILE__) + '/lib')
require 'dnsruby-jsonquery'
require 'sinatra'
def ttl_for(answer)
ttl = 5 # set a 5 second ttl
answer_hash = Yajl::Parser.new(:symbolize_keys => true).parse(answer)
if answer_hash[:header][:rcode] == 'NOERROR' && answer_hash[:answer][0]
ttl = answer_hash[:answer][0][:ttl]
end
ttl
end
resolver = Dnsruby::Resolver.new({:nameserver => "4.2.2.2"})
def status_for(answer)
status = 503
answer_hash = Yajl::Parser.new(:symbolize_keys => true).parse(answer)
rcode = answer_hash[:header][:rcode]
aa = answer_hash[:header][:aa]
# These cover RFC 1035, I haven't looked at RFC 2136 yet ...
if rcode == 'NOERROR' && aa == true
status = 200 # OK
elsif rcode == 'NOERROR' && aa == false
status = 203 # Non-Authoritative Information
elsif rcode == 'FORMERR'
status = 400 # Bad Request
elsif rcode == 'SERVFAIL'
status = 503 # Service Unavailable
elsif rcode == 'NXDOMAIN'
status = 404 # Not Found
elsif rcode == 'NOTIMP'
status = 501 # Not Implemented
elsif rcode == 'REFUSED'
status = 403 # Forbidden
end
status
end
get '/' do
erb :index
end
get '/IN/:domain/:type' do
answer = resolver.jsonquery(params[:domain],params[:type])
status status_for(answer)
response.headers['Content-Type'] = 'text/plain'
response.headers['Cache-Control'] = 'public, max-age=' + ttl_for(answer).to_s
if params[:callback] =~ /^[a-zA-Z_$][a-zA-Z0-9_$]*$/
status 200
params[:callback] + '(' + answer + ')' # JSONP
else
answer
end
end
# Return a blank result for invalid requests.
get '/IN*' do
answer = resolver.jsonquery(nil,nil)
status status_for(answer)
response.headers['Content-Type'] = 'text/plain'
response.headers['Cache-Control'] = 'public, max-age=' + ttl_for(answer).to_s
answer
end