File: punycode.cpp

package info (click to toggle)
scummvm 2.9.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 450,580 kB
  • sloc: cpp: 4,299,825; asm: 28,322; python: 12,901; sh: 11,302; java: 9,289; xml: 7,895; perl: 2,639; ansic: 2,465; yacc: 1,670; javascript: 1,020; makefile: 933; lex: 578; awk: 275; objc: 82; sed: 11; php: 1
file content (419 lines) | stat: -rw-r--r-- 10,025 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
/* ScummVM - Graphic Adventure Engine
 *
 * ScummVM is the legal property of its developers, whose names
 * are too numerous to list here. Please refer to the COPYRIGHT
 * file distributed with this source distribution.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

/**
 * Copyright (C) 2011 by Ben Noordhuis <info@bnoordhuis.nl>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include "common/punycode.h"
#include "common/debug.h"
#include "common/util.h"

namespace Common {

// punycode parameters, see https://datatracker.ietf.org/doc/html/rfc3492#section-5
#define BASE 36
#define TMIN 1
#define TMAX 26
#define SKEW 38
#define DAMP 700
#define INITIAL_N 128
#define INITIAL_BIAS 72
#define SMAX 2147483647 // maximum Unicode code point

#define SPECIAL_SYMBOLS "/\":*|\\?%<>\x7f"

static uint32 adapt_bias(uint32 delta, unsigned n_points, int is_first) {
	uint32 k;

	delta /= is_first ? DAMP : 2;
	delta += delta / n_points;

	// while delta > 455: delta /= 35
	for (k = 0; delta > ((BASE - TMIN) * TMAX) / 2; k += BASE) {
		delta /= (BASE - TMIN);
	}

	return k + (((BASE - TMIN + 1) * delta) / (delta + SKEW));
}

static char encode_digit(int c) {
	assert(c >= 0 && c <= BASE - TMIN);
	if (c > 25) {
		return c + 22; // '0'..'9'
	} else {
		return c + 0x61; // 'a'..'z'
	}
}

// Encode as a generalized variable-length integer. Returns number of bytes written.
static String encode_var_int(const size_t bias, const size_t delta) {
	size_t k, q, t;
	String dst;

	k = BASE;
	q = delta;

	while (true) {
		if (k <= bias) {
			t = TMIN;
		} else if (k >= bias + TMAX) {
			t = TMAX;
		} else {
			t = k - bias;
		}

		if (q < t) {
			break;
		}

		dst += encode_digit(t + (q - t) % (BASE - t));

		q = (q - t) / (BASE - t);
		k += BASE;
	}

	dst += encode_digit(q);

	return dst;
}

static size_t decode_digit(uint32 v) {
	if (Common::isDigit(v)) {
		return 26 + (v - '0');
	}
	if (Common::isLower(v)) {
		return v - 'a';
	}
	if (Common::isUpper(v)) {
		return v - 'A';
	}
	return SMAX;
}

String punycode_encode(const U32String &src) {
	size_t srclen = src.size();
	size_t h = 0, si;
	String dst = "xn--";

	if (!srclen)
		return src;

	for (si = 0; si < srclen; si++) {
		if (src[si] < 128) {
			dst += src[si];
			h++;
		}
	}

	size_t b = h;

	// If every character is ASCII, return the original string.
	if (h == srclen) {
		// If string ends with space or dot, still punycode it
		// because certain FSes do not support files with those
		// endings
		if (src[h - 1] == ' ' || src[h - 1] == '.')
			return dst + '-';
		if (srclen > 4 && src[0] == 'x' && src[1] == 'n' &&
			src[2] == '-' && src[3] == '-')
			return dst + '-';


		return src;
	}

	// If we have any ASCII characters, add '-' to separate them from
	// the non-ASCII character insertions.
	if (h > 0)
		dst += "-";

	size_t n = INITIAL_N;
	size_t bias = INITIAL_BIAS;
	size_t delta = 0;
	size_t m;

	for (; h < srclen; n++, delta++) {
		// Find next smallest non-basic code point.
		for (m = SMAX, si = 0; si < srclen; si++) {
			if (src[si] >= n && src[si] < m) {
				m = src[si];
			}
		}

		if ((m - n) > (SMAX - delta) / (h + 1)) {
			// OVERFLOW
			warning("punycode_encode: overflow1 for string (%s)", src.encode().c_str());
			return src;
		}

		delta += (m - n) * (h + 1);
		n = m;

		for (si = 0; si < srclen; si++) {
			if (src[si] < n) {
				if (++delta == 0) {
					// OVERFLOW
					warning("punycode_encode: overflow2 for string (%s)", src.encode().c_str());
					return src;
				}
			} else if (src[si] == n) {
				dst += encode_var_int(bias, delta);
				bias = adapt_bias(delta, h + 1, h == b);
				delta = 0;
				h++;
			}
		}
	}

	// Return how many Unicode code points were converted.
	return dst;
}

bool punycode_needEncode(const String &src) {
	if (!src.size())
		return false;

	// If name begins with xn-- this could become ambiguous
	if (src.size() > 4 && src[0] == 'x' && src[1] == 'n' &&
		src[2] == '-' && src[3] == '-')
		return true;

	for (uint si = 0; si < src.size(); si++) {
		if (src[si] & 0x80 || src[si] < 0x20 || strchr(SPECIAL_SYMBOLS, src[si])) {
			return true;
		}
	}

	// If name ends with space or dot, we have to encode it
	if (src[src.size() - 1] == ' ' || src[src.size() - 1] == '.')
		return true;

	return false;
}

U32String punycode_decode(const String &src1, bool *error) {
	if (error) *error = true;
	if (!src1.hasPrefix("xn--")) {
		return src1;
	}

	const char *src = src1.c_str() + 4; // Skip the prefix for simplification
	uint srclen = src1.size() - 4;

	// Ensure that the input contains only ASCII characters.
	for (uint si = 0; si < srclen; si++) {
		if (src[si] & 0x80) {
			return src1;
		}
	}

	// Look for start insertions
	const char *startinsert = strrchr(src, '-');
	// If we have no '-', the entire string is non-ASCII character insertions.
	if (!startinsert) {
		startinsert = src;
	} else {
		startinsert++;
	}

	const char *tail = src + srclen;

	while(true) {
		// Check that the insertions string is valid
		const char *p;
		for(p = startinsert; p < tail; p++) {
			if (!((*p >= '0' && *p <= '9') || (*p >= 'a' && *p <= 'z'))) {
				// Invalid code
				break;
			}
		}
		if (p == tail) {
			// Everything was good
			break;
		}

		if (*p == '.') {
			// Until then we got valid insertions, chop off what looks like an extension
			// We are now good
			tail = p;
			srclen = tail - src;
			break;
		}

		// We got something invalid: assume it was garbage from start
		// Look for another insertions start
		if (startinsert == src) {
			warning("punycode_decode: malformed string for string (%s)", src1.c_str());
			return src1;
		}

		// Move back to the dash
		startinsert--;
		tail = startinsert;
		for(; startinsert > src; startinsert--) {
			if (*(startinsert - 1) == '-') {
				break;
			}
		}
		// Try another round
	}

	// Create dst with ASCII characters
	U32String dst(src, startinsert == src ? src : startinsert - 1);

	const char *b = startinsert;
	size_t di = dst.size();
	size_t i = 0;
	size_t n = INITIAL_N;
	size_t bias = INITIAL_BIAS;

	for (const char *si = b; si < tail; di++) {
		size_t org_i = i;

		for (size_t w = 1, k = BASE; true; k += BASE) {
			if (si >= tail) {
				warning("punycode_decode: incorrect digit for string (%s)", src1.c_str());
				return src1;
			}

			size_t digit = decode_digit(*si++);

			if (digit == SMAX) {
				warning("punycode_decode: incorrect digit2 for string (%s)", src1.c_str());
				return src1;
			}

			if (digit > (SMAX - i) / w) {
				// OVERFLOW
				warning("punycode_decode: overflow1 for string (%s)", src1.c_str());
				return src1;
			}

			i += digit * w;
			size_t t;

			if (k <= bias) {
				t = TMIN;
			} else if (k >= bias + TMAX) {
				t = TMAX;
			} else {
				t = k - bias;
			}

			if (digit < t) {
				break;
			}

			if (w > SMAX / (BASE - t)) {
				// OVERFLOW
				warning("punycode_decode: overflow2 for string (%s)", src1.c_str());
				return src1;
			}

			w *= BASE - t;
		}

		bias = adapt_bias(i - org_i, di + 1, org_i == 0);

		if (i / (di + 1) > SMAX - n) {
			// OVERFLOW
			warning("punycode_decode: overflow3 for string (%s)", src1.c_str());
			return src1;
		}

		n += i / (di + 1);
		i %= (di + 1);

		dst.insertChar(n, i);
		i++;
	}

	// If we chopped off tail, readd it here
	dst += Common::U32String(tail);

	debug(9, "punycode_decode: returning %s", Common::U32String(dst).encode().c_str());
	if (error) *error = false;
	return dst;
}

String punycode_encodefilename(const U32String &src) {
	U32String dst;

	for (uint i = 0; i < src.size(); i++) {
		if (src[i] == 0x81) {	// In case we have our escape character present
			dst += 0x81;
			dst += 0x79;
		// Encode special symbols and non-printables
		} else if ((src[i] < 0x80 && strchr(SPECIAL_SYMBOLS, (byte)src[i])) || src[i] < 0x20) {
			dst += 0x81;
			dst += src[i] + 0x80;
		} else {
			dst += src[i];
		}
	}

	return punycode_encode(dst);
}

U32String punycode_decodefilename(const String &src) {
	bool error;
	U32String dst = punycode_decode(src, &error);

	if (error)
		return dst;

	uint32 i = dst.find(0x81, 0);
	while (i < dst.size() - 1) {
		U32String::value_type c = dst[i + 1];
		if (c == 0x79) {
			// 0x81 0x79 means 0x81: delete 0x79
			dst.deleteChar(i + 1);
		} else {
			// 0x81 0xXX means 0xXX - 0x80: delete 0x81 and change 0xXX
			dst.deleteChar(i);
			dst.setChar(c - 0x80, i);
		}
		i = dst.find(0x81, i + 1);
	}

	return dst;
}

} // end of namespace Common