Path: blob/main/crypto/heimdal/lib/wind/rfc3492.txt
34914 views
123456Network Working Group A. Costello7Request for Comments: 3492 Univ. of California, Berkeley8Category: Standards Track March 200391011Punycode: A Bootstring encoding of Unicode12for Internationalized Domain Names in Applications (IDNA)1314Status of this Memo1516This document specifies an Internet standards track protocol for the17Internet community, and requests discussion and suggestions for18improvements. Please refer to the current edition of the "Internet19Official Protocol Standards" (STD 1) for the standardization state20and status of this protocol. Distribution of this memo is unlimited.2122Copyright Notice2324Copyright (C) The Internet Society (2003). All Rights Reserved.2526Abstract2728Punycode is a simple and efficient transfer encoding syntax designed29for use with Internationalized Domain Names in Applications (IDNA).30It uniquely and reversibly transforms a Unicode string into an ASCII31string. ASCII characters in the Unicode string are represented32literally, and non-ASCII characters are represented by ASCII33characters that are allowed in host name labels (letters, digits, and34hyphens). This document defines a general algorithm called35Bootstring that allows a string of basic code points to uniquely36represent any string of code points drawn from a larger set.37Punycode is an instance of Bootstring that uses particular parameter38values specified by this document, appropriate for IDNA.3940Table of Contents41421. Introduction...............................................2431.1 Features..............................................2441.2 Interaction of protocol parts.........................3452. Terminology................................................3463. Bootstring description.....................................4473.1 Basic code point segregation..........................4483.2 Insertion unsort coding...............................4493.3 Generalized variable-length integers..................5503.4 Bias adaptation.......................................7514. Bootstring parameters......................................8525. Parameter values for Punycode..............................8536. Bootstring algorithms......................................954555657Costello Standards Track [Page 1]5859RFC 3492 IDNA Punycode March 20036061626.1 Bias adaptation function.............................10636.2 Decoding procedure...................................11646.3 Encoding procedure...................................12656.4 Overflow handling....................................13667. Punycode examples.........................................14677.1 Sample strings.......................................14687.2 Decoding traces......................................17697.3 Encoding traces......................................19708. Security Considerations...................................20719. References................................................21729.1 Normative References.................................21739.2 Informative References...............................2174A. Mixed-case annotation.....................................2275B. Disclaimer and license....................................2276C. Punycode sample implementation............................2377Author's Address.............................................3478Full Copyright Statement.....................................3579801. Introduction8182[IDNA] describes an architecture for supporting internationalized83domain names. Labels containing non-ASCII characters can be84represented by ACE labels, which begin with a special ACE prefix and85contain only ASCII characters. The remainder of the label after the86prefix is a Punycode encoding of a Unicode string satisfying certain87constraints. For the details of the prefix and constraints, see88[IDNA] and [NAMEPREP].8990Punycode is an instance of a more general algorithm called91Bootstring, which allows strings composed from a small set of "basic"92code points to uniquely represent any string of code points drawn93from a larger set. Punycode is Bootstring with particular parameter94values appropriate for IDNA.95961.1 Features9798Bootstring has been designed to have the following features:99100* Completeness: Every extended string (sequence of arbitrary code101points) can be represented by a basic string (sequence of basic102code points). Restrictions on what strings are allowed, and on103length, can be imposed by higher layers.104105* Uniqueness: There is at most one basic string that represents a106given extended string.107108* Reversibility: Any extended string mapped to a basic string can109be recovered from that basic string.110111112113Costello Standards Track [Page 2]114115RFC 3492 IDNA Punycode March 2003116117118* Efficient encoding: The ratio of basic string length to extended119string length is small. This is important in the context of120domain names because RFC 1034 [RFC1034] restricts the length of a121domain label to 63 characters.122123* Simplicity: The encoding and decoding algorithms are reasonably124simple to implement. The goals of efficiency and simplicity are125at odds; Bootstring aims at a good balance between them.126127* Readability: Basic code points appearing in the extended string128are represented as themselves in the basic string (although the129main purpose is to improve efficiency, not readability).130131Punycode can also support an additional feature that is not used by132the ToASCII and ToUnicode operations of [IDNA]. When extended133strings are case-folded prior to encoding, the basic string can use134mixed case to tell how to convert the folded string into a mixed-case135string. See appendix A "Mixed-case annotation".1361371.2 Interaction of protocol parts138139Punycode is used by the IDNA protocol [IDNA] for converting domain140labels into ASCII; it is not designed for any other purpose. It is141explicitly not designed for processing arbitrary free text.1421432. Terminology144145The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT",146"SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this147document are to be interpreted as described in BCP 14, RFC 2119148[RFC2119].149150A code point is an integral value associated with a character in a151coded character set.152153As in the Unicode Standard [UNICODE], Unicode code points are denoted154by "U+" followed by four to six hexadecimal digits, while a range of155code points is denoted by two hexadecimal numbers separated by "..",156with no prefixes.157158The operators div and mod perform integer division; (x div y) is the159quotient of x divided by y, discarding the remainder, and (x mod y)160is the remainder, so (x div y) * y + (x mod y) == x. Bootstring uses161these operators only with nonnegative operands, so the quotient and162remainder are always nonnegative.163164The break statement jumps out of the innermost loop (as in C).165166167168169Costello Standards Track [Page 3]170171RFC 3492 IDNA Punycode March 2003172173174An overflow is an attempt to compute a value that exceeds the maximum175value of an integer variable.1761773. Bootstring description178179Bootstring represents an arbitrary sequence of code points (the180"extended string") as a sequence of basic code points (the "basic181string"). This section describes the representation. Section 6182"Bootstring algorithms" presents the algorithms as pseudocode.183Sections 7.1 "Decoding traces" and 7.2 "Encoding traces" trace the184algorithms for sample inputs.185186The following sections describe the four techniques used in187Bootstring. "Basic code point segregation" is a very simple and188efficient encoding for basic code points occurring in the extended189string: they are simply copied all at once. "Insertion unsort190coding" encodes the non-basic code points as deltas, and processes191the code points in numerical order rather than in order of192appearance, which typically results in smaller deltas. The deltas193are represented as "generalized variable-length integers", which use194basic code points to represent nonnegative integers. The parameters195of this integer representation are dynamically adjusted using "bias196adaptation", to improve efficiency when consecutive deltas have197similar magnitudes.1981993.1 Basic code point segregation200201All basic code points appearing in the extended string are202represented literally at the beginning of the basic string, in their203original order, followed by a delimiter if (and only if) the number204of basic code points is nonzero. The delimiter is a particular basic205code point, which never appears in the remainder of the basic string.206The decoder can therefore find the end of the literal portion (if207there is one) by scanning for the last delimiter.2082093.2 Insertion unsort coding210211The remainder of the basic string (after the last delimiter if there212is one) represents a sequence of nonnegative integral deltas as213generalized variable-length integers, described in section 3.3. The214meaning of the deltas is best understood in terms of the decoder.215216The decoder builds the extended string incrementally. Initially, the217extended string is a copy of the literal portion of the basic string218(excluding the last delimiter). The decoder inserts non-basic code219points, one for each delta, into the extended string, ultimately220arriving at the final decoded string.221222223224225Costello Standards Track [Page 4]226227RFC 3492 IDNA Punycode March 2003228229230At the heart of this process is a state machine with two state231variables: an index i and a counter n. The index i refers to a232position in the extended string; it ranges from 0 (the first233position) to the current length of the extended string (which refers234to a potential position beyond the current end). If the current235state is <n,i>, the next state is <n,i+1> if i is less than the236length of the extended string, or <n+1,0> if i equals the length of237the extended string. In other words, each state change causes i to238increment, wrapping around to zero if necessary, and n counts the239number of wrap-arounds.240241Notice that the state always advances monotonically (there is no way242for the decoder to return to an earlier state). At each state, an243insertion is either performed or not performed. At most one244insertion is performed in a given state. An insertion inserts the245value of n at position i in the extended string. The deltas are a246run-length encoding of this sequence of events: they are the lengths247of the runs of non-insertion states preceeding the insertion states.248Hence, for each delta, the decoder performs delta state changes, then249an insertion, and then one more state change. (An implementation250need not perform each state change individually, but can instead use251division and remainder calculations to compute the next insertion252state directly.) It is an error if the inserted code point is a253basic code point (because basic code points were supposed to be254segregated as described in section 3.1).255256The encoder's main task is to derive the sequence of deltas that will257cause the decoder to construct the desired string. It can do this by258repeatedly scanning the extended string for the next code point that259the decoder would need to insert, and counting the number of state260changes the decoder would need to perform, mindful of the fact that261the decoder's extended string will include only those code points262that have already been inserted. Section 6.3 "Encoding procedure"263gives a precise algorithm.2642653.3 Generalized variable-length integers266267In a conventional integer representation the base is the number of268distinct symbols for digits, whose values are 0 through base-1. Let269digit_0 denote the least significant digit, digit_1 the next least270significant, and so on. The value represented is the sum over j of271digit_j * w(j), where w(j) = base^j is the weight (scale factor) for272position j. For example, in the base 8 integer 437, the digits are2737, 3, and 4, and the weights are 1, 8, and 64, so the value is 7 +2743*8 + 4*64 = 287. This representation has two disadvantages: First,275there are multiple encodings of each value (because there can be276extra zeros in the most significant positions), which is inconvenient277278279280281Costello Standards Track [Page 5]282283RFC 3492 IDNA Punycode March 2003284285286when unique encodings are needed. Second, the integer is not self-287delimiting, so if multiple integers are concatenated the boundaries288between them are lost.289290The generalized variable-length representation solves these two291problems. The digit values are still 0 through base-1, but now the292integer is self-delimiting by means of thresholds t(j), each of which293is in the range 0 through base-1. Exactly one digit, the most294significant, satisfies digit_j < t(j). Therefore, if several295integers are concatenated, it is easy to separate them, starting with296the first if they are little-endian (least significant digit first),297or starting with the last if they are big-endian (most significant298digit first). As before, the value is the sum over j of digit_j *299w(j), but the weights are different:300301w(0) = 1302w(j) = w(j-1) * (base - t(j-1)) for j > 0303304For example, consider the little-endian sequence of base 8 digits305734251... Suppose the thresholds are 2, 3, 5, 5, 5, 5... This306implies that the weights are 1, 1*(8-2) = 6, 6*(8-3) = 30, 30*(8-5) =30790, 90*(8-5) = 270, and so on. 7 is not less than 2, and 3 is not308less than 3, but 4 is less than 5, so 4 is the last digit. The value309of 734 is 7*1 + 3*6 + 4*30 = 145. The next integer is 251, with310value 2*1 + 5*6 + 1*30 = 62. Decoding this representation is very311similar to decoding a conventional integer: Start with a current312value of N = 0 and a weight w = 1. Fetch the next digit d and313increase N by d * w. If d is less than the current threshold (t)314then stop, otherwise increase w by a factor of (base - t), update t315for the next position, and repeat.316317Encoding this representation is similar to encoding a conventional318integer: If N < t then output one digit for N and stop, otherwise319output the digit for t + ((N - t) mod (base - t)), then replace N320with (N - t) div (base - t), update t for the next position, and321repeat.322323For any particular set of values of t(j), there is exactly one324generalized variable-length representation of each nonnegative325integral value.326327Bootstring uses little-endian ordering so that the deltas can be328separated starting with the first. The t(j) values are defined in329terms of the constants base, tmin, and tmax, and a state variable330called bias:331332t(j) = base * (j + 1) - bias,333clamped to the range tmin through tmax334335336337Costello Standards Track [Page 6]338339RFC 3492 IDNA Punycode March 2003340341342The clamping means that if the formula yields a value less than tmin343or greater than tmax, then t(j) = tmin or tmax, respectively. (In344the pseudocode in section 6 "Bootstring algorithms", the expression345base * (j + 1) is denoted by k for performance reasons.) These t(j)346values cause the representation to favor integers within a particular347range determined by the bias.3483493.4 Bias adaptation350351After each delta is encoded or decoded, bias is set for the next352delta as follows:3533541. Delta is scaled in order to avoid overflow in the next step:355356let delta = delta div 2357358But when this is the very first delta, the divisor is not 2, but359instead a constant called damp. This compensates for the fact360that the second delta is usually much smaller than the first.3613622. Delta is increased to compensate for the fact that the next delta363will be inserting into a longer string:364365let delta = delta + (delta div numpoints)366367numpoints is the total number of code points encoded/decoded so368far (including the one corresponding to this delta itself, and369including the basic code points).3703713. Delta is repeatedly divided until it falls within a threshold, to372predict the minimum number of digits needed to represent the next373delta:374375while delta > ((base - tmin) * tmax) div 2376do let delta = delta div (base - tmin)3773784. The bias is set:379380let bias =381(base * the number of divisions performed in step 3) +382(((base - tmin + 1) * delta) div (delta + skew))383384The motivation for this procedure is that the current delta385provides a hint about the likely size of the next delta, and so386t(j) is set to tmax for the more significant digits starting with387the one expected to be last, tmin for the less significant digits388up through the one expected to be third-last, and somewhere389between tmin and tmax for the digit expected to be second-last390391392393Costello Standards Track [Page 7]394395RFC 3492 IDNA Punycode March 2003396397398(balancing the hope of the expected-last digit being unnecessary399against the danger of it being insufficient).4004014. Bootstring parameters402403Given a set of basic code points, one needs to be designated as the404delimiter. The base cannot be greater than the number of405distinguishable basic code points remaining. The digit-values in the406range 0 through base-1 need to be associated with distinct non-407delimiter basic code points. In some cases multiple code points need408to have the same digit-value; for example, uppercase and lowercase409versions of the same letter need to be equivalent if basic strings410are case-insensitive.411412The initial value of n cannot be greater than the minimum non-basic413code point that could appear in extended strings.414415The remaining five parameters (tmin, tmax, skew, damp, and the416initial value of bias) need to satisfy the following constraints:4174180 <= tmin <= tmax <= base-1419skew >= 1420damp >= 2421initial_bias mod base <= base - tmin422423Provided the constraints are satisfied, these five parameters affect424efficiency but not correctness. They are best chosen empirically.425426If support for mixed-case annotation is desired (see appendix A),427make sure that the code points corresponding to 0 through tmax-1 all428have both uppercase and lowercase forms.4294305. Parameter values for Punycode431432Punycode uses the following Bootstring parameter values:433434base = 36435tmin = 1436tmax = 26437skew = 38438damp = 700439initial_bias = 72440initial_n = 128 = 0x80441442Although the only restriction Punycode imposes on the input integers443is that they be nonnegative, these parameters are especially designed444to work well with Unicode [UNICODE] code points, which are integers445in the range 0..10FFFF (but not D800..DFFF, which are reserved for446447448449Costello Standards Track [Page 8]450451RFC 3492 IDNA Punycode March 2003452453454use by the UTF-16 encoding of Unicode). The basic code points are455the ASCII [ASCII] code points (0..7F), of which U+002D (-) is the456delimiter, and some of the others have digit-values as follows:457458code points digit-values459------------ ----------------------46041..5A (A-Z) = 0 to 25, respectively46161..7A (a-z) = 0 to 25, respectively46230..39 (0-9) = 26 to 35, respectively463464Using hyphen-minus as the delimiter implies that the encoded string465can end with a hyphen-minus only if the Unicode string consists466entirely of basic code points, but IDNA forbids such strings from467being encoded. The encoded string can begin with a hyphen-minus, but468IDNA prepends a prefix. Therefore IDNA using Punycode conforms to469the RFC 952 rule that host name labels neither begin nor end with a470hyphen-minus [RFC952].471472A decoder MUST recognize the letters in both uppercase and lowercase473forms (including mixtures of both forms). An encoder SHOULD output474only uppercase forms or only lowercase forms, unless it uses mixed-475case annotation (see appendix A).476477Presumably most users will not manually write or type encoded strings478(as opposed to cutting and pasting them), but those who do will need479to be alert to the potential visual ambiguity between the following480sets of characters:481482G 6483I l 1484O 0485S 5486U V487Z 2488489Such ambiguities are usually resolved by context, but in a Punycode490encoded string there is no context apparent to humans.4914926. Bootstring algorithms493494Some parts of the pseudocode can be omitted if the parameters satisfy495certain conditions (for which Punycode qualifies). These parts are496enclosed in {braces}, and notes immediately following the pseudocode497explain the conditions under which they can be omitted.498499500501502503504505Costello Standards Track [Page 9]506507RFC 3492 IDNA Punycode March 2003508509510Formally, code points are integers, and hence the pseudocode assumes511that arithmetic operations can be performed directly on code points.512In some programming languages, explicit conversion between code513points and integers might be necessary.5145156.1 Bias adaptation function516517function adapt(delta,numpoints,firsttime):518if firsttime then let delta = delta div damp519else let delta = delta div 2520let delta = delta + (delta div numpoints)521let k = 0522while delta > ((base - tmin) * tmax) div 2 do begin523let delta = delta div (base - tmin)524let k = k + base525end526return k + (((base - tmin + 1) * delta) div (delta + skew))527528It does not matter whether the modifications to delta and k inside529adapt() affect variables of the same name inside the530encoding/decoding procedures, because after calling adapt() the531caller does not read those variables before overwriting them.532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561Costello Standards Track [Page 10]562563RFC 3492 IDNA Punycode March 20035645655666.2 Decoding procedure567568let n = initial_n569let i = 0570let bias = initial_bias571let output = an empty string indexed from 0572consume all code points before the last delimiter (if there is one)573and copy them to output, fail on any non-basic code point574if more than zero code points were consumed then consume one more575(which will be the last delimiter)576while the input is not exhausted do begin577let oldi = i578let w = 1579for k = base to infinity in steps of base do begin580consume a code point, or fail if there was none to consume581let digit = the code point's digit-value, fail if it has none582let i = i + digit * w, fail on overflow583let t = tmin if k <= bias {+ tmin}, or584tmax if k >= bias + tmax, or k - bias otherwise585if digit < t then break586let w = w * (base - t), fail on overflow587end588let bias = adapt(i - oldi, length(output) + 1, test oldi is 0?)589let n = n + i div (length(output) + 1), fail on overflow590let i = i mod (length(output) + 1)591{if n is a basic code point then fail}592insert n into output at position i593increment i594end595596The full statement enclosed in braces (checking whether n is a basic597code point) can be omitted if initial_n exceeds all basic code points598(which is true for Punycode), because n is never less than initial_n.599600In the assignment of t, where t is clamped to the range tmin through601tmax, "+ tmin" can always be omitted. This makes the clamping602calculation incorrect when bias < k < bias + tmin, but that cannot603happen because of the way bias is computed and because of the604constraints on the parameters.605606Because the decoder state can only advance monotonically, and there607is only one representation of any delta, there is therefore only one608encoded string that can represent a given sequence of integers. The609only error conditions are invalid code points, unexpected end-of-610input, overflow, and basic code points encoded using deltas instead611of appearing literally. If the decoder fails on these errors as612shown above, then it cannot produce the same output for two distinct613inputs. Without this property it would have been necessary to re-614615616617Costello Standards Track [Page 11]618619RFC 3492 IDNA Punycode March 2003620621622encode the output and verify that it matches the input in order to623guarantee the uniqueness of the encoding.6246256.3 Encoding procedure626627let n = initial_n628let delta = 0629let bias = initial_bias630let h = b = the number of basic code points in the input631copy them to the output in order, followed by a delimiter if b > 0632{if the input contains a non-basic code point < n then fail}633while h < length(input) do begin634let m = the minimum {non-basic} code point >= n in the input635let delta = delta + (m - n) * (h + 1), fail on overflow636let n = m637for each code point c in the input (in order) do begin638if c < n {or c is basic} then increment delta, fail on overflow639if c == n then begin640let q = delta641for k = base to infinity in steps of base do begin642let t = tmin if k <= bias {+ tmin}, or643tmax if k >= bias + tmax, or k - bias otherwise644if q < t then break645output the code point for digit t + ((q - t) mod (base - t))646let q = (q - t) div (base - t)647end648output the code point for digit q649let bias = adapt(delta, h + 1, test h equals b?)650let delta = 0651increment h652end653end654increment delta and n655end656657The full statement enclosed in braces (checking whether the input658contains a non-basic code point less than n) can be omitted if all659code points less than initial_n are basic code points (which is true660for Punycode if code points are unsigned).661662The brace-enclosed conditions "non-basic" and "or c is basic" can be663omitted if initial_n exceeds all basic code points (which is true for664Punycode), because the code point being tested is never less than665initial_n.666667In the assignment of t, where t is clamped to the range tmin through668tmax, "+ tmin" can always be omitted. This makes the clamping669calculation incorrect when bias < k < bias + tmin, but that cannot670671672673Costello Standards Track [Page 12]674675RFC 3492 IDNA Punycode March 2003676677678happen because of the way bias is computed and because of the679constraints on the parameters.680681The checks for overflow are necessary to avoid producing invalid682output when the input contains very large values or is very long.683684The increment of delta at the bottom of the outer loop cannot685overflow because delta < length(input) before the increment, and686length(input) is already assumed to be representable. The increment687of n could overflow, but only if h == length(input), in which case688the procedure is finished anyway.6896906.4 Overflow handling691692For IDNA, 26-bit unsigned integers are sufficient to handle all valid693IDNA labels without overflow, because any string that needed a 27-bit694delta would have to exceed either the code point limit (0..10FFFF) or695the label length limit (63 characters). However, overflow handling696is necessary because the inputs are not necessarily valid IDNA697labels.698699If the programming language does not provide overflow detection, the700following technique can be used. Suppose A, B, and C are701representable nonnegative integers and C is nonzero. Then A + B702overflows if and only if B > maxint - A, and A + (B * C) overflows if703and only if B > (maxint - A) div C, where maxint is the greatest704integer for which maxint + 1 cannot be represented. Refer to705appendix C "Punycode sample implementation" for demonstrations of706this technique in the C language.707708The decoding and encoding algorithms shown in sections 6.2 and 6.3709handle overflow by detecting it whenever it happens. Another710approach is to enforce limits on the inputs that prevent overflow711from happening. For example, if the encoder were to verify that no712input code points exceed M and that the input length does not exceed713L, then no delta could ever exceed (M - initial_n) * (L + 1), and714hence no overflow could occur if integer variables were capable of715representing values that large. This prevention approach would716impose more restrictions on the input than the detection approach717does, but might be considered simpler in some programming languages.718719In theory, the decoder could use an analogous approach, limiting the720number of digits in a variable-length integer (that is, limiting the721number of iterations in the innermost loop). However, the number of722digits that suffice to represent a given delta can sometimes723represent much larger deltas (because of the adaptation), and hence724this approach would probably need integers wider than 32 bits.725726727728729Costello Standards Track [Page 13]730731RFC 3492 IDNA Punycode March 2003732733734Yet another approach for the decoder is to allow overflow to occur,735but to check the final output string by re-encoding it and comparing736to the decoder input. If and only if they do not match (using a737case-insensitive ASCII comparison) overflow has occurred. This738delayed-detection approach would not impose any more restrictions on739the input than the immediate-detection approach does, and might be740considered simpler in some programming languages.741742In fact, if the decoder is used only inside the IDNA ToUnicode743operation [IDNA], then it need not check for overflow at all, because744ToUnicode performs a higher level re-encoding and comparison, and a745mismatch has the same consequence as if the Punycode decoder had746failed.7477487. Punycode examples7497507.1 Sample strings751752In the Punycode encodings below, the ACE prefix is not shown.753Backslashes show where line breaks have been inserted in strings too754long for one line.755756The first several examples are all translations of the sentence "Why757can't they just speak in <language>?" (courtesy of Michael Kaplan's758"provincial" page [PROVINCIAL]). Word breaks and punctuation have759been removed, as is often done in domain names.760761(A) Arabic (Egyptian):762u+0644 u+064A u+0647 u+0645 u+0627 u+0628 u+062A u+0643 u+0644763u+0645 u+0648 u+0634 u+0639 u+0631 u+0628 u+064A u+061F764Punycode: egbpdaj6bu4bxfgehfvwxn765766(B) Chinese (simplified):767u+4ED6 u+4EEC u+4E3A u+4EC0 u+4E48 u+4E0D u+8BF4 u+4E2D u+6587768Punycode: ihqwcrb4cv8a8dqg056pqjye769770(C) Chinese (traditional):771u+4ED6 u+5011 u+7232 u+4EC0 u+9EBD u+4E0D u+8AAA u+4E2D u+6587772Punycode: ihqwctvzc91f659drss3x8bo0yb773774(D) Czech: Pro<ccaron>prost<ecaron>nemluv<iacute><ccaron>esky775U+0050 u+0072 u+006F u+010D u+0070 u+0072 u+006F u+0073 u+0074776u+011B u+006E u+0065 u+006D u+006C u+0075 u+0076 u+00ED u+010D777u+0065 u+0073 u+006B u+0079778Punycode: Proprostnemluvesky-uyb24dma41a779780781782783784785Costello Standards Track [Page 14]786787RFC 3492 IDNA Punycode March 2003788789790(E) Hebrew:791u+05DC u+05DE u+05D4 u+05D4 u+05DD u+05E4 u+05E9 u+05D5 u+05D8792u+05DC u+05D0 u+05DE u+05D3 u+05D1 u+05E8 u+05D9 u+05DD u+05E2793u+05D1 u+05E8 u+05D9 u+05EA794Punycode: 4dbcagdahymbxekheh6e0a7fei0b795796(F) Hindi (Devanagari):797u+092F u+0939 u+0932 u+094B u+0917 u+0939 u+093F u+0928 u+094D798u+0926 u+0940 u+0915 u+094D u+092F u+094B u+0902 u+0928 u+0939799u+0940 u+0902 u+092C u+094B u+0932 u+0938 u+0915 u+0924 u+0947800u+0939 u+0948 u+0902801Punycode: i1baa7eci9glrd9b2ae1bj0hfcgg6iyaf8o0a1dig0cd802803(G) Japanese (kanji and hiragana):804u+306A u+305C u+307F u+3093 u+306A u+65E5 u+672C u+8A9E u+3092805u+8A71 u+3057 u+3066 u+304F u+308C u+306A u+3044 u+306E u+304B806Punycode: n8jok5ay5dzabd5bym9f0cm5685rrjetr6pdxa807808(H) Korean (Hangul syllables):809u+C138 u+ACC4 u+C758 u+BAA8 u+B4E0 u+C0AC u+B78C u+B4E4 u+C774810u+D55C u+AD6D u+C5B4 u+B97C u+C774 u+D574 u+D55C u+B2E4 u+BA74811u+C5BC u+B9C8 u+B098 u+C88B u+C744 u+AE4C812Punycode: 989aomsvi5e83db1d2a355cv1e0vak1dwrv93d5xbh15a0dt30a5j\813psd879ccm6fea98c814815(I) Russian (Cyrillic):816U+043F u+043E u+0447 u+0435 u+043C u+0443 u+0436 u+0435 u+043E817u+043D u+0438 u+043D u+0435 u+0433 u+043E u+0432 u+043E u+0440818u+044F u+0442 u+043F u+043E u+0440 u+0443 u+0441 u+0441 u+043A819u+0438820Punycode: b1abfaaepdrnnbgefbaDotcwatmq2g4l821822(J) Spanish: Porqu<eacute>nopuedensimplementehablarenEspa<ntilde>ol823U+0050 u+006F u+0072 u+0071 u+0075 u+00E9 u+006E u+006F u+0070824u+0075 u+0065 u+0064 u+0065 u+006E u+0073 u+0069 u+006D u+0070825u+006C u+0065 u+006D u+0065 u+006E u+0074 u+0065 u+0068 u+0061826u+0062 u+006C u+0061 u+0072 u+0065 u+006E U+0045 u+0073 u+0070827u+0061 u+00F1 u+006F u+006C828Punycode: PorqunopuedensimplementehablarenEspaol-fmd56a829830(K) Vietnamese:831T<adotbelow>isaoh<odotbelow>kh<ocirc>ngth<ecirchookabove>ch\832<ihookabove>n<oacute>iti<ecircacute>ngVi<ecircdotbelow>t833U+0054 u+1EA1 u+0069 u+0073 u+0061 u+006F u+0068 u+1ECD u+006B834u+0068 u+00F4 u+006E u+0067 u+0074 u+0068 u+1EC3 u+0063 u+0068835u+1EC9 u+006E u+00F3 u+0069 u+0074 u+0069 u+1EBF u+006E u+0067836U+0056 u+0069 u+1EC7 u+0074837Punycode: TisaohkhngthchnitingVit-kjcr8268qyxafd2f1b9g838839840841Costello Standards Track [Page 15]842843RFC 3492 IDNA Punycode March 2003844845846The next several examples are all names of Japanese music artists,847song titles, and TV programs, just because the author happens to have848them handy (but Japanese is useful for providing examples of single-849row text, two-row text, ideographic text, and various mixtures850thereof).851852(L) 3<nen>B<gumi><kinpachi><sensei>853u+0033 u+5E74 U+0042 u+7D44 u+91D1 u+516B u+5148 u+751F854Punycode: 3B-ww4c5e180e575a65lsy2b855856(M) <amuro><namie>-with-SUPER-MONKEYS857u+5B89 u+5BA4 u+5948 u+7F8E u+6075 u+002D u+0077 u+0069 u+0074858u+0068 u+002D U+0053 U+0055 U+0050 U+0045 U+0052 u+002D U+004D859U+004F U+004E U+004B U+0045 U+0059 U+0053860Punycode: -with-SUPER-MONKEYS-pc58ag80a8qai00g7n9n861862(N) Hello-Another-Way-<sorezore><no><basho>863U+0048 u+0065 u+006C u+006C u+006F u+002D U+0041 u+006E u+006F864u+0074 u+0068 u+0065 u+0072 u+002D U+0057 u+0061 u+0079 u+002D865u+305D u+308C u+305E u+308C u+306E u+5834 u+6240866Punycode: Hello-Another-Way--fc4qua05auwb3674vfr0b867868(O) <hitotsu><yane><no><shita>2869u+3072 u+3068 u+3064 u+5C4B u+6839 u+306E u+4E0B u+0032870Punycode: 2-u9tlzr9756bt3uc0v871872(P) Maji<de>Koi<suru>5<byou><mae>873U+004D u+0061 u+006A u+0069 u+3067 U+004B u+006F u+0069 u+3059874u+308B u+0035 u+79D2 u+524D875Punycode: MajiKoi5-783gue6qz075azm5e876877(Q) <pafii>de<runba>878u+30D1 u+30D5 u+30A3 u+30FC u+0064 u+0065 u+30EB u+30F3 u+30D0879Punycode: de-jg4avhby1noc0d880881(R) <sono><supiido><de>882u+305D u+306E u+30B9 u+30D4 u+30FC u+30C9 u+3067883Punycode: d9juau41awczczp884885The last example is an ASCII string that breaks the existing rules886for host name labels. (It is not a realistic example for IDNA,887because IDNA never encodes pure ASCII labels.)888889(S) -> $1.00 <-890u+002D u+003E u+0020 u+0024 u+0031 u+002E u+0030 u+0030 u+0020891u+003C u+002D892Punycode: -> $1.00 <--893894895896897Costello Standards Track [Page 16]898899RFC 3492 IDNA Punycode March 20039009019027.2 Decoding traces903904In the following traces, the evolving state of the decoder is shown905as a sequence of hexadecimal values, representing the code points in906the extended string. An asterisk appears just after the most907recently inserted code point, indicating both n (the value preceeding908the asterisk) and i (the position of the value just after the909asterisk). Other numerical values are decimal.910911Decoding trace of example B from section 7.1:912913n is 128, i is 0, bias is 72914input is "ihqwcrb4cv8a8dqg056pqjye"915there is no delimiter, so extended string starts empty916delta "ihq" decodes to 19853917bias becomes 219184E0D *919delta "wc" decodes to 64920bias becomes 209214E0D 4E2D *922delta "rb" decodes to 37923bias becomes 139244E3A * 4E0D 4E2D925delta "4c" decodes to 56926bias becomes 179274E3A 4E48 * 4E0D 4E2D928delta "v8a" decodes to 599929bias becomes 329304E3A 4EC0 * 4E48 4E0D 4E2D931delta "8d" decodes to 130932bias becomes 239334ED6 * 4E3A 4EC0 4E48 4E0D 4E2D934delta "qg" decodes to 154935bias becomes 259364ED6 4EEC * 4E3A 4EC0 4E48 4E0D 4E2D937delta "056p" decodes to 46301938bias becomes 849394ED6 4EEC 4E3A 4EC0 4E48 4E0D 4E2D 6587 *940delta "qjye" decodes to 88531941bias becomes 909424ED6 4EEC 4E3A 4EC0 4E48 4E0D 8BF4 * 4E2D 6587943944945946947948949950951952953Costello Standards Track [Page 17]954955RFC 3492 IDNA Punycode March 2003956957958Decoding trace of example L from section 7.1:959960n is 128, i is 0, bias is 72961input is "3B-ww4c5e180e575a65lsy2b"962literal portion is "3B-", so extended string starts as:9630033 0042964delta "ww4c" decodes to 62042965bias becomes 279660033 0042 5148 *967delta "5e" decodes to 139968bias becomes 249690033 0042 516B * 5148970delta "180e" decodes to 16683971bias becomes 679720033 5E74 * 0042 516B 5148973delta "575a" decodes to 34821974bias becomes 829750033 5E74 0042 516B 5148 751F *976delta "65l" decodes to 14592977bias becomes 679780033 5E74 0042 7D44 * 516B 5148 751F979delta "sy2b" decodes to 42088980bias becomes 849810033 5E74 0042 7D44 91D1 * 516B 5148 751F9829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009Costello Standards Track [Page 18]10101011RFC 3492 IDNA Punycode March 20031012101310147.3 Encoding traces10151016In the following traces, code point values are hexadecimal, while1017other numerical values are decimal.10181019Encoding trace of example B from section 7.1:10201021bias is 721022input is:10234ED6 4EEC 4E3A 4EC0 4E48 4E0D 8BF4 4E2D 65871024there are no basic code points, so no literal portion1025next code point to insert is 4E0D1026needed delta is 19853, encodes as "ihq"1027bias becomes 211028next code point to insert is 4E2D1029needed delta is 64, encodes as "wc"1030bias becomes 201031next code point to insert is 4E3A1032needed delta is 37, encodes as "rb"1033bias becomes 131034next code point to insert is 4E481035needed delta is 56, encodes as "4c"1036bias becomes 171037next code point to insert is 4EC01038needed delta is 599, encodes as "v8a"1039bias becomes 321040next code point to insert is 4ED61041needed delta is 130, encodes as "8d"1042bias becomes 231043next code point to insert is 4EEC1044needed delta is 154, encodes as "qg"1045bias becomes 251046next code point to insert is 65871047needed delta is 46301, encodes as "056p"1048bias becomes 841049next code point to insert is 8BF41050needed delta is 88531, encodes as "qjye"1051bias becomes 901052output is "ihqwcrb4cv8a8dqg056pqjye"1053105410551056105710581059106010611062106310641065Costello Standards Track [Page 19]10661067RFC 3492 IDNA Punycode March 2003106810691070Encoding trace of example L from section 7.1:10711072bias is 721073input is:10740033 5E74 0042 7D44 91D1 516B 5148 751F1075basic code points (0033, 0042) are copied to literal portion: "3B-"1076next code point to insert is 51481077needed delta is 62042, encodes as "ww4c"1078bias becomes 271079next code point to insert is 516B1080needed delta is 139, encodes as "5e"1081bias becomes 241082next code point to insert is 5E741083needed delta is 16683, encodes as "180e"1084bias becomes 671085next code point to insert is 751F1086needed delta is 34821, encodes as "575a"1087bias becomes 821088next code point to insert is 7D441089needed delta is 14592, encodes as "65l"1090bias becomes 671091next code point to insert is 91D11092needed delta is 42088, encodes as "sy2b"1093bias becomes 841094output is "3B-ww4c5e180e575a65lsy2b"109510968. Security Considerations10971098Users expect each domain name in DNS to be controlled by a single1099authority. If a Unicode string intended for use as a domain label1100could map to multiple ACE labels, then an internationalized domain1101name could map to multiple ASCII domain names, each controlled by a1102different authority, some of which could be spoofs that hijack1103service requests intended for another. Therefore Punycode is1104designed so that each Unicode string has a unique encoding.11051106However, there can still be multiple Unicode representations of the1107"same" text, for various definitions of "same". This problem is1108addressed to some extent by the Unicode standard under the topic of1109canonicalization, and this work is leveraged for domain names by1110Nameprep [NAMEPREP].11111112111311141115111611171118111911201121Costello Standards Track [Page 20]11221123RFC 3492 IDNA Punycode March 20031124112511269. References112711289.1 Normative References11291130[RFC2119] Bradner, S., "Key words for use in RFCs to Indicate1131Requirement Levels", BCP 14, RFC 2119, March 1997.113211339.2 Informative References11341135[RFC952] Harrenstien, K., Stahl, M. and E. Feinler, "DOD Internet1136Host Table Specification", RFC 952, October 1985.11371138[RFC1034] Mockapetris, P., "Domain Names - Concepts and1139Facilities", STD 13, RFC 1034, November 1987.11401141[IDNA] Faltstrom, P., Hoffman, P. and A. Costello,1142"Internationalizing Domain Names in Applications1143(IDNA)", RFC 3490, March 2003.11441145[NAMEPREP] Hoffman, P. and M. Blanchet, "Nameprep: A Stringprep1146Profile for Internationalized Domain Names (IDN)", RFC11473491, March 2003.11481149[ASCII] Cerf, V., "ASCII format for Network Interchange", RFC115020, October 1969.11511152[PROVINCIAL] Kaplan, M., "The 'anyone can be provincial!' page",1153http://www.trigeminal.com/samples/provincial.html.11541155[UNICODE] The Unicode Consortium, "The Unicode Standard",1156http://www.unicode.org/unicode/standard/standard.html.115711581159116011611162116311641165116611671168116911701171117211731174117511761177Costello Standards Track [Page 21]11781179RFC 3492 IDNA Punycode March 2003118011811182A. Mixed-case annotation11831184In order to use Punycode to represent case-insensitive strings,1185higher layers need to case-fold the strings prior to Punycode1186encoding. The encoded string can use mixed case as an annotation1187telling how to convert the folded string into a mixed-case string for1188display purposes. Note, however, that mixed-case annotation is not1189used by the ToASCII and ToUnicode operations specified in [IDNA], and1190therefore implementors of IDNA can disregard this appendix.11911192Basic code points can use mixed case directly, because the decoder1193copies them verbatim, leaving lowercase code points lowercase, and1194leaving uppercase code points uppercase. Each non-basic code point1195is represented by a delta, which is represented by a sequence of1196basic code points, the last of which provides the annotation. If it1197is uppercase, it is a suggestion to map the non-basic code point to1198uppercase (if possible); if it is lowercase, it is a suggestion to1199map the non-basic code point to lowercase (if possible).12001201These annotations do not alter the code points returned by decoders;1202the annotations are returned separately, for the caller to use or1203ignore. Encoders can accept annotations in addition to code points,1204but the annotations do not alter the output, except to influence the1205uppercase/lowercase form of ASCII letters.12061207Punycode encoders and decoders need not support these annotations,1208and higher layers need not use them.12091210B. Disclaimer and license12111212Regarding this entire document or any portion of it (including the1213pseudocode and C code), the author makes no guarantees and is not1214responsible for any damage resulting from its use. The author grants1215irrevocable permission to anyone to use, modify, and distribute it in1216any way that does not diminish the rights of anyone else to use,1217modify, and distribute it, provided that redistributed derivative1218works do not contain misleading author or version information.1219Derivative works need not be licensed under similar terms.12201221122212231224122512261227122812291230123112321233Costello Standards Track [Page 22]12341235RFC 3492 IDNA Punycode March 2003123612371238C. Punycode sample implementation12391240/*1241punycode.c from RFC 34921242http://www.nicemice.net/idn/1243Adam M. Costello1244http://www.nicemice.net/amc/12451246This is ANSI C code (C89) implementing Punycode (RFC 3492).12471248*/124912501251/************************************************************/1252/* Public interface (would normally go in its own .h file): */12531254#include <limits.h>12551256enum punycode_status {1257punycode_success,1258punycode_bad_input, /* Input is invalid. */1259punycode_big_output, /* Output would exceed the space provided. */1260punycode_overflow /* Input needs wider integers to process. */1261};12621263#if UINT_MAX >= (1 << 26) - 11264typedef unsigned int punycode_uint;1265#else1266typedef unsigned long punycode_uint;1267#endif12681269enum punycode_status punycode_encode(1270punycode_uint input_length,1271const punycode_uint input[],1272const unsigned char case_flags[],1273punycode_uint *output_length,1274char output[] );12751276/* punycode_encode() converts Unicode to Punycode. The input */1277/* is represented as an array of Unicode code points (not code */1278/* units; surrogate pairs are not allowed), and the output */1279/* will be represented as an array of ASCII code points. The */1280/* output string is *not* null-terminated; it will contain */1281/* zeros if and only if the input contains zeros. (Of course */1282/* the caller can leave room for a terminator and add one if */1283/* needed.) The input_length is the number of code points in */1284/* the input. The output_length is an in/out argument: the */1285/* caller passes in the maximum number of code points that it */1286128712881289Costello Standards Track [Page 23]12901291RFC 3492 IDNA Punycode March 2003129212931294/* can receive, and on successful return it will contain the */1295/* number of code points actually output. The case_flags array */1296/* holds input_length boolean values, where nonzero suggests that */1297/* the corresponding Unicode character be forced to uppercase */1298/* after being decoded (if possible), and zero suggests that */1299/* it be forced to lowercase (if possible). ASCII code points */1300/* are encoded literally, except that ASCII letters are forced */1301/* to uppercase or lowercase according to the corresponding */1302/* uppercase flags. If case_flags is a null pointer then ASCII */1303/* letters are left as they are, and other code points are */1304/* treated as if their uppercase flags were zero. The return */1305/* value can be any of the punycode_status values defined above */1306/* except punycode_bad_input; if not punycode_success, then */1307/* output_size and output might contain garbage. */13081309enum punycode_status punycode_decode(1310punycode_uint input_length,1311const char input[],1312punycode_uint *output_length,1313punycode_uint output[],1314unsigned char case_flags[] );13151316/* punycode_decode() converts Punycode to Unicode. The input is */1317/* represented as an array of ASCII code points, and the output */1318/* will be represented as an array of Unicode code points. The */1319/* input_length is the number of code points in the input. The */1320/* output_length is an in/out argument: the caller passes in */1321/* the maximum number of code points that it can receive, and */1322/* on successful return it will contain the actual number of */1323/* code points output. The case_flags array needs room for at */1324/* least output_length values, or it can be a null pointer if the */1325/* case information is not needed. A nonzero flag suggests that */1326/* the corresponding Unicode character be forced to uppercase */1327/* by the caller (if possible), while zero suggests that it be */1328/* forced to lowercase (if possible). ASCII code points are */1329/* output already in the proper case, but their flags will be set */1330/* appropriately so that applying the flags would be harmless. */1331/* The return value can be any of the punycode_status values */1332/* defined above; if not punycode_success, then output_length, */1333/* output, and case_flags might contain garbage. On success, the */1334/* decoder will never need to write an output_length greater than */1335/* input_length, because of how the encoding is defined. */13361337/**********************************************************/1338/* Implementation (would normally go in its own .c file): */13391340#include <string.h>13411342134313441345Costello Standards Track [Page 24]13461347RFC 3492 IDNA Punycode March 2003134813491350/*** Bootstring parameters for Punycode ***/13511352enum { base = 36, tmin = 1, tmax = 26, skew = 38, damp = 700,1353initial_bias = 72, initial_n = 0x80, delimiter = 0x2D };13541355/* basic(cp) tests whether cp is a basic code point: */1356#define basic(cp) ((punycode_uint)(cp) < 0x80)13571358/* delim(cp) tests whether cp is a delimiter: */1359#define delim(cp) ((cp) == delimiter)13601361/* decode_digit(cp) returns the numeric value of a basic code */1362/* point (for use in representing integers) in the range 0 to */1363/* base-1, or base if cp is does not represent a value. */13641365static punycode_uint decode_digit(punycode_uint cp)1366{1367return cp - 48 < 10 ? cp - 22 : cp - 65 < 26 ? cp - 65 :1368cp - 97 < 26 ? cp - 97 : base;1369}13701371/* encode_digit(d,flag) returns the basic code point whose value */1372/* (when used for representing integers) is d, which needs to be in */1373/* the range 0 to base-1. The lowercase form is used unless flag is */1374/* nonzero, in which case the uppercase form is used. The behavior */1375/* is undefined if flag is nonzero and digit d has no uppercase form. */13761377static char encode_digit(punycode_uint d, int flag)1378{1379return d + 22 + 75 * (d < 26) - ((flag != 0) << 5);1380/* 0..25 map to ASCII a..z or A..Z */1381/* 26..35 map to ASCII 0..9 */1382}13831384/* flagged(bcp) tests whether a basic code point is flagged */1385/* (uppercase). The behavior is undefined if bcp is not a */1386/* basic code point. */13871388#define flagged(bcp) ((punycode_uint)(bcp) - 65 < 26)13891390/* encode_basic(bcp,flag) forces a basic code point to lowercase */1391/* if flag is zero, uppercase if flag is nonzero, and returns */1392/* the resulting code point. The code point is unchanged if it */1393/* is caseless. The behavior is undefined if bcp is not a basic */1394/* code point. */13951396static char encode_basic(punycode_uint bcp, int flag)1397{1398139914001401Costello Standards Track [Page 25]14021403RFC 3492 IDNA Punycode March 2003140414051406bcp -= (bcp - 97 < 26) << 5;1407return bcp + ((!flag && (bcp - 65 < 26)) << 5);1408}14091410/*** Platform-specific constants ***/14111412/* maxint is the maximum value of a punycode_uint variable: */1413static const punycode_uint maxint = -1;1414/* Because maxint is unsigned, -1 becomes the maximum value. */14151416/*** Bias adaptation function ***/14171418static punycode_uint adapt(1419punycode_uint delta, punycode_uint numpoints, int firsttime )1420{1421punycode_uint k;14221423delta = firsttime ? delta / damp : delta >> 1;1424/* delta >> 1 is a faster way of doing delta / 2 */1425delta += delta / numpoints;14261427for (k = 0; delta > ((base - tmin) * tmax) / 2; k += base) {1428delta /= base - tmin;1429}14301431return k + (base - tmin + 1) * delta / (delta + skew);1432}14331434/*** Main encode function ***/14351436enum punycode_status punycode_encode(1437punycode_uint input_length,1438const punycode_uint input[],1439const unsigned char case_flags[],1440punycode_uint *output_length,1441char output[] )1442{1443punycode_uint n, delta, h, b, out, max_out, bias, j, m, q, k, t;14441445/* Initialize the state: */14461447n = initial_n;1448delta = out = 0;1449max_out = *output_length;1450bias = initial_bias;14511452/* Handle the basic code points: */14531454145514561457Costello Standards Track [Page 26]14581459RFC 3492 IDNA Punycode March 2003146014611462for (j = 0; j < input_length; ++j) {1463if (basic(input[j])) {1464if (max_out - out < 2) return punycode_big_output;1465output[out++] =1466case_flags ? encode_basic(input[j], case_flags[j]) : input[j];1467}1468/* else if (input[j] < n) return punycode_bad_input; */1469/* (not needed for Punycode with unsigned code points) */1470}14711472h = b = out;14731474/* h is the number of code points that have been handled, b is the */1475/* number of basic code points, and out is the number of characters */1476/* that have been output. */14771478if (b > 0) output[out++] = delimiter;14791480/* Main encoding loop: */14811482while (h < input_length) {1483/* All non-basic code points < n have been */1484/* handled already. Find the next larger one: */14851486for (m = maxint, j = 0; j < input_length; ++j) {1487/* if (basic(input[j])) continue; */1488/* (not needed for Punycode) */1489if (input[j] >= n && input[j] < m) m = input[j];1490}14911492/* Increase delta enough to advance the decoder's */1493/* <n,i> state to <m,0>, but guard against overflow: */14941495if (m - n > (maxint - delta) / (h + 1)) return punycode_overflow;1496delta += (m - n) * (h + 1);1497n = m;14981499for (j = 0; j < input_length; ++j) {1500/* Punycode does not need to check whether input[j] is basic: */1501if (input[j] < n /* || basic(input[j]) */ ) {1502if (++delta == 0) return punycode_overflow;1503}15041505if (input[j] == n) {1506/* Represent delta as a generalized variable-length integer: */15071508for (q = delta, k = base; ; k += base) {1509if (out >= max_out) return punycode_big_output;1510151115121513Costello Standards Track [Page 27]15141515RFC 3492 IDNA Punycode March 2003151615171518t = k <= bias /* + tmin */ ? tmin : /* +tmin not needed */1519k >= bias + tmax ? tmax : k - bias;1520if (q < t) break;1521output[out++] = encode_digit(t + (q - t) % (base - t), 0);1522q = (q - t) / (base - t);1523}15241525output[out++] = encode_digit(q, case_flags && case_flags[j]);1526bias = adapt(delta, h + 1, h == b);1527delta = 0;1528++h;1529}1530}15311532++delta, ++n;1533}15341535*output_length = out;1536return punycode_success;1537}15381539/*** Main decode function ***/15401541enum punycode_status punycode_decode(1542punycode_uint input_length,1543const char input[],1544punycode_uint *output_length,1545punycode_uint output[],1546unsigned char case_flags[] )1547{1548punycode_uint n, out, i, max_out, bias,1549b, j, in, oldi, w, k, digit, t;15501551/* Initialize the state: */15521553n = initial_n;1554out = i = 0;1555max_out = *output_length;1556bias = initial_bias;15571558/* Handle the basic code points: Let b be the number of input code */1559/* points before the last delimiter, or 0 if there is none, then */1560/* copy the first b code points to the output. */15611562for (b = j = 0; j < input_length; ++j) if (delim(input[j])) b = j;1563if (b > max_out) return punycode_big_output;15641565for (j = 0; j < b; ++j) {1566156715681569Costello Standards Track [Page 28]15701571RFC 3492 IDNA Punycode March 2003157215731574if (case_flags) case_flags[out] = flagged(input[j]);1575if (!basic(input[j])) return punycode_bad_input;1576output[out++] = input[j];1577}15781579/* Main decoding loop: Start just after the last delimiter if any */1580/* basic code points were copied; start at the beginning otherwise. */15811582for (in = b > 0 ? b + 1 : 0; in < input_length; ++out) {15831584/* in is the index of the next character to be consumed, and */1585/* out is the number of code points in the output array. */15861587/* Decode a generalized variable-length integer into delta, */1588/* which gets added to i. The overflow checking is easier */1589/* if we increase i as we go, then subtract off its starting */1590/* value at the end to obtain delta. */15911592for (oldi = i, w = 1, k = base; ; k += base) {1593if (in >= input_length) return punycode_bad_input;1594digit = decode_digit(input[in++]);1595if (digit >= base) return punycode_bad_input;1596if (digit > (maxint - i) / w) return punycode_overflow;1597i += digit * w;1598t = k <= bias /* + tmin */ ? tmin : /* +tmin not needed */1599k >= bias + tmax ? tmax : k - bias;1600if (digit < t) break;1601if (w > maxint / (base - t)) return punycode_overflow;1602w *= (base - t);1603}16041605bias = adapt(i - oldi, out + 1, oldi == 0);16061607/* i was supposed to wrap around from out+1 to 0, */1608/* incrementing n each time, so we'll fix that now: */16091610if (i / (out + 1) > maxint - n) return punycode_overflow;1611n += i / (out + 1);1612i %= (out + 1);16131614/* Insert n at position i of the output: */16151616/* not needed for Punycode: */1617/* if (decode_digit(n) <= base) return punycode_invalid_input; */1618if (out >= max_out) return punycode_big_output;16191620if (case_flags) {1621memmove(case_flags + i + 1, case_flags + i, out - i);1622162316241625Costello Standards Track [Page 29]16261627RFC 3492 IDNA Punycode March 2003162816291630/* Case of last character determines uppercase flag: */1631case_flags[i] = flagged(input[in - 1]);1632}16331634memmove(output + i + 1, output + i, (out - i) * sizeof *output);1635output[i++] = n;1636}16371638*output_length = out;1639return punycode_success;1640}16411642/******************************************************************/1643/* Wrapper for testing (would normally go in a separate .c file): */16441645#include <assert.h>1646#include <stdio.h>1647#include <stdlib.h>1648#include <string.h>16491650/* For testing, we'll just set some compile-time limits rather than */1651/* use malloc(), and set a compile-time option rather than using a */1652/* command-line option. */16531654enum {1655unicode_max_length = 256,1656ace_max_length = 2561657};16581659static void usage(char **argv)1660{1661fprintf(stderr,1662"\n"1663"%s -e reads code points and writes a Punycode string.\n"1664"%s -d reads a Punycode string and writes code points.\n"1665"\n"1666"Input and output are plain text in the native character set.\n"1667"Code points are in the form u+hex separated by whitespace.\n"1668"Although the specification allows Punycode strings to contain\n"1669"any characters from the ASCII repertoire, this test code\n"1670"supports only the printable characters, and needs the Punycode\n"1671"string to be followed by a newline.\n"1672"The case of the u in u+hex is the force-to-uppercase flag.\n"1673, argv[0], argv[0]);1674exit(EXIT_FAILURE);1675}16761677static void fail(const char *msg)1678167916801681Costello Standards Track [Page 30]16821683RFC 3492 IDNA Punycode March 2003168416851686{1687fputs(msg,stderr);1688exit(EXIT_FAILURE);1689}16901691static const char too_big[] =1692"input or output is too large, recompile with larger limits\n";1693static const char invalid_input[] = "invalid input\n";1694static const char overflow[] = "arithmetic overflow\n";1695static const char io_error[] = "I/O error\n";16961697/* The following string is used to convert printable */1698/* characters between ASCII and the native charset: */16991700static const char print_ascii[] =1701"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"1702"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"1703" !\"#$%&'()*+,-./"1704"0123456789:;<=>?"1705"@ABCDEFGHIJKLMNO"1706"PQRSTUVWXYZ[\\]^_"1707"`abcdefghijklmno"1708"pqrstuvwxyz{|}~\n";17091710int main(int argc, char **argv)1711{1712enum punycode_status status;1713int r;1714unsigned int input_length, output_length, j;1715unsigned char case_flags[unicode_max_length];17161717if (argc != 2) usage(argv);1718if (argv[1][0] != '-') usage(argv);1719if (argv[1][2] != 0) usage(argv);17201721if (argv[1][1] == 'e') {1722punycode_uint input[unicode_max_length];1723unsigned long codept;1724char output[ace_max_length+1], uplus[3];1725int c;17261727/* Read the input code points: */17281729input_length = 0;17301731for (;;) {1732r = scanf("%2s%lx", uplus, &codept);1733if (ferror(stdin)) fail(io_error);1734173517361737Costello Standards Track [Page 31]17381739RFC 3492 IDNA Punycode March 2003174017411742if (r == EOF || r == 0) break;17431744if (r != 2 || uplus[1] != '+' || codept > (punycode_uint)-1) {1745fail(invalid_input);1746}17471748if (input_length == unicode_max_length) fail(too_big);17491750if (uplus[0] == 'u') case_flags[input_length] = 0;1751else if (uplus[0] == 'U') case_flags[input_length] = 1;1752else fail(invalid_input);17531754input[input_length++] = codept;1755}17561757/* Encode: */17581759output_length = ace_max_length;1760status = punycode_encode(input_length, input, case_flags,1761&output_length, output);1762if (status == punycode_bad_input) fail(invalid_input);1763if (status == punycode_big_output) fail(too_big);1764if (status == punycode_overflow) fail(overflow);1765assert(status == punycode_success);17661767/* Convert to native charset and output: */17681769for (j = 0; j < output_length; ++j) {1770c = output[j];1771assert(c >= 0 && c <= 127);1772if (print_ascii[c] == 0) fail(invalid_input);1773output[j] = print_ascii[c];1774}17751776output[j] = 0;1777r = puts(output);1778if (r == EOF) fail(io_error);1779return EXIT_SUCCESS;1780}17811782if (argv[1][1] == 'd') {1783char input[ace_max_length+2], *p, *pp;1784punycode_uint output[unicode_max_length];17851786/* Read the Punycode input string and convert to ASCII: */17871788fgets(input, ace_max_length+2, stdin);1789if (ferror(stdin)) fail(io_error);1790179117921793Costello Standards Track [Page 32]17941795RFC 3492 IDNA Punycode March 2003179617971798if (feof(stdin)) fail(invalid_input);1799input_length = strlen(input) - 1;1800if (input[input_length] != '\n') fail(too_big);1801input[input_length] = 0;18021803for (p = input; *p != 0; ++p) {1804pp = strchr(print_ascii, *p);1805if (pp == 0) fail(invalid_input);1806*p = pp - print_ascii;1807}18081809/* Decode: */18101811output_length = unicode_max_length;1812status = punycode_decode(input_length, input, &output_length,1813output, case_flags);1814if (status == punycode_bad_input) fail(invalid_input);1815if (status == punycode_big_output) fail(too_big);1816if (status == punycode_overflow) fail(overflow);1817assert(status == punycode_success);18181819/* Output the result: */18201821for (j = 0; j < output_length; ++j) {1822r = printf("%s+%04lX\n",1823case_flags[j] ? "U" : "u",1824(unsigned long) output[j] );1825if (r < 0) fail(io_error);1826}18271828return EXIT_SUCCESS;1829}18301831usage(argv);1832return EXIT_SUCCESS; /* not reached, but quiets compiler warning */1833}1834183518361837183818391840184118421843184418451846184718481849Costello Standards Track [Page 33]18501851RFC 3492 IDNA Punycode March 2003185218531854Author's Address18551856Adam M. Costello1857University of California, Berkeley1858http://www.nicemice.net/amc/18591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905Costello Standards Track [Page 34]19061907RFC 3492 IDNA Punycode March 2003190819091910Full Copyright Statement19111912Copyright (C) The Internet Society (2003). All Rights Reserved.19131914This document and translations of it may be copied and furnished to1915others, and derivative works that comment on or otherwise explain it1916or assist in its implementation may be prepared, copied, published1917and distributed, in whole or in part, without restriction of any1918kind, provided that the above copyright notice and this paragraph are1919included on all such copies and derivative works. However, this1920document itself may not be modified in any way, such as by removing1921the copyright notice or references to the Internet Society or other1922Internet organizations, except as needed for the purpose of1923developing Internet standards in which case the procedures for1924copyrights defined in the Internet Standards process must be1925followed, or as required to translate it into languages other than1926English.19271928The limited permissions granted above are perpetual and will not be1929revoked by the Internet Society or its successors or assigns.19301931This document and the information contained herein is provided on an1932"AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING1933TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING1934BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION1935HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF1936MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.19371938Acknowledgement19391940Funding for the RFC Editor function is currently provided by the1941Internet Society.19421943194419451946194719481949195019511952195319541955195619571958195919601961Costello Standards Track [Page 35]1962196319641965