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