Correctly handle CIDR notation in BypassCondition.

This commit is contained in:
FelisCatus 2014-11-07 17:25:15 +08:00
parent 51be2b9ff2
commit 6c8b478d1a
3 changed files with 51 additions and 43 deletions

View File

@ -17,7 +17,7 @@
"minifyify": "^4.1.1"
},
"dependencies": {
"ipv6": "^3.1.1",
"ipv6": "beaugunderson/javascript-ipv6",
"uglify-js": "^2.4.15"
},
"browser": {

View File

@ -143,6 +143,7 @@ module.exports = exports =
return addr
normalizeIp: (addr) ->
return (addr.correctForm ? addr.canonicalForm).call(addr)
ipv6Max: new IP.v6.Address('::/0').endAddress().canonicalForm()
localHosts: ["127.0.0.1", "[::1]", "localhost"]
@ -247,11 +248,14 @@ module.exports = exports =
parts = server.split '/'
if parts.length > 1
addr = @parseIp parts[0]
prefixLen = parseInt(parts[1])
if addr and prefixLen
cache.ip =
conditionType: 'IpCondition'
ip: parts[0]
prefixLength: parseInt parts[1]
else
prefixLength: prefixLen
return cache
if server.charCodeAt(server.length - 1) != ']'.charCodeAt(0)
pos = server.lastIndexOf(':')
if pos >= 0
@ -264,8 +268,8 @@ module.exports = exports =
# TODO(felis): IPv6 regex is not fully supported by the ipv6
# module. Even simple addresses like ::1 will fail. Shall we
# implement that instead?
regexStr = serverIp.regularExpressionString()
regexStr = regexStr.substring 2, regexStr.length - 2
regexStr = serverIp.regularExpressionString(true)
console.log(regexStr)
serverRegex = '\\[' + regexStr + '\\]'
else
server = @normalizeIp serverIp
@ -374,10 +378,14 @@ module.exports = exports =
if not cache.addr?
throw new Error "Invalid IP address #{addr}"
cache.normalized = @normalizeIp cache.addr
cache.mask = @normalizeIp cache.addr.startAddress()
mask = if cache.addr.v4
new IP.v4.Address('255.255.255.255/' + cache.addr.subnetMask)
else
new IP.v6.Address(@ipv6Max + cache.addr.subnetMask)
cache.mask = @normalizeIp mask.startAddress()
cache
match: (condition, request, cache) ->
addr = @parseIp addr
addr = @parseIp request.host
return false if not addr?
cache = cache.analyzed
return false if addr.v4 != cache.addr.v4

View File

@ -167,12 +167,12 @@ describe 'Conditions', ->
testCond(cond, 'http://127.0.0.1:8080/', 'match')
testCond(cond, 'http://127.0.0.2:8080/', not 'match')
# TODO(felis): Not yet supported. See the code for BypassCondition.
it.skip 'should correctly support IPv6 canonicalization', ->
it 'should correctly support IPv6 canonicalization', ->
cond =
conditionType: 'BypassCondition'
pattern: 'http://[0:0::1]:8080'
Conditions.analyze(cond)
cond._analyzed().url.should.equal '999'
result = Conditions.analyze(cond)
console.log(result.analyzed)
testCond(cond, 'http://[::1]:8080/', 'match')
testCond(cond, 'http://[1::1]:8080/', not 'match')