]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/utf8.c
basic/utf8: reduce memory usage
[thirdparty/systemd.git] / src / basic / utf8.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
7f110ff9 2
036ae95a 3/* Parts of this file are based on the GLIB utf8 validation functions. The
7f110ff9
LP
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
23757887 12 * modify it under the terms of the GNU Library General Public
7f110ff9
LP
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
23757887
SK
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Library General Public License for more details.
7f110ff9 20 *
23757887
SK
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
7f110ff9
LP
24 */
25
26#include <errno.h>
7f110ff9 27#include <stdbool.h>
cf0fbc49
TA
28#include <stdlib.h>
29#include <string.h>
7f110ff9 30
b5efdb8a 31#include "alloc-util.h"
3f536d5b 32#include "gunicode.h"
e4e73a63 33#include "hexdecoct.h"
11c3a366 34#include "macro.h"
4c6d5139 35#include "string-util.h"
7f110ff9
LP
36#include "utf8.h"
37
c932fb71 38bool unichar_is_valid(char32_t ch) {
7f110ff9
LP
39
40 if (ch >= 0x110000) /* End of unicode space */
41 return false;
42 if ((ch & 0xFFFFF800) == 0xD800) /* Reserved area for UTF-16 */
43 return false;
44 if ((ch >= 0xFDD0) && (ch <= 0xFDEF)) /* Reserved */
45 return false;
46 if ((ch & 0xFFFE) == 0xFFFE) /* BOM (Byte Order Mark) */
47 return false;
48
49 return true;
50}
51
c932fb71 52static bool unichar_is_control(char32_t ch) {
ba961854
ZJS
53
54 /*
55 0 to ' '-1 is the C0 range.
56 DEL=0x7F, and DEL+1 to 0x9F is C1 range.
57 '\t' is in C0 range, but more or less harmless and commonly used.
58 */
59
4c701096 60 return (ch < ' ' && !IN_SET(ch, '\t', '\n')) ||
ba961854
ZJS
61 (0x7F <= ch && ch <= 0x9F);
62}
63
7991ac34 64/* count of characters used to encode one unicode char */
84319aa7 65static size_t utf8_encoded_expected_len(uint8_t c) {
7991ac34
DR
66 if (c < 0x80)
67 return 1;
68 if ((c & 0xe0) == 0xc0)
69 return 2;
70 if ((c & 0xf0) == 0xe0)
71 return 3;
72 if ((c & 0xf8) == 0xf0)
73 return 4;
74 if ((c & 0xfc) == 0xf8)
75 return 5;
76 if ((c & 0xfe) == 0xfc)
77 return 6;
7e8185ef 78
7991ac34
DR
79 return 0;
80}
ba961854 81
7991ac34 82/* decode one unicode char */
c932fb71
SL
83int utf8_encoded_to_unichar(const char *str, char32_t *ret_unichar) {
84 char32_t unichar;
7c421857 85 size_t len, i;
7e8185ef
LP
86
87 assert(str);
ba961854 88
84319aa7 89 len = utf8_encoded_expected_len(str[0]);
7e8185ef 90
7991ac34
DR
91 switch (len) {
92 case 1:
c932fb71
SL
93 *ret_unichar = (char32_t)str[0];
94 return 0;
7991ac34
DR
95 case 2:
96 unichar = str[0] & 0x1f;
97 break;
98 case 3:
c932fb71 99 unichar = (char32_t)str[0] & 0x0f;
7991ac34
DR
100 break;
101 case 4:
c932fb71 102 unichar = (char32_t)str[0] & 0x07;
7991ac34
DR
103 break;
104 case 5:
c932fb71 105 unichar = (char32_t)str[0] & 0x03;
7991ac34
DR
106 break;
107 case 6:
c932fb71 108 unichar = (char32_t)str[0] & 0x01;
7991ac34
DR
109 break;
110 default:
7e8185ef 111 return -EINVAL;
ba961854
ZJS
112 }
113
7991ac34 114 for (i = 1; i < len; i++) {
c932fb71 115 if (((char32_t)str[i] & 0xc0) != 0x80)
7e8185ef 116 return -EINVAL;
7c421857 117
7991ac34 118 unichar <<= 6;
c932fb71 119 unichar |= (char32_t)str[i] & 0x3f;
7991ac34
DR
120 }
121
c932fb71
SL
122 *ret_unichar = unichar;
123
124 return 0;
ba961854
ZJS
125}
126
0ade5ffe 127bool utf8_is_printable_newline(const char* str, size_t length, bool newline) {
6ed62be0 128 const char *p;
7f110ff9
LP
129
130 assert(str);
131
92e068b4 132 for (p = str; length > 0;) {
c932fb71
SL
133 int encoded_len, r;
134 char32_t val;
7e8185ef 135
92e068b4
ZJS
136 encoded_len = utf8_encoded_valid_unichar(p, length);
137 if (encoded_len < 0)
144b3d9e 138 return false;
92e068b4 139 assert(encoded_len > 0 && (size_t) encoded_len <= length);
144b3d9e 140
c932fb71
SL
141 r = utf8_encoded_to_unichar(p, &val);
142 if (r < 0 ||
f3ee6297 143 unichar_is_control(val) ||
0ade5ffe 144 (!newline && val == '\n'))
7991ac34 145 return false;
7f110ff9 146
7991ac34 147 length -= encoded_len;
a7176505 148 p += encoded_len;
7f110ff9
LP
149 }
150
7991ac34 151 return true;
7f110ff9
LP
152}
153
e71fb4b3
LP
154char *utf8_is_valid(const char *str) {
155 const char *p;
7f110ff9
LP
156
157 assert(str);
158
e71fb4b3
LP
159 p = str;
160 while (*p) {
faaa5728
LP
161 int len;
162
92e068b4 163 len = utf8_encoded_valid_unichar(p, (size_t) -1);
7991ac34
DR
164 if (len < 0)
165 return NULL;
166
167 p += len;
168 }
7f110ff9 169
e71fb4b3 170 return (char*) str;
7f110ff9
LP
171}
172
550a40ec
ZJS
173char *utf8_escape_invalid(const char *str) {
174 char *p, *s;
175
176 assert(str);
177
178 p = s = malloc(strlen(str) * 4 + 1);
179 if (!p)
180 return NULL;
181
182 while (*str) {
183 int len;
184
92e068b4 185 len = utf8_encoded_valid_unichar(str, (size_t) -1);
550a40ec
ZJS
186 if (len > 0) {
187 s = mempcpy(s, str, len);
188 str += len;
189 } else {
3c6d3052 190 s = stpcpy(s, UTF8_REPLACEMENT_CHARACTER);
550a40ec
ZJS
191 str += 1;
192 }
193 }
7e8185ef 194
550a40ec 195 *s = '\0';
4c6d5139 196 (void) str_realloc(&p);
550a40ec
ZJS
197 return p;
198}
199
da88f542
ZJS
200static 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
213char *utf8_escape_non_printable_full(const char *str, size_t console_width) {
214 char *p, *s, *prev_s;
215 size_t n = 0; /* estimated print width */
fec84576
WC
216
217 assert(str);
218
da88f542
ZJS
219 if (console_width == 0)
220 return strdup("");
221
222 p = s = prev_s = malloc(strlen(str) * 4 + 1);
fec84576
WC
223 if (!p)
224 return NULL;
225
da88f542 226 for (;;) {
fec84576 227 int len;
da88f542
ZJS
228 char *saved_s = s;
229
230 if (!*str) /* done! */
231 goto finish;
fec84576 232
92e068b4 233 len = utf8_encoded_valid_unichar(str, (size_t) -1);
fec84576
WC
234 if (len > 0) {
235 if (utf8_is_printable(str, len)) {
da88f542
ZJS
236 int w;
237
238 w = utf8_char_console_width(str);
239 assert(w >= 0);
240 if (n + w > console_width)
241 goto truncation;
242
fec84576
WC
243 s = mempcpy(s, str, len);
244 str += len;
da88f542
ZJS
245 n += w;
246
fec84576 247 } else {
da88f542
ZJS
248 for (; len > 0; len--) {
249 if (n + 4 > console_width)
250 goto truncation;
251
fec84576
WC
252 *(s++) = '\\';
253 *(s++) = 'x';
254 *(s++) = hexchar((int) *str >> 4);
255 *(s++) = hexchar((int) *str);
fec84576 256
3c6d3052 257 str += 1;
da88f542 258 n += 4;
3c6d3052 259 }
fec84576
WC
260 }
261 } else {
da88f542
ZJS
262 if (n + 1 > console_width)
263 goto truncation;
264
265 s = mempcpy(s, UTF8_REPLACEMENT_CHARACTER, strlen(UTF8_REPLACEMENT_CHARACTER));
fec84576 266 str += 1;
da88f542 267 n += 1;
fec84576 268 }
da88f542
ZJS
269
270 prev_s = saved_s;
fec84576
WC
271 }
272
da88f542
ZJS
273 truncation:
274 /* Try to go back one if we don't have enough space for the ellipsis */
275 if (n + 1 >= console_width)
276 s = prev_s;
277
278 s = mempcpy(s, "…", strlen("…"));
fec84576 279
da88f542
ZJS
280 finish:
281 *s = '\0';
4c6d5139 282 (void) str_realloc(&p);
fec84576
WC
283 return p;
284}
285
7f110ff9
LP
286char *ascii_is_valid(const char *str) {
287 const char *p;
288
294a3121
ZJS
289 /* Check whether the string consists of valid ASCII bytes,
290 * i.e values between 0 and 127, inclusive. */
291
7f110ff9
LP
292 assert(str);
293
294 for (p = str; *p; p++)
295 if ((unsigned char) *p >= 128)
296 return NULL;
297
298 return (char*) str;
299}
300
294a3121
ZJS
301char *ascii_is_valid_n(const char *str, size_t len) {
302 size_t i;
303
304 /* Very similar to ascii_is_valid(), but checks exactly len
305 * bytes and rejects any NULs in that range. */
306
307 assert(str);
308
309 for (i = 0; i < len; i++)
310 if ((unsigned char) str[i] >= 128 || str[i] == 0)
311 return NULL;
312
313 return (char*) str;
314}
315
2bb4c7e3
TG
316/**
317 * utf8_encode_unichar() - Encode single UCS-4 character as UTF-8
318 * @out_utf8: output buffer of at least 4 bytes or NULL
319 * @g: UCS-4 character to encode
320 *
321 * This encodes a single UCS-4 character as UTF-8 and writes it into @out_utf8.
322 * The length of the character is returned. It is not zero-terminated! If the
323 * output buffer is NULL, only the length is returned.
324 *
325 * Returns: The length in bytes that the UTF-8 representation does or would
326 * occupy.
327 */
c932fb71 328size_t utf8_encode_unichar(char *out_utf8, char32_t g) {
f3ee6297 329
2bb4c7e3
TG
330 if (g < (1 << 7)) {
331 if (out_utf8)
332 out_utf8[0] = g & 0x7f;
e7eebcfc 333 return 1;
2bb4c7e3
TG
334 } else if (g < (1 << 11)) {
335 if (out_utf8) {
336 out_utf8[0] = 0xc0 | ((g >> 6) & 0x1f);
337 out_utf8[1] = 0x80 | (g & 0x3f);
338 }
e7eebcfc 339 return 2;
2bb4c7e3
TG
340 } else if (g < (1 << 16)) {
341 if (out_utf8) {
342 out_utf8[0] = 0xe0 | ((g >> 12) & 0x0f);
343 out_utf8[1] = 0x80 | ((g >> 6) & 0x3f);
344 out_utf8[2] = 0x80 | (g & 0x3f);
345 }
e7eebcfc 346 return 3;
2bb4c7e3
TG
347 } else if (g < (1 << 21)) {
348 if (out_utf8) {
349 out_utf8[0] = 0xf0 | ((g >> 18) & 0x07);
350 out_utf8[1] = 0x80 | ((g >> 12) & 0x3f);
351 out_utf8[2] = 0x80 | ((g >> 6) & 0x3f);
352 out_utf8[3] = 0x80 | (g & 0x3f);
353 }
354 return 4;
e7eebcfc 355 }
f3ee6297
LP
356
357 return 0;
e7eebcfc
LP
358}
359
2ac2ff3f 360char *utf16_to_utf8(const char16_t *s, size_t length /* bytes! */) {
2e3d0692 361 const uint8_t *f;
e7eebcfc 362 char *r, *t;
2e3d0692 363
2ac2ff3f
LP
364 assert(s);
365
366 /* Input length is in bytes, i.e. the shortest possible character takes 2 bytes. Each unicode character may
367 * take up to 4 bytes in UTF-8. Let's also account for a trailing NUL byte. */
368 if (length * 2 < length)
369 return NULL; /* overflow */
370
371 r = new(char, length * 2 + 1);
2e3d0692
LP
372 if (!r)
373 return NULL;
374
2ac2ff3f 375 f = (const uint8_t*) s;
04166cb7
TG
376 t = r;
377
2ac2ff3f 378 while (f + 1 < (const uint8_t*) s + length) {
c932fb71 379 char16_t w1, w2;
04166cb7
TG
380
381 /* see RFC 2781 section 2.2 */
382
383 w1 = f[1] << 8 | f[0];
384 f += 2;
385
386 if (!utf16_is_surrogate(w1)) {
dcd12626 387 t += utf8_encode_unichar(t, w1);
04166cb7
TG
388 continue;
389 }
390
391 if (utf16_is_trailing_surrogate(w1))
2ac2ff3f
LP
392 continue; /* spurious trailing surrogate, ignore */
393
394 if (f + 1 >= (const uint8_t*) s + length)
04166cb7
TG
395 break;
396
397 w2 = f[1] << 8 | f[0];
398 f += 2;
399
400 if (!utf16_is_trailing_surrogate(w2)) {
401 f -= 2;
2ac2ff3f 402 continue; /* surrogate missing its trailing surrogate, ignore */
04166cb7
TG
403 }
404
405 t += utf8_encode_unichar(t, utf16_surrogate_pair_to_unichar(w1, w2));
406 }
2e3d0692
LP
407
408 *t = 0;
7b4d7cc0 409 return r;
2e3d0692 410}
02a36bc9 411
80b0a597
LP
412size_t utf16_encode_unichar(char16_t *out, char32_t c) {
413
414 /* Note that this encodes as little-endian. */
415
416 switch (c) {
417
418 case 0 ... 0xd7ffU:
419 case 0xe000U ... 0xffffU:
420 out[0] = htole16(c);
421 return 1;
422
423 case 0x10000U ... 0x10ffffU:
424 c -= 0x10000U;
425 out[0] = htole16((c >> 10) + 0xd800U);
426 out[1] = htole16((c & 0x3ffU) + 0xdc00U);
427 return 2;
428
429 default: /* A surrogate (invalid) */
430 return 0;
431 }
432}
433
434char16_t *utf8_to_utf16(const char *s, size_t length) {
435 char16_t *n, *p;
436 size_t i;
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 (i = 0; i < length;) {
448 char32_t unichar;
449 size_t e;
450
84319aa7 451 e = utf8_encoded_expected_len(s[i]);
80b0a597
LP
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
474size_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
02a36bc9 485/* expected size used to encode one unicode char */
c932fb71 486static int utf8_unichar_to_encoded_len(char32_t unichar) {
7e8185ef 487
02a36bc9
DR
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;
7e8185ef 498
02a36bc9
DR
499 return 6;
500}
501
502/* validate one encoded unicode char and return its length */
92e068b4 503int utf8_encoded_valid_unichar(const char *str, size_t length /* bytes */) {
c932fb71 504 char32_t unichar;
7c421857
LP
505 size_t len, i;
506 int r;
7e8185ef
LP
507
508 assert(str);
92e068b4
ZJS
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. */
02a36bc9 512
84319aa7 513 len = utf8_encoded_expected_len(str[0]);
02a36bc9 514 if (len == 0)
7e8185ef 515 return -EINVAL;
02a36bc9 516
92e068b4
ZJS
517 /* Do we have a truncated multi-byte character? */
518 if (len > length)
519 return -EINVAL;
520
02a36bc9
DR
521 /* ascii is valid */
522 if (len == 1)
523 return 1;
524
525 /* check if expected encoded chars are available */
526 for (i = 0; i < len; i++)
527 if ((str[i] & 0x80) != 0x80)
7e8185ef 528 return -EINVAL;
02a36bc9 529
c932fb71
SL
530 r = utf8_encoded_to_unichar(str, &unichar);
531 if (r < 0)
532 return r;
02a36bc9
DR
533
534 /* check if encoded length matches encoded value */
7c421857 535 if (utf8_unichar_to_encoded_len(unichar) != (int) len)
7e8185ef 536 return -EINVAL;
02a36bc9
DR
537
538 /* check if value has valid range */
f3ee6297 539 if (!unichar_is_valid(unichar))
7e8185ef 540 return -EINVAL;
02a36bc9 541
7c421857 542 return (int) len;
02a36bc9 543}
65ee8660
LP
544
545size_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
92e068b4 553 k = utf8_encoded_valid_unichar(str, (size_t) -1);
65ee8660
LP
554 if (k < 0)
555 return (size_t) -1;
556
557 str += k;
558 n++;
559 }
560
561 return n;
562}
3f536d5b
LP
563
564size_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
da88f542
ZJS
570 while (*str) {
571 int w;
3f536d5b 572
da88f542
ZJS
573 w = utf8_char_console_width(str);
574 if (w < 0)
3f536d5b
LP
575 return (size_t) -1;
576
da88f542 577 n += w;
3f536d5b 578 str = utf8_next_char(str);
3f536d5b
LP
579 }
580
581 return n;
582}