ipaddr.coffee 11 KB

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