Sync Citrus iconv support with NetBSD.
[dragonfly.git] / lib / libc / citrus / modules / citrus_utf7.c
1 /* $NetBSD: citrus_utf7.c,v 1.5 2006/08/23 12:57:24 tnozaki Exp $ */
2 /* $DragonFly: src/lib/libc/citrus/modules/citrus_utf7.c,v 1.3 2008/04/10 10:21:02 hasso Exp $ */
3
4 /*-
5  * Copyright (c)2004, 2005 Citrus Project,
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  */
30
31 #include <assert.h>
32 #include <errno.h>
33 #include <limits.h>
34 #include <stdint.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <wchar.h>
39
40 #include "citrus_namespace.h"
41 #include "citrus_types.h"
42 #include "citrus_module.h"
43 #include "citrus_ctype.h"
44 #include "citrus_stdenc.h"
45 #include "citrus_utf7.h"
46
47 /* ----------------------------------------------------------------------
48  * private stuffs used by templates
49  */
50
51 typedef struct {
52         uint16_t        cell[0x80];
53 #define EI_MASK         UINT16_C(0xff)
54 #define EI_DIRECT       UINT16_C(0x100)
55 #define EI_OPTION       UINT16_C(0x200)
56 #define EI_SPACE        UINT16_C(0x400)
57 } _UTF7EncodingInfo;
58
59 typedef struct {
60         unsigned int
61                 mode: 1,        /* whether base64 mode */
62                 bits: 4,        /* need to hold 0 - 15 */
63                 cache: 22,      /* 22 = BASE64_BIT + UTF16_BIT */
64                 surrogate: 1;   /* whether surrogate pair or not */
65         int chlen;
66         char ch[4]; /* BASE64_IN, 3 * 6 = 18, most closed to UTF16_BIT */
67 } _UTF7State;
68
69 typedef struct {
70         _UTF7EncodingInfo       ei;
71         struct {
72                 /* for future multi-locale facility */
73                 _UTF7State      s_mblen;
74                 _UTF7State      s_mbrlen;
75                 _UTF7State      s_mbrtowc;
76                 _UTF7State      s_mbtowc;
77                 _UTF7State      s_mbsrtowcs;
78                 _UTF7State      s_wcrtomb;
79                 _UTF7State      s_wcsrtombs;
80                 _UTF7State      s_wctomb;
81         } states;
82 } _UTF7CTypeInfo;
83
84 #define _CEI_TO_EI(_cei_)               (&(_cei_)->ei)
85 #define _CEI_TO_STATE(_cei_, _func_)    (_cei_)->states.s_##_func_
86
87 #define _FUNCNAME(m)                    _citrus_UTF7_##m
88 #define _ENCODING_INFO                  _UTF7EncodingInfo
89 #define _CTYPE_INFO                     _UTF7CTypeInfo
90 #define _ENCODING_STATE                 _UTF7State
91 #define _ENCODING_MB_CUR_MAX(_ei_)              4
92 #define _ENCODING_IS_STATE_DEPENDENT            1
93 #define _STATE_NEEDS_EXPLICIT_INIT(_ps_)        0
94
95 static __inline void
96 /*ARGSUSED*/
97 _citrus_UTF7_init_state(_UTF7EncodingInfo * __restrict ei,
98         _UTF7State * __restrict s)
99 {
100         /* ei appears to be unused */
101         _DIAGASSERT(s != NULL);
102
103         memset((void *)s, 0, sizeof(*s));
104 }
105
106 static __inline void
107 /*ARGSUSED*/
108 _citrus_UTF7_pack_state(_UTF7EncodingInfo * __restrict ei,
109         void *__restrict pspriv, const _UTF7State * __restrict s)
110 {
111         /* ei seem to be unused */
112         _DIAGASSERT(pspriv != NULL);
113         _DIAGASSERT(s != NULL);
114
115         memcpy(pspriv, (const void *)s, sizeof(*s));
116 }
117
118 static __inline void
119 /*ARGSUSED*/
120 _citrus_UTF7_unpack_state(_UTF7EncodingInfo * __restrict ei,
121         _UTF7State * __restrict s, const void * __restrict pspriv)
122 {
123         /* ei seem to be unused */
124         _DIAGASSERT(s != NULL);
125         _DIAGASSERT(pspriv != NULL);
126
127         memcpy((void *)s, pspriv, sizeof(*s));
128 }
129
130 static const char base64[] =
131         "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
132         "abcdefghijklmnopqrstuvwxyz"
133         "0123456789+/";
134
135 static const char direct[] =
136         "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
137         "abcdefghijklmnopqrstuvwxyz"
138         "0123456789(),-./:?";
139
140 static const char option[] = "!\"#$%&';<=>@[]^_`{|}";
141 static const char spaces[] = " \t\r\n";
142
143 #define BASE64_BIT      6
144 #define UTF16_BIT       16
145
146 #define BASE64_MAX      0x3f
147 #define UTF16_MAX       UINT16_C(0xffff)
148 #define UTF32_MAX       UINT32_C(0x10ffff)
149
150 #define BASE64_IN       '+'
151 #define BASE64_OUT      '-'
152
153 #define SHIFT7BIT(c)    ((c) >> 7)
154 #define ISSPECIAL(c)    ((c) == '\0' || (c) == BASE64_IN)
155
156 #define FINDLEN(ei, c) \
157         (SHIFT7BIT((c)) ? -1 : (((ei)->cell[(c)] & EI_MASK) - 1))
158
159 #define ISDIRECT(ei, c) (!SHIFT7BIT((c)) && (ISSPECIAL((c)) || \
160         ei->cell[(c)] & (EI_DIRECT | EI_OPTION | EI_SPACE)))
161
162 #define ISSAFE(ei, c)   (!SHIFT7BIT((c)) && (ISSPECIAL((c)) || \
163         (c < 0x80 && ei->cell[(c)] & (EI_DIRECT | EI_SPACE))))
164
165 /* surrogate pair */
166 #define SRG_BASE        UINT32_C(0x10000)
167 #define HISRG_MIN       UINT16_C(0xd800)
168 #define HISRG_MAX       UINT16_C(0xdbff)
169 #define LOSRG_MIN       UINT16_C(0xdc00)
170 #define LOSRG_MAX       UINT16_C(0xdfff)
171
172 static int
173 _citrus_UTF7_mbtoutf16(_UTF7EncodingInfo * __restrict ei,
174         uint16_t * __restrict u16, const char ** __restrict s, size_t n,
175         _UTF7State * __restrict psenc, size_t * __restrict nresult)
176 {
177         _UTF7State sv;
178         const char *s0;
179         int i, done, len;
180  
181         _DIAGASSERT(ei != NULL);
182         _DIAGASSERT(s != NULL && *s != NULL);
183         _DIAGASSERT(psenc != NULL);
184
185         s0 = *s;
186         sv = *psenc;
187
188         for (i = 0, done = 0; done == 0; i++) {
189                 _DIAGASSERT(i <= psenc->chlen);
190                 if (i == psenc->chlen) {
191                         if (n-- < 1) {
192                                 *nresult = (size_t)-2;
193                                 *s = s0;
194                                 sv.chlen = psenc->chlen;
195                                 *psenc = sv;
196                                 return 0;
197                         }
198                         psenc->ch[psenc->chlen++] = *s0++;
199                 }
200                 if (SHIFT7BIT((int)psenc->ch[i]))
201                         goto ilseq;
202                 if (!psenc->mode) {
203                         if (psenc->bits > 0 || psenc->cache > 0)
204                                 return EINVAL;
205                         if (psenc->ch[i] == BASE64_IN) {
206                                 psenc->mode = 1;
207                         } else {
208                                 if (!ISDIRECT(ei, (int)psenc->ch[i]))
209                                         goto ilseq;
210                                 *u16 = (uint16_t)psenc->ch[i];
211                                 done = 1;
212                                 continue;
213                         }
214                 } else {
215                         if (psenc->ch[i] == BASE64_OUT && psenc->cache == 0) {
216                                 psenc->mode = 0;
217                                 *u16 = (uint16_t)BASE64_IN;
218                                 done = 1;
219                                 continue;
220                         }
221                         len = FINDLEN(ei, (int)psenc->ch[i]);
222                         if (len < 0) {
223                                 if (psenc->bits >= BASE64_BIT)
224                                         return EINVAL;
225                                 psenc->mode = 0;
226                                 psenc->bits = psenc->cache = 0;
227                                 if (psenc->ch[i] != BASE64_OUT) {
228                                         if (!ISDIRECT(ei, (int)psenc->ch[i]))
229                                                 goto ilseq;
230                                         *u16 = (uint16_t)psenc->ch[i];
231                                         done = 1;
232                                 }
233                         } else {
234                                 psenc->cache =
235                                     (psenc->cache << BASE64_BIT) | len;
236                                 switch (psenc->bits) {
237                                 case 0: case 2: case 4: case 6: case 8:
238                                         psenc->bits += BASE64_BIT;
239                                         break;
240                                 case 10: case 12: case 14:
241                                         psenc->bits -= (UTF16_BIT - BASE64_BIT);
242                                         *u16 = (psenc->cache >> psenc->bits)
243                                             & UTF16_MAX;
244                                         done = 1;
245                                         break;
246                                 default:
247                                         return EINVAL;
248                                 }
249                         }
250                 }
251         }
252
253         if (psenc->chlen > i)
254                 return EINVAL;
255         psenc->chlen = 0;
256         *nresult = (size_t)((*u16 == 0) ? 0 : s0 - *s);
257         *s = s0;
258
259         return 0;
260
261 ilseq:
262         *nresult = (size_t)-1;
263         return EILSEQ;
264 }
265
266 static int
267 _citrus_UTF7_mbrtowc_priv(_UTF7EncodingInfo * __restrict ei,
268         wchar_t * __restrict pwc, const char ** __restrict s, size_t n,
269         _UTF7State * __restrict psenc, size_t * __restrict nresult)
270 {
271         const char *s0;
272         uint32_t u32;
273         uint16_t hi, lo;
274         size_t siz, nr;
275         int err;
276
277         _DIAGASSERT(ei != NULL);
278         /* pwc may be null */
279         _DIAGASSERT(s != NULL);
280         _DIAGASSERT(psenc != NULL);
281
282         if (*s == NULL) {
283                 _citrus_UTF7_init_state(ei, psenc);
284                 *nresult = (size_t)_ENCODING_IS_STATE_DEPENDENT;
285                 return 0;
286         }
287         s0 = *s;
288         if (psenc->surrogate) {
289                 hi = (psenc->cache >> 2) & UTF16_MAX;
290                 if (hi < HISRG_MIN || hi > HISRG_MAX)
291                         return EINVAL;
292                 siz = 0;
293         } else {
294                 err = _citrus_UTF7_mbtoutf16(ei, &hi, &s0, n, psenc, &nr);
295                 if (nr == (size_t)-1 || nr == (size_t)-2) {
296                         *nresult = nr;
297                         return err;
298                 }
299                 if (err != 0)
300                         return err;
301                 n -= nr;
302                 siz = nr;
303                 if (hi < HISRG_MIN || hi > HISRG_MAX) {
304                         u32 = (uint32_t)hi;
305                         goto done;
306                 }
307                 psenc->surrogate = 1;
308         }
309         err = _citrus_UTF7_mbtoutf16(ei, &lo, &s0, n, psenc, &nr);
310         if (nr == (size_t)-1 || nr == (size_t)-2) {
311                 *nresult = nr;
312                 return err;
313         }
314         if (err != 0)
315                 return err;
316         hi -= HISRG_MIN;
317         lo -= LOSRG_MIN;
318         u32 = (hi << 10 | lo) + SRG_BASE;
319         siz += nr;
320 done:
321         *s = s0;
322         if (pwc != NULL)
323                 *pwc = (wchar_t)u32;
324         if (u32 == (uint32_t)0) {
325                 *nresult = (size_t)0;
326                 _citrus_UTF7_init_state(ei, psenc);
327         } else {
328                 *nresult = siz;
329                 psenc->surrogate = 0;
330         }
331         return err;
332 }
333
334 static int
335 _citrus_UTF7_utf16tomb(_UTF7EncodingInfo * __restrict ei,
336         char * __restrict s, size_t n, uint16_t u16,
337         _UTF7State * __restrict psenc, size_t * __restrict nresult)
338 {
339         int bits, i;
340
341         _DIAGASSERT(ei != NULL);
342         _DIAGASSERT(psenc != NULL);
343
344         if (psenc->chlen != 0 || psenc->bits > BASE64_BIT)
345                 return EINVAL;
346
347         if (ISSAFE(ei, u16)) {
348                 if (psenc->mode) {
349                         if (psenc->bits > 0) {
350                                 bits = BASE64_BIT - psenc->bits;
351                                 i = (psenc->cache << bits) & BASE64_MAX;
352                                 psenc->ch[psenc->chlen++] = base64[i];
353                                 psenc->bits = psenc->cache = 0;
354                         }
355                         if (u16 == BASE64_OUT || FINDLEN(ei, u16) >= 0)
356                                 psenc->ch[psenc->chlen++] = BASE64_OUT;
357                         psenc->mode = 0;
358                 }
359                 if (psenc->bits != 0)
360                         return EINVAL;
361                 psenc->ch[psenc->chlen++] = (char)u16;
362                 if (u16 == BASE64_IN)
363                         psenc->ch[psenc->chlen++] = BASE64_OUT;
364         } else {
365                 if (!psenc->mode) {
366                         if (psenc->bits > 0)
367                                 return EINVAL;
368                         psenc->ch[psenc->chlen++] = BASE64_IN;
369                         psenc->mode = 1;
370                 }
371                 psenc->cache = (psenc->cache << UTF16_BIT) | u16;
372                 bits = UTF16_BIT + psenc->bits;
373                 psenc->bits = bits % BASE64_BIT;
374                 while ((bits -= BASE64_BIT) >= 0) {
375                         i = (psenc->cache >> bits) & BASE64_MAX;
376                         psenc->ch[psenc->chlen++] = base64[i];
377                 }
378         }
379         memcpy(s, psenc->ch, psenc->chlen);
380         *nresult = psenc->chlen;
381         psenc->chlen = 0;
382
383         return 0;
384 }
385
386 static int
387 _citrus_UTF7_wcrtomb_priv(_UTF7EncodingInfo * __restrict ei,
388         char * __restrict s, size_t n, wchar_t wchar,
389         _UTF7State * __restrict psenc, size_t * __restrict nresult)
390 {
391         uint32_t u32;
392         uint16_t u16[2];
393         int err, len, i;
394         size_t siz, nr;
395
396         _DIAGASSERT(ei != NULL);
397         _DIAGASSERT(s != NULL);
398         _DIAGASSERT(psenc != NULL);
399         _DIAGASSERT(nresult != NULL);
400
401         u32 = (uint32_t)wchar;
402         if (u32 <= UTF16_MAX) {
403                 u16[0] = (uint16_t)u32;
404                 len = 1;
405         } else if (u32 <= UTF32_MAX) {
406                 u32 -= SRG_BASE;
407                 u16[0] = (u32 >> 10) + HISRG_MIN;
408                 u16[1] = ((uint16_t)(u32 & UINT32_C(0x3ff))) + LOSRG_MIN;
409                 len = 2;
410         } else {
411                 *nresult = (size_t)-1;
412                 return EILSEQ;
413         }
414         siz = 0;
415         for (i = 0; i < len; ++i) {
416                 err = _citrus_UTF7_utf16tomb(ei, s, n, u16[i], psenc, &nr);
417                 if (err != 0)
418                         return err; /* XXX: state has been modified */
419                 s += nr;
420                 n -= nr;
421                 siz += nr;
422         }
423         *nresult = siz;
424
425         return 0;
426 }
427
428 static int
429 /* ARGSUSED */
430 _citrus_UTF7_put_state_reset(_UTF7EncodingInfo * __restrict ei,
431         char * __restrict s, size_t n, _UTF7State * __restrict psenc,
432         size_t * __restrict nresult)
433 {
434         int bits, pos;
435
436         _DIAGASSERT(ei != NULL);
437         _DIAGASSERT(s != NULL);
438         _DIAGASSERT(psenc != NULL);
439         _DIAGASSERT(nresult != NULL);
440
441         if (psenc->chlen != 0 || psenc->bits > BASE64_BIT || psenc->surrogate)
442                 return EINVAL;
443
444         if (psenc->mode) {
445                 if (psenc->bits > 0) {
446                         if (n-- < 1)
447                                 return E2BIG;
448                         bits = BASE64_BIT - psenc->bits;
449                         pos = (psenc->cache << bits) & BASE64_MAX;
450                         psenc->ch[psenc->chlen++] = base64[pos];
451                         psenc->ch[psenc->chlen++] = BASE64_OUT;
452                         psenc->bits = psenc->cache = 0;
453                 }
454                 psenc->mode = 0;
455         }
456         if (psenc->bits != 0)
457                 return EINVAL;
458         if (n-- < 1)
459                 return E2BIG;
460
461         _DIAGASSERT(n >= psenc->chlen);
462         *nresult = (size_t)psenc->chlen;
463         if (psenc->chlen > 0) {
464                 memcpy(s, psenc->ch, psenc->chlen);
465                 psenc->chlen = 0;
466         }
467
468         return 0;
469 }
470
471 static __inline int
472 /*ARGSUSED*/
473 _citrus_UTF7_stdenc_wctocs(_UTF7EncodingInfo * __restrict ei,
474                            _csid_t * __restrict csid,
475                            _index_t * __restrict idx, wchar_t wc)
476 {
477         /* ei seem to be unused */
478         _DIAGASSERT(csid != NULL);
479         _DIAGASSERT(idx != NULL);
480
481         *csid = 0;
482         *idx = (_index_t)wc;
483
484         return 0;
485 }
486
487 static __inline int
488 /*ARGSUSED*/
489 _citrus_UTF7_stdenc_cstowc(_UTF7EncodingInfo * __restrict ei,
490                            wchar_t * __restrict wc,
491                            _csid_t csid, _index_t idx)
492 {
493         /* ei seem to be unused */
494         _DIAGASSERT(wc != NULL);
495
496         if (csid != 0)
497                 return EILSEQ;
498         *wc = (wchar_t)idx;
499
500         return 0;
501 }
502
503 static __inline int
504 /*ARGSUSED*/
505 _citrus_UTF7_stdenc_get_state_desc_generic(_UTF7EncodingInfo * __restrict ei,
506                                            _UTF7State * __restrict psenc,
507                                            int * __restrict rstate)
508 {
509
510         if (psenc->chlen == 0)
511                 *rstate = _STDENC_SDGEN_INITIAL;
512         else
513                 *rstate = _STDENC_SDGEN_INCOMPLETE_CHAR;
514
515         return 0;
516 }
517
518 static void
519 /*ARGSUSED*/
520 _citrus_UTF7_encoding_module_uninit(_UTF7EncodingInfo *ei)
521 {
522         /* ei seems to be unused */
523 }
524
525 static int
526 /*ARGSUSED*/
527 _citrus_UTF7_encoding_module_init(_UTF7EncodingInfo * __restrict ei,
528                                   const void * __restrict var, size_t lenvar)
529 {
530         const char *s;
531
532         _DIAGASSERT(ei != NULL);
533         /* var may be null */
534
535         memset(ei, 0, sizeof(*ei));
536
537 #define FILL(str, flag)                         \
538 do {                                            \
539         for (s = str; *s != '\0'; s++)          \
540                 ei->cell[*s & 0x7f] |= flag;    \
541 } while (/*CONSTCOND*/0)
542
543         FILL(base64, (s - base64) + 1);
544         FILL(direct, EI_DIRECT);
545         FILL(option, EI_OPTION);
546         FILL(spaces, EI_SPACE);
547
548         return 0;
549 }
550
551 /* ----------------------------------------------------------------------
552  * public interface for ctype
553  */
554
555 _CITRUS_CTYPE_DECLS(UTF7);
556 _CITRUS_CTYPE_DEF_OPS(UTF7);
557
558 #include "citrus_ctype_template.h"
559
560 /* ----------------------------------------------------------------------
561  * public interface for stdenc
562  */
563
564 _CITRUS_STDENC_DECLS(UTF7);
565 _CITRUS_STDENC_DEF_OPS(UTF7);
566
567 #include "citrus_stdenc_template.h"