MediaWiki REL1_34
IP.php
Go to the documentation of this file.
1<?php
24use Wikimedia\IPSet;
25
26// Some regex definition to "play" with IP address and IP address ranges
27
28// An IPv4 address is made of 4 bytes from x00 to xFF which is d0 to d255
29define( 'RE_IP_BYTE', '(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])' );
30define( 'RE_IP_ADD', RE_IP_BYTE . '\.' . RE_IP_BYTE . '\.' . RE_IP_BYTE . '\.' . RE_IP_BYTE );
31// An IPv4 range is an IP address and a prefix (d1 to d32)
32define( 'RE_IP_PREFIX', '(3[0-2]|[12]?\d)' );
33define( 'RE_IP_RANGE', RE_IP_ADD . '\/' . RE_IP_PREFIX );
34
35// An IPv6 address is made up of 8 words (each x0000 to xFFFF).
36// However, the "::" abbreviation can be used on consecutive x0000 words.
37define( 'RE_IPV6_WORD', '([0-9A-Fa-f]{1,4})' );
38define( 'RE_IPV6_PREFIX', '(12[0-8]|1[01][0-9]|[1-9]?\d)' );
39define( 'RE_IPV6_ADD',
40 '(?:' . // starts with "::" (including "::")
41 ':(?::|(?::' . RE_IPV6_WORD . '){1,7})' .
42 '|' . // ends with "::" (except "::")
43 RE_IPV6_WORD . '(?::' . RE_IPV6_WORD . '){0,6}::' .
44 '|' . // contains one "::" in the middle (the ^ makes the test fail if none found)
45 RE_IPV6_WORD . '(?::((?(-1)|:))?' . RE_IPV6_WORD . '){1,6}(?(-2)|^)' .
46 '|' . // contains no "::"
47 RE_IPV6_WORD . '(?::' . RE_IPV6_WORD . '){7}' .
48 ')'
49);
50// An IPv6 range is an IP address and a prefix (d1 to d128)
51define( 'RE_IPV6_RANGE', RE_IPV6_ADD . '\/' . RE_IPV6_PREFIX );
52// For IPv6 canonicalization (NOT for strict validation; these are quite lax!)
53define( 'RE_IPV6_GAP', ':(?:0+:)*(?::(?:0+:)*)?' );
54define( 'RE_IPV6_V4_PREFIX', '0*' . RE_IPV6_GAP . '(?:ffff:)?' );
55
56// This might be useful for regexps used elsewhere, matches any IPv4 or IPv6 address or network
57define( 'IP_ADDRESS_STRING',
58 '(?:' .
59 RE_IP_ADD . '(?:\/' . RE_IP_PREFIX . ')?' . // IPv4
60 '|' .
61 RE_IPV6_ADD . '(?:\/' . RE_IPV6_PREFIX . ')?' . // IPv6
62 ')'
63);
64
69class IP {
70
79 public static function isIPAddress( $ip ) {
80 return (bool)preg_match( '/^' . IP_ADDRESS_STRING . '$/', $ip );
81 }
82
90 public static function isIPv6( $ip ) {
91 return (bool)preg_match( '/^' . RE_IPV6_ADD . '(?:\/' . RE_IPV6_PREFIX . ')?$/', $ip );
92 }
93
101 public static function isIPv4( $ip ) {
102 return (bool)preg_match( '/^' . RE_IP_ADD . '(?:\/' . RE_IP_PREFIX . ')?$/', $ip );
103 }
104
113 public static function isValid( $ip ) {
114 return ( preg_match( '/^' . RE_IP_ADD . '$/', $ip )
115 || preg_match( '/^' . RE_IPV6_ADD . '$/', $ip ) );
116 }
117
127 public static function isValidRange( $ipRange ) {
128 return ( preg_match( '/^' . RE_IPV6_RANGE . '$/', $ipRange )
129 || preg_match( '/^' . RE_IP_RANGE . '$/', $ipRange ) );
130 }
131
141 public static function sanitizeIP( $ip ) {
142 $ip = trim( $ip );
143 if ( $ip === '' ) {
144 return null;
145 }
146 /* If not an IP, just return trimmed value, since sanitizeIP() is called
147 * in a number of contexts where usernames are supplied as input.
148 */
149 if ( !self::isIPAddress( $ip ) ) {
150 return $ip;
151 }
152 if ( self::isIPv4( $ip ) ) {
153 // Remove leading 0's from octet representation of IPv4 address
154 $ip = preg_replace( '!(?:^|(?<=\.))0+(?=[1-9]|0[./]|0$)!', '', $ip );
155 return $ip;
156 }
157 // Remove any whitespaces, convert to upper case
158 $ip = strtoupper( $ip );
159 // Expand zero abbreviations
160 $abbrevPos = strpos( $ip, '::' );
161 if ( $abbrevPos !== false ) {
162 // We know this is valid IPv6. Find the last index of the
163 // address before any CIDR number (e.g. "a:b:c::/24").
164 $CIDRStart = strpos( $ip, "/" );
165 $addressEnd = ( $CIDRStart !== false )
166 ? $CIDRStart - 1
167 : strlen( $ip ) - 1;
168 // If the '::' is at the beginning...
169 if ( $abbrevPos == 0 ) {
170 $repeat = '0:';
171 $extra = ( $ip == '::' ) ? '0' : ''; // for the address '::'
172 $pad = 9; // 7+2 (due to '::')
173 // If the '::' is at the end...
174 } elseif ( $abbrevPos == ( $addressEnd - 1 ) ) {
175 $repeat = ':0';
176 $extra = '';
177 $pad = 9; // 7+2 (due to '::')
178 // If the '::' is in the middle...
179 } else {
180 $repeat = ':0';
181 $extra = ':';
182 $pad = 8; // 6+2 (due to '::')
183 }
184 $ip = str_replace( '::',
185 str_repeat( $repeat, $pad - substr_count( $ip, ':' ) ) . $extra,
186 $ip
187 );
188 }
189 // Remove leading zeros from each bloc as needed
190 $ip = preg_replace( '/(^|:)0+(' . RE_IPV6_WORD . ')/', '$1$2', $ip );
191
192 return $ip;
193 }
194
202 public static function prettifyIP( $ip ) {
203 $ip = self::sanitizeIP( $ip ); // normalize (removes '::')
204 if ( self::isIPv6( $ip ) ) {
205 // Split IP into an address and a CIDR
206 if ( strpos( $ip, '/' ) !== false ) {
207 list( $ip, $cidr ) = explode( '/', $ip, 2 );
208 } else {
209 list( $ip, $cidr ) = [ $ip, '' ];
210 }
211 // Get the largest slice of words with multiple zeros
212 $offset = 0;
213 $longest = $longestPos = false;
214 while ( preg_match(
215 '!(?:^|:)0(?::0)+(?:$|:)!', $ip, $m, PREG_OFFSET_CAPTURE, $offset
216 ) ) {
217 list( $match, $pos ) = $m[0]; // full match
218 if ( strlen( $match ) > strlen( $longest ) ) {
219 $longest = $match;
220 $longestPos = $pos;
221 }
222 $offset = ( $pos + strlen( $match ) ); // advance
223 }
224 if ( $longest !== false ) {
225 // Replace this portion of the string with the '::' abbreviation
226 $ip = substr_replace( $ip, '::', $longestPos, strlen( $longest ) );
227 }
228 // Add any CIDR back on
229 if ( $cidr !== '' ) {
230 $ip = "{$ip}/{$cidr}";
231 }
232 // Convert to lower case to make it more readable
233 $ip = strtolower( $ip );
234 }
235
236 return $ip;
237 }
238
255 public static function splitHostAndPort( $both ) {
256 if ( substr( $both, 0, 1 ) === '[' ) {
257 if ( preg_match( '/^\[(' . RE_IPV6_ADD . ')\](?::(?P<port>\d+))?$/', $both, $m ) ) {
258 if ( isset( $m['port'] ) ) {
259 return [ $m[1], intval( $m['port'] ) ];
260 } else {
261 return [ $m[1], false ];
262 }
263 } else {
264 // Square bracket found but no IPv6
265 return false;
266 }
267 }
268 $numColons = substr_count( $both, ':' );
269 if ( $numColons >= 2 ) {
270 // Is it a bare IPv6 address?
271 if ( preg_match( '/^' . RE_IPV6_ADD . '$/', $both ) ) {
272 return [ $both, false ];
273 } else {
274 // Not valid IPv6, but too many colons for anything else
275 return false;
276 }
277 }
278 if ( $numColons >= 1 ) {
279 // Host:port?
280 $bits = explode( ':', $both );
281 if ( preg_match( '/^\d+/', $bits[1] ) ) {
282 return [ $bits[0], intval( $bits[1] ) ];
283 } else {
284 // Not a valid port
285 return false;
286 }
287 }
288
289 // Plain hostname
290 return [ $both, false ];
291 }
292
304 public static function combineHostAndPort( $host, $port, $defaultPort = false ) {
305 if ( strpos( $host, ':' ) !== false ) {
306 $host = "[$host]";
307 }
308 if ( $defaultPort !== false && $port == $defaultPort ) {
309 return $host;
310 } else {
311 return "$host:$port";
312 }
313 }
314
321 public static function formatHex( $hex ) {
322 if ( substr( $hex, 0, 3 ) == 'v6-' ) { // IPv6
323 return self::hexToOctet( substr( $hex, 3 ) );
324 } else { // IPv4
325 return self::hexToQuad( $hex );
326 }
327 }
328
335 public static function hexToOctet( $ip_hex ) {
336 // Pad hex to 32 chars (128 bits)
337 $ip_hex = str_pad( strtoupper( $ip_hex ), 32, '0', STR_PAD_LEFT );
338 // Separate into 8 words
339 $ip_oct = substr( $ip_hex, 0, 4 );
340 for ( $n = 1; $n < 8; $n++ ) {
341 $ip_oct .= ':' . substr( $ip_hex, 4 * $n, 4 );
342 }
343 // NO leading zeroes
344 $ip_oct = preg_replace( '/(^|:)0+(' . RE_IPV6_WORD . ')/', '$1$2', $ip_oct );
345
346 return $ip_oct;
347 }
348
355 public static function hexToQuad( $ip_hex ) {
356 // Pad hex to 8 chars (32 bits)
357 $ip_hex = str_pad( strtoupper( $ip_hex ), 8, '0', STR_PAD_LEFT );
358 // Separate into four quads
359 $s = '';
360 for ( $i = 0; $i < 4; $i++ ) {
361 if ( $s !== '' ) {
362 $s .= '.';
363 }
364 $s .= base_convert( substr( $ip_hex, $i * 2, 2 ), 16, 10 );
365 }
366
367 return $s;
368 }
369
377 public static function isPublic( $ip ) {
378 static $privateSet = null;
379 if ( !$privateSet ) {
380 $privateSet = new IPSet( [
381 '10.0.0.0/8', # RFC 1918 (private)
382 '172.16.0.0/12', # RFC 1918 (private)
383 '192.168.0.0/16', # RFC 1918 (private)
384 '0.0.0.0/8', # this network
385 '127.0.0.0/8', # loopback
386 'fc00::/7', # RFC 4193 (local)
387 '0:0:0:0:0:0:0:1', # loopback
388 '169.254.0.0/16', # link-local
389 'fe80::/10', # link-local
390 ] );
391 }
392 return !$privateSet->match( $ip );
393 }
394
406 public static function toHex( $ip ) {
407 if ( self::isIPv6( $ip ) ) {
408 $n = 'v6-' . self::IPv6ToRawHex( $ip );
409 } elseif ( self::isIPv4( $ip ) ) {
410 // T62035/T97897: An IP with leading 0's fails in ip2long sometimes (e.g. *.08),
411 // also double/triple 0 needs to be changed to just a single 0 for ip2long.
412 $ip = self::sanitizeIP( $ip );
413 $n = ip2long( $ip );
414 if ( $n < 0 ) {
415 $n += 2 ** 32;
416 # On 32-bit platforms (and on Windows), 2^32 does not fit into an int,
417 # so $n becomes a float. We convert it to string instead.
418 if ( is_float( $n ) ) {
419 $n = (string)$n;
420 }
421 }
422 if ( $n !== false ) {
423 # Floating points can handle the conversion; faster than Wikimedia\base_convert()
424 $n = strtoupper( str_pad( base_convert( $n, 10, 16 ), 8, '0', STR_PAD_LEFT ) );
425 }
426 } else {
427 $n = false;
428 }
429
430 return $n;
431 }
432
439 private static function IPv6ToRawHex( $ip ) {
440 $ip = self::sanitizeIP( $ip );
441 if ( !$ip ) {
442 return false;
443 }
444 $r_ip = '';
445 foreach ( explode( ':', $ip ) as $v ) {
446 $r_ip .= str_pad( $v, 4, 0, STR_PAD_LEFT );
447 }
448
449 return $r_ip;
450 }
451
459 public static function parseCIDR( $range ) {
460 if ( self::isIPv6( $range ) ) {
461 return self::parseCIDR6( $range );
462 }
463 $parts = explode( '/', $range, 2 );
464 if ( count( $parts ) != 2 ) {
465 return [ false, false ];
466 }
467 list( $network, $bits ) = $parts;
468 $network = ip2long( $network );
469 if ( $network !== false && is_numeric( $bits ) && $bits >= 0 && $bits <= 32 ) {
470 if ( $bits == 0 ) {
471 $network = 0;
472 } else {
473 $network &= ~( ( 1 << ( 32 - $bits ) ) - 1 );
474 }
475 # Convert to unsigned
476 if ( $network < 0 ) {
477 $network += 2 ** 32;
478 }
479 } else {
480 $network = false;
481 $bits = false;
482 }
483
484 return [ $network, $bits ];
485 }
486
502 public static function parseRange( $range ) {
503 // CIDR notation
504 if ( strpos( $range, '/' ) !== false ) {
505 if ( self::isIPv6( $range ) ) {
506 return self::parseRange6( $range );
507 }
508 list( $network, $bits ) = self::parseCIDR( $range );
509 if ( $network === false ) {
510 $start = $end = false;
511 } else {
512 $start = sprintf( '%08X', $network );
513 $end = sprintf( '%08X', $network + 2 ** ( 32 - $bits ) - 1 );
514 }
515 // Explicit range
516 } elseif ( strpos( $range, '-' ) !== false ) {
517 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
518 if ( self::isIPv6( $start ) && self::isIPv6( $end ) ) {
519 return self::parseRange6( $range );
520 }
521 if ( self::isIPv4( $start ) && self::isIPv4( $end ) ) {
522 $start = self::toHex( $start );
523 $end = self::toHex( $end );
524 if ( $start > $end ) {
525 $start = $end = false;
526 }
527 } else {
528 $start = $end = false;
529 }
530 } else {
531 # Single IP
532 $start = $end = self::toHex( $range );
533 }
534 if ( $start === false || $end === false ) {
535 return [ false, false ];
536 } else {
537 return [ $start, $end ];
538 }
539 }
540
549 private static function parseCIDR6( $range ) {
550 # Explode into <expanded IP,range>
551 $parts = explode( '/', self::sanitizeIP( $range ), 2 );
552 if ( count( $parts ) != 2 ) {
553 return [ false, false ];
554 }
555 list( $network, $bits ) = $parts;
556 $network = self::IPv6ToRawHex( $network );
557 if ( $network !== false && is_numeric( $bits ) && $bits >= 0 && $bits <= 128 ) {
558 if ( $bits == 0 ) {
559 $network = "0";
560 } else {
561 # Native 32 bit functions WONT work here!!!
562 # Convert to a padded binary number
563 $network = Wikimedia\base_convert( $network, 16, 2, 128 );
564 # Truncate the last (128-$bits) bits and replace them with zeros
565 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT );
566 # Convert back to an integer
567 $network = Wikimedia\base_convert( $network, 2, 10 );
568 }
569 } else {
570 $network = false;
571 $bits = false;
572 }
573
574 return [ $network, (int)$bits ];
575 }
576
590 private static function parseRange6( $range ) {
591 # Expand any IPv6 IP
592 $range = self::sanitizeIP( $range );
593 // CIDR notation...
594 if ( strpos( $range, '/' ) !== false ) {
595 list( $network, $bits ) = self::parseCIDR6( $range );
596 if ( $network === false ) {
597 $start = $end = false;
598 } else {
599 $start = Wikimedia\base_convert( $network, 10, 16, 32, false );
600 # Turn network to binary (again)
601 $end = Wikimedia\base_convert( $network, 10, 2, 128 );
602 # Truncate the last (128-$bits) bits and replace them with ones
603 $end = str_pad( substr( $end, 0, $bits ), 128, 1, STR_PAD_RIGHT );
604 # Convert to hex
605 $end = Wikimedia\base_convert( $end, 2, 16, 32, false );
606 # see toHex() comment
607 $start = "v6-$start";
608 $end = "v6-$end";
609 }
610 // Explicit range notation...
611 } elseif ( strpos( $range, '-' ) !== false ) {
612 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
613 $start = self::toHex( $start );
614 $end = self::toHex( $end );
615 if ( $start > $end ) {
616 $start = $end = false;
617 }
618 } else {
619 # Single IP
620 $start = $end = self::toHex( $range );
621 }
622 if ( $start === false || $end === false ) {
623 return [ false, false ];
624 } else {
625 return [ $start, $end ];
626 }
627 }
628
639 public static function isInRange( $addr, $range ) {
640 $hexIP = self::toHex( $addr );
641 list( $start, $end ) = self::parseRange( $range );
642
643 return ( strcmp( $hexIP, $start ) >= 0 &&
644 strcmp( $hexIP, $end ) <= 0 );
645 }
646
657 public static function isInRanges( $ip, $ranges ) {
658 foreach ( $ranges as $range ) {
659 if ( self::isInRange( $ip, $range ) ) {
660 return true;
661 }
662 }
663 return false;
664 }
665
676 public static function canonicalize( $addr ) {
677 // remove zone info (T37738)
678 $addr = preg_replace( '/\%.*/', '', $addr );
679
680 if ( self::isValid( $addr ) ) {
681 return $addr;
682 }
683 // Turn mapped addresses from ::ce:ffff:1.2.3.4 to 1.2.3.4
684 if ( strpos( $addr, ':' ) !== false && strpos( $addr, '.' ) !== false ) {
685 $addr = substr( $addr, strrpos( $addr, ':' ) + 1 );
686 if ( self::isIPv4( $addr ) ) {
687 return $addr;
688 }
689 }
690 // IPv6 loopback address
691 $m = [];
692 if ( preg_match( '/^0*' . RE_IPV6_GAP . '1$/', $addr, $m ) ) {
693 return '127.0.0.1';
694 }
695 // IPv4-mapped and IPv4-compatible IPv6 addresses
696 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX . '(' . RE_IP_ADD . ')$/i', $addr, $m ) ) {
697 return $m[1];
698 }
699 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX . RE_IPV6_WORD .
700 ':' . RE_IPV6_WORD . '$/i', $addr, $m )
701 ) {
702 return long2ip( ( hexdec( $m[1] ) << 16 ) + hexdec( $m[2] ) );
703 }
704
705 return null; // give up
706 }
707
714 public static function sanitizeRange( $range ) {
715 list( /*...*/, $bits ) = self::parseCIDR( $range );
716 list( $start, /*...*/ ) = self::parseRange( $range );
717 $start = self::formatHex( $start );
718 if ( $bits === false ) {
719 return $start; // wasn't actually a range
720 }
721
722 return "$start/$bits";
723 }
724
731 public static function getSubnet( $ip ) {
732 $matches = [];
733 $subnet = false;
734 if ( self::isIPv6( $ip ) ) {
735 $parts = self::parseRange( "$ip/64" );
736 $subnet = $parts[0];
737 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
738 // IPv4
739 $subnet = $matches[1];
740 }
741 return $subnet;
742 }
743}
const RE_IPV6_WORD
Definition IP.php:37
const RE_IP_BYTE
Definition IP.php:29
const RE_IPV6_GAP
Definition IP.php:52
const RE_IPV6_RANGE
Definition IP.php:50
const RE_IPV6_V4_PREFIX
Definition IP.php:53
const RE_IP_RANGE
Definition IP.php:33
const RE_IP_ADD
Definition IP.php:30
const RE_IP_PREFIX
Definition IP.php:32
const RE_IPV6_PREFIX
Definition IP.php:38
const RE_IPV6_ADD
Definition IP.php:39
const IP_ADDRESS_STRING
Definition IP.php:56
A collection of public static functions to play with IP address and IP ranges.
Definition IP.php:67
static combineHostAndPort( $host, $port, $defaultPort=false)
Given a host name and a port, combine them into host/port string like you might find in a URL.
Definition IP.php:302
static isValid( $ip)
Validate an IP address.
Definition IP.php:111
static prettifyIP( $ip)
Prettify an IP for display to end users.
Definition IP.php:200
static isIPv4( $ip)
Given a string, determine if it as valid IP in IPv4 only.
Definition IP.php:99
static parseRange( $range)
Given a string range in a number of formats, return the start and end of the range in hexadecimal.
Definition IP.php:500
static sanitizeIP( $ip)
Convert an IP into a verbose, uppercase, normalized form.
Definition IP.php:139
static formatHex( $hex)
Convert an IPv4 or IPv6 hexadecimal representation back to readable format.
Definition IP.php:319
static parseCIDR6( $range)
Convert a network specification in IPv6 CIDR notation to an integer network and a number of bits.
Definition IP.php:547
static IPv6ToRawHex( $ip)
Given an IPv6 address in octet notation, returns a pure hex string.
Definition IP.php:437
static canonicalize( $addr)
Convert some unusual representations of IPv4 addresses to their canonical dotted quad representation.
Definition IP.php:674
static getSubnet( $ip)
Returns the subnet of a given IP.
Definition IP.php:729
static parseRange6( $range)
Given a string range in a number of formats, return the start and end of the range in hexadecimal.
Definition IP.php:588
static sanitizeRange( $range)
Gets rid of unneeded numbers in quad-dotted/octet IP strings For example, 127.111....
Definition IP.php:712
static hexToQuad( $ip_hex)
Converts a hexadecimal number to an IPv4 address in quad-dotted notation.
Definition IP.php:353
static toHex( $ip)
Return a zero-padded upper case hexadecimal representation of an IP address.
Definition IP.php:404
static isPublic( $ip)
Determine if an IP address really is an IP address, and if it is public, i.e.
Definition IP.php:375
static hexToOctet( $ip_hex)
Converts a hexadecimal number to an IPv6 address in octet notation.
Definition IP.php:333
static isInRange( $addr, $range)
Determine if a given IPv4/IPv6 address is in a given CIDR network.
Definition IP.php:637
static isValidRange( $ipRange)
Validate an IP range (valid address with a valid CIDR prefix).
Definition IP.php:125
static isIPv6( $ip)
Given a string, determine if it as valid IP in IPv6 only.
Definition IP.php:88
static isInRanges( $ip, $ranges)
Determines if an IP address is a list of CIDR a.b.c.d/n ranges.
Definition IP.php:655
static parseCIDR( $range)
Convert a network specification in CIDR notation to an integer network and a number of bits.
Definition IP.php:457
static splitHostAndPort( $both)
Given a host/port string, like one might find in the host part of a URL per RFC 2732,...
Definition IP.php:253