Fix cluster-geo code to cache IPv6 by first 64 bits to prevent cache fillup due to IPv6 privacy extensions.

This commit is contained in:
Adam Ierymenko 2016-03-03 15:33:38 -08:00
parent 1fe251d0a0
commit 60ab565185
3 changed files with 16 additions and 9 deletions

View File

@ -7,6 +7,8 @@ If a cluster-mode instance detects a file in the ZeroTier home folder called *cl
IP,result code,latitude,longitude,x,y,z
IPv6 IPs must be sent *without* compression / zero-removal.
The first field is the IP echoed back. The second field is 0 if the result is pending and may be ready in the future or 1 if the result is ready now. If the second field is 0 the remaining fields should be 0. Otherwise the remaining fields contain the IP's latitude, longitude, and X/Y/Z coordinates.
ZeroTier's cluster route optimization code only uses the X/Y/Z values. These are computed by this cluster-geo code as the spherical coordinates of the IP address using the Earth's center as the point of origin and using an approximation of the Earth as a sphere. This doesn't yield *exact* coordinates, but it's good enough for our purposes since the goal is to route clients to the geographically closest endpoint.

View File

@ -25,7 +25,15 @@ var cache = require('levelup')(__dirname + '/cache.leveldb');
function lookup(ip,callback)
{
cache.get(ip,function(err,cachedEntryJson) {
if (!ip)
return callback(null,null);
var ipKey = ip;
if ((ipKey.indexOf(':') === 4)&&(ipKey.length > 19))
ipKey = ipKey.substr(0,19); // we key in the cache using only the first 64 bits of IPv6 addresses
cache.get(ipKey,function(err,cachedEntryJson) {
if ((!err)&&(cachedEntryJson)) {
try {
let cachedEntry = JSON.parse(cachedEntryJson.toString());
@ -40,30 +48,27 @@ function lookup(ip,callback)
} catch (e) {}
}
cache.put(ip,JSON.stringify({
cache.put(ipKey,JSON.stringify({
ts: Date.now() - (CACHE_TTL - 30000), // set ts to expire in 30 seconds while the query is in progress
r: null
}),function(err) {
geo(ip,function(err,result) {
if (err) {
//console.error(err);
return callback(err,null);
}
if (!result)
result = null;
cache.put(ip,JSON.stringify({
cache.put(ipKey,JSON.stringify({
ts: Date.now(),
r: result
}),function(err) {
if (err)
console.error('Error saving to cache: '+err);
//if (err)
// console.error('Error saving to cache: '+err);
return callback(null,result);
});
});
});
});

View File

@ -10,7 +10,7 @@
"license": "GPL-3.0",
"dependencies": {
"geoip2ws": "^1.7.1",
"leveldown": "^1.4.2",
"leveldown": "^1.4.4",
"levelup": "^1.3.0"
}
}