92742b677a08d0e840097ea40781bf475d15ce9c
[dragonfly.git] / usr.bin / localedef / wide.c
1 /*
2  * Copyright 2011 Nexenta Systems, Inc.  All rights reserved.
3  * Copyright 2012 Garrett D'Amore <garrett@damore.org>  All rights reserved.
4  * Copyright 2015 John Marino <draco@marino.st>
5  *
6  * This source code is derived from the illumos localedef command, and
7  * provided under BSD-style license terms by Nexenta Systems, Inc.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
23  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31
32 /*
33  * The functions in this file convert from the standard multibyte forms
34  * to the wide character forms used internally by libc.  Unfortunately,
35  * this approach means that we need a method for each and every encoding.
36  */
37
38 #include <stdlib.h>
39 #include <wchar.h>
40 #include <string.h>
41 #include <sys/types.h>
42 #include "localedef.h"
43
44 static int towide_none(wchar_t *, const char *, unsigned);
45 static int towide_utf8(wchar_t *, const char *, unsigned);
46 static int towide_big5(wchar_t *, const char *, unsigned);
47 static int towide_gbk(wchar_t *, const char *, unsigned);
48 static int towide_gb2312(wchar_t *, const char *, unsigned);
49 static int towide_gb18030(wchar_t *, const char *, unsigned);
50 static int towide_mskanji(wchar_t *, const char *, unsigned);
51 static int towide_euccn(wchar_t *, const char *, unsigned);
52 static int towide_eucjp(wchar_t *, const char *, unsigned);
53 static int towide_euckr(wchar_t *, const char *, unsigned);
54 static int towide_euctw(wchar_t *, const char *, unsigned);
55
56 static int tomb_none(char *, wchar_t);
57 static int tomb_utf8(char *, wchar_t);
58 static int tomb_mbs(char *, wchar_t);
59
60 static int (*_towide)(wchar_t *, const char *, unsigned) = towide_none;
61 static int (*_tomb)(char *, wchar_t) = tomb_none;
62 static const char *_encoding = "NONE";
63 static int _nbits = 7;
64
65 /*
66  * Table of supported encodings.  We only bother to list the multibyte
67  * encodings here, because single byte locales are handed by "NONE".
68  */
69 static struct {
70         const char *name;
71         /* the name that the underlying libc implemenation uses */
72         const char *cname;
73         /* the maximum number of bits required for priorities */
74         int nbits;
75         int (*towide)(wchar_t *, const char *, unsigned);
76         int (*tomb)(char *, wchar_t);
77 } mb_encodings[] = {
78         /*
79          * UTF8 values max out at 0x1fffff (although in theory there could
80          * be later extensions, but it won't happen.)  This means we only need
81          * 21 bits to be able to encode the entire range of priorities.
82          */
83         { "UTF-8",      "UTF-8",        21, towide_utf8, tomb_utf8 },
84         { "UTF8",       "UTF-8",        21, towide_utf8, tomb_utf8 },
85         { "utf8",       "UTF-8",        21, towide_utf8, tomb_utf8 },
86         { "utf-8",      "UTF-8",        21, towide_utf8, tomb_utf8 },
87
88         { "EUC-CN",     "EUC-CN",       16, towide_euccn, tomb_mbs },
89         { "eucCN",      "EUC-CN",       16, towide_euccn, tomb_mbs },
90         /*
91          * Becuase the 3-byte form of EUC-JP use the same leading byte,
92          * only 17 bits required to provide unique priorities.  (The low
93          * bit of that first byte is set.)  By setting this value low,
94          * we can get by with only 3 bytes in the strxfrm expansion.
95          */
96         { "EUC-JP",     "EUC-JP",       17, towide_eucjp, tomb_mbs },
97         { "eucJP",      "EUC-JP",       17, towide_eucjp, tomb_mbs },
98
99         { "EUC-KR",     "EUC-KR",       16, towide_euckr, tomb_mbs },
100         { "eucKR",      "EUC-KR",       16, towide_euckr, tomb_mbs },
101         /*
102          * EUC-TW uses 2 bytes most of the time, but 4 bytes if the
103          * high order byte is 0x8E.  However, with 4 byte encodings,
104          * the third byte will be A0-B0.  So we only need to consider
105          * the lower order 24 bits for collation.
106          */
107         { "EUC-TW",     "EUC-TW",       24, towide_euctw, tomb_mbs },
108         { "eucTW",      "EUC-TW",       24, towide_euctw, tomb_mbs },
109
110         { "MS_Kanji",   "MSKanji",      16, towide_mskanji, tomb_mbs },
111         { "MSKanji",    "MSKanji",      16, towide_mskanji, tomb_mbs },
112         { "PCK",        "MSKanji",      16, towide_mskanji, tomb_mbs },
113         { "SJIS",       "MSKanji",      16, towide_mskanji, tomb_mbs },
114         { "Shift_JIS",  "MSKanji",      16, towide_mskanji, tomb_mbs },
115
116         { "BIG5",       "BIG5",         16, towide_big5, tomb_mbs },
117         { "big5",       "BIG5",         16, towide_big5, tomb_mbs },
118         { "Big5",       "BIG5",         16, towide_big5, tomb_mbs },
119
120         { "GBK",        "GBK",          16, towide_gbk, tomb_mbs },
121
122         /*
123          * GB18030 can get away with just 31 bits.  This is because the
124          * high order bit is always set for 4 byte values, and the
125          * at least one of the other bits in that 4 byte value will
126          * be non-zero.
127          */
128         { "GB18030",    "GB18030",      31, towide_gb18030, tomb_mbs },
129
130         /*
131          * This should probably be an aliase for euc-cn, or vice versa.
132          */
133         { "GB2312",     "GB2312",       16, towide_gb2312, tomb_mbs },
134
135         { NULL, NULL, 0, 0, 0 },
136 };
137
138 static char *
139 show_mb(const char *mb)
140 {
141         static char buf[64];
142
143         /* ASCII stuff we just print */
144         if (isascii(*mb) && isgraph(*mb)) {
145                 buf[0] = *mb;
146                 buf[1] = 0;
147                 return (buf);
148         }
149         buf[0] = 0;
150         while (*mb != 0) {
151                 char scr[8];
152                 (void) snprintf(scr, sizeof (scr), "\\x%02x", *mb);
153                 (void) strlcat(buf, scr, sizeof (buf));
154                 mb++;
155         }
156         return (buf);
157 }
158
159 static char     *widemsg;
160
161 void
162 werr(const char *fmt, ...)
163 {
164         char    *msg;
165
166         va_list va;
167         va_start(va, fmt);
168         (void) vasprintf(&msg, fmt, va);
169         va_end(va);
170
171         free(widemsg);
172         widemsg = msg;
173 }
174
175 /*
176  * This is used for 8-bit encodings.
177  */
178 int
179 towide_none(wchar_t *c, const char *mb, unsigned n __unused)
180 {
181         if (mb_cur_max != 1) {
182                 werr("invalid or unsupported multibyte locale");
183                 return (-1);
184         }
185         *c = (uint8_t)*mb;
186         return (1);
187 }
188
189 int
190 tomb_none(char *mb, wchar_t wc)
191 {
192         if (mb_cur_max != 1) {
193                 werr("invalid or unsupported multibyte locale");
194                 return (-1);
195         }
196         *(uint8_t *)mb = (wc & 0xff);
197         mb[1] = 0;
198         return (1);
199 }
200
201 /*
202  * UTF-8 stores wide characters in UTF-32 form.
203  */
204 int
205 towide_utf8(wchar_t *wc, const char *mb, unsigned n)
206 {
207         wchar_t c;
208         int     nb;
209         int     lv;     /* lowest legal value */
210         int     i;
211         const uint8_t *s = (const uint8_t *)mb;
212
213         c = *s;
214
215         if ((c & 0x80) == 0) {
216                 /* 7-bit ASCII */
217                 *wc = c;
218                 return (1);
219         } else if ((c & 0xe0) == 0xc0) {
220                 /* u80-u7ff - two bytes encoded */
221                 nb = 2;
222                 lv = 0x80;
223                 c &= ~0xe0;
224         } else if ((c & 0xf0) == 0xe0) {
225                 /* u800-uffff - three bytes encoded */
226                 nb = 3;
227                 lv = 0x800;
228                 c &= ~0xf0;
229         } else if ((c & 0xf8) == 0xf0) {
230                 /* u1000-u1fffff - four bytes encoded */
231                 nb = 4;
232                 lv = 0x1000;
233                 c &= ~0xf8;
234         } else {
235                 /* 5 and 6 byte encodings are not legal unicode */
236                 werr("utf8 encoding too large (%s)", show_mb(mb));
237                 return (-1);
238         }
239         if (nb > (int)n) {
240                 werr("incomplete utf8 sequence (%s)", show_mb(mb));
241                 return (-1);
242         }
243
244         for (i = 1; i < nb; i++) {
245                 if (((s[i]) & 0xc0) != 0x80) {
246                         werr("illegal utf8 byte (%x)", s[i]);
247                         return (-1);
248                 }
249                 c <<= 6;
250                 c |= (s[i] & 0x3f);
251         }
252
253         if (c < lv) {
254                 werr("illegal redundant utf8 encoding (%s)", show_mb(mb));
255                 return (-1);
256         }
257         *wc = c;
258         return (nb);
259 }
260
261 int
262 tomb_utf8(char *mb, wchar_t wc)
263 {
264         uint8_t *s = (uint8_t *)mb;
265         uint8_t msk;
266         int cnt;
267         int i;
268
269         if (wc <= 0x7f) {
270                 s[0] = wc & 0x7f;
271                 s[1] = 0;
272                 return (1);
273         }
274         if (wc <= 0x7ff) {
275                 cnt = 2;
276                 msk = 0xc0;
277         } else if (wc <= 0xffff) {
278                 cnt = 3;
279                 msk = 0xe0;
280         } else if (wc <= 0x1fffff) {
281                 cnt = 4;
282                 msk = 0xf0;
283         } else {
284                 werr("illegal uf8 char (%x)", wc);
285                 return (-1);
286         }
287         for (i = cnt - 1; i; i--) {
288                 s[i] = (wc & 0x3f) | 0x80;
289                 wc >>= 6;
290         }
291         s[0] = (msk) | wc;
292         s[cnt] = 0;
293         return (cnt);
294 }
295
296 /*
297  * Several encodings share a simplistic dual byte encoding.  In these
298  * forms, they all indicate that a two byte sequence is to be used if
299  * the first byte has its high bit set.  They all store this simple
300  * encoding as a 16-bit value, although a great many of the possible
301  * code points are not used in most character sets.  This gives a possible
302  * set of just over 32,000 valid code points.
303  *
304  * 0x00 - 0x7f          - 1 byte encoding
305  * 0x80 - 0x7fff        - illegal
306  * 0x8000 - 0xffff      - 2 byte encoding
307  */
308
309 #pragma GCC diagnostic push
310 #pragma GCC diagnostic ignored "-Wcast-qual"
311
312 static int
313 towide_dbcs(wchar_t *wc, const char *mb, unsigned n)
314 {
315         wchar_t c;
316
317         c = *(uint8_t *)mb;
318
319         if ((c & 0x80) == 0) {
320                 /* 7-bit */
321                 *wc = c;
322                 return (1);
323         }
324         if (n < 2) {
325                 werr("incomplete character sequence (%s)", show_mb(mb));
326                 return (-1);
327         }
328
329         /* Store both bytes as a single 16-bit wide. */
330         c <<= 8;
331         c |= (uint8_t)(mb[1]);
332         *wc = c;
333         return (2);
334 }
335
336 /*
337  * Most multibyte locales just convert the wide character to the multibyte
338  * form by stripping leading null bytes, and writing the 32-bit quantity
339  * in big-endian order.
340  */
341 int
342 tomb_mbs(char *mb, wchar_t wc)
343 {
344         uint8_t *s = (uint8_t *)mb;
345         int     n = 0, c;
346
347         if ((wc & 0xff000000U) != 0) {
348                 n = 4;
349         } else if ((wc & 0x00ff0000U) != 0) {
350                 n = 3;
351         } else if ((wc & 0x0000ff00U) != 0) {
352                 n = 2;
353         } else {
354                 n = 1;
355         }
356         c = n;
357         while (n) {
358                 n--;
359                 s[n] = wc & 0xff;
360                 wc >>= 8;
361         }
362         /* ensure null termination */
363         s[c] = 0;
364         return (c);
365 }
366
367
368 /*
369  * big5 is a simple dual byte character set.
370  */
371 int
372 towide_big5(wchar_t *wc, const char *mb, unsigned n)
373 {
374         return (towide_dbcs(wc, mb, n));
375 }
376
377 /*
378  * GBK encodes wides in the same way that big5 does, the high order
379  * bit of the first byte indicates a double byte character.
380  */
381 int
382 towide_gbk(wchar_t *wc, const char *mb, unsigned n)
383 {
384         return (towide_dbcs(wc, mb, n));
385 }
386
387 /*
388  * GB2312 is another DBCS.  Its cleaner than others in that the second
389  * byte does not encode ASCII, but it supports characters.
390  */
391 int
392 towide_gb2312(wchar_t *wc, const char *mb, unsigned n)
393 {
394         return (towide_dbcs(wc, mb, n));
395 }
396
397 /*
398  * GB18030.  This encodes as 8, 16, or 32-bits.
399  * 7-bit values are in 1 byte,  4 byte sequences are used when
400  * the second byte encodes 0x30-39 and all other sequences are 2 bytes.
401  */
402 int
403 towide_gb18030(wchar_t *wc, const char *mb, unsigned n)
404 {
405         wchar_t c;
406
407         c = *(uint8_t *)mb;
408
409         if ((c & 0x80) == 0) {
410                 /* 7-bit */
411                 *wc = c;
412                 return (1);
413         }
414         if (n < 2) {
415                 werr("incomplete character sequence (%s)", show_mb(mb));
416                 return (-1);
417         }
418
419         /* pull in the second byte */
420         c <<= 8;
421         c |= (uint8_t)(mb[1]);
422
423         if (((c & 0xff) >= 0x30) && ((c & 0xff) <= 0x39)) {
424                 if (n < 4) {
425                         werr("incomplete 4-byte character sequence (%s)",
426                             show_mb(mb));
427                         return (-1);
428                 }
429                 c <<= 8;
430                 c |= (uint8_t)(mb[2]);
431                 c <<= 8;
432                 c |= (uint8_t)(mb[3]);
433                 *wc = c;
434                 return (4);
435         }
436
437         *wc = c;
438         return (2);
439 }
440
441 /*
442  * MS-Kanji (aka SJIS) is almost a clean DBCS like the others, but it
443  * also has a range of single byte characters above 0x80.  (0xa1-0xdf).
444  */
445 int
446 towide_mskanji(wchar_t *wc, const char *mb, unsigned n)
447 {
448         wchar_t c;
449
450         c = *(uint8_t *)mb;
451
452         if ((c < 0x80) || ((c > 0xa0) && (c < 0xe0))) {
453                 /* 7-bit */
454                 *wc = c;
455                 return (1);
456         }
457
458         if (n < 2) {
459                 werr("incomplete character sequence (%s)", show_mb(mb));
460                 return (-1);
461         }
462
463         /* Store both bytes as a single 16-bit wide. */
464         c <<= 8;
465         c |= (uint8_t)(mb[1]);
466         *wc = c;
467         return (2);
468 }
469
470 /*
471  * EUC forms.  EUC encodings are "variable".  FreeBSD carries some additional
472  * variable data to encode these, but we're going to treat each as independent
473  * instead.  Its the only way we can sensibly move forward.
474  *
475  * Note that the way in which the different EUC forms vary is how wide
476  * CS2 and CS3 are and what the first byte of them is.
477  */
478 static int
479 towide_euc_impl(wchar_t *wc, const char *mb, unsigned n,
480     uint8_t cs2, uint8_t cs2width, uint8_t cs3, uint8_t cs3width)
481 {
482         int i;
483         int width = 2;
484         wchar_t c;
485
486         c = *(uint8_t *)mb;
487
488         /*
489          * All variations of EUC encode 7-bit ASCII as one byte, and use
490          * additional bytes for more than that.
491          */
492         if ((c & 0x80) == 0) {
493                 /* 7-bit */
494                 *wc = c;
495                 return (1);
496         }
497
498         /*
499          * All EUC variants reserve 0xa1-0xff to identify CS1, which
500          * is always two bytes wide.  Note that unused CS will be zero,
501          * and that cannot be true because we know that the high order
502          * bit must be set.
503          */
504         if (c >= 0xa1) {
505                 width = 2;
506         } else if (c == cs2) {
507                 width = cs2width;
508         } else if (c == cs3) {
509                 width = cs3width;
510         }
511
512         if ((int)n < width) {
513                 werr("incomplete character sequence (%s)", show_mb(mb));
514                 return (-1);
515         }
516
517         for (i = 1; i < width; i++) {
518                 /* pull in the next byte */
519                 c <<= 8;
520                 c |= (uint8_t)(mb[i]);
521         }
522
523         *wc = c;
524         return (width);
525 }
526
527 #pragma GCC diagnostic pop
528
529 /*
530  * EUC-CN encodes as follows:
531  *
532  * Code set 0 (ASCII):                          0x21-0x7E
533  * Code set 1 (CNS 11643-1992 Plane 1):         0xA1A1-0xFEFE
534  * Code set 2:                                  unused
535  * Code set 3:                                  unused
536  */
537 int
538 towide_euccn(wchar_t *wc, const char *mb, unsigned n)
539 {
540         return (towide_euc_impl(wc, mb, n, 0x8e, 4, 0, 0));
541 }
542
543 /*
544  * EUC-JP encodes as follows:
545  *
546  * Code set 0 (ASCII or JIS X 0201-1976 Roman): 0x21-0x7E
547  * Code set 1 (JIS X 0208):                     0xA1A1-0xFEFE
548  * Code set 2 (half-width katakana):            0x8EA1-0x8EDF
549  * Code set 3 (JIS X 0212-1990):                0x8FA1A1-0x8FFEFE
550  */
551 int
552 towide_eucjp(wchar_t *wc, const char *mb, unsigned n)
553 {
554         return (towide_euc_impl(wc, mb, n, 0x8e, 2, 0x8f, 3));
555 }
556
557 /*
558  * EUC-KR encodes as follows:
559  *
560  * Code set 0 (ASCII or KS C 5636-1993):        0x21-0x7E
561  * Code set 1 (KS C 5601-1992):                 0xA1A1-0xFEFE
562  * Code set 2:                                  unused
563  * Code set 3:                                  unused
564  */
565 int
566 towide_euckr(wchar_t *wc, const char *mb, unsigned n)
567 {
568         return (towide_euc_impl(wc, mb, n, 0, 0, 0, 0));
569 }
570
571 /*
572  * EUC-TW encodes as follows:
573  *
574  * Code set 0 (ASCII):                          0x21-0x7E
575  * Code set 1 (CNS 11643-1992 Plane 1):         0xA1A1-0xFEFE
576  * Code set 2 (CNS 11643-1992 Planes 1-16):     0x8EA1A1A1-0x8EB0FEFE
577  * Code set 3:                                  unused
578  */
579 int
580 towide_euctw(wchar_t *wc, const char *mb, unsigned n)
581 {
582         return (towide_euc_impl(wc, mb, n, 0x8e, 4, 0, 0));
583 }
584
585 /*
586  * Public entry points.
587  */
588
589 int
590 to_wide(wchar_t *wc, const char *mb)
591 {
592         /* this won't fail hard */
593         return (_towide(wc, mb, strlen(mb)));
594 }
595
596 int
597 to_mb(char *mb, wchar_t wc)
598 {
599         int     rv;
600
601         if ((rv = _tomb(mb, wc)) < 0) {
602                 errf(widemsg);
603                 free(widemsg);
604                 widemsg = NULL;
605         }
606         return (rv);
607 }
608
609 char *
610 to_mb_string(const wchar_t *wcs)
611 {
612         char    *mbs;
613         char    *ptr;
614         int     len;
615
616         mbs = malloc((wcslen(wcs) * mb_cur_max) + 1);
617         if (mbs == NULL) {
618                 errf("out of memory");
619                 return (NULL);
620         }
621         ptr = mbs;
622         while (*wcs) {
623                 if ((len = to_mb(ptr, *wcs)) < 0) {
624                         INTERR;
625                         free(mbs);
626                         return (NULL);
627                 }
628                 wcs++;
629                 ptr += len;
630         }
631         *ptr = 0;
632         return (mbs);
633 }
634
635 void
636 set_wide_encoding(const char *encoding)
637 {
638         int i;
639
640         _towide = towide_none;
641         _tomb = tomb_none;
642         _encoding = "NONE";
643         _nbits = 8;
644
645         for (i = 0; mb_encodings[i].name; i++) {
646                 if (strcasecmp(encoding, mb_encodings[i].name) == 0) {
647                         _towide = mb_encodings[i].towide;
648                         _tomb = mb_encodings[i].tomb;
649                         _encoding = mb_encodings[i].cname;
650                         _nbits = mb_encodings[i].nbits;
651                         break;
652                 }
653         }
654 }
655
656 const char *
657 get_wide_encoding(void)
658 {
659         return (_encoding);
660 }
661
662 int
663 max_wide(void)
664 {
665         return ((int)((1U << _nbits) - 1));
666 }