IdnaEncoder.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. <?php
  2. namespace WpOrg\Requests;
  3. use WpOrg\Requests\Exception;
  4. use WpOrg\Requests\Exception\InvalidArgument;
  5. use WpOrg\Requests\Utility\InputValidator;
  6. /**
  7. * IDNA URL encoder
  8. *
  9. * Note: Not fully compliant, as nameprep does nothing yet.
  10. *
  11. * @package Requests\Utilities
  12. *
  13. * @link https://tools.ietf.org/html/rfc3490 IDNA specification
  14. * @link https://tools.ietf.org/html/rfc3492 Punycode/Bootstrap specification
  15. */
  16. class IdnaEncoder {
  17. /**
  18. * ACE prefix used for IDNA
  19. *
  20. * @link https://tools.ietf.org/html/rfc3490#section-5
  21. * @var string
  22. */
  23. const ACE_PREFIX = 'xn--';
  24. /**
  25. * Maximum length of a IDNA URL in ASCII.
  26. *
  27. * @see \WpOrg\Requests\IdnaEncoder::to_ascii()
  28. *
  29. * @since 2.0.0
  30. *
  31. * @var int
  32. */
  33. const MAX_LENGTH = 64;
  34. /**#@+
  35. * Bootstrap constant for Punycode
  36. *
  37. * @link https://tools.ietf.org/html/rfc3492#section-5
  38. * @var int
  39. */
  40. const BOOTSTRAP_BASE = 36;
  41. const BOOTSTRAP_TMIN = 1;
  42. const BOOTSTRAP_TMAX = 26;
  43. const BOOTSTRAP_SKEW = 38;
  44. const BOOTSTRAP_DAMP = 700;
  45. const BOOTSTRAP_INITIAL_BIAS = 72;
  46. const BOOTSTRAP_INITIAL_N = 128;
  47. /**#@-*/
  48. /**
  49. * Encode a hostname using Punycode
  50. *
  51. * @param string|Stringable $hostname Hostname
  52. * @return string Punycode-encoded hostname
  53. * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed argument is not a string or a stringable object.
  54. */
  55. public static function encode($hostname) {
  56. if (InputValidator::is_string_or_stringable($hostname) === false) {
  57. throw InvalidArgument::create(1, '$hostname', 'string|Stringable', gettype($hostname));
  58. }
  59. $parts = explode('.', $hostname);
  60. foreach ($parts as &$part) {
  61. $part = self::to_ascii($part);
  62. }
  63. return implode('.', $parts);
  64. }
  65. /**
  66. * Convert a UTF-8 text string to an ASCII string using Punycode
  67. *
  68. * @param string $text ASCII or UTF-8 string (max length 64 characters)
  69. * @return string ASCII string
  70. *
  71. * @throws \WpOrg\Requests\Exception Provided string longer than 64 ASCII characters (`idna.provided_too_long`)
  72. * @throws \WpOrg\Requests\Exception Prepared string longer than 64 ASCII characters (`idna.prepared_too_long`)
  73. * @throws \WpOrg\Requests\Exception Provided string already begins with xn-- (`idna.provided_is_prefixed`)
  74. * @throws \WpOrg\Requests\Exception Encoded string longer than 64 ASCII characters (`idna.encoded_too_long`)
  75. */
  76. public static function to_ascii($text) {
  77. // Step 1: Check if the text is already ASCII
  78. if (self::is_ascii($text)) {
  79. // Skip to step 7
  80. if (strlen($text) < self::MAX_LENGTH) {
  81. return $text;
  82. }
  83. throw new Exception('Provided string is too long', 'idna.provided_too_long', $text);
  84. }
  85. // Step 2: nameprep
  86. $text = self::nameprep($text);
  87. // Step 3: UseSTD3ASCIIRules is false, continue
  88. // Step 4: Check if it's ASCII now
  89. if (self::is_ascii($text)) {
  90. // Skip to step 7
  91. /*
  92. * As the `nameprep()` method returns the original string, this code will never be reached until
  93. * that method is properly implemented.
  94. */
  95. // @codeCoverageIgnoreStart
  96. if (strlen($text) < self::MAX_LENGTH) {
  97. return $text;
  98. }
  99. throw new Exception('Prepared string is too long', 'idna.prepared_too_long', $text);
  100. // @codeCoverageIgnoreEnd
  101. }
  102. // Step 5: Check ACE prefix
  103. if (strpos($text, self::ACE_PREFIX) === 0) {
  104. throw new Exception('Provided string begins with ACE prefix', 'idna.provided_is_prefixed', $text);
  105. }
  106. // Step 6: Encode with Punycode
  107. $text = self::punycode_encode($text);
  108. // Step 7: Prepend ACE prefix
  109. $text = self::ACE_PREFIX . $text;
  110. // Step 8: Check size
  111. if (strlen($text) < self::MAX_LENGTH) {
  112. return $text;
  113. }
  114. throw new Exception('Encoded string is too long', 'idna.encoded_too_long', $text);
  115. }
  116. /**
  117. * Check whether a given text string contains only ASCII characters
  118. *
  119. * @internal (Testing found regex was the fastest implementation)
  120. *
  121. * @param string $text
  122. * @return bool Is the text string ASCII-only?
  123. */
  124. protected static function is_ascii($text) {
  125. return (preg_match('/(?:[^\x00-\x7F])/', $text) !== 1);
  126. }
  127. /**
  128. * Prepare a text string for use as an IDNA name
  129. *
  130. * @todo Implement this based on RFC 3491 and the newer 5891
  131. * @param string $text
  132. * @return string Prepared string
  133. */
  134. protected static function nameprep($text) {
  135. return $text;
  136. }
  137. /**
  138. * Convert a UTF-8 string to a UCS-4 codepoint array
  139. *
  140. * Based on \WpOrg\Requests\Iri::replace_invalid_with_pct_encoding()
  141. *
  142. * @param string $input
  143. * @return array Unicode code points
  144. *
  145. * @throws \WpOrg\Requests\Exception Invalid UTF-8 codepoint (`idna.invalidcodepoint`)
  146. */
  147. protected static function utf8_to_codepoints($input) {
  148. $codepoints = [];
  149. // Get number of bytes
  150. $strlen = strlen($input);
  151. // phpcs:ignore Generic.CodeAnalysis.JumbledIncrementer -- This is a deliberate choice.
  152. for ($position = 0; $position < $strlen; $position++) {
  153. $value = ord($input[$position]);
  154. if ((~$value & 0x80) === 0x80) { // One byte sequence:
  155. $character = $value;
  156. $length = 1;
  157. $remaining = 0;
  158. } elseif (($value & 0xE0) === 0xC0) { // Two byte sequence:
  159. $character = ($value & 0x1F) << 6;
  160. $length = 2;
  161. $remaining = 1;
  162. } elseif (($value & 0xF0) === 0xE0) { // Three byte sequence:
  163. $character = ($value & 0x0F) << 12;
  164. $length = 3;
  165. $remaining = 2;
  166. } elseif (($value & 0xF8) === 0xF0) { // Four byte sequence:
  167. $character = ($value & 0x07) << 18;
  168. $length = 4;
  169. $remaining = 3;
  170. } else { // Invalid byte:
  171. throw new Exception('Invalid Unicode codepoint', 'idna.invalidcodepoint', $value);
  172. }
  173. if ($remaining > 0) {
  174. if ($position + $length > $strlen) {
  175. throw new Exception('Invalid Unicode codepoint', 'idna.invalidcodepoint', $character);
  176. }
  177. for ($position++; $remaining > 0; $position++) {
  178. $value = ord($input[$position]);
  179. // If it is invalid, count the sequence as invalid and reprocess the current byte:
  180. if (($value & 0xC0) !== 0x80) {
  181. throw new Exception('Invalid Unicode codepoint', 'idna.invalidcodepoint', $character);
  182. }
  183. --$remaining;
  184. $character |= ($value & 0x3F) << ($remaining * 6);
  185. }
  186. $position--;
  187. }
  188. if (// Non-shortest form sequences are invalid
  189. $length > 1 && $character <= 0x7F
  190. || $length > 2 && $character <= 0x7FF
  191. || $length > 3 && $character <= 0xFFFF
  192. // Outside of range of ucschar codepoints
  193. // Noncharacters
  194. || ($character & 0xFFFE) === 0xFFFE
  195. || $character >= 0xFDD0 && $character <= 0xFDEF
  196. || (
  197. // Everything else not in ucschar
  198. $character > 0xD7FF && $character < 0xF900
  199. || $character < 0x20
  200. || $character > 0x7E && $character < 0xA0
  201. || $character > 0xEFFFD
  202. )
  203. ) {
  204. throw new Exception('Invalid Unicode codepoint', 'idna.invalidcodepoint', $character);
  205. }
  206. $codepoints[] = $character;
  207. }
  208. return $codepoints;
  209. }
  210. /**
  211. * RFC3492-compliant encoder
  212. *
  213. * @internal Pseudo-code from Section 6.3 is commented with "#" next to relevant code
  214. *
  215. * @param string $input UTF-8 encoded string to encode
  216. * @return string Punycode-encoded string
  217. *
  218. * @throws \WpOrg\Requests\Exception On character outside of the domain (never happens with Punycode) (`idna.character_outside_domain`)
  219. */
  220. public static function punycode_encode($input) {
  221. $output = '';
  222. // let n = initial_n
  223. $n = self::BOOTSTRAP_INITIAL_N;
  224. // let delta = 0
  225. $delta = 0;
  226. // let bias = initial_bias
  227. $bias = self::BOOTSTRAP_INITIAL_BIAS;
  228. // let h = b = the number of basic code points in the input
  229. $h = 0;
  230. $b = 0; // see loop
  231. // copy them to the output in order
  232. $codepoints = self::utf8_to_codepoints($input);
  233. $extended = [];
  234. foreach ($codepoints as $char) {
  235. if ($char < 128) {
  236. // Character is valid ASCII
  237. // TODO: this should also check if it's valid for a URL
  238. $output .= chr($char);
  239. $h++;
  240. // Check if the character is non-ASCII, but below initial n
  241. // This never occurs for Punycode, so ignore in coverage
  242. // @codeCoverageIgnoreStart
  243. } elseif ($char < $n) {
  244. throw new Exception('Invalid character', 'idna.character_outside_domain', $char);
  245. // @codeCoverageIgnoreEnd
  246. } else {
  247. $extended[$char] = true;
  248. }
  249. }
  250. $extended = array_keys($extended);
  251. sort($extended);
  252. $b = $h;
  253. // [copy them] followed by a delimiter if b > 0
  254. if (strlen($output) > 0) {
  255. $output .= '-';
  256. }
  257. // {if the input contains a non-basic code point < n then fail}
  258. // while h < length(input) do begin
  259. $codepointcount = count($codepoints);
  260. while ($h < $codepointcount) {
  261. // let m = the minimum code point >= n in the input
  262. $m = array_shift($extended);
  263. //printf('next code point to insert is %s' . PHP_EOL, dechex($m));
  264. // let delta = delta + (m - n) * (h + 1), fail on overflow
  265. $delta += ($m - $n) * ($h + 1);
  266. // let n = m
  267. $n = $m;
  268. // for each code point c in the input (in order) do begin
  269. for ($num = 0; $num < $codepointcount; $num++) {
  270. $c = $codepoints[$num];
  271. // if c < n then increment delta, fail on overflow
  272. if ($c < $n) {
  273. $delta++;
  274. } elseif ($c === $n) { // if c == n then begin
  275. // let q = delta
  276. $q = $delta;
  277. // for k = base to infinity in steps of base do begin
  278. for ($k = self::BOOTSTRAP_BASE; ; $k += self::BOOTSTRAP_BASE) {
  279. // let t = tmin if k <= bias {+ tmin}, or
  280. // tmax if k >= bias + tmax, or k - bias otherwise
  281. if ($k <= ($bias + self::BOOTSTRAP_TMIN)) {
  282. $t = self::BOOTSTRAP_TMIN;
  283. } elseif ($k >= ($bias + self::BOOTSTRAP_TMAX)) {
  284. $t = self::BOOTSTRAP_TMAX;
  285. } else {
  286. $t = $k - $bias;
  287. }
  288. // if q < t then break
  289. if ($q < $t) {
  290. break;
  291. }
  292. // output the code point for digit t + ((q - t) mod (base - t))
  293. $digit = $t + (($q - $t) % (self::BOOTSTRAP_BASE - $t));
  294. $output .= self::digit_to_char($digit);
  295. // let q = (q - t) div (base - t)
  296. $q = floor(($q - $t) / (self::BOOTSTRAP_BASE - $t));
  297. } // end
  298. // output the code point for digit q
  299. $output .= self::digit_to_char($q);
  300. // let bias = adapt(delta, h + 1, test h equals b?)
  301. $bias = self::adapt($delta, $h + 1, $h === $b);
  302. // let delta = 0
  303. $delta = 0;
  304. // increment h
  305. $h++;
  306. } // end
  307. } // end
  308. // increment delta and n
  309. $delta++;
  310. $n++;
  311. } // end
  312. return $output;
  313. }
  314. /**
  315. * Convert a digit to its respective character
  316. *
  317. * @link https://tools.ietf.org/html/rfc3492#section-5
  318. *
  319. * @param int $digit Digit in the range 0-35
  320. * @return string Single character corresponding to digit
  321. *
  322. * @throws \WpOrg\Requests\Exception On invalid digit (`idna.invalid_digit`)
  323. */
  324. protected static function digit_to_char($digit) {
  325. // @codeCoverageIgnoreStart
  326. // As far as I know, this never happens, but still good to be sure.
  327. if ($digit < 0 || $digit > 35) {
  328. throw new Exception(sprintf('Invalid digit %d', $digit), 'idna.invalid_digit', $digit);
  329. }
  330. // @codeCoverageIgnoreEnd
  331. $digits = 'abcdefghijklmnopqrstuvwxyz0123456789';
  332. return substr($digits, $digit, 1);
  333. }
  334. /**
  335. * Adapt the bias
  336. *
  337. * @link https://tools.ietf.org/html/rfc3492#section-6.1
  338. * @param int $delta
  339. * @param int $numpoints
  340. * @param bool $firsttime
  341. * @return int New bias
  342. *
  343. * function adapt(delta,numpoints,firsttime):
  344. */
  345. protected static function adapt($delta, $numpoints, $firsttime) {
  346. // if firsttime then let delta = delta div damp
  347. if ($firsttime) {
  348. $delta = floor($delta / self::BOOTSTRAP_DAMP);
  349. } else {
  350. // else let delta = delta div 2
  351. $delta = floor($delta / 2);
  352. }
  353. // let delta = delta + (delta div numpoints)
  354. $delta += floor($delta / $numpoints);
  355. // let k = 0
  356. $k = 0;
  357. // while delta > ((base - tmin) * tmax) div 2 do begin
  358. $max = floor(((self::BOOTSTRAP_BASE - self::BOOTSTRAP_TMIN) * self::BOOTSTRAP_TMAX) / 2);
  359. while ($delta > $max) {
  360. // let delta = delta div (base - tmin)
  361. $delta = floor($delta / (self::BOOTSTRAP_BASE - self::BOOTSTRAP_TMIN));
  362. // let k = k + base
  363. $k += self::BOOTSTRAP_BASE;
  364. } // end
  365. // return k + (((base - tmin + 1) * delta) div (delta + skew))
  366. return $k + floor(((self::BOOTSTRAP_BASE - self::BOOTSTRAP_TMIN + 1) * $delta) / ($delta + self::BOOTSTRAP_SKEW));
  367. }
  368. }