Initial commit for OpenECOMP SDN-C OA&M
[sdnc/oam.git] / dgbuilder / dgeflows / node_modules / express / node_modules / proxy-addr / node_modules / ipaddr.js / src / ipaddr.coffee
1 # Define the main object
2 ipaddr = {}
3
4 root = this
5
6 # Export for both the CommonJS and browser-like environment
7 if module? && module.exports
8   module.exports = ipaddr
9 else
10   root['ipaddr'] = ipaddr
11
12 # A generic CIDR (Classless Inter-Domain Routing) RFC1518 range matcher.
13 matchCIDR = (first, second, partSize, cidrBits) ->
14   if first.length != second.length
15     throw new Error "ipaddr: cannot match CIDR for objects with different lengths"
16
17   part = 0
18   while cidrBits > 0
19     shift = partSize - cidrBits
20     shift = 0 if shift < 0
21
22     if first[part] >> shift != second[part] >> shift
23       return false
24
25     cidrBits -= partSize
26     part     += 1
27
28   return true
29
30 # An utility function to ease named range matching. See examples below.
31 ipaddr.subnetMatch = (address, rangeList, defaultName='unicast') ->
32   for rangeName, rangeSubnets of rangeList
33     # ECMA5 Array.isArray isn't available everywhere
34     if toString.call(rangeSubnets[0]) != '[object Array]'
35       rangeSubnets = [ rangeSubnets ]
36
37     for subnet in rangeSubnets
38       return rangeName if address.match.apply(address, subnet)
39
40   return defaultName
41
42 # An IPv4 address (RFC791).
43 class ipaddr.IPv4
44   # Constructs a new IPv4 address from an array of four octets.
45   # Verifies the input.
46   constructor: (octets) ->
47     if octets.length != 4
48       throw new Error "ipaddr: ipv4 octet count should be 4"
49
50     for octet in octets
51       if !(0 <= octet <= 255)
52         throw new Error "ipaddr: ipv4 octet is a byte"
53
54     @octets = octets
55
56   # The 'kind' method exists on both IPv4 and IPv6 classes.
57   kind: ->
58     return 'ipv4'
59
60   # Returns the address in convenient, decimal-dotted format.
61   toString: ->
62     return @octets.join "."
63
64   # Returns an array of byte-sized values in network order
65   toByteArray: ->
66     return @octets.slice(0) # octets.clone
67
68   # Checks if this address matches other one within given CIDR range.
69   match: (other, cidrRange) ->
70     if other.kind() != 'ipv4'
71       throw new Error "ipaddr: cannot match ipv4 address with non-ipv4 one"
72
73     return matchCIDR(this.octets, other.octets, 8, cidrRange)
74
75   # Special IPv4 address ranges.
76   SpecialRanges:
77     unspecified: [
78       [ new IPv4([0,     0,    0,   0]),  8 ]
79     ]
80     broadcast: [
81       [ new IPv4([255, 255,  255, 255]), 32 ]
82     ]
83     multicast: [ # RFC3171
84       [ new IPv4([224,   0,    0,   0]), 4  ]
85     ]
86     linkLocal: [ # RFC3927
87       [ new IPv4([169,   254,  0,   0]), 16 ]
88     ]
89     loopback: [ # RFC5735
90       [ new IPv4([127,   0,    0,   0]), 8  ]
91     ]
92     private: [ # RFC1918
93       [ new IPv4([10,    0,    0,   0]), 8  ]
94       [ new IPv4([172,   16,   0,   0]), 12 ]
95       [ new IPv4([192,   168,  0,   0]), 16 ]
96     ]
97     reserved: [ # Reserved and testing-only ranges; RFCs 5735, 5737, 2544, 1700
98       [ new IPv4([192,   0,    0,   0]), 24 ]
99       [ new IPv4([192,   0,    2,   0]), 24 ]
100       [ new IPv4([192,  88,   99,   0]), 24 ]
101       [ new IPv4([198,  51,  100,   0]), 24 ]
102       [ new IPv4([203,   0,  113,   0]), 24 ]
103       [ new IPv4([240,   0,    0,   0]), 4  ]
104     ]
105
106   # Checks if the address corresponds to one of the special ranges.
107   range: ->
108     return ipaddr.subnetMatch(this, @SpecialRanges)
109
110   # Convrets this IPv4 address to an IPv4-mapped IPv6 address.
111   toIPv4MappedAddress: ->
112     return ipaddr.IPv6.parse "::ffff:#{@toString()}"
113
114 # A list of regular expressions that match arbitrary IPv4 addresses,
115 # for which a number of weird notations exist.
116 # Note that an address like 0010.0xa5.1.1 is considered legal.
117 ipv4Part = "(0?\\d+|0x[a-f0-9]+)"
118 ipv4Regexes =
119   fourOctet: new RegExp "^#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}$", 'i'
120   longValue: new RegExp "^#{ipv4Part}$", 'i'
121
122 # Classful variants (like a.b, where a is an octet, and b is a 24-bit
123 # value representing last three octets; this corresponds to a class C
124 # address) are omitted due to classless nature of modern Internet.
125 ipaddr.IPv4.parser = (string) ->
126   parseIntAuto = (string) ->
127     if string[0] == "0" && string[1] != "x"
128       parseInt(string, 8)
129     else
130       parseInt(string)
131
132   # parseInt recognizes all that octal & hexadecimal weirdness for us
133   if match = string.match(ipv4Regexes.fourOctet)
134     return (parseIntAuto(part) for part in match[1..5])
135   else if match = string.match(ipv4Regexes.longValue)
136     value = parseIntAuto(match[1])
137     if value > 0xffffffff || value < 0
138       throw new Error "ipaddr: address outside defined range"
139     return ((value >> shift) & 0xff for shift in [0..24] by 8).reverse()
140   else
141     return null
142
143 # An IPv6 address (RFC2460)
144 class ipaddr.IPv6
145   # Constructs an IPv6 address from an array of eight 16-bit parts.
146   # Throws an error if the input is invalid.
147   constructor: (parts) ->
148     if parts.length != 8
149       throw new Error "ipaddr: ipv6 part count should be 8"
150
151     for part in parts
152       if !(0 <= part <= 0xffff)
153         throw new Error "ipaddr: ipv6 part should fit to two octets"
154
155     @parts = parts
156
157   # The 'kind' method exists on both IPv4 and IPv6 classes.
158   kind: ->
159     return 'ipv6'
160
161   # Returns the address in compact, human-readable format like
162   # 2001:db8:8:66::1
163   toString: ->
164     stringParts = (part.toString(16) for part in @parts)
165
166     compactStringParts = []
167     pushPart = (part) -> compactStringParts.push part
168
169     state = 0
170     for part in stringParts
171       switch state
172         when 0
173           if part == '0'
174             pushPart('')
175           else
176             pushPart(part)
177
178           state = 1
179         when 1
180           if part == '0'
181             state = 2
182           else
183             pushPart(part)
184         when 2
185           unless part == '0'
186             pushPart('')
187             pushPart(part)
188             state = 3
189         when 3
190           pushPart(part)
191
192     if state == 2
193       pushPart('')
194       pushPart('')
195
196     return compactStringParts.join ":"
197
198   # Returns an array of byte-sized values in network order
199   toByteArray: ->
200     bytes = []
201     for part in @parts
202       bytes.push(part >> 8)
203       bytes.push(part & 0xff)
204
205     return bytes
206
207   # Returns the address in expanded format with all zeroes included, like
208   # 2001:db8:8:66:0:0:0:1
209   toNormalizedString: ->
210     return (part.toString(16) for part in @parts).join ":"
211
212   # Checks if this address matches other one within given CIDR range.
213   match: (other, cidrRange) ->
214     if other.kind() != 'ipv6'
215       throw new Error "ipaddr: cannot match ipv6 address with non-ipv6 one"
216
217     return matchCIDR(this.parts, other.parts, 16, cidrRange)
218
219   # Special IPv6 ranges
220   SpecialRanges:
221     unspecified: [ new IPv6([0,      0,      0, 0, 0,      0,      0, 0]), 128 ] # RFC4291, here and after
222     linkLocal:   [ new IPv6([0xfe80, 0,      0, 0, 0,      0,      0, 0]), 10  ]
223     multicast:   [ new IPv6([0xff00, 0,      0, 0, 0,      0,      0, 0]), 8   ]
224     loopback:    [ new IPv6([0,      0,      0, 0, 0,      0,      0, 1]), 128 ]
225     uniqueLocal: [ new IPv6([0xfc00, 0,      0, 0, 0,      0,      0, 0]), 7   ]
226     ipv4Mapped:  [ new IPv6([0,      0,      0, 0, 0,      0xffff, 0, 0]), 96  ]
227     rfc6145:     [ new IPv6([0,      0,      0, 0, 0xffff, 0,      0, 0]), 96  ] # RFC6145
228     rfc6052:     [ new IPv6([0x64,   0xff9b, 0, 0, 0,      0,      0, 0]), 96  ] # RFC6052
229     '6to4':      [ new IPv6([0x2002, 0,      0, 0, 0,      0,      0, 0]), 16  ] # RFC3056
230     teredo:      [ new IPv6([0x2001, 0,      0, 0, 0,      0,      0, 0]), 32  ] # RFC6052, RFC6146
231     reserved: [
232       [ new IPv6([ 0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32 ] # RFC4291
233     ]
234
235   # Checks if the address corresponds to one of the special ranges.
236   range: ->
237     return ipaddr.subnetMatch(this, @SpecialRanges)
238
239   # Checks if this address is an IPv4-mapped IPv6 address.
240   isIPv4MappedAddress: ->
241     return @range() == 'ipv4Mapped'
242
243   # Converts this address to IPv4 address if it is an IPv4-mapped IPv6 address.
244   # Throws an error otherwise.
245   toIPv4Address: ->
246     unless @isIPv4MappedAddress()
247       throw new Error "ipaddr: trying to convert a generic ipv6 address to ipv4"
248
249     [high, low] = @parts[-2..-1]
250
251     return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff])
252
253 # IPv6-matching regular expressions.
254 # For IPv6, the task is simpler: it is enough to match the colon-delimited
255 # hexadecimal IPv6 and a transitional variant with dotted-decimal IPv4 at
256 # the end.
257 ipv6Part = "(?:[0-9a-f]+::?)+"
258 ipv6Regexes =
259   native:       new RegExp "^(::)?(#{ipv6Part})?([0-9a-f]+)?(::)?$", 'i'
260   transitional: new RegExp "^((?:#{ipv6Part})|(?:::)(?:#{ipv6Part})?)" +
261                            "#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}$", 'i'
262
263 # Expand :: in an IPv6 address or address part consisting of `parts` groups.
264 expandIPv6 = (string, parts) ->
265   # More than one '::' means invalid adddress
266   if string.indexOf('::') != string.lastIndexOf('::')
267     return null
268
269   # How many parts do we already have?
270   colonCount = 0
271   lastColon = -1
272   while (lastColon = string.indexOf(':', lastColon + 1)) >= 0
273     colonCount++
274
275   # 0::0 is two parts more than ::
276   colonCount-- if string[0] == ':'
277   colonCount-- if string[string.length-1] == ':'
278
279   # replacement = ':' + '0:' * (parts - colonCount)
280   replacementCount = parts - colonCount
281   replacement = ':'
282   while replacementCount--
283     replacement += '0:'
284
285   # Insert the missing zeroes
286   string = string.replace('::', replacement)
287
288   # Trim any garbage which may be hanging around if :: was at the edge in
289   # the source string
290   string = string[1..-1] if string[0] == ':'
291   string = string[0..-2] if string[string.length-1] == ':'
292
293   return (parseInt(part, 16) for part in string.split(":"))
294
295 # Parse an IPv6 address.
296 ipaddr.IPv6.parser = (string) ->
297   if string.match(ipv6Regexes['native'])
298     return expandIPv6(string, 8)
299
300   else if match = string.match(ipv6Regexes['transitional'])
301     parts = expandIPv6(match[1][0..-2], 6)
302     if parts
303       parts.push(parseInt(match[2]) << 8 | parseInt(match[3]))
304       parts.push(parseInt(match[4]) << 8 | parseInt(match[5]))
305       return parts
306
307   return null
308
309 # Checks if a given string is formatted like IPv4/IPv6 address.
310 ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = (string) ->
311   return @parser(string) != null
312
313 # Checks if a given string is a valid IPv4/IPv6 address.
314 ipaddr.IPv4.isValid = ipaddr.IPv6.isValid = (string) ->
315   try
316     new this(@parser(string))
317     return true
318   catch e
319     return false
320
321 # Tries to parse and validate a string with IPv4/IPv6 address.
322 # Throws an error if it fails.
323 ipaddr.IPv4.parse = ipaddr.IPv6.parse = (string) ->
324   parts = @parser(string)
325   if parts == null
326     throw new Error "ipaddr: string is not formatted like ip address"
327
328   return new this(parts)
329
330 # Checks if the address is valid IP address
331 ipaddr.isValid = (string) ->
332   return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string)
333
334 # Try to parse an address and throw an error if it is impossible
335 ipaddr.parse = (string) ->
336   if ipaddr.IPv6.isValid(string)
337     return ipaddr.IPv6.parse(string)
338   else if ipaddr.IPv4.isValid(string)
339     return ipaddr.IPv4.parse(string)
340   else
341     throw new Error "ipaddr: the address has neither IPv6 nor IPv4 format"
342
343 # Parse an address and return plain IPv4 address if it is an IPv4-mapped address
344 ipaddr.process = (string) ->
345   addr = @parse(string)
346   if addr.kind() == 'ipv6' && addr.isIPv4MappedAddress()
347     return addr.toIPv4Address()
348   else
349     return addr