1 /* punycode.c - punycode encoding/decoding
2    Copyright (C) 2011-2021 Simon Josefsson
3 
4    Libidn2 is free software: you can redistribute it and/or modify it
5    under the terms of either:
6 
7      * the GNU Lesser General Public License as published by the Free
8        Software Foundation; either version 3 of the License, or (at
9        your option) any later version.
10 
11    or
12 
13      * the GNU General Public License as published by the Free
14        Software Foundation; either version 2 of the License, or (at
15        your option) any later version.
16 
17    or both in parallel, as here.
18 
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23 
24    You should have received copies of the GNU General Public License and
25    the GNU Lesser General Public License along with this program.  If
26    not, see <http://www.gnu.org/licenses/>.
27 */
28 
29 /*
30   Code copied from http://www.nicemice.net/idn/punycode-spec.gz on
31   2011-01-04 with SHA-1 a966a8017f6be579d74a50a226accc7607c40133
32   labeled punycode-spec 1.0.3 (2006-Mar-23-Thu).  It is modified for
33   Libidn2 by Simon Josefsson.  License on the original code:
34 
35   punycode-spec 1.0.3 (2006-Mar-23-Thu)
36   http://www.nicemice.net/idn/
37   Adam M. Costello
38   http://www.nicemice.net/amc/
39 
40   B. Disclaimer and license
41 
42     Regarding this entire document or any portion of it (including
43     the pseudocode and C code), the author makes no guarantees and
44     is not responsible for any damage resulting from its use.  The
45     author grants irrevocable permission to anyone to use, modify,
46     and distribute it in any way that does not diminish the rights
47     of anyone else to use, modify, and distribute it, provided that
48     redistributed derivative works do not contain misleading author or
49     version information.  Derivative works need not be licensed under
50     similar terms.
51 
52   C. Punycode sample implementation
53 
54   punycode-sample.c 2.0.0 (2004-Mar-21-Sun)
55   http://www.nicemice.net/idn/
56   Adam M. Costello
57   http://www.nicemice.net/amc/
58 
59   This is ANSI C code (C89) implementing Punycode 1.0.x.
60 */
61 
62 #include <config.h>
63 
64 #include "idn2.h"		/* IDN2_OK, ... */
65 
66 /* Re-definitions to avoid modifying code below too much. */
67 #define punycode_uint uint32_t
68 #define punycode_success IDN2_OK
69 #define punycode_overflow IDN2_PUNYCODE_OVERFLOW
70 #define punycode_big_output IDN2_PUNYCODE_BIG_OUTPUT
71 #define punycode_bad_input IDN2_PUNYCODE_BAD_INPUT
72 #define punycode_decode _idn2_punycode_decode_internal
73 
74 /**********************************************************/
75 /* Implementation (would normally go in its own .c file): */
76 
77 #include <stdio.h>
78 #include <string.h>
79 
80 #include "punycode.h"
81 
82 /*** Bootstring parameters for Punycode ***/
83 
84 enum
85 { base = 36, tmin = 1, tmax = 26, skew = 38, damp = 700,
86   initial_bias = 72, initial_n = 0x80, delimiter = 0x2D
87 };
88 
89 /* basic(cp) tests whether cp is a basic code point: */
90 #define basic(cp) ((cp >= 'a' && cp <= 'z') || (cp >= '0' && cp <='9') || (cp >= 'A' && cp <='Z') || cp == '-' || cp == '_')
91 
92 /* decode_digit(cp) returns the numeric value of a basic code */
93 /* point (for use in representing integers) in the range 0 to */
94 /* base-1, or base if cp does not represent a value.          */
95 
96 static unsigned
decode_digit(int cp)97 decode_digit (int cp)
98 {
99   if (cp >= 'a' && cp <= 'z')
100     return cp - 'a';
101   if (cp >= '0' && cp <= '9')
102     return cp - '0' + 26;
103   if (cp >= 'A' && cp <= 'Z')
104     return cp - 'A';
105 
106   return 0;
107 }
108 
109 /*** Platform-specific constants ***/
110 
111 /* maxint is the maximum value of a punycode_uint variable: */
112 static const punycode_uint maxint = -1;
113 /* Because maxint is unsigned, -1 becomes the maximum value. */
114 
115 /*** Bias adaptation function ***/
116 
117 static punycode_uint
118 adapt (punycode_uint delta, punycode_uint numpoints, int firsttime)
119   _GL_ATTRIBUTE_CONST;
120 
adapt(punycode_uint delta,punycode_uint numpoints,int firsttime)121      static punycode_uint adapt (punycode_uint delta, punycode_uint numpoints,
122 				 int firsttime)
123 {
124   punycode_uint k;
125 
126   delta = firsttime ? delta / damp : delta >> 1;
127   /* delta >> 1 is a faster way of doing delta / 2 */
128   delta += delta / numpoints;
129 
130   for (k = 0; delta > ((base - tmin) * tmax) / 2; k += base)
131     {
132       delta /= base - tmin;
133     }
134 
135   return k + (base - tmin + 1) * delta / (delta + skew);
136 }
137 
138 /*** Main decode function ***/
139 
140 int
punycode_decode(size_t input_length,const char input[],size_t * output_length,punycode_uint output[])141 punycode_decode (size_t input_length,
142 		 const char input[],
143 		 size_t *output_length, punycode_uint output[])
144 {
145   punycode_uint n, out = 0, i, max_out, bias, oldi, w, k, digit, t;
146   size_t b = 0, j, in;
147 
148   if (!input_length)
149     return punycode_bad_input;
150 
151   /* Check that all chars are basic */
152   for (j = 0; j < input_length; ++j)
153     {
154       if (!basic (input[j]))
155 	return punycode_bad_input;
156       if (input[j] == delimiter)
157 	b = j;
158     }
159 
160   max_out =
161     *output_length > maxint ? maxint : (punycode_uint) * output_length;
162 
163   if (input[b] == delimiter)
164     {
165       /* do not accept leading or trailing delimiter
166        *   - leading delim must be omitted if there is no ASCII char in u-label
167        *   - trailing delim means there where no non-ASCII chars in u-label
168        */
169       if (!b || b == input_length - 1)
170 	return punycode_bad_input;
171 
172       if (b >= max_out)
173 	return punycode_big_output;
174 
175       /* Check that all chars before last delimiter are basic chars */
176       /* and copy the first b code points to the output. */
177       for (j = 0; j < b; j++)
178 	output[out++] = input[j];
179 
180       b += 1;			/* advance to non-basic char encoding */
181     }
182 
183   /* Initialize the state: */
184   n = initial_n;
185   i = 0;
186   bias = initial_bias;
187 
188   /* Main decoding loop:  Start just after the last delimiter if any  */
189   /* basic code points were copied; start at the beginning otherwise. */
190   for (in = b; in < input_length; ++out)
191     {
192 
193       /* in is the index of the next ASCII code point to be consumed, */
194       /* and out is the number of code points in the output array.    */
195 
196       /* Decode a generalized variable-length integer into delta,  */
197       /* which gets added to i.  The overflow checking is easier   */
198       /* if we increase i as we go, then subtract off its starting */
199       /* value at the end to obtain delta.                         */
200       for (oldi = i, w = 1, k = base;; k += base)
201 	{
202 	  if (in >= input_length)
203 	    return punycode_bad_input;
204 	  digit = decode_digit (input[in++]);
205 	  if (digit >= base)
206 	    return punycode_bad_input;
207 	  if (digit > (maxint - i) / w)
208 	    return punycode_overflow;
209 	  i += digit * w;
210 	  t = k <= bias /* + tmin */ ? tmin :	/* +tmin not needed */
211 	    k >= bias + tmax ? tmax : k - bias;
212 	  if (digit < t)
213 	    break;
214 	  if (w > maxint / (base - t))
215 	    return punycode_overflow;
216 	  w *= (base - t);
217 	}
218 
219       bias = adapt (i - oldi, out + 1, oldi == 0);
220 
221       /* i was supposed to wrap around from out+1 to 0,   */
222       /* incrementing n each time, so we'll fix that now: */
223       if (i / (out + 1) > maxint - n)
224 	return punycode_overflow;
225       n += i / (out + 1);
226       if (n > 0x10FFFF || (n >= 0xD800 && n <= 0xDBFF))
227 	return punycode_bad_input;
228       i %= (out + 1);
229 
230       /* Insert n at position i of the output: */
231 
232       /* not needed for Punycode: */
233       /* if (basic(n)) return punycode_bad_input; */
234       if (out >= max_out)
235 	return punycode_big_output;
236 
237       memmove (output + i + 1, output + i, (out - i) * sizeof *output);
238       output[i++] = n;
239     }
240 
241   *output_length = (size_t) out;
242   /* cannot overflow because out <= old value of *output_length */
243   return punycode_success;
244 }
245 
246 /* Create a compatibility symbol if supported.  Hidden references make
247    the target symbol hidden, hence the alias.  */
248 #ifdef HAVE_SYMVER_ALIAS_SUPPORT
249 __typeof__ (_idn2_punycode_decode_internal) _idn2_punycode_decode
250   __attribute__((visibility ("default"),
251 		 alias ("_idn2_punycode_decode_internal")));
252 __asm__ (".symver _idn2_punycode_decode, _idn2_punycode_decode@IDN2_0.0.0");
253 #endif
254