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