* Added a test for a link with multiple pipes
[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 = array_map( 'trim', explode( ',', $_SERVER['HTTP_X_FORWARDED_FOR'] ) );
36 $xff = array_reverse( $xff );
37 $ipchain = array_merge( $ipchain, $xff );
38 }
39 # Step through XFF list and find the last address in the list which is a trusted server
40 # Set $ip to the IP address given by that trusted server, unless the address is not sensible (e.g. private)
41 foreach ( $ipchain as $i => $curIP ) {
42 if ( array_key_exists( $curIP, $trustedProxies ) ) {
43 if ( isset( $ipchain[$i + 1] ) && wfIsIPPublic( $ipchain[$i + 1] ) ) {
44 $ip = $ipchain[$i + 1];
45 }
46 } else {
47 break;
48 }
49 }
50 }
51
52 return $ip;
53 }
54
55 function wfIP2Unsigned( $ip )
56 {
57 $n = ip2long( $ip );
58 if ( $n == -1 ) {
59 $n = false;
60 } elseif ( $n < 0 ) {
61 $n += pow( 2, 32 );
62 }
63 return $n;
64 }
65
66 /**
67 * Determine if an IP address really is an IP address, and if it is public,
68 * i.e. not RFC 1918 or similar
69 */
70 function wfIsIPPublic( $ip )
71 {
72 $n = wfIP2Unsigned( $ip );
73 if ( !$n ) {
74 return false;
75 }
76
77 static $privateRanges = false;
78 if ( !$privateRanges ) {
79 $privateRanges = array(
80 array( '10.0.0.0', '10.255.255.255' ), # RFC 1918 (private)
81 array( '172.16.0.0', '172.31.255.255' ), # "
82 array( '192.168.0.0', '192.168.255.255' ), # "
83 array( '0.0.0.0', '0.255.255.255' ), # this network
84 array( '127.0.0.0', '127.255.255.255' ), # loopback
85 );
86 }
87
88 foreach ( $privateRanges as $r ) {
89 $start = wfIP2Unsigned( $r[0] );
90 $end = wfIP2Unsigned( $r[1] );
91 if ( $n >= $start && $n <= $end ) {
92 return false;
93 }
94 }
95 return true;
96 }
97
98 ?>