1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 /* Parts of this file are based on the GLIB utf8 validation functions. The
4 * original license text follows. */
5
6 /* gutf8.c - Operations on UTF-8 strings.
7 *
8 * Copyright (C) 1999 Tom Tromey
9 * Copyright (C) 2000 Red Hat, Inc.
10 *
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Library General Public
13 * License as published by the Free Software Foundation; either
14 * version 2 of the License, or (at your option) any later version.
15 *
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Library General Public License for more details.
20 *
21 * You should have received a copy of the GNU Library General Public
22 * License along with this library; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 */
25
26 #include <errno.h>
27 #include <stdbool.h>
28 #include <stdlib.h>
29
30 #include "alloc-util.h"
31 #include "gunicode.h"
32 #include "hexdecoct.h"
33 #include "macro.h"
34 #include "string-util.h"
35 #include "utf8.h"
36
unichar_is_valid(char32_t ch)37 bool unichar_is_valid(char32_t ch) {
38
39 if (ch >= 0x110000) /* End of unicode space */
40 return false;
41 if ((ch & 0xFFFFF800) == 0xD800) /* Reserved area for UTF-16 */
42 return false;
43 if ((ch >= 0xFDD0) && (ch <= 0xFDEF)) /* Reserved */
44 return false;
45 if ((ch & 0xFFFE) == 0xFFFE) /* BOM (Byte Order Mark) */
46 return false;
47
48 return true;
49 }
50
unichar_is_control(char32_t ch)51 static bool unichar_is_control(char32_t ch) {
52
53 /*
54 0 to ' '-1 is the C0 range.
55 DEL=0x7F, and DEL+1 to 0x9F is C1 range.
56 '\t' is in C0 range, but more or less harmless and commonly used.
57 */
58
59 return (ch < ' ' && !IN_SET(ch, '\t', '\n')) ||
60 (0x7F <= ch && ch <= 0x9F);
61 }
62
63 /* count of characters used to encode one unicode char */
utf8_encoded_expected_len(uint8_t c)64 static size_t utf8_encoded_expected_len(uint8_t c) {
65 if (c < 0x80)
66 return 1;
67 if ((c & 0xe0) == 0xc0)
68 return 2;
69 if ((c & 0xf0) == 0xe0)
70 return 3;
71 if ((c & 0xf8) == 0xf0)
72 return 4;
73 if ((c & 0xfc) == 0xf8)
74 return 5;
75 if ((c & 0xfe) == 0xfc)
76 return 6;
77
78 return 0;
79 }
80
81 /* decode one unicode char */
utf8_encoded_to_unichar(const char * str,char32_t * ret_unichar)82 int utf8_encoded_to_unichar(const char *str, char32_t *ret_unichar) {
83 char32_t unichar;
84 size_t len;
85
86 assert(str);
87
88 len = utf8_encoded_expected_len(str[0]);
89
90 switch (len) {
91 case 1:
92 *ret_unichar = (char32_t)str[0];
93 return 0;
94 case 2:
95 unichar = str[0] & 0x1f;
96 break;
97 case 3:
98 unichar = (char32_t)str[0] & 0x0f;
99 break;
100 case 4:
101 unichar = (char32_t)str[0] & 0x07;
102 break;
103 case 5:
104 unichar = (char32_t)str[0] & 0x03;
105 break;
106 case 6:
107 unichar = (char32_t)str[0] & 0x01;
108 break;
109 default:
110 return -EINVAL;
111 }
112
113 for (size_t i = 1; i < len; i++) {
114 if (((char32_t)str[i] & 0xc0) != 0x80)
115 return -EINVAL;
116
117 unichar <<= 6;
118 unichar |= (char32_t)str[i] & 0x3f;
119 }
120
121 *ret_unichar = unichar;
122
123 return 0;
124 }
125
utf8_is_printable_newline(const char * str,size_t length,bool allow_newline)126 bool utf8_is_printable_newline(const char* str, size_t length, bool allow_newline) {
127 assert(str);
128
129 for (const char *p = str; length > 0;) {
130 int encoded_len, r;
131 char32_t val;
132
133 encoded_len = utf8_encoded_valid_unichar(p, length);
134 if (encoded_len < 0)
135 return false;
136 assert(encoded_len > 0 && (size_t) encoded_len <= length);
137
138 r = utf8_encoded_to_unichar(p, &val);
139 if (r < 0 ||
140 unichar_is_control(val) ||
141 (!allow_newline && val == '\n'))
142 return false;
143
144 length -= encoded_len;
145 p += encoded_len;
146 }
147
148 return true;
149 }
150
utf8_is_valid_n(const char * str,size_t len_bytes)151 char *utf8_is_valid_n(const char *str, size_t len_bytes) {
152 /* Check if the string is composed of valid utf8 characters. If length len_bytes is given, stop after
153 * len_bytes. Otherwise, stop at NUL. */
154
155 assert(str);
156
157 for (const char *p = str; len_bytes != SIZE_MAX ? (size_t) (p - str) < len_bytes : *p != '\0'; ) {
158 int len;
159
160 if (_unlikely_(*p == '\0') && len_bytes != SIZE_MAX)
161 return NULL; /* embedded NUL */
162
163 len = utf8_encoded_valid_unichar(p,
164 len_bytes != SIZE_MAX ? len_bytes - (p - str) : SIZE_MAX);
165 if (_unlikely_(len < 0))
166 return NULL; /* invalid character */
167
168 p += len;
169 }
170
171 return (char*) str;
172 }
173
utf8_escape_invalid(const char * str)174 char *utf8_escape_invalid(const char *str) {
175 char *p, *s;
176
177 assert(str);
178
179 p = s = malloc(strlen(str) * 4 + 1);
180 if (!p)
181 return NULL;
182
183 while (*str) {
184 int len;
185
186 len = utf8_encoded_valid_unichar(str, SIZE_MAX);
187 if (len > 0) {
188 s = mempcpy(s, str, len);
189 str += len;
190 } else {
191 s = stpcpy(s, UTF8_REPLACEMENT_CHARACTER);
192 str += 1;
193 }
194 }
195
196 *s = '\0';
197 return str_realloc(p);
198 }
199
utf8_char_console_width(const char * str)200 static int utf8_char_console_width(const char *str) {
201 char32_t c;
202 int r;
203
204 r = utf8_encoded_to_unichar(str, &c);
205 if (r < 0)
206 return r;
207
208 /* TODO: we should detect combining characters */
209
210 return unichar_iswide(c) ? 2 : 1;
211 }
212
utf8_escape_non_printable_full(const char * str,size_t console_width,bool force_ellipsis)213 char *utf8_escape_non_printable_full(const char *str, size_t console_width, bool force_ellipsis) {
214 char *p, *s, *prev_s;
215 size_t n = 0; /* estimated print width */
216
217 assert(str);
218
219 if (console_width == 0)
220 return strdup("");
221
222 p = s = prev_s = malloc(strlen(str) * 4 + 1);
223 if (!p)
224 return NULL;
225
226 for (;;) {
227 int len;
228 char *saved_s = s;
229
230 if (!*str) { /* done! */
231 if (force_ellipsis)
232 goto truncation;
233 else
234 goto finish;
235 }
236
237 len = utf8_encoded_valid_unichar(str, SIZE_MAX);
238 if (len > 0) {
239 if (utf8_is_printable(str, len)) {
240 int w;
241
242 w = utf8_char_console_width(str);
243 assert(w >= 0);
244 if (n + w > console_width)
245 goto truncation;
246
247 s = mempcpy(s, str, len);
248 str += len;
249 n += w;
250
251 } else {
252 for (; len > 0; len--) {
253 if (n + 4 > console_width)
254 goto truncation;
255
256 *(s++) = '\\';
257 *(s++) = 'x';
258 *(s++) = hexchar((int) *str >> 4);
259 *(s++) = hexchar((int) *str);
260
261 str += 1;
262 n += 4;
263 }
264 }
265 } else {
266 if (n + 1 > console_width)
267 goto truncation;
268
269 s = mempcpy(s, UTF8_REPLACEMENT_CHARACTER, strlen(UTF8_REPLACEMENT_CHARACTER));
270 str += 1;
271 n += 1;
272 }
273
274 prev_s = saved_s;
275 }
276
277 truncation:
278 /* Try to go back one if we don't have enough space for the ellipsis */
279 if (n + 1 > console_width)
280 s = prev_s;
281
282 s = mempcpy(s, "…", strlen("…"));
283
284 finish:
285 *s = '\0';
286 return str_realloc(p);
287 }
288
ascii_is_valid(const char * str)289 char *ascii_is_valid(const char *str) {
290 /* Check whether the string consists of valid ASCII bytes,
291 * i.e values between 0 and 127, inclusive. */
292
293 assert(str);
294
295 for (const char *p = str; *p; p++)
296 if ((unsigned char) *p >= 128)
297 return NULL;
298
299 return (char*) str;
300 }
301
ascii_is_valid_n(const char * str,size_t len)302 char *ascii_is_valid_n(const char *str, size_t len) {
303 /* Very similar to ascii_is_valid(), but checks exactly len
304 * bytes and rejects any NULs in that range. */
305
306 assert(str);
307
308 for (size_t i = 0; i < len; i++)
309 if ((unsigned char) str[i] >= 128 || str[i] == 0)
310 return NULL;
311
312 return (char*) str;
313 }
314
utf8_to_ascii(const char * str,char replacement_char,char ** ret)315 int utf8_to_ascii(const char *str, char replacement_char, char **ret) {
316 /* Convert to a string that has only ASCII chars, replacing anything that is not ASCII
317 * by replacement_char. */
318
319 _cleanup_free_ char *ans = new(char, strlen(str) + 1);
320 if (!ans)
321 return -ENOMEM;
322
323 char *q = ans;
324
325 for (const char *p = str; *p; q++) {
326 int l;
327
328 l = utf8_encoded_valid_unichar(p, SIZE_MAX);
329 if (l < 0) /* Non-UTF-8, let's not even try to propagate the garbage */
330 return l;
331
332 if (l == 1)
333 *q = *p;
334 else
335 /* non-ASCII, we need to replace it */
336 *q = replacement_char;
337
338 p += l;
339 }
340 *q = '\0';
341
342 *ret = TAKE_PTR(ans);
343 return 0;
344 }
345
346 /**
347 * utf8_encode_unichar() - Encode single UCS-4 character as UTF-8
348 * @out_utf8: output buffer of at least 4 bytes or NULL
349 * @g: UCS-4 character to encode
350 *
351 * This encodes a single UCS-4 character as UTF-8 and writes it into @out_utf8.
352 * The length of the character is returned. It is not zero-terminated! If the
353 * output buffer is NULL, only the length is returned.
354 *
355 * Returns: The length in bytes that the UTF-8 representation does or would
356 * occupy.
357 */
utf8_encode_unichar(char * out_utf8,char32_t g)358 size_t utf8_encode_unichar(char *out_utf8, char32_t g) {
359
360 if (g < (1 << 7)) {
361 if (out_utf8)
362 out_utf8[0] = g & 0x7f;
363 return 1;
364 } else if (g < (1 << 11)) {
365 if (out_utf8) {
366 out_utf8[0] = 0xc0 | ((g >> 6) & 0x1f);
367 out_utf8[1] = 0x80 | (g & 0x3f);
368 }
369 return 2;
370 } else if (g < (1 << 16)) {
371 if (out_utf8) {
372 out_utf8[0] = 0xe0 | ((g >> 12) & 0x0f);
373 out_utf8[1] = 0x80 | ((g >> 6) & 0x3f);
374 out_utf8[2] = 0x80 | (g & 0x3f);
375 }
376 return 3;
377 } else if (g < (1 << 21)) {
378 if (out_utf8) {
379 out_utf8[0] = 0xf0 | ((g >> 18) & 0x07);
380 out_utf8[1] = 0x80 | ((g >> 12) & 0x3f);
381 out_utf8[2] = 0x80 | ((g >> 6) & 0x3f);
382 out_utf8[3] = 0x80 | (g & 0x3f);
383 }
384 return 4;
385 }
386
387 return 0;
388 }
389
utf16_to_utf8(const char16_t * s,size_t length)390 char *utf16_to_utf8(const char16_t *s, size_t length /* bytes! */) {
391 const uint8_t *f;
392 char *r, *t;
393
394 assert(s);
395
396 /* Input length is in bytes, i.e. the shortest possible character takes 2 bytes. Each unicode character may
397 * take up to 4 bytes in UTF-8. Let's also account for a trailing NUL byte. */
398 if (length * 2 < length)
399 return NULL; /* overflow */
400
401 r = new(char, length * 2 + 1);
402 if (!r)
403 return NULL;
404
405 f = (const uint8_t*) s;
406 t = r;
407
408 while (f + 1 < (const uint8_t*) s + length) {
409 char16_t w1, w2;
410
411 /* see RFC 2781 section 2.2 */
412
413 w1 = f[1] << 8 | f[0];
414 f += 2;
415
416 if (!utf16_is_surrogate(w1)) {
417 t += utf8_encode_unichar(t, w1);
418 continue;
419 }
420
421 if (utf16_is_trailing_surrogate(w1))
422 continue; /* spurious trailing surrogate, ignore */
423
424 if (f + 1 >= (const uint8_t*) s + length)
425 break;
426
427 w2 = f[1] << 8 | f[0];
428 f += 2;
429
430 if (!utf16_is_trailing_surrogate(w2)) {
431 f -= 2;
432 continue; /* surrogate missing its trailing surrogate, ignore */
433 }
434
435 t += utf8_encode_unichar(t, utf16_surrogate_pair_to_unichar(w1, w2));
436 }
437
438 *t = 0;
439 return r;
440 }
441
utf16_encode_unichar(char16_t * out,char32_t c)442 size_t utf16_encode_unichar(char16_t *out, char32_t c) {
443
444 /* Note that this encodes as little-endian. */
445
446 switch (c) {
447
448 case 0 ... 0xd7ffU:
449 case 0xe000U ... 0xffffU:
450 out[0] = htole16(c);
451 return 1;
452
453 case 0x10000U ... 0x10ffffU:
454 c -= 0x10000U;
455 out[0] = htole16((c >> 10) + 0xd800U);
456 out[1] = htole16((c & 0x3ffU) + 0xdc00U);
457 return 2;
458
459 default: /* A surrogate (invalid) */
460 return 0;
461 }
462 }
463
utf8_to_utf16(const char * s,size_t length)464 char16_t *utf8_to_utf16(const char *s, size_t length) {
465 char16_t *n, *p;
466 int r;
467
468 assert(s);
469
470 n = new(char16_t, length + 1);
471 if (!n)
472 return NULL;
473
474 p = n;
475
476 for (size_t i = 0; i < length;) {
477 char32_t unichar;
478 size_t e;
479
480 e = utf8_encoded_expected_len(s[i]);
481 if (e <= 1) /* Invalid and single byte characters are copied as they are */
482 goto copy;
483
484 if (i + e > length) /* sequence longer than input buffer, then copy as-is */
485 goto copy;
486
487 r = utf8_encoded_to_unichar(s + i, &unichar);
488 if (r < 0) /* sequence invalid, then copy as-is */
489 goto copy;
490
491 p += utf16_encode_unichar(p, unichar);
492 i += e;
493 continue;
494
495 copy:
496 *(p++) = htole16(s[i++]);
497 }
498
499 *p = 0;
500 return n;
501 }
502
char16_strlen(const char16_t * s)503 size_t char16_strlen(const char16_t *s) {
504 size_t n = 0;
505
506 assert(s);
507
508 while (*s != 0)
509 n++, s++;
510
511 return n;
512 }
513
514 /* expected size used to encode one unicode char */
utf8_unichar_to_encoded_len(char32_t unichar)515 static int utf8_unichar_to_encoded_len(char32_t unichar) {
516
517 if (unichar < 0x80)
518 return 1;
519 if (unichar < 0x800)
520 return 2;
521 if (unichar < 0x10000)
522 return 3;
523 if (unichar < 0x200000)
524 return 4;
525 if (unichar < 0x4000000)
526 return 5;
527
528 return 6;
529 }
530
531 /* validate one encoded unicode char and return its length */
utf8_encoded_valid_unichar(const char * str,size_t length)532 int utf8_encoded_valid_unichar(const char *str, size_t length /* bytes */) {
533 char32_t unichar;
534 size_t len;
535 int r;
536
537 assert(str);
538 assert(length > 0);
539
540 /* We read until NUL, at most length bytes. SIZE_MAX may be used to disable the length check. */
541
542 len = utf8_encoded_expected_len(str[0]);
543 if (len == 0)
544 return -EINVAL;
545
546 /* Do we have a truncated multi-byte character? */
547 if (len > length)
548 return -EINVAL;
549
550 /* ascii is valid */
551 if (len == 1)
552 return 1;
553
554 /* check if expected encoded chars are available */
555 for (size_t i = 0; i < len; i++)
556 if ((str[i] & 0x80) != 0x80)
557 return -EINVAL;
558
559 r = utf8_encoded_to_unichar(str, &unichar);
560 if (r < 0)
561 return r;
562
563 /* check if encoded length matches encoded value */
564 if (utf8_unichar_to_encoded_len(unichar) != (int) len)
565 return -EINVAL;
566
567 /* check if value has valid range */
568 if (!unichar_is_valid(unichar))
569 return -EINVAL;
570
571 return (int) len;
572 }
573
utf8_n_codepoints(const char * str)574 size_t utf8_n_codepoints(const char *str) {
575 size_t n = 0;
576
577 /* Returns the number of UTF-8 codepoints in this string, or SIZE_MAX if the string is not valid UTF-8. */
578
579 while (*str != 0) {
580 int k;
581
582 k = utf8_encoded_valid_unichar(str, SIZE_MAX);
583 if (k < 0)
584 return SIZE_MAX;
585
586 str += k;
587 n++;
588 }
589
590 return n;
591 }
592
utf8_console_width(const char * str)593 size_t utf8_console_width(const char *str) {
594 size_t n = 0;
595
596 /* Returns the approximate width a string will take on screen when printed on a character cell
597 * terminal/console. */
598
599 while (*str) {
600 int w;
601
602 w = utf8_char_console_width(str);
603 if (w < 0)
604 return SIZE_MAX;
605
606 n += w;
607 str = utf8_next_char(str);
608 }
609
610 return n;
611 }
612