]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/utf8.c
d61692d07f191790045b1edf30209a6fc5e370ae
[thirdparty/systemd.git] / src / basic / utf8.c
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
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
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 */
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 */
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
126 bool utf8_is_printable_newline(const char* str, size_t length, bool allow_newline) {
127 const char *p;
128
129 assert(str);
130
131 for (p = str; length > 0;) {
132 int encoded_len, r;
133 char32_t val;
134
135 encoded_len = utf8_encoded_valid_unichar(p, length);
136 if (encoded_len < 0)
137 return false;
138 assert(encoded_len > 0 && (size_t) encoded_len <= length);
139
140 r = utf8_encoded_to_unichar(p, &val);
141 if (r < 0 ||
142 unichar_is_control(val) ||
143 (!allow_newline && val == '\n'))
144 return false;
145
146 length -= encoded_len;
147 p += encoded_len;
148 }
149
150 return true;
151 }
152
153 char *utf8_is_valid_n(const char *str, size_t len_bytes) {
154 /* Check if the string is composed of valid utf8 characters. If length len_bytes is given, stop after
155 * len_bytes. Otherwise, stop at NUL. */
156
157 assert(str);
158
159 for (const char *p = str; len_bytes != (size_t) -1 ? (size_t) (p - str) < len_bytes : *p != '\0'; ) {
160 int len;
161
162 if (_unlikely_(*p == '\0') && len_bytes != (size_t) -1)
163 return NULL; /* embedded NUL */
164
165 len = utf8_encoded_valid_unichar(p,
166 len_bytes != (size_t) -1 ? len_bytes - (p - str) : (size_t) -1);
167 if (_unlikely_(len < 0))
168 return NULL; /* invalid character */
169
170 p += len;
171 }
172
173 return (char*) str;
174 }
175
176 char *utf8_escape_invalid(const char *str) {
177 char *p, *s;
178
179 assert(str);
180
181 p = s = malloc(strlen(str) * 4 + 1);
182 if (!p)
183 return NULL;
184
185 while (*str) {
186 int len;
187
188 len = utf8_encoded_valid_unichar(str, (size_t) -1);
189 if (len > 0) {
190 s = mempcpy(s, str, len);
191 str += len;
192 } else {
193 s = stpcpy(s, UTF8_REPLACEMENT_CHARACTER);
194 str += 1;
195 }
196 }
197
198 *s = '\0';
199 (void) str_realloc(&p);
200 return p;
201 }
202
203 static int utf8_char_console_width(const char *str) {
204 char32_t c;
205 int r;
206
207 r = utf8_encoded_to_unichar(str, &c);
208 if (r < 0)
209 return r;
210
211 /* TODO: we should detect combining characters */
212
213 return unichar_iswide(c) ? 2 : 1;
214 }
215
216 char *utf8_escape_non_printable_full(const char *str, size_t console_width) {
217 char *p, *s, *prev_s;
218 size_t n = 0; /* estimated print width */
219
220 assert(str);
221
222 if (console_width == 0)
223 return strdup("");
224
225 p = s = prev_s = malloc(strlen(str) * 4 + 1);
226 if (!p)
227 return NULL;
228
229 for (;;) {
230 int len;
231 char *saved_s = s;
232
233 if (!*str) /* done! */
234 goto finish;
235
236 len = utf8_encoded_valid_unichar(str, (size_t) -1);
237 if (len > 0) {
238 if (utf8_is_printable(str, len)) {
239 int w;
240
241 w = utf8_char_console_width(str);
242 assert(w >= 0);
243 if (n + w > console_width)
244 goto truncation;
245
246 s = mempcpy(s, str, len);
247 str += len;
248 n += w;
249
250 } else {
251 for (; len > 0; len--) {
252 if (n + 4 > console_width)
253 goto truncation;
254
255 *(s++) = '\\';
256 *(s++) = 'x';
257 *(s++) = hexchar((int) *str >> 4);
258 *(s++) = hexchar((int) *str);
259
260 str += 1;
261 n += 4;
262 }
263 }
264 } else {
265 if (n + 1 > console_width)
266 goto truncation;
267
268 s = mempcpy(s, UTF8_REPLACEMENT_CHARACTER, strlen(UTF8_REPLACEMENT_CHARACTER));
269 str += 1;
270 n += 1;
271 }
272
273 prev_s = saved_s;
274 }
275
276 truncation:
277 /* Try to go back one if we don't have enough space for the ellipsis */
278 if (n + 1 >= console_width)
279 s = prev_s;
280
281 s = mempcpy(s, "…", strlen("…"));
282
283 finish:
284 *s = '\0';
285 (void) str_realloc(&p);
286 return p;
287 }
288
289 char *ascii_is_valid(const char *str) {
290 const char *p;
291
292 /* Check whether the string consists of valid ASCII bytes,
293 * i.e values between 0 and 127, inclusive. */
294
295 assert(str);
296
297 for (p = str; *p; p++)
298 if ((unsigned char) *p >= 128)
299 return NULL;
300
301 return (char*) str;
302 }
303
304 char *ascii_is_valid_n(const char *str, size_t len) {
305 /* Very similar to ascii_is_valid(), but checks exactly len
306 * bytes and rejects any NULs in that range. */
307
308 assert(str);
309
310 for (size_t i = 0; i < len; i++)
311 if ((unsigned char) str[i] >= 128 || str[i] == 0)
312 return NULL;
313
314 return (char*) str;
315 }
316
317 /**
318 * utf8_encode_unichar() - Encode single UCS-4 character as UTF-8
319 * @out_utf8: output buffer of at least 4 bytes or NULL
320 * @g: UCS-4 character to encode
321 *
322 * This encodes a single UCS-4 character as UTF-8 and writes it into @out_utf8.
323 * The length of the character is returned. It is not zero-terminated! If the
324 * output buffer is NULL, only the length is returned.
325 *
326 * Returns: The length in bytes that the UTF-8 representation does or would
327 * occupy.
328 */
329 size_t utf8_encode_unichar(char *out_utf8, char32_t g) {
330
331 if (g < (1 << 7)) {
332 if (out_utf8)
333 out_utf8[0] = g & 0x7f;
334 return 1;
335 } else if (g < (1 << 11)) {
336 if (out_utf8) {
337 out_utf8[0] = 0xc0 | ((g >> 6) & 0x1f);
338 out_utf8[1] = 0x80 | (g & 0x3f);
339 }
340 return 2;
341 } else if (g < (1 << 16)) {
342 if (out_utf8) {
343 out_utf8[0] = 0xe0 | ((g >> 12) & 0x0f);
344 out_utf8[1] = 0x80 | ((g >> 6) & 0x3f);
345 out_utf8[2] = 0x80 | (g & 0x3f);
346 }
347 return 3;
348 } else if (g < (1 << 21)) {
349 if (out_utf8) {
350 out_utf8[0] = 0xf0 | ((g >> 18) & 0x07);
351 out_utf8[1] = 0x80 | ((g >> 12) & 0x3f);
352 out_utf8[2] = 0x80 | ((g >> 6) & 0x3f);
353 out_utf8[3] = 0x80 | (g & 0x3f);
354 }
355 return 4;
356 }
357
358 return 0;
359 }
360
361 char *utf16_to_utf8(const char16_t *s, size_t length /* bytes! */) {
362 const uint8_t *f;
363 char *r, *t;
364
365 assert(s);
366
367 /* Input length is in bytes, i.e. the shortest possible character takes 2 bytes. Each unicode character may
368 * take up to 4 bytes in UTF-8. Let's also account for a trailing NUL byte. */
369 if (length * 2 < length)
370 return NULL; /* overflow */
371
372 r = new(char, length * 2 + 1);
373 if (!r)
374 return NULL;
375
376 f = (const uint8_t*) s;
377 t = r;
378
379 while (f + 1 < (const uint8_t*) s + length) {
380 char16_t w1, w2;
381
382 /* see RFC 2781 section 2.2 */
383
384 w1 = f[1] << 8 | f[0];
385 f += 2;
386
387 if (!utf16_is_surrogate(w1)) {
388 t += utf8_encode_unichar(t, w1);
389 continue;
390 }
391
392 if (utf16_is_trailing_surrogate(w1))
393 continue; /* spurious trailing surrogate, ignore */
394
395 if (f + 1 >= (const uint8_t*) s + length)
396 break;
397
398 w2 = f[1] << 8 | f[0];
399 f += 2;
400
401 if (!utf16_is_trailing_surrogate(w2)) {
402 f -= 2;
403 continue; /* surrogate missing its trailing surrogate, ignore */
404 }
405
406 t += utf8_encode_unichar(t, utf16_surrogate_pair_to_unichar(w1, w2));
407 }
408
409 *t = 0;
410 return r;
411 }
412
413 size_t utf16_encode_unichar(char16_t *out, char32_t c) {
414
415 /* Note that this encodes as little-endian. */
416
417 switch (c) {
418
419 case 0 ... 0xd7ffU:
420 case 0xe000U ... 0xffffU:
421 out[0] = htole16(c);
422 return 1;
423
424 case 0x10000U ... 0x10ffffU:
425 c -= 0x10000U;
426 out[0] = htole16((c >> 10) + 0xd800U);
427 out[1] = htole16((c & 0x3ffU) + 0xdc00U);
428 return 2;
429
430 default: /* A surrogate (invalid) */
431 return 0;
432 }
433 }
434
435 char16_t *utf8_to_utf16(const char *s, size_t length) {
436 char16_t *n, *p;
437 int r;
438
439 assert(s);
440
441 n = new(char16_t, length + 1);
442 if (!n)
443 return NULL;
444
445 p = n;
446
447 for (size_t i = 0; i < length;) {
448 char32_t unichar;
449 size_t e;
450
451 e = utf8_encoded_expected_len(s[i]);
452 if (e <= 1) /* Invalid and single byte characters are copied as they are */
453 goto copy;
454
455 if (i + e > length) /* sequence longer than input buffer, then copy as-is */
456 goto copy;
457
458 r = utf8_encoded_to_unichar(s + i, &unichar);
459 if (r < 0) /* sequence invalid, then copy as-is */
460 goto copy;
461
462 p += utf16_encode_unichar(p, unichar);
463 i += e;
464 continue;
465
466 copy:
467 *(p++) = htole16(s[i++]);
468 }
469
470 *p = 0;
471 return n;
472 }
473
474 size_t char16_strlen(const char16_t *s) {
475 size_t n = 0;
476
477 assert(s);
478
479 while (*s != 0)
480 n++, s++;
481
482 return n;
483 }
484
485 /* expected size used to encode one unicode char */
486 static int utf8_unichar_to_encoded_len(char32_t unichar) {
487
488 if (unichar < 0x80)
489 return 1;
490 if (unichar < 0x800)
491 return 2;
492 if (unichar < 0x10000)
493 return 3;
494 if (unichar < 0x200000)
495 return 4;
496 if (unichar < 0x4000000)
497 return 5;
498
499 return 6;
500 }
501
502 /* validate one encoded unicode char and return its length */
503 int utf8_encoded_valid_unichar(const char *str, size_t length /* bytes */) {
504 char32_t unichar;
505 size_t len;
506 int r;
507
508 assert(str);
509 assert(length > 0);
510
511 /* We read until NUL, at most length bytes. (size_t) -1 may be used to disable the length check. */
512
513 len = utf8_encoded_expected_len(str[0]);
514 if (len == 0)
515 return -EINVAL;
516
517 /* Do we have a truncated multi-byte character? */
518 if (len > length)
519 return -EINVAL;
520
521 /* ascii is valid */
522 if (len == 1)
523 return 1;
524
525 /* check if expected encoded chars are available */
526 for (size_t i = 0; i < len; i++)
527 if ((str[i] & 0x80) != 0x80)
528 return -EINVAL;
529
530 r = utf8_encoded_to_unichar(str, &unichar);
531 if (r < 0)
532 return r;
533
534 /* check if encoded length matches encoded value */
535 if (utf8_unichar_to_encoded_len(unichar) != (int) len)
536 return -EINVAL;
537
538 /* check if value has valid range */
539 if (!unichar_is_valid(unichar))
540 return -EINVAL;
541
542 return (int) len;
543 }
544
545 size_t utf8_n_codepoints(const char *str) {
546 size_t n = 0;
547
548 /* Returns the number of UTF-8 codepoints in this string, or (size_t) -1 if the string is not valid UTF-8. */
549
550 while (*str != 0) {
551 int k;
552
553 k = utf8_encoded_valid_unichar(str, (size_t) -1);
554 if (k < 0)
555 return (size_t) -1;
556
557 str += k;
558 n++;
559 }
560
561 return n;
562 }
563
564 size_t utf8_console_width(const char *str) {
565 size_t n = 0;
566
567 /* Returns the approximate width a string will take on screen when printed on a character cell
568 * terminal/console. */
569
570 while (*str) {
571 int w;
572
573 w = utf8_char_console_width(str);
574 if (w < 0)
575 return (size_t) -1;
576
577 n += w;
578 str = utf8_next_char(str);
579 }
580
581 return n;
582 }