MediaWiki  REL1_24
IP.php
Go to the documentation of this file.
00001 <?php
00024 // Some regex definition to "play" with IP address and IP address blocks
00025 
00026 // An IPv4 address is made of 4 bytes from x00 to xFF which is d0 to d255
00027 define( 'RE_IP_BYTE', '(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])' );
00028 define( 'RE_IP_ADD', RE_IP_BYTE . '\.' . RE_IP_BYTE . '\.' . RE_IP_BYTE . '\.' . RE_IP_BYTE );
00029 // An IPv4 block is an IP address and a prefix (d1 to d32)
00030 define( 'RE_IP_PREFIX', '(3[0-2]|[12]?\d)' );
00031 define( 'RE_IP_BLOCK', RE_IP_ADD . '\/' . RE_IP_PREFIX );
00032 
00033 // An IPv6 address is made up of 8 words (each x0000 to xFFFF).
00034 // However, the "::" abbreviation can be used on consecutive x0000 words.
00035 define( 'RE_IPV6_WORD', '([0-9A-Fa-f]{1,4})' );
00036 define( 'RE_IPV6_PREFIX', '(12[0-8]|1[01][0-9]|[1-9]?\d)' );
00037 define( 'RE_IPV6_ADD',
00038     '(?:' . // starts with "::" (including "::")
00039         ':(?::|(?::' . RE_IPV6_WORD . '){1,7})' .
00040     '|' . // ends with "::" (except "::")
00041         RE_IPV6_WORD . '(?::' . RE_IPV6_WORD . '){0,6}::' .
00042     '|' . // contains one "::" in the middle (the ^ makes the test fail if none found)
00043         RE_IPV6_WORD . '(?::((?(-1)|:))?' . RE_IPV6_WORD . '){1,6}(?(-2)|^)' .
00044     '|' . // contains no "::"
00045         RE_IPV6_WORD . '(?::' . RE_IPV6_WORD . '){7}' .
00046     ')'
00047 );
00048 // An IPv6 block is an IP address and a prefix (d1 to d128)
00049 define( 'RE_IPV6_BLOCK', RE_IPV6_ADD . '\/' . RE_IPV6_PREFIX );
00050 // For IPv6 canonicalization (NOT for strict validation; these are quite lax!)
00051 define( 'RE_IPV6_GAP', ':(?:0+:)*(?::(?:0+:)*)?' );
00052 define( 'RE_IPV6_V4_PREFIX', '0*' . RE_IPV6_GAP . '(?:ffff:)?' );
00053 
00054 // This might be useful for regexps used elsewhere, matches any IPv6 or IPv6 address or network
00055 define( 'IP_ADDRESS_STRING',
00056     '(?:' .
00057         RE_IP_ADD . '(?:\/' . RE_IP_PREFIX . ')?' . // IPv4
00058     '|' .
00059         RE_IPV6_ADD . '(?:\/' . RE_IPV6_PREFIX . ')?' . // IPv6
00060     ')'
00061 );
00062 
00067 class IP {
00069     private static $proxyIpSet = null;
00070 
00079     public static function isIPAddress( $ip ) {
00080         return (bool)preg_match( '/^' . IP_ADDRESS_STRING . '$/', $ip );
00081     }
00082 
00090     public static function isIPv6( $ip ) {
00091         return (bool)preg_match( '/^' . RE_IPV6_ADD . '(?:\/' . RE_IPV6_PREFIX . ')?$/', $ip );
00092     }
00093 
00101     public static function isIPv4( $ip ) {
00102         return (bool)preg_match( '/^' . RE_IP_ADD . '(?:\/' . RE_IP_PREFIX . ')?$/', $ip );
00103     }
00104 
00113     public static function isValid( $ip ) {
00114         return ( preg_match( '/^' . RE_IP_ADD . '$/', $ip )
00115             || preg_match( '/^' . RE_IPV6_ADD . '$/', $ip ) );
00116     }
00117 
00126     public static function isValidBlock( $ipblock ) {
00127         return ( preg_match( '/^' . RE_IPV6_BLOCK . '$/', $ipblock )
00128             || preg_match( '/^' . RE_IP_BLOCK . '$/', $ipblock ) );
00129     }
00130 
00139     public static function sanitizeIP( $ip ) {
00140         $ip = trim( $ip );
00141         if ( $ip === '' ) {
00142             return null;
00143         }
00144         if ( self::isIPv4( $ip ) || !self::isIPv6( $ip ) ) {
00145             return $ip; // nothing else to do for IPv4 addresses or invalid ones
00146         }
00147         // Remove any whitespaces, convert to upper case
00148         $ip = strtoupper( $ip );
00149         // Expand zero abbreviations
00150         $abbrevPos = strpos( $ip, '::' );
00151         if ( $abbrevPos !== false ) {
00152             // We know this is valid IPv6. Find the last index of the
00153             // address before any CIDR number (e.g. "a:b:c::/24").
00154             $CIDRStart = strpos( $ip, "/" );
00155             $addressEnd = ( $CIDRStart !== false )
00156                 ? $CIDRStart - 1
00157                 : strlen( $ip ) - 1;
00158             // If the '::' is at the beginning...
00159             if ( $abbrevPos == 0 ) {
00160                 $repeat = '0:';
00161                 $extra = ( $ip == '::' ) ? '0' : ''; // for the address '::'
00162                 $pad = 9; // 7+2 (due to '::')
00163             // If the '::' is at the end...
00164             } elseif ( $abbrevPos == ( $addressEnd - 1 ) ) {
00165                 $repeat = ':0';
00166                 $extra = '';
00167                 $pad = 9; // 7+2 (due to '::')
00168             // If the '::' is in the middle...
00169             } else {
00170                 $repeat = ':0';
00171                 $extra = ':';
00172                 $pad = 8; // 6+2 (due to '::')
00173             }
00174             $ip = str_replace( '::',
00175                 str_repeat( $repeat, $pad - substr_count( $ip, ':' ) ) . $extra,
00176                 $ip
00177             );
00178         }
00179         // Remove leading zeros from each bloc as needed
00180         $ip = preg_replace( '/(^|:)0+(' . RE_IPV6_WORD . ')/', '$1$2', $ip );
00181 
00182         return $ip;
00183     }
00184 
00192     public static function prettifyIP( $ip ) {
00193         $ip = self::sanitizeIP( $ip ); // normalize (removes '::')
00194         if ( self::isIPv6( $ip ) ) {
00195             // Split IP into an address and a CIDR
00196             if ( strpos( $ip, '/' ) !== false ) {
00197                 list( $ip, $cidr ) = explode( '/', $ip, 2 );
00198             } else {
00199                 list( $ip, $cidr ) = array( $ip, '' );
00200             }
00201             // Get the largest slice of words with multiple zeros
00202             $offset = 0;
00203             $longest = $longestPos = false;
00204             while ( preg_match(
00205                 '!(?:^|:)0(?::0)+(?:$|:)!', $ip, $m, PREG_OFFSET_CAPTURE, $offset
00206             ) ) {
00207                 list( $match, $pos ) = $m[0]; // full match
00208                 if ( strlen( $match ) > strlen( $longest ) ) {
00209                     $longest = $match;
00210                     $longestPos = $pos;
00211                 }
00212                 $offset = ( $pos + strlen( $match ) ); // advance
00213             }
00214             if ( $longest !== false ) {
00215                 // Replace this portion of the string with the '::' abbreviation
00216                 $ip = substr_replace( $ip, '::', $longestPos, strlen( $longest ) );
00217             }
00218             // Add any CIDR back on
00219             if ( $cidr !== '' ) {
00220                 $ip = "{$ip}/{$cidr}";
00221             }
00222             // Convert to lower case to make it more readable
00223             $ip = strtolower( $ip );
00224         }
00225 
00226         return $ip;
00227     }
00228 
00245     public static function splitHostAndPort( $both ) {
00246         if ( substr( $both, 0, 1 ) === '[' ) {
00247             if ( preg_match( '/^\[(' . RE_IPV6_ADD . ')\](?::(?P<port>\d+))?$/', $both, $m ) ) {
00248                 if ( isset( $m['port'] ) ) {
00249                     return array( $m[1], intval( $m['port'] ) );
00250                 } else {
00251                     return array( $m[1], false );
00252                 }
00253             } else {
00254                 // Square bracket found but no IPv6
00255                 return false;
00256             }
00257         }
00258         $numColons = substr_count( $both, ':' );
00259         if ( $numColons >= 2 ) {
00260             // Is it a bare IPv6 address?
00261             if ( preg_match( '/^' . RE_IPV6_ADD . '$/', $both ) ) {
00262                 return array( $both, false );
00263             } else {
00264                 // Not valid IPv6, but too many colons for anything else
00265                 return false;
00266             }
00267         }
00268         if ( $numColons >= 1 ) {
00269             // Host:port?
00270             $bits = explode( ':', $both );
00271             if ( preg_match( '/^\d+/', $bits[1] ) ) {
00272                 return array( $bits[0], intval( $bits[1] ) );
00273             } else {
00274                 // Not a valid port
00275                 return false;
00276             }
00277         }
00278 
00279         // Plain hostname
00280         return array( $both, false );
00281     }
00282 
00294     public static function combineHostAndPort( $host, $port, $defaultPort = false ) {
00295         if ( strpos( $host, ':' ) !== false ) {
00296             $host = "[$host]";
00297         }
00298         if ( $defaultPort !== false && $port == $defaultPort ) {
00299             return $host;
00300         } else {
00301             return "$host:$port";
00302         }
00303     }
00304 
00311     public static function formatHex( $hex ) {
00312         if ( substr( $hex, 0, 3 ) == 'v6-' ) { // IPv6
00313             return self::hexToOctet( substr( $hex, 3 ) );
00314         } else { // IPv4
00315             return self::hexToQuad( $hex );
00316         }
00317     }
00318 
00325     public static function hexToOctet( $ip_hex ) {
00326         // Pad hex to 32 chars (128 bits)
00327         $ip_hex = str_pad( strtoupper( $ip_hex ), 32, '0', STR_PAD_LEFT );
00328         // Separate into 8 words
00329         $ip_oct = substr( $ip_hex, 0, 4 );
00330         for ( $n = 1; $n < 8; $n++ ) {
00331             $ip_oct .= ':' . substr( $ip_hex, 4 * $n, 4 );
00332         }
00333         // NO leading zeroes
00334         $ip_oct = preg_replace( '/(^|:)0+(' . RE_IPV6_WORD . ')/', '$1$2', $ip_oct );
00335 
00336         return $ip_oct;
00337     }
00338 
00345     public static function hexToQuad( $ip_hex ) {
00346         // Pad hex to 8 chars (32 bits)
00347         $ip_hex = str_pad( strtoupper( $ip_hex ), 8, '0', STR_PAD_LEFT );
00348         // Separate into four quads
00349         $s = '';
00350         for ( $i = 0; $i < 4; $i++ ) {
00351             if ( $s !== '' ) {
00352                 $s .= '.';
00353             }
00354             $s .= base_convert( substr( $ip_hex, $i * 2, 2 ), 16, 10 );
00355         }
00356 
00357         return $s;
00358     }
00359 
00367     public static function isPublic( $ip ) {
00368         static $privateSet = null;
00369         if ( !$privateSet ) {
00370             $privateSet = new IPSet( array(
00371                 '10.0.0.0/8', # RFC 1918 (private)
00372                 '172.16.0.0/12', # RFC 1918 (private)
00373                 '192.168.0.0/16', # RFC 1918 (private)
00374                 '0.0.0.0/8', # this network
00375                 '127.0.0.0/8', # loopback
00376                 'fc00::/7', # RFC 4193 (local)
00377                 '0:0:0:0:0:0:0:1', # loopback
00378             ) );
00379         }
00380         return !$privateSet->match( $ip );
00381     }
00382 
00394     public static function toHex( $ip ) {
00395         if ( self::isIPv6( $ip ) ) {
00396             $n = 'v6-' . self::IPv6ToRawHex( $ip );
00397         } elseif ( self::isIPv4( $ip ) ) {
00398             // Bug 60035: an IP with leading 0's fails in ip2long sometimes (e.g. *.08)
00399             $ip = preg_replace( '/(?<=\.)0+(?=[1-9])/', '', $ip );
00400             $n = ip2long( $ip );
00401             if ( $n < 0 ) {
00402                 $n += pow( 2, 32 );
00403                 # On 32-bit platforms (and on Windows), 2^32 does not fit into an int,
00404                 # so $n becomes a float. We convert it to string instead.
00405                 if ( is_float( $n ) ) {
00406                     $n = (string)$n;
00407                 }
00408             }
00409             if ( $n !== false ) {
00410                 # Floating points can handle the conversion; faster than wfBaseConvert()
00411                 $n = strtoupper( str_pad( base_convert( $n, 10, 16 ), 8, '0', STR_PAD_LEFT ) );
00412             }
00413         } else {
00414             $n = false;
00415         }
00416 
00417         return $n;
00418     }
00419 
00426     private static function IPv6ToRawHex( $ip ) {
00427         $ip = self::sanitizeIP( $ip );
00428         if ( !$ip ) {
00429             return false;
00430         }
00431         $r_ip = '';
00432         foreach ( explode( ':', $ip ) as $v ) {
00433             $r_ip .= str_pad( $v, 4, 0, STR_PAD_LEFT );
00434         }
00435 
00436         return $r_ip;
00437     }
00438 
00446     public static function parseCIDR( $range ) {
00447         if ( self::isIPv6( $range ) ) {
00448             return self::parseCIDR6( $range );
00449         }
00450         $parts = explode( '/', $range, 2 );
00451         if ( count( $parts ) != 2 ) {
00452             return array( false, false );
00453         }
00454         list( $network, $bits ) = $parts;
00455         $network = ip2long( $network );
00456         if ( $network !== false && is_numeric( $bits ) && $bits >= 0 && $bits <= 32 ) {
00457             if ( $bits == 0 ) {
00458                 $network = 0;
00459             } else {
00460                 $network &= ~( ( 1 << ( 32 - $bits ) ) - 1 );
00461             }
00462             # Convert to unsigned
00463             if ( $network < 0 ) {
00464                 $network += pow( 2, 32 );
00465             }
00466         } else {
00467             $network = false;
00468             $bits = false;
00469         }
00470 
00471         return array( $network, $bits );
00472     }
00473 
00489     public static function parseRange( $range ) {
00490         // CIDR notation
00491         if ( strpos( $range, '/' ) !== false ) {
00492             if ( self::isIPv6( $range ) ) {
00493                 return self::parseRange6( $range );
00494             }
00495             list( $network, $bits ) = self::parseCIDR( $range );
00496             if ( $network === false ) {
00497                 $start = $end = false;
00498             } else {
00499                 $start = sprintf( '%08X', $network );
00500                 $end = sprintf( '%08X', $network + pow( 2, ( 32 - $bits ) ) - 1 );
00501             }
00502         // Explicit range
00503         } elseif ( strpos( $range, '-' ) !== false ) {
00504             list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
00505             if ( self::isIPv6( $start ) && self::isIPv6( $end ) ) {
00506                 return self::parseRange6( $range );
00507             }
00508             if ( self::isIPv4( $start ) && self::isIPv4( $end ) ) {
00509                 $start = self::toHex( $start );
00510                 $end = self::toHex( $end );
00511                 if ( $start > $end ) {
00512                     $start = $end = false;
00513                 }
00514             } else {
00515                 $start = $end = false;
00516             }
00517         } else {
00518             # Single IP
00519             $start = $end = self::toHex( $range );
00520         }
00521         if ( $start === false || $end === false ) {
00522             return array( false, false );
00523         } else {
00524             return array( $start, $end );
00525         }
00526     }
00527 
00536     private static function parseCIDR6( $range ) {
00537         # Explode into <expanded IP,range>
00538         $parts = explode( '/', IP::sanitizeIP( $range ), 2 );
00539         if ( count( $parts ) != 2 ) {
00540             return array( false, false );
00541         }
00542         list( $network, $bits ) = $parts;
00543         $network = self::IPv6ToRawHex( $network );
00544         if ( $network !== false && is_numeric( $bits ) && $bits >= 0 && $bits <= 128 ) {
00545             if ( $bits == 0 ) {
00546                 $network = "0";
00547             } else {
00548                 # Native 32 bit functions WONT work here!!!
00549                 # Convert to a padded binary number
00550                 $network = wfBaseConvert( $network, 16, 2, 128 );
00551                 # Truncate the last (128-$bits) bits and replace them with zeros
00552                 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT );
00553                 # Convert back to an integer
00554                 $network = wfBaseConvert( $network, 2, 10 );
00555             }
00556         } else {
00557             $network = false;
00558             $bits = false;
00559         }
00560 
00561         return array( $network, (int)$bits );
00562     }
00563 
00577     private static function parseRange6( $range ) {
00578         # Expand any IPv6 IP
00579         $range = IP::sanitizeIP( $range );
00580         // CIDR notation...
00581         if ( strpos( $range, '/' ) !== false ) {
00582             list( $network, $bits ) = self::parseCIDR6( $range );
00583             if ( $network === false ) {
00584                 $start = $end = false;
00585             } else {
00586                 $start = wfBaseConvert( $network, 10, 16, 32, false );
00587                 # Turn network to binary (again)
00588                 $end = wfBaseConvert( $network, 10, 2, 128 );
00589                 # Truncate the last (128-$bits) bits and replace them with ones
00590                 $end = str_pad( substr( $end, 0, $bits ), 128, 1, STR_PAD_RIGHT );
00591                 # Convert to hex
00592                 $end = wfBaseConvert( $end, 2, 16, 32, false );
00593                 # see toHex() comment
00594                 $start = "v6-$start";
00595                 $end = "v6-$end";
00596             }
00597         // Explicit range notation...
00598         } elseif ( strpos( $range, '-' ) !== false ) {
00599             list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
00600             $start = self::toHex( $start );
00601             $end = self::toHex( $end );
00602             if ( $start > $end ) {
00603                 $start = $end = false;
00604             }
00605         } else {
00606             # Single IP
00607             $start = $end = self::toHex( $range );
00608         }
00609         if ( $start === false || $end === false ) {
00610             return array( false, false );
00611         } else {
00612             return array( $start, $end );
00613         }
00614     }
00615 
00623     public static function isInRange( $addr, $range ) {
00624         $hexIP = self::toHex( $addr );
00625         list( $start, $end ) = self::parseRange( $range );
00626 
00627         return ( strcmp( $hexIP, $start ) >= 0 &&
00628             strcmp( $hexIP, $end ) <= 0 );
00629     }
00630 
00641     public static function canonicalize( $addr ) {
00642         // remove zone info (bug 35738)
00643         $addr = preg_replace( '/\%.*/', '', $addr );
00644 
00645         if ( self::isValid( $addr ) ) {
00646             return $addr;
00647         }
00648         // Turn mapped addresses from ::ce:ffff:1.2.3.4 to 1.2.3.4
00649         if ( strpos( $addr, ':' ) !== false && strpos( $addr, '.' ) !== false ) {
00650             $addr = substr( $addr, strrpos( $addr, ':' ) + 1 );
00651             if ( self::isIPv4( $addr ) ) {
00652                 return $addr;
00653             }
00654         }
00655         // IPv6 loopback address
00656         $m = array();
00657         if ( preg_match( '/^0*' . RE_IPV6_GAP . '1$/', $addr, $m ) ) {
00658             return '127.0.0.1';
00659         }
00660         // IPv4-mapped and IPv4-compatible IPv6 addresses
00661         if ( preg_match( '/^' . RE_IPV6_V4_PREFIX . '(' . RE_IP_ADD . ')$/i', $addr, $m ) ) {
00662             return $m[1];
00663         }
00664         if ( preg_match( '/^' . RE_IPV6_V4_PREFIX . RE_IPV6_WORD .
00665             ':' . RE_IPV6_WORD . '$/i', $addr, $m )
00666         ) {
00667             return long2ip( ( hexdec( $m[1] ) << 16 ) + hexdec( $m[2] ) );
00668         }
00669 
00670         return null; // give up
00671     }
00672 
00679     public static function sanitizeRange( $range ) {
00680         list( /*...*/, $bits ) = self::parseCIDR( $range );
00681         list( $start, /*...*/ ) = self::parseRange( $range );
00682         $start = self::formatHex( $start );
00683         if ( $bits === false ) {
00684             return $start; // wasn't actually a range
00685         }
00686 
00687         return "$start/$bits";
00688     }
00689 
00699     public static function isTrustedProxy( $ip ) {
00700         $trusted = self::isConfiguredProxy( $ip );
00701         wfRunHooks( 'IsTrustedProxy', array( &$ip, &$trusted ) );
00702         return $trusted;
00703     }
00704 
00712     public static function isConfiguredProxy( $ip ) {
00713         global $wgSquidServers, $wgSquidServersNoPurge;
00714 
00715         wfProfileIn( __METHOD__ );
00716         // Quick check of known singular proxy servers
00717         $trusted = in_array( $ip, $wgSquidServers );
00718 
00719         // Check against addresses and CIDR nets in the NoPurge list
00720         if ( !$trusted ) {
00721             if ( !self::$proxyIpSet ) {
00722                 self::$proxyIpSet = new IPSet( $wgSquidServersNoPurge );
00723             }
00724             $trusted = self::$proxyIpSet->match( $ip );
00725         }
00726         wfProfileOut( __METHOD__ );
00727 
00728         return $trusted;
00729     }
00730 
00735     public static function clearCaches() {
00736         self::$proxyIpSet = null;
00737     }
00738 }