-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
345 lines (285 loc) · 7.57 KB
/
index.js
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
var fs = require('fs');
var join = require('path').join;
var iconv = require('iconv-lite');
var debug = require('debug')('ip');
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var thunkify = require('thunkify-wrap');
function IpUtil(ipFile, encoding, isLoad) {
if (typeof encoding === 'function') {
isLoad = encoding;
encoding = null;
}
this.ipFile = joinDirectory(process.cwd(), ipFile);
this.ipList = [];
if (encoding && encoding.toLowerCase().indexOf('utf') > -1) {
this.filter = function(buf) {
return buf.toString();
};
} else {
this.filter = function(buf) {
return iconv.decode(new Buffer(buf), 'gbk');
};
}
this.isLoad = isLoad || function(){
return true;
};
this.init();
}
util.inherits(IpUtil, EventEmitter);
IpUtil.prototype.init = function() {
var that = this;
var isLoad = this.isLoad;
debug('begin parse ipfile %s', this.ipFile);
if (!fs.existsSync(this.ipFile)) {
debug('not found ip file!');
that.emit('error', 'ipfile_not_found');
return;
}
var ipMap = this.ipMap = {};
var ipList = this.ipList;
var getLine = readLine(this.ipFile, this.filter);
var result = getLine.next();
var line;
var lineNum = 0;
var counter = 1;
var _readLine = function () {
if (result.done) {
that.emit('loaded');
return;
}
// 避免ip读取独占cpu.
if (counter % 100000 === 0) {
counter = 1;
setImmediate(_readLine);
return;
}
counter++;
lineNum++;
line = result.value;
if (!line || !line.trim()) {
result = getLine.next();
_readLine();
return;
}
var tokens = line.split(',', 6);
if (tokens.length !== 6) {
debug('第%d行格式不正确: %s', lineNum, line);
result = getLine.next();
_readLine();
return;
}
var startIp = ip2Long(tokens[0]);
var endIp = ip2Long(tokens[1]);
if (!startIp || !endIp) {
debug('第%d行格式不正确: %s', lineNum, line);
result = getLine.next();
_readLine();
return;
}
var country = getValue(tokens[2]);
var province = getValue(tokens[3]);
var city = getValue(tokens[4]);
var address = getValue(tokens[5]);
// 针对国家、省份、城市解析的统一判空修改
// 首先对特殊值的解析
if ('IANA' === country) {
country = 'IANA';
province = 'IANA';
city = 'IANA';
}
if ('局域网' === country) {
country = '局域网';
province = '局域网';
city = '局域网';
}
if('国外' === country) {
country = '国外';
province = '国外';
city = '国外';
}
if('中国' === country && ('中国' === province || '中国' === city)) {
country = '中国';
province = '中国';
city = '中国';
}
if (!isLoad(country, province, city)) {
result = getLine.next();
setImmediate(_readLine);
return;
}
ipMap[startIp] = {
startIp: startIp,
endIp: endIp,
country: country,
province: province,
city: city,
address: address
};
ipList.push(startIp);
result = getLine.next();
setImmediate(_readLine);
};
_readLine();
var sortIp = function () {
//debug(this.ipMap)
debug('完成IP库的载入. 共载入 %d 条IP纪录', ipList.length);
ipList.sort(function(a, b) {
return a - b;
});
debug('ip 索引排序完成.');
that.emit('done');
};
this.on('loaded', sortIp);
};
function getValue(val) {
if (!val) {
return null;
}
val = val.trim();
if (val === 'null') {
return null;
}
return val;
}
IpUtil.prototype.getIpInfo = function(ip) {
if (!isIp(ip)) {
return null;
}
if (typeof ip === 'string') {
ip = ip2Long(ip);
}
var ipStart = this.locatStartIP(ip);
debug('开始获取 ip 信息: %d', ipStart);
var ipInfo = this.ipMap[ipStart];
debug('查找IP, %s 成功.', long2IP(ip));
if (ipInfo.endIp < ip) {
debug('在IP库中找不到IP[%s]', long2IP(ip));
return null;
}
return ipInfo;
};
IpUtil.prototype.refreshData = function() {
};
/**
* 查找ip对应的开始IP地址。如果IP库中正好有以该ip开始的IP信息,那么就是返回这个ip。
* 如果没有,则应该是比这个ip小的最大的start
* @param ip
* @return
*/
IpUtil.prototype.locatStartIP = function(ip) {
debug('开始查找IP: %d', ip);
var centerIP = 0;
var centerIndex = 0; // 当前指针位置
var startIndex = 0; // 起始位置
var endIndex = this.ipList.length - 1; // 结束位置
var count = 0; // 循环次数
while (true) {
debug('%d. start = %d, end = %d', count++, startIndex, endIndex);
// 中间位置
centerIndex = Math.floor((startIndex + endIndex) / 2);
centerIP = this.ipList[centerIndex];
if (centerIP < ip) {
// 如果中间位置的IP小于要查询的IP,那么下一次查找后半段
startIndex = centerIndex;
} else if (centerIP > ip) {
// 如果中间位置的IP大于要查询的IP,那么下一次查找前半段
endIndex = centerIndex;
} else {
// 如果相等,那么已经找到要查询的IP
break;
}
if (startIndex + 1 === endIndex) {
// 如果开始指针和结束指针相差只有1,那么说明IP库中没有正好以该ip开始的IP信息
// 只能返回IP信息的start ip比这个ip小的最大的那条IP信息的start ip
if (centerIP > ip) {
centerIP = this.ipList[centerIndex - 1];
}
break;
}
}
debug('对应的IP开始地址为: %d', centerIP, centerIndex);
return centerIP;
};
/**
* a,b,c ==> a/b/c
* a,b,/tmp ==> /tmp
* /a/b, c ==> /a/b/c
*/
function joinDirectory() {
var dirs = [].slice.call(arguments, 1);
var dir;
for (var i = 0, len = dirs.length; i < len; i++) {
dir = dirs[i];
if (/^\//.test(dir)) {
// 发现根目录, 直接返回.
return dir;
}
}
return join.apply(null, [].slice.call(arguments));
}
function ip2Long(ip) {
if (!isIp(ip)) {
return 0;
}
var segs = ip.split('.');
var iplong =(parseInt(segs[0]) << 24
| parseInt(segs[1]) << 16
| parseInt(segs[2]) << 8
| parseInt(segs[3])) >>> 0;
return iplong;
}
var IP_REGEXP = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
function isIp(str) {
if (!str) {
return false;
}
str = str.trim();
return IP_REGEXP.test(str);
/**
var tokens = str.split('.');
if (tokens.length !== 4) {
return false;
}
for (var i = 0, len = tokens.length; i < len; i++) {
if (parseInt(tokens[i]) > 255 || parseInt(tokens[i]) < 0) {
return false;
}
}
return true;
**/
}
function long2IP(ipLong) {
var ip = [ipLong >> 24];
ip.push((ipLong & 16711680) >> 16);
ip.push((ipLong & 65280) >> 8);
ip.push(ipLong & 255);
return ip.join('.');
}
function *readLine(file, filter) {
var buffer = fs.readFileSync(file);
var i = 0, len = 0 || buffer.length;
debug('load file succ', len);
// 换行符.
var nl = require('os').EOL.charCodeAt(0);
var buf = [];
while(i < len) {
if (buffer[i] !== nl) {
buf.push(buffer[i]);
} else {
yield filter(new Buffer(buf));
buf = [];
}
i++;
}
}
module.exports = IpUtil;
module.exports.isIP = isIp;
module.exports.ip2Long = ip2Long;
module.exports.long2Ip = long2IP;
module.exports.getIpUtil = function *(ipFile, encoding, ipFilter) {
var iputil = new IpUtil(ipFile, encoding, ipFilter);
var end = thunkify.event(iputil, ['done', 'error']);
yield end();
return iputil;
};