-
Notifications
You must be signed in to change notification settings - Fork 1
/
geoip-skel
executable file
·261 lines (213 loc) · 5.34 KB
/
geoip-skel
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
#!/usr/bin/env ruby
#require 'pry'
require 'csv'
require 'zlib'
require 'socket'
require 'fileutils'
require 'optparse'
geoinfo = []
#binding.pry
PROGRAM_NAME=File.basename($PROGRAM_NAME)
GEOIP_ENDPOINT="/tmp/geoip"
$PIDFILE="/tmp/geoip.pid"
$DEBUG=(ENV["DEBUG"].to_i != 0)
$DAEMONIZE=true
def error(code, msg)
$stderr.write("#{PROGRAM_NAME}: #{msg}\n")
exit code if code != 0
end
def debug(msg)
$stderr.write("#{PROGRAM_NAME}: debug: #{msg}\n") if $DEBUG
end
class Server
def initialize
@data = []
end
def prepare
fd = Zlib::GzipReader.new(DATA)
fd.each_line do |ln|
f = CSV.parse_line ln
@data << IPRange.new(f[2].to_i, f[3].to_i, f[4], f[5])
end
end
def get_range(ipval)
from = 0
to = @data.length - 1
while from <= to
mid = (from + to) / 2
if ipval < @data[mid].from
to = mid - 1
elsif ipval <= @data[mid].to
return @data[mid]
else
from = mid + 1
end
end
raise RuntimeError.new("not found")
end
def self.stop
open($PIDFILE, "r") { |fd|
ln = fd.readline
debug "reading #{$PIDFILE}, send SIGTERM to #{ln}"
Process.kill("TERM", ln.to_i)
}
rescue SystemCallError
error(0, "sometime went wrong, you'll need to clean manually")
error(1, "by removing #{$PIDFILE} and #{GEOIP_ENDPOINT}")
end
def self.clean
debug "removing the socket, #{GEOIP_ENDPOINT}"
FileUtils::rm_f GEOIP_ENDPOINT
# TODO: better to delete $PIDFILE when $PIDFILE's content is the
# same as the current pid?
debug "removing the pidfile, #{$PIDFILE}"
FileUtils::rm_f $PIDFILE
end
def start
prepare if @data.length == 0
begin
FileUtils::rm_f GEOIP_ENDPOINT, :verbose => false
rescue SystemCallError
end
@serv = UNIXServer.new(GEOIP_ENDPOINT)
# TODO: handle Errno::EADDRINUSE
puts "Ready"
while true
s = @serv.accept
begin
s.each_line do |ln|
fields = ln.split(".").map { |x| x.to_i }
if fields.length == 1
ipval = fields[0].to_i
elsif fields.length == 4
ipval = (fields[0] << 24) + (fields[1] << 16) +
(fields[0] << 8) + (fields[0] << 0)
else
puts "fields len: #{fields.length}"
next
end
begin
answer = get_range(ipval)
debug "req[#{ipval_s(ipval)}] => #{answer.country}"
s.write("#{answer.country}\n")
rescue SystemCallError
# Errno::EPIPE
puts "debug: client disconnected"
rescue RuntimeError
puts "N/A"
s.write("N/A\n")
end
end
ensure
s.close
end
end
end
end
class IPRange
attr_reader :from, :to, :code, :country
def initialize(f, t, code, country)
@from = f
@to = t
@code = code
@country = country
end
def hash
[@from, @to].hash
end
def ==(other)
@from == other.from and @to == other.to
end
def <=>(other)
@from - other.from
end
def dotted(ival)
sprintf("%d.%d.%d.%d", (ival & 0xFF000000) >> 24,
(ival & 0x00FF0000) >> 16,
(ival & 0x0000FF00) >> 8,
(ival & 0x000000FF) >> 0)
end
def to_s
"#{dotted(@from)} - #{dotted(@to)} #{@code} (#{@country})"
end
include Comparable
end
def ipval_s(ipval)
"%d.%d.%d.%d" % [(ipval & 0xFF000000) >> 24,
(ipval & 0xFF0000) >> 16,
(ipval & 0xFF00) >> 8,
(ipval & 0xFF)]
end
def query(s)
fd = UNIXSocket.new(GEOIP_ENDPOINT)
fd.write("#{s}\n")
return fd.readline()
rescue SystemCallError => e
debug("#{e}")
nil
ensure
fd.close unless fd.nil?
end
def help_and_exit
puts <<EOF
Show geo-location information for given IP address
Usage: #{PROGRAM_NAME} [OPTION...] start|stop|ADDRESS
-P, --pidfile=FILE Use FILE to save the server PID
-F, --foreground when starting the server, run it as foreground process
--help display this help and exit
--version output version information and exit
EOF
exit 0
end
$OPTIONS = {}
begin
OptionParser.new { |opts|
opts.banner = "Usage #{PROGRAM_NAME} [options]"
opts.on("-P", "--pidfile") { |arg| $PIDFILE = arg }
opts.on("-F", "--foreground") { $DAEMONIZE = false}
opts.on("--debug") { $DEBUG = true }
opts.on("--help") { help_and_exit }
}.parse!
rescue OptionParser::InvalidOption => e
error(1, "#{e.message}")
end
if ARGV[0] == "server" || ARGV[0] == "start"
puts "starting server, please wait for a while..."
server = Server.new
server.prepare
if $DAEMONIZE
if Process.respond_to?(:daemon)
Process.daemon(true, true)
else
begin
require 'daemon'
Daemon.daemonize
rescue
error(1, "'daemon' gem not found")
exit 1
end
end
end
Signal.trap("TERM") { Server.clean; exit 0 }
Signal.trap("INT") { Server.clean; exit 0 }
open($PIDFILE, "w") { |fd|
debug "writig current pid(#{Process.pid}) to {$PIDFILE}"
fd.write("#{Process.pid}\n")
}
server.start
exit 0
elsif ARGV[0] == 'stop'
Server.stop
exit 0
end
#puts $PROGRAM_NAME
#binding.pry
# if query("").nil?
# $stderr.write("error: server not found\n")
# exit 1
# end
#binding.pry
puts query(ARGV[0]) if ARGV.length > 0
#binding.pry
exit 0
__END__