1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
3 /* GLIB - Library of useful routines for C programming
4 * Copyright (C) 2008 Red Hat, Inc.
6 * This library 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 * This library 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
17 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
21 #include "glibconfig.h"
29 #include "ghostutils.h"
34 #include "gstrfuncs.h"
37 #ifdef G_PLATFORM_WIN32
44 * @short_description: Internet hostname utilities
46 * Functions for manipulating internet hostnames; in particular, for
47 * converting between Unicode and ASCII-encoded forms of
48 * Internationalized Domain Names (IDNs).
51 * [Internationalized Domain Names for Applications (IDNA)](http://www.ietf.org/rfc/rfc3490.txt)
52 * standards allow for the use
53 * of Unicode domain names in applications, while providing
54 * backward-compatibility with the old ASCII-only DNS, by defining an
55 * ASCII-Compatible Encoding of any given Unicode name, which can be
56 * used with non-IDN-aware applications and protocols. (For example,
57 * "Παν語.org" maps to "xn--4wa8awb4637h.org".)
60 #define IDNA_ACE_PREFIX "xn--"
61 #define IDNA_ACE_PREFIX_LEN 4
63 /* Punycode constants, from RFC 3492. */
65 #define PUNYCODE_BASE 36
66 #define PUNYCODE_TMIN 1
67 #define PUNYCODE_TMAX 26
68 #define PUNYCODE_SKEW 38
69 #define PUNYCODE_DAMP 700
70 #define PUNYCODE_INITIAL_BIAS 72
71 #define PUNYCODE_INITIAL_N 0x80
73 #define PUNYCODE_IS_BASIC(cp) ((guint)(cp) < 0x80)
75 /* Encode/decode a single base-36 digit */
77 encode_digit (guint dig)
82 return dig - 26 + '0';
86 decode_digit (gchar dig)
88 if (dig >= 'A' && dig <= 'Z')
90 else if (dig >= 'a' && dig <= 'z')
92 else if (dig >= '0' && dig <= '9')
93 return dig - '0' + 26;
98 /* Punycode bias adaptation algorithm, RFC 3492 section 6.1 */
106 delta = firsttime ? delta / PUNYCODE_DAMP : delta / 2;
107 delta += delta / numpoints;
110 while (delta > ((PUNYCODE_BASE - PUNYCODE_TMIN) * PUNYCODE_TMAX) / 2)
112 delta /= PUNYCODE_BASE - PUNYCODE_TMIN;
116 return k + ((PUNYCODE_BASE - PUNYCODE_TMIN + 1) * delta /
117 (delta + PUNYCODE_SKEW));
120 /* Punycode encoder, RFC 3492 section 6.3. The algorithm is
121 * sufficiently bizarre that it's not really worth trying to explain
125 punycode_encode (const gchar *input_utf8,
126 gsize input_utf8_length,
129 guint delta, handled_chars, num_basic_chars, bias, j, q, k, t, digit;
130 gunichar n, m, *input;
132 gboolean success = FALSE;
134 /* Convert from UTF-8 to Unicode code points */
135 input = g_utf8_to_ucs4 (input_utf8, input_utf8_length, NULL,
136 &input_length, NULL);
140 /* Copy basic chars */
141 for (j = num_basic_chars = 0; j < input_length; j++)
143 if (PUNYCODE_IS_BASIC (input[j]))
145 g_string_append_c (output, g_ascii_tolower (input[j]));
150 g_string_append_c (output, '-');
152 handled_chars = num_basic_chars;
154 /* Encode non-basic chars */
156 bias = PUNYCODE_INITIAL_BIAS;
157 n = PUNYCODE_INITIAL_N;
158 while (handled_chars < input_length)
160 /* let m = the minimum {non-basic} code point >= n in the input */
161 for (m = G_MAXUINT, j = 0; j < input_length; j++)
163 if (input[j] >= n && input[j] < m)
167 if (m - n > (G_MAXUINT - delta) / (handled_chars + 1))
169 delta += (m - n) * (handled_chars + 1);
172 for (j = 0; j < input_length; j++)
179 else if (input[j] == n)
182 for (k = PUNYCODE_BASE; ; k += PUNYCODE_BASE)
186 else if (k >= bias + PUNYCODE_TMAX)
192 digit = t + (q - t) % (PUNYCODE_BASE - t);
193 g_string_append_c (output, encode_digit (digit));
194 q = (q - t) / (PUNYCODE_BASE - t);
197 g_string_append_c (output, encode_digit (q));
198 bias = adapt (delta, handled_chars + 1, handled_chars == num_basic_chars);
215 /* From RFC 3454, Table B.1 */
216 #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))
218 /* Scan @str for "junk" and return a cleaned-up string if any junk
219 * is found. Else return %NULL.
222 remove_junk (const gchar *str,
225 GString *cleaned = NULL;
229 for (p = str; len == -1 ? *p : p < str + len; p = g_utf8_next_char (p))
231 ch = g_utf8_get_char (p);
232 if (idna_is_junk (ch))
236 cleaned = g_string_new (NULL);
237 g_string_append_len (cleaned, str, p - str);
241 g_string_append_unichar (cleaned, ch);
245 return g_string_free (cleaned, FALSE);
250 static inline gboolean
251 contains_uppercase_letters (const gchar *str,
256 for (p = str; len == -1 ? *p : p < str + len; p = g_utf8_next_char (p))
258 if (g_unichar_isupper (g_utf8_get_char (p)))
264 static inline gboolean
265 contains_non_ascii (const gchar *str,
270 for (p = str; len == -1 ? *p : p < str + len; p++)
272 if ((guchar)*p > 0x80)
278 /* RFC 3454, Appendix C. ish. */
279 static inline gboolean
280 idna_is_prohibited (gunichar ch)
282 switch (g_unichar_type (ch))
284 case G_UNICODE_CONTROL:
285 case G_UNICODE_FORMAT:
286 case G_UNICODE_UNASSIGNED:
287 case G_UNICODE_PRIVATE_USE:
288 case G_UNICODE_SURROGATE:
289 case G_UNICODE_LINE_SEPARATOR:
290 case G_UNICODE_PARAGRAPH_SEPARATOR:
291 case G_UNICODE_SPACE_SEPARATOR:
294 case G_UNICODE_OTHER_SYMBOL:
295 if (ch == 0xFFFC || ch == 0xFFFD ||
296 (ch >= 0x2FF0 && ch <= 0x2FFB))
300 case G_UNICODE_NON_SPACING_MARK:
301 if (ch == 0x0340 || ch == 0x0341)
310 /* RFC 3491 IDN cleanup algorithm. */
312 nameprep (const gchar *hostname,
314 gboolean *is_unicode)
316 gchar *name, *tmp = NULL, *p;
318 /* It would be nice if we could do this without repeatedly
319 * allocating strings and converting back and forth between
320 * gunichars and UTF-8... The code does at least avoid doing most of
321 * the sub-operations when they would just be equivalent to a
325 /* Remove presentation-only characters */
326 name = remove_junk (hostname, len);
333 name = (gchar *)hostname;
335 /* Convert to lowercase */
336 if (contains_uppercase_letters (name, len))
338 name = g_utf8_strdown (name, len);
344 /* If there are no UTF8 characters, we're done. */
345 if (!contains_non_ascii (name, len))
348 if (name == (gchar *)hostname)
349 return len == -1 ? g_strdup (hostname) : g_strndup (hostname, len);
357 name = g_utf8_normalize (name, len, G_NORMALIZE_NFKC);
364 /* KC normalization may have created more capital letters (eg,
365 * angstrom -> capital A with ring). So we have to lowercasify a
366 * second time. (This is more-or-less how the nameprep algorithm
367 * does it. If tolower(nfkc(tolower(X))) is guaranteed to be the
368 * same as tolower(nfkc(X)), then we could skip the first tolower,
369 * but I'm not sure it is.)
371 if (contains_uppercase_letters (name, -1))
373 name = g_utf8_strdown (name, -1);
378 /* Check for prohibited characters */
379 for (p = name; *p; p = g_utf8_next_char (p))
381 if (idna_is_prohibited (g_utf8_get_char (p)))
389 /* FIXME: We're supposed to verify certain constraints on bidi
390 * characters, but glib does not appear to have that information.
397 /* RFC 3490, section 3.1 says '.', 0x3002, 0xFF0E, and 0xFF61 count as
398 * label-separating dots. @str must be '\0'-terminated.
400 #define idna_is_dot(str) ( \
401 ((guchar)(str)[0] == '.') || \
402 ((guchar)(str)[0] == 0xE3 && (guchar)(str)[1] == 0x80 && (guchar)(str)[2] == 0x82) || \
403 ((guchar)(str)[0] == 0xEF && (guchar)(str)[1] == 0xBC && (guchar)(str)[2] == 0x8E) || \
404 ((guchar)(str)[0] == 0xEF && (guchar)(str)[1] == 0xBD && (guchar)(str)[2] == 0xA1) )
407 idna_end_of_label (const gchar *str)
409 for (; *str; str = g_utf8_next_char (str))
411 if (idna_is_dot (str))
418 get_hostname_max_length_bytes (void)
420 #if defined(G_OS_WIN32)
421 wchar_t tmp[MAX_COMPUTERNAME_LENGTH];
422 return sizeof (tmp) / sizeof (tmp[0]);
423 #elif defined(_SC_HOST_NAME_MAX)
424 glong max = sysconf (_SC_HOST_NAME_MAX);
429 return HOST_NAME_MAX;
431 return _POSIX_HOST_NAME_MAX;
432 #endif /* HOST_NAME_MAX */
434 /* Fallback to some reasonable value
435 * See https://stackoverflow.com/questions/8724954/what-is-the-maximum-number-of-characters-for-a-host-name-in-unix/28918017#28918017 */
440 /* Returns %TRUE if `strlen (str) > comparison_length`, but without actually
441 * running `strlen(str)`, as that would take a very long time for long
442 * (untrusted) input strings. */
444 strlen_greater_than (const gchar *str,
445 gsize comparison_length)
449 for (i = 0; str[i] != '\0'; i++)
450 if (i > comparison_length)
457 * g_hostname_to_ascii:
458 * @hostname: a valid UTF-8 or ASCII hostname
460 * Converts @hostname to its canonical ASCII form; an ASCII-only
461 * string containing no uppercase letters and not ending with a
464 * Returns: (nullable) (transfer full): an ASCII hostname, which must be freed,
465 * or %NULL if @hostname is in some way invalid.
470 g_hostname_to_ascii (const gchar *hostname)
472 gchar *name, *label, *p;
476 gsize hostname_max_length_bytes = get_hostname_max_length_bytes ();
478 /* Do an initial check on the hostname length, as overlong hostnames take a
479 * long time in the IDN cleanup algorithm in nameprep(). The ultimate
480 * restriction is that the IDN-decoded (i.e. pure ASCII) hostname cannot be
481 * longer than 255 bytes. That’s the least restrictive limit on hostname
482 * length of all the ways hostnames can be interpreted. Typically, the
483 * hostname will be an FQDN, which is limited to 253 bytes long. POSIX
484 * hostnames are limited to `get_hostname_max_length_bytes()` (typically 255
487 * See https://stackoverflow.com/a/28918017/2931197
489 * It’s possible for a hostname to be %-encoded, in which case its decoded
490 * length will be as much as 3× shorter.
492 * It’s also possible for a hostname to use overlong UTF-8 encodings, in which
493 * case its decoded length will be as much as 4× shorter.
495 * Note: This check is not intended as an absolute guarantee that a hostname
496 * is the right length and will be accepted by other systems. It’s intended to
497 * stop wildly-invalid hostnames from taking forever in nameprep().
499 if (hostname_max_length_bytes <= G_MAXSIZE / 4 &&
500 strlen_greater_than (hostname, 4 * MAX (255, hostname_max_length_bytes)))
503 label = name = nameprep (hostname, -1, &unicode);
504 if (!name || !unicode)
507 out = g_string_new (NULL);
512 for (p = label; *p && !idna_is_dot (p); p++)
514 if ((guchar)*p > 0x80)
522 if (!strncmp (label, IDNA_ACE_PREFIX, IDNA_ACE_PREFIX_LEN))
525 g_string_append (out, IDNA_ACE_PREFIX);
526 if (!punycode_encode (label, llen, out))
530 g_string_append_len (out, label, llen);
532 if (out->len - oldlen > 63)
537 label = g_utf8_next_char (label);
539 g_string_append_c (out, '.');
544 return g_string_free (out, FALSE);
548 g_string_free (out, TRUE);
553 * g_hostname_is_non_ascii:
554 * @hostname: a hostname
556 * Tests if @hostname contains Unicode characters. If this returns
557 * %TRUE, you need to encode the hostname with g_hostname_to_ascii()
558 * before using it in non-IDN-aware contexts.
560 * Note that a hostname might contain a mix of encoded and unencoded
561 * segments, and so it is possible for g_hostname_is_non_ascii() and
562 * g_hostname_is_ascii_encoded() to both return %TRUE for a name.
564 * Returns: %TRUE if @hostname contains any non-ASCII characters
569 g_hostname_is_non_ascii (const gchar *hostname)
571 return contains_non_ascii (hostname, -1);
574 /* Punycode decoder, RFC 3492 section 6.2. As with punycode_encode(),
575 * read the RFC if you want to understand what this is actually doing.
578 punycode_decode (const gchar *input,
582 GArray *output_chars;
585 guint oldi, w, k, digit, t;
588 n = PUNYCODE_INITIAL_N;
590 bias = PUNYCODE_INITIAL_BIAS;
592 split = input + input_length - 1;
593 while (split > input && *split != '-')
597 output_chars = g_array_sized_new (FALSE, FALSE, sizeof (gunichar),
599 input_length -= (split - input) + 1;
600 while (input < split)
602 gunichar ch = (gunichar)*input++;
603 if (!PUNYCODE_IS_BASIC (ch))
605 g_array_append_val (output_chars, ch);
610 output_chars = g_array_new (FALSE, FALSE, sizeof (gunichar));
616 for (k = PUNYCODE_BASE; ; k += PUNYCODE_BASE)
620 digit = decode_digit (*input++);
621 if (digit >= PUNYCODE_BASE)
623 if (digit > (G_MAXUINT - i) / w)
628 else if (k >= bias + PUNYCODE_TMAX)
634 if (w > G_MAXUINT / (PUNYCODE_BASE - t))
636 w *= (PUNYCODE_BASE - t);
639 bias = adapt (i - oldi, output_chars->len + 1, oldi == 0);
641 if (i / (output_chars->len + 1) > G_MAXUINT - n)
643 n += i / (output_chars->len + 1);
644 i %= (output_chars->len + 1);
646 g_array_insert_val (output_chars, i++, n);
649 for (i = 0; i < output_chars->len; i++)
650 g_string_append_unichar (output, g_array_index (output_chars, gunichar, i));
651 g_array_free (output_chars, TRUE);
655 g_array_free (output_chars, TRUE);
660 * g_hostname_to_unicode:
661 * @hostname: a valid UTF-8 or ASCII hostname
663 * Converts @hostname to its canonical presentation form; a UTF-8
664 * string in Unicode normalization form C, containing no uppercase
665 * letters, no forbidden characters, and no ASCII-encoded segments,
666 * and not ending with a trailing dot.
668 * Of course if @hostname is not an internationalized hostname, then
669 * the canonical presentation form will be entirely ASCII.
671 * Returns: (nullable) (transfer full): a UTF-8 hostname, which must be freed,
672 * or %NULL if @hostname is in some way invalid.
677 g_hostname_to_unicode (const gchar *hostname)
681 gsize hostname_max_length_bytes = get_hostname_max_length_bytes ();
683 /* See the comment at the top of g_hostname_to_ascii(). */
684 if (hostname_max_length_bytes <= G_MAXSIZE / 4 &&
685 strlen_greater_than (hostname, 4 * MAX (255, hostname_max_length_bytes)))
688 out = g_string_new (NULL);
692 llen = idna_end_of_label (hostname) - hostname;
693 if (!g_ascii_strncasecmp (hostname, IDNA_ACE_PREFIX, IDNA_ACE_PREFIX_LEN))
695 hostname += IDNA_ACE_PREFIX_LEN;
696 llen -= IDNA_ACE_PREFIX_LEN;
697 if (!punycode_decode (hostname, llen, out))
699 g_string_free (out, TRUE);
706 gchar *canonicalized = nameprep (hostname, llen, &unicode);
710 g_string_free (out, TRUE);
713 g_string_append (out, canonicalized);
714 g_free (canonicalized);
719 hostname = g_utf8_next_char (hostname);
721 g_string_append_c (out, '.');
725 return g_string_free (out, FALSE);
729 * g_hostname_is_ascii_encoded:
730 * @hostname: a hostname
732 * Tests if @hostname contains segments with an ASCII-compatible
733 * encoding of an Internationalized Domain Name. If this returns
734 * %TRUE, you should decode the hostname with g_hostname_to_unicode()
735 * before displaying it to the user.
737 * Note that a hostname might contain a mix of encoded and unencoded
738 * segments, and so it is possible for g_hostname_is_non_ascii() and
739 * g_hostname_is_ascii_encoded() to both return %TRUE for a name.
741 * Returns: %TRUE if @hostname contains any ASCII-encoded
747 g_hostname_is_ascii_encoded (const gchar *hostname)
751 if (!g_ascii_strncasecmp (hostname, IDNA_ACE_PREFIX, IDNA_ACE_PREFIX_LEN))
753 hostname = idna_end_of_label (hostname);
755 hostname = g_utf8_next_char (hostname);
762 * g_hostname_is_ip_address:
763 * @hostname: a hostname (or IP address in string form)
765 * Tests if @hostname is the string form of an IPv4 or IPv6 address.
766 * (Eg, "192.168.0.1".)
768 * Since 2.66, IPv6 addresses with a zone-id are accepted (RFC6874).
770 * Returns: %TRUE if @hostname is an IP address
775 g_hostname_is_ip_address (const gchar *hostname)
778 gint nsegments, octet;
780 /* On Linux we could implement this using inet_pton, but the Windows
781 * equivalent of that requires linking against winsock, so we just
782 * figure this out ourselves. Tested by tests/hostutils.c.
785 p = (char *)hostname;
791 /* If it contains a ':', it's an IPv6 address (assuming it's an
792 * IP address at all). This consists of eight ':'-separated
793 * segments, each containing a 1-4 digit hex number, except that
794 * optionally: (a) the last two segments can be replaced by an
795 * IPv4 address, and (b) a single span of 1 to 8 "0000" segments
796 * can be replaced with just "::".
801 while (*p && *p != '%' && nsegments < 8)
803 /* Each segment after the first must be preceded by a ':'.
804 * (We also handle half of the "string starts with ::" case
807 if (p != (char *)hostname || (p[0] == ':' && p[1] == ':'))
814 /* If there's another ':', it means we're skipping some segments */
815 if (*p == ':' && !skipped)
820 /* Handle the "string ends with ::" case */
827 /* Read the segment, make sure it's valid. */
828 for (end = p; g_ascii_isxdigit (*end); end++)
830 if (end == p || end > p + 4)
835 if ((nsegments == 6 && !skipped) || (nsegments <= 6 && skipped))
845 return (!*p || (p[0] == '%' && p[1])) && (nsegments == 8 || skipped);
850 /* Parse IPv4: N.N.N.N, where each N <= 255 and doesn't have leading 0s. */
851 for (nsegments = 0; nsegments < 4; nsegments++)
860 /* Check the segment; a little tricker than the IPv6 case since
861 * we can't allow extra leading 0s, and we can't assume that all
862 * strings of valid length are within range.
869 for (end = p; g_ascii_isdigit (*end); end++)
871 octet = 10 * octet + (*end - '0');
877 if (end == p || end > p + 3 || octet > 255)
883 /* If there's nothing left to parse, then it's ok. */