Remove gets declaration
[glibc.git] / libidn / punycode.c
blob372f849c0254fd8765a98c0e23729a4c5dc8a050
1 /* punycode.c Implementation of punycode used to ASCII encode IDN's.
2 * Copyright (C) 2002, 2003 Simon Josefsson
4 * This file is part of GNU Libidn.
6 * GNU Libidn is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * GNU Libidn is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with GNU Libidn; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 * This file is derived from RFC 3492bis written by Adam M. Costello.
25 * Disclaimer and license: Regarding this entire document or any
26 * portion of it (including the pseudocode and C code), the author
27 * makes no guarantees and is not responsible for any damage resulting
28 * from its use. The author grants irrevocable permission to anyone
29 * to use, modify, and distribute it in any way that does not diminish
30 * the rights of anyone else to use, modify, and distribute it,
31 * provided that redistributed derivative works do not contain
32 * misleading author or version information. Derivative works need
33 * not be licensed under similar terms.
35 * Copyright (C) The Internet Society (2003). All Rights Reserved.
37 * This document and translations of it may be copied and furnished to
38 * others, and derivative works that comment on or otherwise explain it
39 * or assist in its implementation may be prepared, copied, published
40 * and distributed, in whole or in part, without restriction of any
41 * kind, provided that the above copyright notice and this paragraph are
42 * included on all such copies and derivative works. However, this
43 * document itself may not be modified in any way, such as by removing
44 * the copyright notice or references to the Internet Society or other
45 * Internet organizations, except as needed for the purpose of
46 * developing Internet standards in which case the procedures for
47 * copyrights defined in the Internet Standards process must be
48 * followed, or as required to translate it into languages other than
49 * English.
51 * The limited permissions granted above are perpetual and will not be
52 * revoked by the Internet Society or its successors or assigns.
54 * This document and the information contained herein is provided on an
55 * "AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING
56 * TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING
57 * BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION
58 * HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF
59 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
62 #include <string.h>
64 #include "punycode.h"
66 /*** Bootstring parameters for Punycode ***/
68 enum
69 { base = 36, tmin = 1, tmax = 26, skew = 38, damp = 700,
70 initial_bias = 72, initial_n = 0x80, delimiter = 0x2D
73 /* basic(cp) tests whether cp is a basic code point: */
74 #define basic(cp) ((punycode_uint)(cp) < 0x80)
76 /* delim(cp) tests whether cp is a delimiter: */
77 #define delim(cp) ((cp) == delimiter)
79 /* decode_digit(cp) returns the numeric value of a basic code */
80 /* point (for use in representing integers) in the range 0 to */
81 /* base-1, or base if cp does not represent a value. */
83 static punycode_uint
84 decode_digit (punycode_uint cp)
86 return cp - 48 < 10 ? cp - 22 : cp - 65 < 26 ? cp - 65 :
87 cp - 97 < 26 ? cp - 97 : base;
90 /* encode_digit(d,flag) returns the basic code point whose value */
91 /* (when used for representing integers) is d, which needs to be in */
92 /* the range 0 to base-1. The lowercase form is used unless flag is */
93 /* nonzero, in which case the uppercase form is used. The behavior */
94 /* is undefined if flag is nonzero and digit d has no uppercase form. */
96 static char
97 encode_digit (punycode_uint d, int flag)
99 return d + 22 + 75 * (d < 26) - ((flag != 0) << 5);
100 /* 0..25 map to ASCII a..z or A..Z */
101 /* 26..35 map to ASCII 0..9 */
104 /* flagged(bcp) tests whether a basic code point is flagged */
105 /* (uppercase). The behavior is undefined if bcp is not a */
106 /* basic code point. */
108 #define flagged(bcp) ((punycode_uint)(bcp) - 65 < 26)
110 /* encode_basic(bcp,flag) forces a basic code point to lowercase */
111 /* if flag is zero, uppercase if flag is nonzero, and returns */
112 /* the resulting code point. The code point is unchanged if it */
113 /* is caseless. The behavior is undefined if bcp is not a basic */
114 /* code point. */
116 static char
117 encode_basic (punycode_uint bcp, int flag)
119 bcp -= (bcp - 97 < 26) << 5;
120 return bcp + ((!flag && (bcp - 65 < 26)) << 5);
123 /*** Platform-specific constants ***/
125 /* maxint is the maximum value of a punycode_uint variable: */
126 static const punycode_uint maxint = -1;
127 /* Because maxint is unsigned, -1 becomes the maximum value. */
129 /*** Bias adaptation function ***/
131 static punycode_uint
132 adapt (punycode_uint delta, punycode_uint numpoints, int firsttime)
134 punycode_uint k;
136 delta = firsttime ? delta / damp : delta >> 1;
137 /* delta >> 1 is a faster way of doing delta / 2 */
138 delta += delta / numpoints;
140 for (k = 0; delta > ((base - tmin) * tmax) / 2; k += base)
142 delta /= base - tmin;
145 return k + (base - tmin + 1) * delta / (delta + skew);
148 /*** Main encode function ***/
151 * punycode_encode:
152 * @input_length: The number of code points in the @input array and
153 * the number of flags in the @case_flags array.
154 * @input: An array of code points. They are presumed to be Unicode
155 * code points, but that is not strictly REQUIRED. The array
156 * contains code points, not code units. UTF-16 uses code units
157 * D800 through DFFF to refer to code points 10000..10FFFF. The
158 * code points D800..DFFF do not occur in any valid Unicode string.
159 * The code points that can occur in Unicode strings (0..D7FF and
160 * E000..10FFFF) are also called Unicode scalar values.
161 * @case_flags: A %NULL pointer or an array of boolean values parallel
162 * to the @input array. Nonzero (true, flagged) suggests that the
163 * corresponding Unicode character be forced to uppercase after
164 * being decoded (if possible), and zero (false, unflagged) suggests
165 * that it be forced to lowercase (if possible). ASCII code points
166 * (0..7F) are encoded literally, except that ASCII letters are
167 * forced to uppercase or lowercase according to the corresponding
168 * case flags. If @case_flags is a %NULL pointer then ASCII letters
169 * are left as they are, and other code points are treated as
170 * unflagged.
171 * @output_length: The caller passes in the maximum number of ASCII
172 * code points that it can receive. On successful return it will
173 * contain the number of ASCII code points actually output.
174 * @output: An array of ASCII code points. It is *not*
175 * null-terminated; it will contain zeros if and only if the @input
176 * contains zeros. (Of course the caller can leave room for a
177 * terminator and add one if needed.)
179 * Converts a sequence of code points (presumed to be Unicode code
180 * points) to Punycode.
182 * Return value: The return value can be any of the punycode_status
183 * values defined above except %punycode_bad_input. If not
184 * %punycode_success, then @output_size and @output might contain
185 * garbage.
188 punycode_encode (size_t input_length,
189 const punycode_uint input[],
190 const unsigned char case_flags[],
191 size_t * output_length, char output[])
193 punycode_uint input_len, n, delta, h, b, bias, j, m, q, k, t;
194 size_t out, max_out;
196 /* The Punycode spec assumes that the input length is the same type */
197 /* of integer as a code point, so we need to convert the size_t to */
198 /* a punycode_uint, which could overflow. */
200 if (input_length > maxint)
201 return punycode_overflow;
202 input_len = (punycode_uint) input_length;
204 /* Initialize the state: */
206 n = initial_n;
207 delta = 0;
208 out = 0;
209 max_out = *output_length;
210 bias = initial_bias;
212 /* Handle the basic code points: */
214 for (j = 0; j < input_len; ++j)
216 if (basic (input[j]))
218 if (max_out - out < 2)
219 return punycode_big_output;
220 output[out++] = case_flags ?
221 encode_basic (input[j], case_flags[j]) : (char) input[j];
223 /* else if (input[j] < n) return punycode_bad_input; */
224 /* (not needed for Punycode with unsigned code points) */
227 h = b = (punycode_uint) out;
228 /* cannot overflow because out <= input_len <= maxint */
230 /* h is the number of code points that have been handled, b is the */
231 /* number of basic code points, and out is the number of ASCII code */
232 /* points that have been output. */
234 if (b > 0)
235 output[out++] = delimiter;
237 /* Main encoding loop: */
239 while (h < input_len)
241 /* All non-basic code points < n have been */
242 /* handled already. Find the next larger one: */
244 for (m = maxint, j = 0; j < input_len; ++j)
246 /* if (basic(input[j])) continue; */
247 /* (not needed for Punycode) */
248 if (input[j] >= n && input[j] < m)
249 m = input[j];
252 /* Increase delta enough to advance the decoder's */
253 /* <n,i> state to <m,0>, but guard against overflow: */
255 if (m - n > (maxint - delta) / (h + 1))
256 return punycode_overflow;
257 delta += (m - n) * (h + 1);
258 n = m;
260 for (j = 0; j < input_len; ++j)
262 /* Punycode does not need to check whether input[j] is basic: */
263 if (input[j] < n /* || basic(input[j]) */ )
265 if (++delta == 0)
266 return punycode_overflow;
269 if (input[j] == n)
271 /* Represent delta as a generalized variable-length integer: */
273 for (q = delta, k = base;; k += base)
275 if (out >= max_out)
276 return punycode_big_output;
277 t = k <= bias /* + tmin */ ? tmin : /* +tmin not needed */
278 k >= bias + tmax ? tmax : k - bias;
279 if (q < t)
280 break;
281 output[out++] = encode_digit (t + (q - t) % (base - t), 0);
282 q = (q - t) / (base - t);
285 output[out++] = encode_digit (q, case_flags && case_flags[j]);
286 bias = adapt (delta, h + 1, h == b);
287 delta = 0;
288 ++h;
292 ++delta, ++n;
295 *output_length = out;
296 return punycode_success;
299 /*** Main decode function ***/
302 * punycode_decode:
303 * @input_length: The number of ASCII code points in the @input array.
304 * @input: An array of ASCII code points (0..7F).
305 * @output_length: The caller passes in the maximum number of code
306 * points that it can receive into the @output array (which is also
307 * the maximum number of flags that it can receive into the
308 * @case_flags array, if @case_flags is not a %NULL pointer). On
309 * successful return it will contain the number of code points
310 * actually output (which is also the number of flags actually
311 * output, if case_flags is not a null pointer). The decoder will
312 * never need to output more code points than the number of ASCII
313 * code points in the input, because of the way the encoding is
314 * defined. The number of code points output cannot exceed the
315 * maximum possible value of a punycode_uint, even if the supplied
316 * @output_length is greater than that.
317 * @output: An array of code points like the input argument of
318 * punycode_encode() (see above).
319 * @case_flags: A %NULL pointer (if the flags are not needed by the
320 * caller) or an array of boolean values parallel to the @output
321 * array. Nonzero (true, flagged) suggests that the corresponding
322 * Unicode character be forced to uppercase by the caller (if
323 * possible), and zero (false, unflagged) suggests that it be forced
324 * to lowercase (if possible). ASCII code points (0..7F) are output
325 * already in the proper case, but their flags will be set
326 * appropriately so that applying the flags would be harmless.
328 * Converts Punycode to a sequence of code points (presumed to be
329 * Unicode code points).
331 * Return value: The return value can be any of the punycode_status
332 * values defined above. If not %punycode_success, then
333 * @output_length, @output, and @case_flags might contain garbage.
337 punycode_decode (size_t input_length,
338 const char input[],
339 size_t * output_length,
340 punycode_uint output[], unsigned char case_flags[])
342 punycode_uint n, out, i, max_out, bias, oldi, w, k, digit, t;
343 size_t b, j, in;
345 /* Initialize the state: */
347 n = initial_n;
348 out = i = 0;
349 max_out = *output_length > maxint ? maxint
350 : (punycode_uint) * output_length;
351 bias = initial_bias;
353 /* Handle the basic code points: Let b be the number of input code */
354 /* points before the last delimiter, or 0 if there is none, then */
355 /* copy the first b code points to the output. */
357 for (b = j = 0; j < input_length; ++j)
358 if (delim (input[j]))
359 b = j;
360 if (b > max_out)
361 return punycode_big_output;
363 for (j = 0; j < b; ++j)
365 if (case_flags)
366 case_flags[out] = flagged (input[j]);
367 if (!basic (input[j]))
368 return punycode_bad_input;
369 output[out++] = input[j];
372 /* Main decoding loop: Start just after the last delimiter if any */
373 /* basic code points were copied; start at the beginning otherwise. */
375 for (in = b > 0 ? b + 1 : 0; in < input_length; ++out)
378 /* in is the index of the next ASCII code point to be consumed, */
379 /* and out is the number of code points in the output array. */
381 /* Decode a generalized variable-length integer into delta, */
382 /* which gets added to i. The overflow checking is easier */
383 /* if we increase i as we go, then subtract off its starting */
384 /* value at the end to obtain delta. */
386 for (oldi = i, w = 1, k = base;; k += base)
388 if (in >= input_length)
389 return punycode_bad_input;
390 digit = decode_digit (input[in++]);
391 if (digit >= base)
392 return punycode_bad_input;
393 if (digit > (maxint - i) / w)
394 return punycode_overflow;
395 i += digit * w;
396 t = k <= bias /* + tmin */ ? tmin : /* +tmin not needed */
397 k >= bias + tmax ? tmax : k - bias;
398 if (digit < t)
399 break;
400 if (w > maxint / (base - t))
401 return punycode_overflow;
402 w *= (base - t);
405 bias = adapt (i - oldi, out + 1, oldi == 0);
407 /* i was supposed to wrap around from out+1 to 0, */
408 /* incrementing n each time, so we'll fix that now: */
410 if (i / (out + 1) > maxint - n)
411 return punycode_overflow;
412 n += i / (out + 1);
413 i %= (out + 1);
415 /* Insert n at position i of the output: */
417 /* not needed for Punycode: */
418 /* if (basic(n)) return punycode_invalid_input; */
419 if (out >= max_out)
420 return punycode_big_output;
422 if (case_flags)
424 memmove (case_flags + i + 1, case_flags + i, out - i);
425 /* Case of last ASCII code point determines case flag: */
426 case_flags[i] = flagged (input[in - 1]);
429 memmove (output + i + 1, output + i, (out - i) * sizeof *output);
430 output[i++] = n;
433 *output_length = (size_t) out;
434 /* cannot overflow because out <= old value of *output_length */
435 return punycode_success;
439 * punycode_uint
441 * Unicode code point data type, this is always a 32 bit unsigned
442 * integer.
446 * Punycode_status
447 * @PUNYCODE_SUCCESS: Successful operation. This value is guaranteed
448 * to always be zero, the remaining ones are only guaranteed to hold
449 * non-zero values, for logical comparison purposes.
450 * @PUNYCODE_BAD_INPUT: Input is invalid.
451 * @PUNYCODE_BIG_OUTPUT: Output would exceed the space provided.
452 * @PUNYCODE_OVERFLOW: Input needs wider integers to process.
454 * Enumerated return codes of punycode_encode() and punycode_decode().
455 * The value 0 is guaranteed to always correspond to success.