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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
|
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
/* GLIB - Library of useful routines for C programming
* Copyright (C) 2008 Red Hat, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307, USA.
*/
#include "config.h"
#include <string.h>
#include "ghostutils.h"
#include "garray.h"
#include "gmem.h"
#include "gstring.h"
#include "gstrfuncs.h"
#include "glibintl.h"
/**
* SECTION:ghostutils
* @short_description: Internet hostname utilities
*
* Functions for manipulating internet hostnames; in particular, for
* converting between Unicode and ASCII-encoded forms of
* Internationalized Domain Names (IDNs).
*
* The <ulink
* url="http://www.ietf.org/rfc/rfc3490.txt">Internationalized Domain
* Names for Applications (IDNA)</ulink> standards allow for the use
* of Unicode domain names in applications, while providing
* backward-compatibility with the old ASCII-only DNS, by defining an
* ASCII-Compatible Encoding of any given Unicode name, which can be
* used with non-IDN-aware applications and protocols. (For example,
* "Παν語.org" maps to "xn--4wa8awb4637h.org".)
**/
#define IDNA_ACE_PREFIX "xn--"
#define IDNA_ACE_PREFIX_LEN 4
/* Punycode constants, from RFC 3492. */
#define PUNYCODE_BASE 36
#define PUNYCODE_TMIN 1
#define PUNYCODE_TMAX 26
#define PUNYCODE_SKEW 38
#define PUNYCODE_DAMP 700
#define PUNYCODE_INITIAL_BIAS 72
#define PUNYCODE_INITIAL_N 0x80
#define PUNYCODE_IS_BASIC(cp) ((guint)(cp) < 0x80)
/* Encode/decode a single base-36 digit */
static inline gchar
encode_digit (guint dig)
{
if (dig < 26)
return dig + 'a';
else
return dig - 26 + '0';
}
static inline guint
decode_digit (gchar dig)
{
if (dig >= 'A' && dig <= 'Z')
return dig - 'A';
else if (dig >= 'a' && dig <= 'z')
return dig - 'a';
else if (dig >= '0' && dig <= '9')
return dig - '0' + 26;
else
return G_MAXUINT;
}
/* Punycode bias adaptation algorithm, RFC 3492 section 6.1 */
static guint
adapt (guint delta,
guint numpoints,
gboolean firsttime)
{
guint k;
delta = firsttime ? delta / PUNYCODE_DAMP : delta / 2;
delta += delta / numpoints;
k = 0;
while (delta > ((PUNYCODE_BASE - PUNYCODE_TMIN) * PUNYCODE_TMAX) / 2)
{
delta /= PUNYCODE_BASE - PUNYCODE_TMIN;
k += PUNYCODE_BASE;
}
return k + ((PUNYCODE_BASE - PUNYCODE_TMIN + 1) * delta /
(delta + PUNYCODE_SKEW));
}
/* Punycode encoder, RFC 3492 section 6.3. The algorithm is
* sufficiently bizarre that it's not really worth trying to explain
* here.
*/
static gboolean
punycode_encode (const gchar *input_utf8,
gsize input_utf8_length,
GString *output)
{
guint delta, handled_chars, num_basic_chars, bias, j, q, k, t, digit;
gunichar n, m, *input;
glong input_length;
gboolean success = FALSE;
/* Convert from UTF-8 to Unicode code points */
input = g_utf8_to_ucs4 (input_utf8, input_utf8_length, NULL,
&input_length, NULL);
if (!input)
return FALSE;
/* Copy basic chars */
for (j = num_basic_chars = 0; j < input_length; j++)
{
if (PUNYCODE_IS_BASIC (input[j]))
{
g_string_append_c (output, g_ascii_tolower (input[j]));
num_basic_chars++;
}
}
if (num_basic_chars)
g_string_append_c (output, '-');
handled_chars = num_basic_chars;
/* Encode non-basic chars */
delta = 0;
bias = PUNYCODE_INITIAL_BIAS;
n = PUNYCODE_INITIAL_N;
while (handled_chars < input_length)
{
/* let m = the minimum {non-basic} code point >= n in the input */
for (m = G_MAXUINT, j = 0; j < input_length; j++)
{
if (input[j] >= n && input[j] < m)
m = input[j];
}
if (m - n > (G_MAXUINT - delta) / (handled_chars + 1))
goto fail;
delta += (m - n) * (handled_chars + 1);
n = m;
for (j = 0; j < input_length; j++)
{
if (input[j] < n)
{
if (++delta == 0)
goto fail;
}
else if (input[j] == n)
{
q = delta;
for (k = PUNYCODE_BASE; ; k += PUNYCODE_BASE)
{
if (k <= bias)
t = PUNYCODE_TMIN;
else if (k >= bias + PUNYCODE_TMAX)
t = PUNYCODE_TMAX;
else
t = k - bias;
if (q < t)
break;
digit = t + (q - t) % (PUNYCODE_BASE - t);
g_string_append_c (output, encode_digit (digit));
q = (q - t) / (PUNYCODE_BASE - t);
}
g_string_append_c (output, encode_digit (q));
bias = adapt (delta, handled_chars + 1, handled_chars == num_basic_chars);
delta = 0;
handled_chars++;
}
}
delta++;
n++;
}
success = TRUE;
fail:
g_free (input);
return success;
}
/* From RFC 3454, Table B.1 */
#define idna_is_junk(ch) ((ch) == 0x00AD || (ch) == 0x1806 || (ch) == 0x200B || (ch) == 0x2060 || (ch) == 0xFEFF || (ch) == 0x034F || (ch) == 0x180B || (ch) == 0x180C || (ch) == 0x180D || (ch) == 0x200C || (ch) == 0x200D || ((ch) >= 0xFE00 && (ch) <= 0xFE0F))
/* Scan @str for "junk" and return a cleaned-up string if any junk
* is found. Else return %NULL.
*/
static gchar *
remove_junk (const gchar *str,
gint len)
{
GString *cleaned = NULL;
const gchar *p;
gunichar ch;
for (p = str; len == -1 ? *p : p < str + len; p = g_utf8_next_char (p))
{
ch = g_utf8_get_char (p);
if (idna_is_junk (ch))
{
if (!cleaned)
{
cleaned = g_string_new (NULL);
g_string_append_len (cleaned, str, p - str);
}
}
else if (cleaned)
g_string_append_unichar (cleaned, ch);
}
if (cleaned)
return g_string_free (cleaned, FALSE);
else
return NULL;
}
static inline gboolean
contains_uppercase_letters (const gchar *str,
gint len)
{
const gchar *p;
for (p = str; len == -1 ? *p : p < str + len; p = g_utf8_next_char (p))
{
if (g_unichar_isupper (g_utf8_get_char (p)))
return TRUE;
}
return FALSE;
}
static inline gboolean
contains_non_ascii (const gchar *str,
gint len)
{
const gchar *p;
for (p = str; len == -1 ? *p : p < str + len; p++)
{
if ((guchar)*p > 0x80)
return TRUE;
}
return FALSE;
}
/* RFC 3454, Appendix C. ish. */
static inline gboolean
idna_is_prohibited (gunichar ch)
{
switch (g_unichar_type (ch))
{
case G_UNICODE_CONTROL:
case G_UNICODE_FORMAT:
case G_UNICODE_UNASSIGNED:
case G_UNICODE_PRIVATE_USE:
case G_UNICODE_SURROGATE:
case G_UNICODE_LINE_SEPARATOR:
case G_UNICODE_PARAGRAPH_SEPARATOR:
case G_UNICODE_SPACE_SEPARATOR:
return TRUE;
case G_UNICODE_OTHER_SYMBOL:
if (ch == 0xFFFC || ch == 0xFFFD ||
(ch >= 0x2FF0 && ch <= 0x2FFB))
return TRUE;
return FALSE;
case G_UNICODE_NON_SPACING_MARK:
if (ch == 0x0340 || ch == 0x0341)
return TRUE;
return FALSE;
default:
return FALSE;
}
}
/* RFC 3491 IDN cleanup algorithm. */
static gchar *
nameprep (const gchar *hostname,
gint len)
{
gchar *name, *tmp = NULL, *p;
/* It would be nice if we could do this without repeatedly
* allocating strings and converting back and forth between
* gunichars and UTF-8... The code does at least avoid doing most of
* the sub-operations when they would just be equivalent to a
* g_strdup().
*/
/* Remove presentation-only characters */
name = remove_junk (hostname, len);
if (name)
{
tmp = name;
len = -1;
}
else
name = (gchar *)hostname;
/* Convert to lowercase */
if (contains_uppercase_letters (name, len))
{
name = g_utf8_strdown (name, len);
g_free (tmp);
tmp = name;
len = -1;
}
/* If there are no UTF8 characters, we're done. */
if (!contains_non_ascii (name, len))
{
if (name == (gchar *)hostname)
return len == -1 ? g_strdup (hostname) : g_strndup (hostname, len);
else
return name;
}
/* Normalize */
name = g_utf8_normalize (name, len, G_NORMALIZE_NFKC);
g_free (tmp);
tmp = name;
if (!name)
return NULL;
/* KC normalization may have created more capital letters (eg,
* angstrom -> capital A with ring). So we have to lowercasify a
* second time. (This is more-or-less how the nameprep algorithm
* does it. If tolower(nfkc(tolower(X))) is guaranteed to be the
* same as tolower(nfkc(X)), then we could skip the first tolower,
* but I'm not sure it is.)
*/
if (contains_uppercase_letters (name, -1))
{
name = g_utf8_strdown (name, -1);
g_free (tmp);
tmp = name;
}
/* Check for prohibited characters */
for (p = name; *p; p = g_utf8_next_char (p))
{
if (idna_is_prohibited (g_utf8_get_char (p)))
{
name = NULL;
g_free (tmp);
goto done;
}
}
/* FIXME: We're supposed to verify certain constraints on bidi
* characters, but glib does not appear to have that information.
*/
done:
return name;
}
/**
* g_hostname_to_ascii:
* @hostname: a valid UTF-8 or ASCII hostname
*
* Converts @hostname to its canonical ASCII form; an ASCII-only
* string containing no uppercase letters and not ending with a
* trailing dot.
*
* Return value: an ASCII hostname, which must be freed, or %NULL if
* @hostname is in some way invalid.
*
* Since: 2.22
**/
gchar *
g_hostname_to_ascii (const gchar *hostname)
{
gchar *name, *label, *p;
GString *out;
gssize llen, oldlen;
gboolean unicode;
label = name = nameprep (hostname, -1);
if (!name)
return NULL;
out = g_string_new (NULL);
do
{
unicode = FALSE;
for (p = label; *p && *p != '.'; p++)
{
if ((guchar)*p > 0x80)
unicode = TRUE;
}
oldlen = out->len;
llen = p - label;
if (unicode)
{
if (!strncmp (label, IDNA_ACE_PREFIX, IDNA_ACE_PREFIX_LEN))
goto fail;
g_string_append (out, IDNA_ACE_PREFIX);
if (!punycode_encode (label, llen, out))
goto fail;
}
else
g_string_append_len (out, label, llen);
if (out->len - oldlen > 63)
goto fail;
label += llen;
if (*label && *++label)
g_string_append_c (out, '.');
}
while (*label);
g_free (name);
return g_string_free (out, FALSE);
fail:
g_free (name);
g_string_free (out, TRUE);
return NULL;
}
/**
* g_hostname_is_non_ascii:
* @hostname: a hostname
*
* Tests if @hostname contains Unicode characters. If this returns
* %TRUE, you need to encode the hostname with g_hostname_to_ascii()
* before using it in non-IDN-aware contexts.
*
* Note that a hostname might contain a mix of encoded and unencoded
* segments, and so it is possible for g_hostname_is_non_ascii() and
* g_hostname_is_ascii_encoded() to both return %TRUE for a name.
*
* Return value: %TRUE if @hostname contains any non-ASCII characters
*
* Since: 2.22
**/
gboolean
g_hostname_is_non_ascii (const gchar *hostname)
{
return contains_non_ascii (hostname, -1);
}
/* Punycode decoder, RFC 3492 section 6.2. As with punycode_encode(),
* read the RFC if you want to understand what this is actually doing.
*/
static gboolean
punycode_decode (const gchar *input,
gsize input_length,
GString *output)
{
GArray *output_chars;
gunichar n;
guint i, bias;
guint oldi, w, k, digit, t;
const gchar *split;
n = PUNYCODE_INITIAL_N;
i = 0;
bias = PUNYCODE_INITIAL_BIAS;
split = input + input_length - 1;
while (split > input && *split != '-')
split--;
if (split > input)
{
output_chars = g_array_sized_new (FALSE, FALSE, sizeof (gunichar),
split - input);
input_length -= (split - input) + 1;
while (input < split)
{
gunichar ch = (gunichar)*input++;
if (!PUNYCODE_IS_BASIC (ch))
goto fail;
g_array_append_val (output_chars, ch);
}
input++;
}
else
output_chars = g_array_new (FALSE, FALSE, sizeof (gunichar));
while (input_length)
{
oldi = i;
w = 1;
for (k = PUNYCODE_BASE; ; k += PUNYCODE_BASE)
{
if (!input_length--)
goto fail;
digit = decode_digit (*input++);
if (digit >= PUNYCODE_BASE)
goto fail;
if (digit > (G_MAXUINT - i) / w)
goto fail;
i += digit * w;
if (k <= bias)
t = PUNYCODE_TMIN;
else if (k >= bias + PUNYCODE_TMAX)
t = PUNYCODE_TMAX;
else
t = k - bias;
if (digit < t)
break;
if (w > G_MAXUINT / (PUNYCODE_BASE - t))
goto fail;
w *= (PUNYCODE_BASE - t);
}
bias = adapt (i - oldi, output_chars->len + 1, oldi == 0);
if (i / (output_chars->len + 1) > G_MAXUINT - n)
goto fail;
n += i / (output_chars->len + 1);
i %= (output_chars->len + 1);
g_array_insert_val (output_chars, i++, n);
}
for (i = 0; i < output_chars->len; i++)
g_string_append_unichar (output, g_array_index (output_chars, gunichar, i));
g_array_free (output_chars, TRUE);
return TRUE;
fail:
g_array_free (output_chars, TRUE);
return FALSE;
}
/**
* g_hostname_to_unicode:
* @hostname: a valid UTF-8 or ASCII hostname
*
* Converts @hostname to its canonical presentation form; a UTF-8
* string in Unicode normalization form C, containing no uppercase
* letters, no forbidden characters, and no ASCII-encoded segments,
* and not ending with a trailing dot.
*
* Of course if @hostname is not an internationalized hostname, then
* the canonical presentation form will be entirely ASCII.
*
* Return value: a UTF-8 hostname, which must be freed, or %NULL if
* @hostname is in some way invalid.
*
* Since: 2.22
**/
gchar *
g_hostname_to_unicode (const gchar *hostname)
{
GString *out;
gssize llen;
out = g_string_new (NULL);
do
{
llen = strcspn (hostname, ".");
if (!g_ascii_strncasecmp (hostname, IDNA_ACE_PREFIX, IDNA_ACE_PREFIX_LEN))
{
hostname += IDNA_ACE_PREFIX_LEN;
llen -= IDNA_ACE_PREFIX_LEN;
if (!punycode_decode (hostname, llen, out))
{
g_string_free (out, TRUE);
return NULL;
}
}
else
{
gchar *canonicalized = nameprep (hostname, llen);
if (!canonicalized)
{
g_string_free (out, TRUE);
return NULL;
}
g_string_append (out, canonicalized);
g_free (canonicalized);
}
hostname += llen;
if (*hostname && *++hostname)
g_string_append_c (out, '.');
}
while (*hostname);
return g_string_free (out, FALSE);
}
/**
* g_hostname_is_ascii_encoded:
* @hostname: a hostname
*
* Tests if @hostname contains segments with an ASCII-compatible
* encoding of an Internationalized Domain Name. If this returns
* %TRUE, you should decode the hostname with g_hostname_to_unicode()
* before displaying it to the user.
*
* Note that a hostname might contain a mix of encoded and unencoded
* segments, and so it is possible for g_hostname_is_non_ascii() and
* g_hostname_is_ascii_encoded() to both return %TRUE for a name.
*
* Return value: %TRUE if @hostname contains any ASCII-encoded
* segments.
*
* Since: 2.22
**/
gboolean
g_hostname_is_ascii_encoded (const gchar *hostname)
{
while (1)
{
if (!g_ascii_strncasecmp (hostname, IDNA_ACE_PREFIX, IDNA_ACE_PREFIX_LEN))
return TRUE;
hostname = strchr (hostname, '.');
if (!hostname++)
return FALSE;
}
}
/**
* g_hostname_is_ip_address:
* @hostname: a hostname (or IP address in string form)
*
* Tests if @hostname is the string form of an IPv4 or IPv6 address.
* (Eg, "192.168.0.1".)
*
* Return value: %TRUE if @hostname is an IP address
*
* Since: 2.22
**/
gboolean
g_hostname_is_ip_address (const gchar *hostname)
{
gchar *p, *end;
gint nsegments, octet;
/* On Linux we could implement this using inet_pton, but the Windows
* equivalent of that requires linking against winsock, so we just
* figure this out ourselves. Tested by tests/hostutils.c.
*/
p = (char *)hostname;
if (strchr (p, ':'))
{
gboolean skipped;
/* If it contains a ':', it's an IPv6 address (assuming it's an
* IP address at all). This consists of eight ':'-separated
* segments, each containing a 1-4 digit hex number, except that
* optionally: (a) the last two segments can be replaced by an
* IPv4 address, and (b) a single span of 1 to 8 "0000" segments
* can be replaced with just "::".
*/
nsegments = 0;
skipped = FALSE;
while (*p && nsegments < 8)
{
/* Each segment after the first must be preceded by a ':'.
* (We also handle half of the "string starts with ::" case
* here.)
*/
if (p != (char *)hostname || (p[0] == ':' && p[1] == ':'))
{
if (*p != ':')
return FALSE;
p++;
}
/* If there's another ':', it means we're skipping some segments */
if (*p == ':' && !skipped)
{
skipped = TRUE;
nsegments++;
/* Handle the "string ends with ::" case */
if (!p[1])
p++;
continue;
}
/* Read the segment, make sure it's valid. */
for (end = p; g_ascii_isxdigit (*end); end++)
;
if (end == p || end > p + 4)
return FALSE;
if (*end == '.')
{
if ((nsegments == 6 && !skipped) || (nsegments <= 6 && skipped))
goto parse_ipv4;
else
return FALSE;
}
nsegments++;
p = end;
}
return !*p && (nsegments == 8 || skipped);
}
parse_ipv4:
/* Parse IPv4: N.N.N.N, where each N <= 255 and doesn't have leading 0s. */
for (nsegments = 0; nsegments < 4; nsegments++)
{
if (nsegments != 0)
{
if (*p != '.')
return FALSE;
p++;
}
/* Check the segment; a little tricker than the IPv6 case since
* we can't allow extra leading 0s, and we can't assume that all
* strings of valid length are within range.
*/
octet = 0;
if (*p == '0')
end = p + 1;
else
{
for (end = p; g_ascii_isdigit (*end); end++)
octet = 10 * octet + (*end - '0');
}
if (end == p || end > p + 3 || octet > 255)
return FALSE;
p = end;
}
/* If there's nothing left to parse, then it's ok. */
return !*p;
}
|