chiark / gitweb /
2bdda21af7d024ffb4e90abb8529ebead2c68f64
[elogind.git] / src / basic / utf8.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3   Copyright © 2008-2011 Kay Sievers
4 ***/
5
6 /* Parts of this file are based on the GLIB utf8 validation functions. The
7  * original license text follows. */
8
9 /* gutf8.c - Operations on UTF-8 strings.
10  *
11  * Copyright (C) 1999 Tom Tromey
12  * Copyright (C) 2000 Red Hat, Inc.
13  *
14  * This library is free software; you can redistribute it and/or
15  * modify it under the terms of the GNU Library General Public
16  * License as published by the Free Software Foundation; either
17  * version 2 of the License, or (at your option) any later version.
18  *
19  * This library is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22  * Library General Public License for more details.
23  *
24  * You should have received a copy of the GNU Library General Public
25  * License along with this library; if not, write to the Free Software
26  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
27  */
28
29 #include <errno.h>
30 #include <stdbool.h>
31 #include <stdlib.h>
32 #include <string.h>
33
34 #include "alloc-util.h"
35 //#include "gunicode.h"
36 #include "hexdecoct.h"
37 #include "macro.h"
38 #include "utf8.h"
39
40 bool unichar_is_valid(char32_t ch) {
41
42         if (ch >= 0x110000) /* End of unicode space */
43                 return false;
44         if ((ch & 0xFFFFF800) == 0xD800) /* Reserved area for UTF-16 */
45                 return false;
46         if ((ch >= 0xFDD0) && (ch <= 0xFDEF)) /* Reserved */
47                 return false;
48         if ((ch & 0xFFFE) == 0xFFFE) /* BOM (Byte Order Mark) */
49                 return false;
50
51         return true;
52 }
53
54 static bool unichar_is_control(char32_t ch) {
55
56         /*
57           0 to ' '-1 is the C0 range.
58           DEL=0x7F, and DEL+1 to 0x9F is C1 range.
59           '\t' is in C0 range, but more or less harmless and commonly used.
60         */
61
62         return (ch < ' ' && !IN_SET(ch, '\t', '\n')) ||
63                 (0x7F <= ch && ch <= 0x9F);
64 }
65
66 /* count of characters used to encode one unicode char */
67 static int utf8_encoded_expected_len(const char *str) {
68         unsigned char c;
69
70         assert(str);
71
72         c = (unsigned char) str[0];
73         if (c < 0x80)
74                 return 1;
75         if ((c & 0xe0) == 0xc0)
76                 return 2;
77         if ((c & 0xf0) == 0xe0)
78                 return 3;
79         if ((c & 0xf8) == 0xf0)
80                 return 4;
81         if ((c & 0xfc) == 0xf8)
82                 return 5;
83         if ((c & 0xfe) == 0xfc)
84                 return 6;
85
86         return 0;
87 }
88
89 /* decode one unicode char */
90 int utf8_encoded_to_unichar(const char *str, char32_t *ret_unichar) {
91         char32_t unichar;
92         int len, i;
93
94         assert(str);
95
96         len = utf8_encoded_expected_len(str);
97
98         switch (len) {
99         case 1:
100                 *ret_unichar = (char32_t)str[0];
101                 return 0;
102         case 2:
103                 unichar = str[0] & 0x1f;
104                 break;
105         case 3:
106                 unichar = (char32_t)str[0] & 0x0f;
107                 break;
108         case 4:
109                 unichar = (char32_t)str[0] & 0x07;
110                 break;
111         case 5:
112                 unichar = (char32_t)str[0] & 0x03;
113                 break;
114         case 6:
115                 unichar = (char32_t)str[0] & 0x01;
116                 break;
117         default:
118                 return -EINVAL;
119         }
120
121         for (i = 1; i < len; i++) {
122                 if (((char32_t)str[i] & 0xc0) != 0x80)
123                         return -EINVAL;
124                 unichar <<= 6;
125                 unichar |= (char32_t)str[i] & 0x3f;
126         }
127
128         *ret_unichar = unichar;
129
130         return 0;
131 }
132
133 bool utf8_is_printable_newline(const char* str, size_t length, bool newline) {
134         const char *p;
135
136         assert(str);
137
138         for (p = str; length;) {
139                 int encoded_len, r;
140                 char32_t val;
141
142                 encoded_len = utf8_encoded_valid_unichar(p);
143                 if (encoded_len < 0 ||
144                     (size_t) encoded_len > length)
145                         return false;
146
147                 r = utf8_encoded_to_unichar(p, &val);
148                 if (r < 0 ||
149                     unichar_is_control(val) ||
150                     (!newline && val == '\n'))
151                         return false;
152
153                 length -= encoded_len;
154                 p += encoded_len;
155         }
156
157         return true;
158 }
159
160 const char *utf8_is_valid(const char *str) {
161         const uint8_t *p;
162
163         assert(str);
164
165         for (p = (const uint8_t*) str; *p; ) {
166                 int len;
167
168                 len = utf8_encoded_valid_unichar((const char *)p);
169                 if (len < 0)
170                         return NULL;
171
172                 p += len;
173         }
174
175         return str;
176 }
177
178 char *utf8_escape_invalid(const char *str) {
179         char *p, *s;
180
181         assert(str);
182
183         p = s = malloc(strlen(str) * 4 + 1);
184         if (!p)
185                 return NULL;
186
187         while (*str) {
188                 int len;
189
190                 len = utf8_encoded_valid_unichar(str);
191                 if (len > 0) {
192                         s = mempcpy(s, str, len);
193                         str += len;
194                 } else {
195                         s = stpcpy(s, UTF8_REPLACEMENT_CHARACTER);
196                         str += 1;
197                 }
198         }
199
200         *s = '\0';
201
202         return p;
203 }
204
205 char *utf8_escape_non_printable(const char *str) {
206         char *p, *s;
207
208         assert(str);
209
210         p = s = malloc(strlen(str) * 4 + 1);
211         if (!p)
212                 return NULL;
213
214         while (*str) {
215                 int len;
216
217                 len = utf8_encoded_valid_unichar(str);
218                 if (len > 0) {
219                         if (utf8_is_printable(str, len)) {
220                                 s = mempcpy(s, str, len);
221                                 str += len;
222                         } else {
223                                 while (len > 0) {
224                                         *(s++) = '\\';
225                                         *(s++) = 'x';
226                                         *(s++) = hexchar((int) *str >> 4);
227                                         *(s++) = hexchar((int) *str);
228
229                                         str += 1;
230                                         len--;
231                                 }
232                         }
233                 } else {
234                         s = stpcpy(s, UTF8_REPLACEMENT_CHARACTER);
235                         str += 1;
236                 }
237         }
238
239         *s = '\0';
240
241         return p;
242 }
243
244 char *ascii_is_valid(const char *str) {
245         const char *p;
246
247         /* Check whether the string consists of valid ASCII bytes,
248          * i.e values between 0 and 127, inclusive. */
249
250         assert(str);
251
252         for (p = str; *p; p++)
253                 if ((unsigned char) *p >= 128)
254                         return NULL;
255
256         return (char*) str;
257 }
258
259 char *ascii_is_valid_n(const char *str, size_t len) {
260         size_t i;
261
262         /* Very similar to ascii_is_valid(), but checks exactly len
263          * bytes and rejects any NULs in that range. */
264
265         assert(str);
266
267         for (i = 0; i < len; i++)
268                 if ((unsigned char) str[i] >= 128 || str[i] == 0)
269                         return NULL;
270
271         return (char*) str;
272 }
273
274 /**
275  * utf8_encode_unichar() - Encode single UCS-4 character as UTF-8
276  * @out_utf8: output buffer of at least 4 bytes or NULL
277  * @g: UCS-4 character to encode
278  *
279  * This encodes a single UCS-4 character as UTF-8 and writes it into @out_utf8.
280  * The length of the character is returned. It is not zero-terminated! If the
281  * output buffer is NULL, only the length is returned.
282  *
283  * Returns: The length in bytes that the UTF-8 representation does or would
284  *          occupy.
285  */
286 size_t utf8_encode_unichar(char *out_utf8, char32_t g) {
287
288         if (g < (1 << 7)) {
289                 if (out_utf8)
290                         out_utf8[0] = g & 0x7f;
291                 return 1;
292         } else if (g < (1 << 11)) {
293                 if (out_utf8) {
294                         out_utf8[0] = 0xc0 | ((g >> 6) & 0x1f);
295                         out_utf8[1] = 0x80 | (g & 0x3f);
296                 }
297                 return 2;
298         } else if (g < (1 << 16)) {
299                 if (out_utf8) {
300                         out_utf8[0] = 0xe0 | ((g >> 12) & 0x0f);
301                         out_utf8[1] = 0x80 | ((g >> 6) & 0x3f);
302                         out_utf8[2] = 0x80 | (g & 0x3f);
303                 }
304                 return 3;
305         } else if (g < (1 << 21)) {
306                 if (out_utf8) {
307                         out_utf8[0] = 0xf0 | ((g >> 18) & 0x07);
308                         out_utf8[1] = 0x80 | ((g >> 12) & 0x3f);
309                         out_utf8[2] = 0x80 | ((g >> 6) & 0x3f);
310                         out_utf8[3] = 0x80 | (g & 0x3f);
311                 }
312                 return 4;
313         }
314
315         return 0;
316 }
317
318 char *utf16_to_utf8(const void *s, size_t length) {
319         const uint8_t *f;
320         char *r, *t;
321
322         r = new(char, (length * 4 + 1) / 2 + 1);
323         if (!r)
324                 return NULL;
325
326         f = s;
327         t = r;
328
329         while (f < (const uint8_t*) s + length) {
330                 char16_t w1, w2;
331
332                 /* see RFC 2781 section 2.2 */
333
334                 w1 = f[1] << 8 | f[0];
335                 f += 2;
336
337                 if (!utf16_is_surrogate(w1)) {
338                         t += utf8_encode_unichar(t, w1);
339
340                         continue;
341                 }
342
343                 if (utf16_is_trailing_surrogate(w1))
344                         continue;
345                 else if (f >= (const uint8_t*) s + length)
346                         break;
347
348                 w2 = f[1] << 8 | f[0];
349                 f += 2;
350
351                 if (!utf16_is_trailing_surrogate(w2)) {
352                         f -= 2;
353                         continue;
354                 }
355
356                 t += utf8_encode_unichar(t, utf16_surrogate_pair_to_unichar(w1, w2));
357         }
358
359         *t = 0;
360         return r;
361 }
362
363 /* expected size used to encode one unicode char */
364 static int utf8_unichar_to_encoded_len(char32_t unichar) {
365
366         if (unichar < 0x80)
367                 return 1;
368         if (unichar < 0x800)
369                 return 2;
370         if (unichar < 0x10000)
371                 return 3;
372         if (unichar < 0x200000)
373                 return 4;
374         if (unichar < 0x4000000)
375                 return 5;
376
377         return 6;
378 }
379
380 /* validate one encoded unicode char and return its length */
381 int utf8_encoded_valid_unichar(const char *str) {
382         int len, i, r;
383         char32_t unichar;
384
385         assert(str);
386
387         len = utf8_encoded_expected_len(str);
388         if (len == 0)
389                 return -EINVAL;
390
391         /* ascii is valid */
392         if (len == 1)
393                 return 1;
394
395         /* check if expected encoded chars are available */
396         for (i = 0; i < len; i++)
397                 if ((str[i] & 0x80) != 0x80)
398                         return -EINVAL;
399
400         r = utf8_encoded_to_unichar(str, &unichar);
401         if (r < 0)
402                 return r;
403
404         /* check if encoded length matches encoded value */
405         if (utf8_unichar_to_encoded_len(unichar) != len)
406                 return -EINVAL;
407
408         /* check if value has valid range */
409         if (!unichar_is_valid(unichar))
410                 return -EINVAL;
411
412         return len;
413 }
414
415 size_t utf8_n_codepoints(const char *str) {
416         size_t n = 0;
417
418         /* Returns the number of UTF-8 codepoints in this string, or (size_t) -1 if the string is not valid UTF-8. */
419
420         while (*str != 0) {
421                 int k;
422
423                 k = utf8_encoded_valid_unichar(str);
424                 if (k < 0)
425                         return (size_t) -1;
426
427                 str += k;
428                 n++;
429         }
430
431         return n;
432 }
433
434 size_t utf8_console_width(const char *str) {
435         size_t n = 0;
436
437         /* Returns the approximate width a string will take on screen when printed on a character cell
438          * terminal/console. */
439
440         while (*str != 0) {
441                 char32_t c;
442
443                 if (utf8_encoded_to_unichar(str, &c) < 0)
444                         return (size_t) -1;
445
446                 str = utf8_next_char(str);
447
448                 n += unichar_iswide(c) ? 2 : 1;
449         }
450
451         return n;
452 }