1// Copyright 2009 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5// IP address manipulations
6//
7// IPv4 addresses are 4 bytes; IPv6 addresses are 16 bytes.
8// An IPv4 address can be converted to an IPv6 address by
9// adding a canonical prefix (10 zeros, 2 0xFFs).
10// This library accepts either size of byte slice but always
11// returns 16-byte addresses.
12
13package net
14
15// IP address lengths (bytes).
16const (
17	IPv4len = 4
18	IPv6len = 16
19)
20
21// An IP is a single IP address, a slice of bytes.
22// Functions in this package accept either 4-byte (IPv4)
23// or 16-byte (IPv6) slices as input.
24//
25// Note that in this documentation, referring to an
26// IP address as an IPv4 address or an IPv6 address
27// is a semantic property of the address, not just the
28// length of the byte slice: a 16-byte slice can still
29// be an IPv4 address.
30type IP []byte
31
32// An IP mask is an IP address.
33type IPMask []byte
34
35// An IPNet represents an IP network.
36type IPNet struct {
37	IP   IP     // network number
38	Mask IPMask // network mask
39	Zone string // IPv6 scoped addressing zone
40}
41
42// IPv4 returns the IP address (in 16-byte form) of the
43// IPv4 address a.b.c.d.
44func IPv4(a, b, c, d byte) IP {
45	p := make(IP, IPv6len)
46	copy(p, v4InV6Prefix)
47	p[12] = a
48	p[13] = b
49	p[14] = c
50	p[15] = d
51	return p
52}
53
54var v4InV6Prefix = []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff}
55
56// IPv4Mask returns the IP mask (in 4-byte form) of the
57// IPv4 mask a.b.c.d.
58func IPv4Mask(a, b, c, d byte) IPMask {
59	p := make(IPMask, IPv4len)
60	p[0] = a
61	p[1] = b
62	p[2] = c
63	p[3] = d
64	return p
65}
66
67// CIDRMask returns an IPMask consisting of `ones' 1 bits
68// followed by 0s up to a total length of `bits' bits.
69// For a mask of this form, CIDRMask is the inverse of IPMask.Size.
70func CIDRMask(ones, bits int) IPMask {
71	if bits != 8*IPv4len && bits != 8*IPv6len {
72		return nil
73	}
74	if ones < 0 || ones > bits {
75		return nil
76	}
77	l := bits / 8
78	m := make(IPMask, l)
79	n := uint(ones)
80	for i := 0; i < l; i++ {
81		if n >= 8 {
82			m[i] = 0xff
83			n -= 8
84			continue
85		}
86		m[i] = ^byte(0xff >> n)
87		n = 0
88	}
89	return m
90}
91
92// Well-known IPv4 addresses
93var (
94	IPv4bcast     = IPv4(255, 255, 255, 255) // broadcast
95	IPv4allsys    = IPv4(224, 0, 0, 1)       // all systems
96	IPv4allrouter = IPv4(224, 0, 0, 2)       // all routers
97	IPv4zero      = IPv4(0, 0, 0, 0)         // all zeros
98)
99
100// Well-known IPv6 addresses
101var (
102	IPv6zero                   = IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
103	IPv6unspecified            = IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
104	IPv6loopback               = IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}
105	IPv6interfacelocalallnodes = IP{0xff, 0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x01}
106	IPv6linklocalallnodes      = IP{0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x01}
107	IPv6linklocalallrouters    = IP{0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x02}
108)
109
110// IsUnspecified returns true if ip is an unspecified address.
111func (ip IP) IsUnspecified() bool {
112	if ip.Equal(IPv4zero) || ip.Equal(IPv6unspecified) {
113		return true
114	}
115	return false
116}
117
118// IsLoopback returns true if ip is a loopback address.
119func (ip IP) IsLoopback() bool {
120	if ip4 := ip.To4(); ip4 != nil && ip4[0] == 127 {
121		return true
122	}
123	return ip.Equal(IPv6loopback)
124}
125
126// IsMulticast returns true if ip is a multicast address.
127func (ip IP) IsMulticast() bool {
128	if ip4 := ip.To4(); ip4 != nil && ip4[0]&0xf0 == 0xe0 {
129		return true
130	}
131	return ip[0] == 0xff
132}
133
134// IsInterfaceLinkLocalMulticast returns true if ip is
135// an interface-local multicast address.
136func (ip IP) IsInterfaceLocalMulticast() bool {
137	return len(ip) == IPv6len && ip[0] == 0xff && ip[1]&0x0f == 0x01
138}
139
140// IsLinkLocalMulticast returns true if ip is a link-local
141// multicast address.
142func (ip IP) IsLinkLocalMulticast() bool {
143	if ip4 := ip.To4(); ip4 != nil && ip4[0] == 224 && ip4[1] == 0 && ip4[2] == 0 {
144		return true
145	}
146	return ip[0] == 0xff && ip[1]&0x0f == 0x02
147}
148
149// IsLinkLocalUnicast returns true if ip is a link-local
150// unicast address.
151func (ip IP) IsLinkLocalUnicast() bool {
152	if ip4 := ip.To4(); ip4 != nil && ip4[0] == 169 && ip4[1] == 254 {
153		return true
154	}
155	return ip[0] == 0xfe && ip[1]&0xc0 == 0x80
156}
157
158// IsGlobalUnicast returns true if ip is a global unicast
159// address.
160func (ip IP) IsGlobalUnicast() bool {
161	return !ip.IsUnspecified() &&
162		!ip.IsLoopback() &&
163		!ip.IsMulticast() &&
164		!ip.IsLinkLocalUnicast()
165}
166
167// Is p all zeros?
168func isZeros(p IP) bool {
169	for i := 0; i < len(p); i++ {
170		if p[i] != 0 {
171			return false
172		}
173	}
174	return true
175}
176
177// To4 converts the IPv4 address ip to a 4-byte representation.
178// If ip is not an IPv4 address, To4 returns nil.
179func (ip IP) To4() IP {
180	if len(ip) == IPv4len {
181		return ip
182	}
183	if len(ip) == IPv6len &&
184		isZeros(ip[0:10]) &&
185		ip[10] == 0xff &&
186		ip[11] == 0xff {
187		return ip[12:16]
188	}
189	return nil
190}
191
192// To16 converts the IP address ip to a 16-byte representation.
193// If ip is not an IP address (it is the wrong length), To16 returns nil.
194func (ip IP) To16() IP {
195	if len(ip) == IPv4len {
196		return IPv4(ip[0], ip[1], ip[2], ip[3])
197	}
198	if len(ip) == IPv6len {
199		return ip
200	}
201	return nil
202}
203
204// Default route masks for IPv4.
205var (
206	classAMask = IPv4Mask(0xff, 0, 0, 0)
207	classBMask = IPv4Mask(0xff, 0xff, 0, 0)
208	classCMask = IPv4Mask(0xff, 0xff, 0xff, 0)
209)
210
211// DefaultMask returns the default IP mask for the IP address ip.
212// Only IPv4 addresses have default masks; DefaultMask returns
213// nil if ip is not a valid IPv4 address.
214func (ip IP) DefaultMask() IPMask {
215	if ip = ip.To4(); ip == nil {
216		return nil
217	}
218	switch true {
219	case ip[0] < 0x80:
220		return classAMask
221	case ip[0] < 0xC0:
222		return classBMask
223	default:
224		return classCMask
225	}
226	return nil // not reached
227}
228
229func allFF(b []byte) bool {
230	for _, c := range b {
231		if c != 0xff {
232			return false
233		}
234	}
235	return true
236}
237
238// Mask returns the result of masking the IP address ip with mask.
239func (ip IP) Mask(mask IPMask) IP {
240	if len(mask) == IPv6len && len(ip) == IPv4len && allFF(mask[:12]) {
241		mask = mask[12:]
242	}
243	if len(mask) == IPv4len && len(ip) == IPv6len && bytesEqual(ip[:12], v4InV6Prefix) {
244		ip = ip[12:]
245	}
246	n := len(ip)
247	if n != len(mask) {
248		return nil
249	}
250	out := make(IP, n)
251	for i := 0; i < n; i++ {
252		out[i] = ip[i] & mask[i]
253	}
254	return out
255}
256
257// String returns the string form of the IP address ip.
258// If the address is an IPv4 address, the string representation
259// is dotted decimal ("74.125.19.99").  Otherwise the representation
260// is IPv6 ("2001:4860:0:2001::68").
261func (ip IP) String() string {
262	p := ip
263
264	if len(ip) == 0 {
265		return "<nil>"
266	}
267
268	// If IPv4, use dotted notation.
269	if p4 := p.To4(); len(p4) == IPv4len {
270		return itod(uint(p4[0])) + "." +
271			itod(uint(p4[1])) + "." +
272			itod(uint(p4[2])) + "." +
273			itod(uint(p4[3]))
274	}
275	if len(p) != IPv6len {
276		return "?"
277	}
278
279	// Find longest run of zeros.
280	e0 := -1
281	e1 := -1
282	for i := 0; i < IPv6len; i += 2 {
283		j := i
284		for j < IPv6len && p[j] == 0 && p[j+1] == 0 {
285			j += 2
286		}
287		if j > i && j-i > e1-e0 {
288			e0 = i
289			e1 = j
290		}
291	}
292	// The symbol "::" MUST NOT be used to shorten just one 16 bit 0 field.
293	if e1-e0 <= 2 {
294		e0 = -1
295		e1 = -1
296	}
297
298	// Print with possible :: in place of run of zeros
299	var s string
300	for i := 0; i < IPv6len; i += 2 {
301		if i == e0 {
302			s += "::"
303			i = e1
304			if i >= IPv6len {
305				break
306			}
307		} else if i > 0 {
308			s += ":"
309		}
310		s += itox((uint(p[i])<<8)|uint(p[i+1]), 1)
311	}
312	return s
313}
314
315// Equal returns true if ip and x are the same IP address.
316// An IPv4 address and that same address in IPv6 form are
317// considered to be equal.
318func (ip IP) Equal(x IP) bool {
319	if len(ip) == len(x) {
320		return bytesEqual(ip, x)
321	}
322	if len(ip) == IPv4len && len(x) == IPv6len {
323		return bytesEqual(x[0:12], v4InV6Prefix) && bytesEqual(ip, x[12:])
324	}
325	if len(ip) == IPv6len && len(x) == IPv4len {
326		return bytesEqual(ip[0:12], v4InV6Prefix) && bytesEqual(ip[12:], x)
327	}
328	return false
329}
330
331func bytesEqual(x, y []byte) bool {
332	if len(x) != len(y) {
333		return false
334	}
335	for i, b := range x {
336		if y[i] != b {
337			return false
338		}
339	}
340	return true
341}
342
343// If mask is a sequence of 1 bits followed by 0 bits,
344// return the number of 1 bits.
345func simpleMaskLength(mask IPMask) int {
346	var n int
347	for i, v := range mask {
348		if v == 0xff {
349			n += 8
350			continue
351		}
352		// found non-ff byte
353		// count 1 bits
354		for v&0x80 != 0 {
355			n++
356			v <<= 1
357		}
358		// rest must be 0 bits
359		if v != 0 {
360			return -1
361		}
362		for i++; i < len(mask); i++ {
363			if mask[i] != 0 {
364				return -1
365			}
366		}
367		break
368	}
369	return n
370}
371
372// Size returns the number of leading ones and total bits in the mask.
373// If the mask is not in the canonical form--ones followed by zeros--then
374// Size returns 0, 0.
375func (m IPMask) Size() (ones, bits int) {
376	ones, bits = simpleMaskLength(m), len(m)*8
377	if ones == -1 {
378		return 0, 0
379	}
380	return
381}
382
383// String returns the hexadecimal form of m, with no punctuation.
384func (m IPMask) String() string {
385	s := ""
386	for _, b := range m {
387		s += itox(uint(b), 2)
388	}
389	if len(s) == 0 {
390		return "<nil>"
391	}
392	return s
393}
394
395func networkNumberAndMask(n *IPNet) (ip IP, m IPMask) {
396	if ip = n.IP.To4(); ip == nil {
397		ip = n.IP
398		if len(ip) != IPv6len {
399			return nil, nil
400		}
401	}
402	m = n.Mask
403	switch len(m) {
404	case IPv4len:
405		if len(ip) != IPv4len {
406			return nil, nil
407		}
408	case IPv6len:
409		if len(ip) == IPv4len {
410			m = m[12:]
411		}
412	default:
413		return nil, nil
414	}
415	return
416}
417
418// Contains reports whether the network includes ip.
419func (n *IPNet) Contains(ip IP) bool {
420	nn, m := networkNumberAndMask(n)
421	if x := ip.To4(); x != nil {
422		ip = x
423	}
424	l := len(ip)
425	if l != len(nn) {
426		return false
427	}
428	for i := 0; i < l; i++ {
429		if nn[i]&m[i] != ip[i]&m[i] {
430			return false
431		}
432	}
433	return true
434}
435
436// String returns the CIDR notation of n like "192.168.100.1/24"
437// or "2001:DB8::/48" as defined in RFC 4632 and RFC 4291.
438// If the mask is not in the canonical form, it returns the
439// string which consists of an IP address, followed by a slash
440// character and a mask expressed as hexadecimal form with no
441// punctuation like "192.168.100.1/c000ff00".
442func (n *IPNet) String() string {
443	nn, m := networkNumberAndMask(n)
444	if nn == nil || m == nil {
445		return "<nil>"
446	}
447	l := simpleMaskLength(m)
448	if l == -1 {
449		return nn.String() + "/" + m.String()
450	}
451	return nn.String() + "/" + itod(uint(l))
452}
453
454// Network returns the address's network name, "ip+net".
455func (n *IPNet) Network() string { return "ip+net" }
456
457// Parse IPv4 address (d.d.d.d).
458func parseIPv4(s string) IP {
459	var p [IPv4len]byte
460	i := 0
461	for j := 0; j < IPv4len; j++ {
462		if i >= len(s) {
463			// Missing octets.
464			return nil
465		}
466		if j > 0 {
467			if s[i] != '.' {
468				return nil
469			}
470			i++
471		}
472		var (
473			n  int
474			ok bool
475		)
476		n, i, ok = dtoi(s, i)
477		if !ok || n > 0xFF {
478			return nil
479		}
480		p[j] = byte(n)
481	}
482	if i != len(s) {
483		return nil
484	}
485	return IPv4(p[0], p[1], p[2], p[3])
486}
487
488// Parse IPv6 address.  Many forms.
489// The basic form is a sequence of eight colon-separated
490// 16-bit hex numbers separated by colons,
491// as in 0123:4567:89ab:cdef:0123:4567:89ab:cdef.
492// Two exceptions:
493//	* A run of zeros can be replaced with "::".
494//	* The last 32 bits can be in IPv4 form.
495// Thus, ::ffff:1.2.3.4 is the IPv4 address 1.2.3.4.
496func parseIPv6(s string) IP {
497	p := make(IP, IPv6len)
498	ellipsis := -1 // position of ellipsis in p
499	i := 0         // index in string s
500
501	// Might have leading ellipsis
502	if len(s) >= 2 && s[0] == ':' && s[1] == ':' {
503		ellipsis = 0
504		i = 2
505		// Might be only ellipsis
506		if i == len(s) {
507			return p
508		}
509	}
510
511	// Loop, parsing hex numbers followed by colon.
512	j := 0
513	for j < IPv6len {
514		// Hex number.
515		n, i1, ok := xtoi(s, i)
516		if !ok || n > 0xFFFF {
517			return nil
518		}
519
520		// If followed by dot, might be in trailing IPv4.
521		if i1 < len(s) && s[i1] == '.' {
522			if ellipsis < 0 && j != IPv6len-IPv4len {
523				// Not the right place.
524				return nil
525			}
526			if j+IPv4len > IPv6len {
527				// Not enough room.
528				return nil
529			}
530			p4 := parseIPv4(s[i:])
531			if p4 == nil {
532				return nil
533			}
534			p[j] = p4[12]
535			p[j+1] = p4[13]
536			p[j+2] = p4[14]
537			p[j+3] = p4[15]
538			i = len(s)
539			j += IPv4len
540			break
541		}
542
543		// Save this 16-bit chunk.
544		p[j] = byte(n >> 8)
545		p[j+1] = byte(n)
546		j += 2
547
548		// Stop at end of string.
549		i = i1
550		if i == len(s) {
551			break
552		}
553
554		// Otherwise must be followed by colon and more.
555		if s[i] != ':' || i+1 == len(s) {
556			return nil
557		}
558		i++
559
560		// Look for ellipsis.
561		if s[i] == ':' {
562			if ellipsis >= 0 { // already have one
563				return nil
564			}
565			ellipsis = j
566			if i++; i == len(s) { // can be at end
567				break
568			}
569		}
570	}
571
572	// Must have used entire string.
573	if i != len(s) {
574		return nil
575	}
576
577	// If didn't parse enough, expand ellipsis.
578	if j < IPv6len {
579		if ellipsis < 0 {
580			return nil
581		}
582		n := IPv6len - j
583		for k := j - 1; k >= ellipsis; k-- {
584			p[k+n] = p[k]
585		}
586		for k := ellipsis + n - 1; k >= ellipsis; k-- {
587			p[k] = 0
588		}
589	}
590	return p
591}
592
593// A ParseError represents a malformed text string and the type of string that was expected.
594type ParseError struct {
595	Type string
596	Text string
597}
598
599func (e *ParseError) Error() string {
600	return "invalid " + e.Type + ": " + e.Text
601}
602
603func parseIP(s string) IP {
604	if p := parseIPv4(s); p != nil {
605		return p
606	}
607	if p := parseIPv6(s); p != nil {
608		return p
609	}
610	return nil
611}
612
613// ParseIP parses s as an IP address, returning the result.
614// The string s can be in dotted decimal ("74.125.19.99")
615// or IPv6 ("2001:4860:0:2001::68") form.
616// If s is not a valid textual representation of an IP address,
617// ParseIP returns nil.
618func ParseIP(s string) IP {
619	if p := parseIPv4(s); p != nil {
620		return p
621	}
622	return parseIPv6(s)
623}
624
625// ParseCIDR parses s as a CIDR notation IP address and mask,
626// like "192.168.100.1/24" or "2001:DB8::/48", as defined in
627// RFC 4632 and RFC 4291.
628//
629// It returns the IP address and the network implied by the IP
630// and mask.  For example, ParseCIDR("192.168.100.1/16") returns
631// the IP address 192.168.100.1 and the network 192.168.0.0/16.
632func ParseCIDR(s string) (IP, *IPNet, error) {
633	i := byteIndex(s, '/')
634	if i < 0 {
635		return nil, nil, &ParseError{"CIDR address", s}
636	}
637	ipstr, maskstr := s[:i], s[i+1:]
638	iplen := IPv4len
639	ip := parseIPv4(ipstr)
640	if ip == nil {
641		iplen = IPv6len
642		ip = parseIPv6(ipstr)
643	}
644	n, i, ok := dtoi(maskstr, 0)
645	if ip == nil || !ok || i != len(maskstr) || n < 0 || n > 8*iplen {
646		return nil, nil, &ParseError{"CIDR address", s}
647	}
648	m := CIDRMask(n, 8*iplen)
649	return ip, &IPNet{IP: ip.Mask(m), Mask: m}, nil
650}
651