fixed bug
[lhc/web/wiklou.git] / includes / ProxyTools.php
1 <?php
2
3 if ( !defined( 'MEDIAWIKI' ) ) {
4 die();
5 }
6
7 /**
8 * Functions for dealing with proxies
9 */
10
11
12 /**
13 * Work out the IP address based on various globals
14 */
15 function wfGetIP()
16 {
17 global $wgSquidServers, $wgSquidServersNoPurge;
18
19 /* collect the originating ips */
20 # Client connecting to this webserver
21 if ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
22 $ipchain = array( $_SERVER['REMOTE_ADDR'] );
23 } else {
24 # Running on CLI?
25 $ipchain = array( '127.0.0.1' );
26 }
27 $ip = $ipchain[0];
28
29 # Get list of trusted proxies
30 # Flipped for quicker access
31 $trustedProxies = array_flip( array_merge( $wgSquidServers, $wgSquidServersNoPurge ) );
32 if ( count( $trustedProxies ) ) {
33 # Append XFF on to $ipchain
34 if ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
35 $xff = explode( ',', $_SERVER['HTTP_X_FORWARDED_FOR'] );
36 for ( $i = 1; $i <= count( $xff ); $i++ ) {
37 $ipchain[$i] = trim( $xff[count($xff) - $i );
38 }
39 }
40 var_dump( $ipchain );
41 # Step through XFF list and find the last address in the list which is a trusted server
42 # Set $ip to the IP address given by that trusted server, unless the address is not sensible (e.g. private)
43 foreach ( $ipchain as $i => $curIP ) {
44 if ( array_key_exists( $curIP, $trustedProxies ) ) {
45 if ( isset( $ipchain[$i + 1] ) && wfIsIPPublic( $ipchain[$i + 1] ) ) {
46 $ip = $ipchain[$i + 1];
47 }
48 } else {
49 break;
50 }
51 }
52 }
53
54 return $ip;
55 }
56
57 function wfIP2Unsigned( $ip )
58 {
59 $n = ip2long( $ip );
60 if ( $n == -1 ) {
61 $n = false;
62 } elseif ( $n < 0 ) {
63 $n += pow( 2, 32 );
64 }
65 return $n;
66 }
67
68 /**
69 * Determine if an IP address really is an IP address, and if it is public,
70 * i.e. not RFC 1918 or similar
71 */
72 function wfIsIPPublic( $ip )
73 {
74 $n = wfIP2Unsigned( $ip );
75 if ( !$n ) {
76 return false;
77 }
78
79 static $privateRanges = false;
80 if ( !$privateRanges ) {
81 $privateRanges = array(
82 array( '10.0.0.0', '10.255.255.255' ), # RFC 1918 (private)
83 array( '172.16.0.0', '172.31.255.255' ), # "
84 array( '192.168.0.0', '192.168.255.255' ), # "
85 array( '0.0.0.0', '0.255.255.255' ), # this network
86 array( '127.0.0.0', '127.255.255.255' ), # loopback
87 );
88 }
89
90 foreach ( $privateRanges as $r ) {
91 $start = wfIP2Unsigned( $r[0] );
92 $end = wfIP2Unsigned( $r[1] );
93 if ( $n >= $start && $n <= $end ) {
94 return false;
95 }
96 }
97 return true;
98 }
99
100 ?>