forked from lionsoul2014/ip2region
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Ip2region.lua
443 lines (366 loc) · 10.9 KB
/
Ip2region.lua
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
--[[
Ip2region lua binding
@author chenxin<chenxin619315@gmail.com>
@date 2018/10/02
]]--
require("bit32");
local INDEX_BLOCK_LENGTH = 12;
local TOTAL_HEADER_LENGTH = 8192;
local _M = {
dbFile = "",
dbFileHandler = "",
dbBinStr = "",
HeaderSip = "",
HeaderPtr = "",
headerLen = 0,
firstIndexPtr = 0,
lastIndexPtr = 0,
totalBlocks = 0
};
_G["Ip2region"] = _M;
-- set the __index to itself
_M.__index = _M;
-- set the print meta-method
_M.__tostring = function(table)
local t = {
"dbFile=" .. table.dbFile,
-- "dbFileHandler=" .. table.dbFileHandler,
"headerLen=" .. table.headerLen,
"firstIndexPtr" .. table.firstIndexPtr,
"lastIndexPtr" .. table.lastIndexPtr,
"totalBlocks" .. table.totalBlocks
};
return table.concat(t, ",");
end
--[[
construct method
@param obj
@return Ip2region object
--]]
function _M.new(dbFile)
obj = {};
setmetatable(obj, _M);
obj.dbFile = dbFile;
return obj;
end
--[[
internal function to get a integer from a binary string
@param dbBinStr
@param idx
@return Integer
]]--
function getLong(bs, idx)
local a1 = string.byte(string.sub(bs, idx, idx));
local a2 = bit32.lshift(string.byte(string.sub(bs, idx+1, idx+1)), 8);
local a3 = bit32.lshift(string.byte(string.sub(bs, idx+2, idx+2)), 16);
local a4 = bit32.lshift(string.byte(string.sub(bs, idx+3, idx+3)), 24);
local val = bit32.bor(a1, a2);
val = bit32.bor(val, a3);
val = bit32.bor(val, a4);
return val;
end
--[[
internal function to convert the string ip to a long value
@param ip
@return Integer
]]--
function _M.ip2long(self, ip)
-- dynamic arguments checking
-- to support object.ip2long and object:ip2long access
if ( type(self) == "string") then
ip = self;
end
local ini = 1;
local iip = 0;
local off = 24;
while true do
local pos = string.find(ip, '.', ini, true);
if ( not pos ) then
break;
end
local sub = string.sub(ip, ini, pos - 1);
if ( string.len(sub) < 1 ) then
return nil;
end
iip = bit32.bor(iip, bit32.lshift(tonumber(sub), off));
ini = pos + 1;
off = off - 8;
end
-- check if it is a valid ip address
if ( off ~= 0 or ini > string.len(ip) ) then
return nil;
end
local sub = string.sub(ip, ini);
if ( string.len(sub) < 1 ) then
return nil;
end
return bit32.bor(iip, bit32.lshift(tonumber(sub), off));
end
--[[
internal function to get the whole content of a file
@param file
@return String
]]--
function get_file_contents(file)
local fi = io.input(file);
if ( not fi ) then
return nil;
end
local str = io.read("*a");
io.close();
return str;
end
--[[
set the current db file path
@param dbFile
]]--
function _M:setDbFile(dbFile)
self.dbFile = dbFile;
end
--[[
all the db binary string will be loaded into memory
then search the memory only and this will a lot faster than disk base search
@Note: invoke it once before put it to public invoke could make it thread safe
@param ip
@return table or nil for failed
]]--
function _M:memorySearch(ip)
-- string ip conversion
if ( type(ip) == "string" ) then
ip = self:ip2long(ip);
if ( ip == nil ) then
return nil;
end
end;
-- check and load the binary string for the first time
if ( self.dbBinStr == "" ) then
self.dbBinStr = get_file_contents(self.dbFile);
if ( not self.dbBinStr ) then
return nil;
end
self.firstIndexPtr = getLong(self.dbBinStr, 1);
self.lastIndexPtr = getLong(self.dbBinStr, 5);
self.totalBlocks = (self.lastIndexPtr - self.firstIndexPtr)/INDEX_BLOCK_LENGTH + 1;
end
-- binary search to define the data
local l = 0;
local h = self.totalBlocks;
local dataPtr = 0;
while ( l <= h ) do
local m = math.floor((l + h) / 2);
local p = self.firstIndexPtr + m * INDEX_BLOCK_LENGTH;
local sip = getLong(self.dbBinStr, p + 1);
if ( ip < sip ) then
h = m - 1;
else
local eip = getLong(self.dbBinStr, p + 5); -- 4 + 1
if ( ip > eip ) then
l = m + 1;
else
dataPtr = getLong(self.dbBinStr, p + 9); -- 8 + 1
break;
end
end
end
-- not matched just stop it here
if ( dataPtr == 0 ) then return nil end
-- get the data
local dataLen = bit32.band(bit32.rshift(dataPtr, 24), 0xFF);
dataPtr = bit32.band(dataPtr, 0x00FFFFFF);
local dptr = dataPtr + 5; -- 4 + 1
return {
city_id = getLong(self.dbBinStr, dataPtr),
region = string.sub(self.dbBinStr, dptr, dptr + dataLen - 5)
};
end
--[[
get the data block through the specified ip address
or long ip numeric with binary search algorithm
@param ip
@return table or nil for failed
]]--
function _M:binarySearch(ip)
-- check and conver the ip address
if ( type(ip) == "string" ) then
ip = self:ip2long(ip);
if ( ip == nil ) then
return nil;
end
end
if ( self.totalBlocks == 0 ) then
-- check and open the original db file
self.dbFileHandler = io.open(self.dbFile, "r");
if ( not self.dbFileHandler ) then
return nil;
end
self.dbFileHandler:seek("set", 0);
local superBlock = self.dbFileHandler:read(8);
self.firstIndexPtr = getLong(superBlock, 1); -- 0 + 1
self.lastIndexPtr = getLong(superBlock, 5); -- 4 + 1
self.totalBlocks = (self.lastIndexPtr-self.firstIndexPtr)/INDEX_BLOCK_LENGTH + 1;
end
-- binary search to define the data
local l = 0;
local h = self.totalBlocks;
local dataPtr = 0;
while ( l <= h ) do
local m = math.floor((l + h) / 2);
local p = m * INDEX_BLOCK_LENGTH;
self.dbFileHandler:seek("set", self.firstIndexPtr + p);
local buffer = self.dbFileHandler:read(INDEX_BLOCK_LENGTH);
local sip = getLong(buffer, 1); -- 0 + 1
if ( ip < sip ) then
h = m - 1;
else
local eip = getLong(buffer, 5); -- 4 + 1
if ( ip > eip ) then
l = m + 1;
else
dataPtr = getLong(buffer, 9); -- 8 + 1
break;
end
end
end
-- not matched just stop it here
if ( dataPtr == 0 ) then return nil; end
-- get the data
local dataLen = bit32.band(bit32.rshift(dataPtr, 24), 0xFF);
dataPtr = bit32.band(dataPtr, 0x00FFFFFF);
self.dbFileHandler:seek("set", dataPtr);
local data = self.dbFileHandler:read(dataLen);
return {
city_id = getLong(data, 1), -- 0 + 1
region = string.sub(data, 5) -- 4 + 1
};
end
--[[
get the data block associated with the specified ip with b-tree search algorithm
@param ip
@return table or nil for failed
]]--
function _M:btreeSearch(ip)
-- string ip to integer conversion
if ( type(ip) == "string" ) then
ip = self:ip2long(ip);
if ( ip == nil ) then
return nil;
end
end
-- check and load the header
if ( self.headerLen == 0 ) then
-- check and open the original db file
self.dbFileHandler = io.open(self.dbFile, 'r');
if ( not self.dbFileHandler ) then
return nil;
end
self.dbFileHandler:seek("set", 8);
local buffer = self.dbFileHandler:read(TOTAL_HEADER_LENGTH);
-- fill the header
local i = 0;
local idx = 0;
self.HeaderSip = {};
self.HeaderPtr = {};
for i=0, TOTAL_HEADER_LENGTH, 8 do
local startIp = getLong(buffer, i + 1); -- 0 + 1
local dataPtr = getLong(buffer, i + 5); -- 4 + 1
if ( dataPtr == 0 ) then
break;
end
table.insert(self.HeaderSip, startIp);
table.insert(self.HeaderPtr, dataPtr);
idx = idx + 1;
end
self.headerLen = idx;
end
-- 1. define the index block with the binary search
local l = 0;
local h = self.headerLen;
local sptr = 0;
local eptr = 0;
while ( l <= h ) do
local m = math.floor((l + h) / 2);
-- perfetc matched, just return it
if ( ip == self.HeaderSip[m] ) then
if ( m > 0 ) then
sptr = self.HeaderPtr[m-1];
eptr = self.HeaderPtr[m ];
else
sptr = self.HeaderPtr[m ];
eptr = self.HeaderPtr[m+1];
end
break;
end
-- less then the middle value
if ( ip < self.HeaderSip[m] ) then
if ( m == 0 ) then
sptr = self.HeaderPtr[m ];
eptr = self.HeaderPtr[m+1];
break;
elseif ( ip > self.HeaderSip[m-1] ) then
sptr = self.HeaderPtr[m-1];
eptr = self.HeaderPtr[m ];
break;
end
h = m - 1;
else
if ( m == self.headerLen - 1 ) then
sptr = self.HeaderPtr[m-1];
eptr = self.HeaderPtr[m ];
break;
elseif ( ip <= self.HeaderSip[m+1] ) then
sptr = self.HeaderPtr[m ];
eptr = self.HeaderPtr[m+1];
break;
end
l = m + 1;
end
end
-- match nothing just stop it
if ( sptr == 0 ) then return nil; end
-- 2. search the index blocks to define the data
self.dbFileHandler:seek("set", sptr);
local blockLen = eptr - sptr;
local index = self.dbFileHandler:read(blockLen + INDEX_BLOCK_LENGTH);
local dataPtr = 0;
l = 0;
h = blockLen / INDEX_BLOCK_LENGTH;
while ( l <= h ) do
local m = math.floor((l + h) / 2);
local p = m * INDEX_BLOCK_LENGTH;
local sip = getLong(index, p + 1); -- 0 + 1
if ( ip < sip ) then
h = m - 1;
else
local eip = getLong(index, p + 5); -- 4 + 1
if ( ip > eip ) then
l = m + 1;
else
dataPtr = getLong(index, p + 9); -- 8 + 1
break;
end
end
end
-- not matched
if ( dataPtr == 0 ) then return nil; end
-- 3. get the data
local dataLen = bit32.band(bit32.rshift(dataPtr, 24), 0xFF);
dataPtr = bit32.band(dataPtr, 0x00FFFFFF);
self.dbFileHandler:seek("set", dataPtr);
local data = self.dbFileHandler:read(dataLen);
return {
city_id = getLong(data, 1), -- 0 + 1
region = string.sub(data, 5) -- 4 + 1
};
end
--[[
close the object and do the basic gc
]]--
function _M.close(self)
if ( self.dbFileHandler ~= "" ) then
self.dbFileHandler:close();
end
if ( self.dbBinStr ~= "" ) then
self.dbBinStr = nil;
end
end
return _M;