Unify domain names in README
[stouyapi.git] / src / push-to-my-ouya-helpers.php
1 <?php
2 /**
3  * Helper methods for the push-to-my-ouya download queue
4  */
5
6 /**
7  * Map local IPs to a single IP so that this the queue can be used
8  * in the home network.
9  *
10  * @see RFC 3330: Special-Use IPv4 Addresses
11  */
12 function mapIp($ip)
13 {
14     if (strpos($ip, ':') !== false) {
15         return mapIpv6($ip);
16     }
17
18     $private = substr($ip, 0, 3) == '10.'
19         || substr($ip, 0, 7) == '172.16.'
20         || substr($ip, 0, 7) == '172.17.'
21         || substr($ip, 0, 7) == '172.18.'
22         || substr($ip, 0, 7) == '172.19.'
23         || substr($ip, 0, 7) == '172.20.'
24         || substr($ip, 0, 7) == '172.21.'
25         || substr($ip, 0, 7) == '172.22.'
26         || substr($ip, 0, 7) == '172.23.'
27         || substr($ip, 0, 7) == '172.24.'
28         || substr($ip, 0, 7) == '172.25.'
29         || substr($ip, 0, 7) == '172.26.'
30         || substr($ip, 0, 7) == '172.27.'
31         || substr($ip, 0, 7) == '172.28.'
32         || substr($ip, 0, 7) == '172.29.'
33         || substr($ip, 0, 7) == '172.30.'
34         || substr($ip, 0, 7) == '172.31.'
35         || substr($ip, 0, 8) == '192.168.'
36         || substr($ip, 0, 8) == '169.254.';
37     $local = substr($ip, 0, 4) == '127.';
38
39     if ($private || $local) {
40         return 'local';
41     }
42     return $ip;
43 }
44
45 /**
46  * Map IPv6 addresses to their 64bit prefix, assuming that the PC and the OUYA
47  * share the same prefix.
48  * Map local IPs to a single IP so that this the queue can be used
49  * in the home network.
50  *
51  * @see  RFC 6890: Special-Purpose IP Address Registries
52  * @see  RFC 4291: IP Version 6 Addressing Architecture
53  * @link https://en.wikipedia.org/wiki/Link-local_address
54  */
55 function mapIpv6($ip)
56 {
57     $ip = strtolower(expandIpv6($ip));
58     if ($ip == '0000:0000:0000:0000:0000:0000:0000:0001') {
59         //localhost
60         return 'local';
61     } else if (substr($ip, 0, 2) == 'fc' || substr($ip, 0, 2) == 'fd') {
62         // fc00::/7 = Unique Local Unicast
63         return 'local';
64     } else if (substr($ip, 0, 3) == 'fe8'
65         || substr($ip, 0, 3) == 'fe9'
66         || substr($ip, 0, 3) == 'fea'
67         || substr($ip, 0, 3) == 'feb'
68     ) {
69         // fe80::/10 = Link-Local unicast
70         return 'local';
71     }
72
73     return substr($ip, 0, 19);
74 }
75
76 function expandIpv6($ip)
77 {
78     $hex = unpack("H*hex", inet_pton($ip));
79     return implode(':', str_split($hex['hex'], 4));
80 }